blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2 values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 986 values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23 values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 145 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 3 10.4M | extension stringclasses 122 values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
74aa07b8f1c063ffdec730e9daea450f0ee3a77e | 7d6f4bc077c6f5be7be2b11ea5fee031a4fed59e | /tests/unit/performance_counter/reinit_counters.cpp | 3ea2c657948e749c7b1fdd029a1862b5ac31f26b | [
"LicenseRef-scancode-free-unknown",
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | ShmuelLevine/hpx | cf73c8d74d26d34e67b4180e72003c691eae8558 | a1621a0cfa58a884b03bc8557d4f5ad896297f14 | refs/heads/master | 2021-01-24T17:59:31.765340 | 2018-03-29T13:41:50 | 2018-03-29T13:41:50 | 35,928,421 | 0 | 0 | BSL-1.0 | 2018-03-23T06:44:59 | 2015-05-20T05:44:06 | C++ | UTF-8 | C++ | false | false | 5,862 | cpp | // Copyright (c) 2018 Hartmut Kaiser
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <hpx/hpx_init.hpp>
#include <hpx/include/components.hpp>
#include <hpx/include/performance_counters.hpp>
#include <hpx/util/lightweight_test.hpp>
#include <atomic>
#include <cstdint>
#include <ctime>
#include <iostream>
#include <numeric>
#include <string>
#include <utility>
#include <vector>
///////////////////////////////////////////////////////////////////////////////
std::atomic<unsigned int> value_count_;
class test_counter
: public hpx::performance_counters::base_performance_counter<test_counter>
{
public:
test_counter() = default;
test_counter(hpx::performance_counters::counter_info const& info)
: hpx::performance_counters::base_performance_counter<test_counter>(info)
, base_counter_(0)
{
value_count_ = std::rand() % 100;
}
hpx::performance_counters::counter_values_array get_counter_values_array(
bool reset) override
{
hpx::performance_counters::counter_values_array value;
value.time_ = hpx::util::high_resolution_clock::now();
value.status_ = hpx::performance_counters::status_new_data;
value.count_ = ++invocation_count_;
std::vector<std::int64_t> result(value_count_.load());
std::iota(result.begin(), result.end(), base_counter_.load());
++base_counter_;
if (reset)
base_counter_.store(0);
value.values_ = std::move(result);
return value;
}
void reinit(bool reset) override
{
value_count_ = std::rand();
}
private:
std::atomic<std::int64_t> base_counter_;
};
typedef hpx::components::component<test_counter> test_counter_type;
HPX_REGISTER_DERIVED_COMPONENT_FACTORY(
test_counter_type, test_counter, "base_performance_counter");
///////////////////////////////////////////////////////////////////////////////
hpx::naming::gid_type test_counter_creator(
hpx::performance_counters::counter_info const& info, hpx::error_code& ec)
{
hpx::performance_counters::counter_path_elements paths;
get_counter_path_elements(info.fullname_, paths, ec);
if (ec) return hpx::naming::invalid_gid;
if (paths.parentinstance_is_basename_) {
HPX_THROWS_IF(ec, hpx::bad_parameter,
"test_counter_creator",
"invalid counter instance parent name: " +
paths.parentinstancename_);
return hpx::naming::invalid_gid;
}
// create individual counter
if (paths.instancename_ == "total" && paths.instanceindex_ == -1)
{
// make sure parent instance name is set properly
hpx::performance_counters::counter_info complemented_info = info;
complement_counter_info(complemented_info, info, ec);
if (ec) return hpx::naming::invalid_gid;
// create the counter as requested
hpx::naming::gid_type id;
try {
id = hpx::components::server::construct<test_counter_type>(
complemented_info);
}
catch (hpx::exception const& e) {
if (&ec == &hpx::throws)
throw;
ec = make_error_code(e.get_error(), e.what());
return hpx::naming::invalid_gid;
}
if (&ec != &hpx::throws)
ec = hpx::make_success_code();
return id;
}
HPX_THROWS_IF(ec, hpx::bad_parameter,
"test_counter_creator",
"invalid counter instance name: " + paths.instancename_);
return hpx::naming::invalid_gid;
}
///////////////////////////////////////////////////////////////////////////////
void register_counter_type()
{
// Call the HPX API function to register the counter type.
hpx::performance_counters::install_counter_type("/test/reinit-values",
hpx::performance_counters::counter_raw_values,
"returns an array of linearly increasing counter values, supports "
"reinit",
&test_counter_creator,
&hpx::performance_counters::locality_counter_discoverer,
HPX_PERFORMANCE_COUNTER_V1);
}
///////////////////////////////////////////////////////////////////////////////
int hpx_main(boost::program_options::variables_map& vm)
{
unsigned int seed = (unsigned int)std::time(nullptr);
if (vm.count("seed"))
seed = vm["seed"].as<unsigned int>();
std::cout << "using seed: " << seed << std::endl;
std::srand(seed);
for (int i = 0; i != 10; ++i)
{
hpx::performance_counters::performance_counter c("/test/reinit-values");
c.reinit();
auto values = c.get_counter_values_array(hpx::launch::sync, false);
HPX_TEST_EQ(values.count_, static_cast<std::uint64_t>(i + 1));
std::vector<std::int64_t> expected(value_count_.load());
std::iota(expected.begin(), expected.end(), i);
HPX_TEST(values.values_ == expected);
std::string name = c.get_name(hpx::launch::sync);
HPX_TEST_EQ(name, std::string("/test{locality#0/total}/reinit-values"));
}
return hpx::finalize();
}
int main(int argc, char* argv[])
{
// add command line option which controls the random number generator seed
using namespace boost::program_options;
options_description desc_commandline(
"Usage: " HPX_APPLICATION_STRING " [options]");
desc_commandline.add_options()
("seed,s", value<unsigned int>(),
"the random number generator seed to use for this run")
;
hpx::register_startup_function(®ister_counter_type);
// Initialize and run HPX.
std::vector<std::string> const cfg = {
"hpx.os_threads=1"
};
HPX_TEST_EQ(hpx::init(desc_commandline, argc, argv, cfg), 0);
return hpx::util::report_errors();
}
| [
"hartmut.kaiser@gmail.com"
] | hartmut.kaiser@gmail.com |
433be9f9929dea363839b8fad725e5d0c4caa010 | a7c07b78c1497807b2fdd77a2a805ac48cc0351b | /src/core/csr/filters/unsupervised_clustering_filter_factory.hpp | 4dfb02c0a89231b5da1865753f649d1af39d5034 | [
"MIT"
] | permissive | luntergroup/octopus | 4cedb3a51f6b91271ab316303fda6bded6362d86 | 17a597d192bcd5192689bf38c5836a98b824867a | refs/heads/develop | 2022-08-18T02:16:40.058928 | 2022-07-08T15:09:38 | 2022-07-08T15:09:38 | 30,291,133 | 311 | 45 | MIT | 2022-02-04T00:24:36 | 2015-02-04T09:24:53 | C++ | UTF-8 | C++ | false | false | 1,921 | hpp | // Copyright (c) 2015-2021 Daniel Cooke
// Use of this source code is governed by the MIT license that can be found in the LICENSE file.
#ifndef unsupervised_clustering_filter_factory_hpp
#define unsupervised_clustering_filter_factory_hpp
#include <memory>
#include <vector>
#include <set>
#include <string>
#include <boost/optional.hpp>
#include "logging/progress_meter.hpp"
#include "../measures/measure.hpp"
#include "variant_call_filter_factory.hpp"
#include "variant_call_filter.hpp"
#include "unsupervised_clustering_filter.hpp"
namespace octopus { namespace csr {
class FacetFactory;
class UnsupervisedClusteringFilterFactory : public VariantCallFilterFactory
{
public:
UnsupervisedClusteringFilterFactory() = default;
UnsupervisedClusteringFilterFactory(const std::set<std::string>& measure_names);
UnsupervisedClusteringFilterFactory(const UnsupervisedClusteringFilterFactory&) = default;
UnsupervisedClusteringFilterFactory& operator=(const UnsupervisedClusteringFilterFactory&) = default;
UnsupervisedClusteringFilterFactory(UnsupervisedClusteringFilterFactory&&) = default;
UnsupervisedClusteringFilterFactory& operator=(UnsupervisedClusteringFilterFactory&&) = default;
~UnsupervisedClusteringFilterFactory() = default;
private:
std::vector<MeasureWrapper> measures_;
std::unique_ptr<VariantCallFilterFactory> do_clone() const override;
std::unique_ptr<VariantCallFilter> do_make(FacetFactory facet_factory,
VariantCallFilter::OutputOptions output_config,
boost::optional<ProgressMeter&> progress,
VariantCallFilter::ConcurrencyPolicy threading) const override;
};
} // namespace csr
using csr::UnsupervisedClusteringFilterFactory;
} // namespace octopus
#endif
| [
"dcooke@well.ox.ac.uk"
] | dcooke@well.ox.ac.uk |
0c33a8bff6c660435ea48a7ccefabee43b498dcb | 07cda1295da0370c630697701df0fc5e3e45ca28 | /components/password_manager/core/browser/affiliation_utils_unittest.cc | 73240bc3560c67c78f19fdfe419e9610cd1e3a1a | [
"BSD-3-Clause"
] | permissive | anawhj/chromium-crosswalk | 8221f9510bfb9df29dab12e6cdc57030380eb3f5 | 97959a5c98a1e18513f3ea21697323634d2fd696 | refs/heads/master | 2021-01-24T17:23:55.447032 | 2015-08-11T23:14:52 | 2015-08-11T23:14:52 | 40,750,463 | 0 | 1 | null | 2015-08-15T07:18:53 | 2015-08-15T07:18:52 | null | UTF-8 | C++ | false | false | 13,545 | cc | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/password_manager/core/browser/affiliation_utils.h"
#include "base/command_line.h"
#include "base/metrics/field_trial.h"
#include "components/password_manager/core/common/password_manager_switches.h"
#include "components/variations/variations_associated_data.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/url_constants.h"
namespace password_manager {
namespace {
const char kFieldTrialName[] = "AffiliationBasedMatching";
const char kTestFacetURI1[] = "https://alpha.example.com/";
const char kTestFacetURI2[] = "https://beta.example.com/";
const char kTestFacetURI3[] = "https://gamma.example.com/";
} // namespace
TEST(AffiliationUtilsTest, ValidWebFacetURIs) {
struct {
const char* valid_facet_uri;
const char* expected_canonical_facet_uri;
} kTestCases[] = {
{"https://www.example.com", "https://www.example.com"},
{"HTTPS://www.EXAMPLE.com", "https://www.example.com"},
{"https://0321.0x86.161.0043", "https://209.134.161.35"},
{"https://www.%65xample.com", "https://www.example.com"},
{"https://sz\xc3\xb3t\xc3\xa1r.example.com",
"https://xn--sztr-7na0i.example.com"},
{"https://www.example.com/", "https://www.example.com"},
{"https://www.example.com:", "https://www.example.com"},
{"https://@www.example.com", "https://www.example.com"},
{"https://:@www.example.com", "https://www.example.com"},
{"https://www.example.com:8080", "https://www.example.com:8080"},
{"https://new-gtld", "https://new-gtld"}};
for (const auto& test_case : kTestCases) {
SCOPED_TRACE(testing::Message("URI = ") << test_case.valid_facet_uri);
FacetURI facet_uri =
FacetURI::FromPotentiallyInvalidSpec(test_case.valid_facet_uri);
ASSERT_TRUE(facet_uri.IsValidWebFacetURI());
EXPECT_EQ(std::string(test_case.expected_canonical_facet_uri),
facet_uri.canonical_spec());
EXPECT_EQ(url::kHttpsScheme, facet_uri.scheme());
EXPECT_EQ("", facet_uri.android_package_name());
}
}
TEST(AffiliationUtilsTest, InvalidWebFacetURIs) {
const char* kInvalidFacetURIs[]{
// Invalid URL (actually, will be treated as having only a host part).
"Does not look like a valid URL.",
// Path is more than just the root path ('/').
"https://www.example.com/path",
// Empty scheme and not HTTPS scheme.
"://www.example.com",
"http://www.example.com/",
// Forbidden non-empty components.
"https://user@www.example.com/",
"https://:password@www.example.com/",
"https://www.example.com/?",
"https://www.example.com/?query",
"https://www.example.com/#",
"https://www.example.com/#ref",
// Valid Android facet URI.
"android://hash@com.example.android"};
for (const char* uri : kInvalidFacetURIs) {
SCOPED_TRACE(testing::Message("URI = ") << uri);
FacetURI facet_uri = FacetURI::FromPotentiallyInvalidSpec(uri);
EXPECT_FALSE(facet_uri.IsValidWebFacetURI());
}
}
TEST(AffiliationUtilsTest, ValidAndroidFacetURIs) {
struct {
const char* valid_facet_uri;
const char* expected_canonical_facet_uri;
const char* expected_package_name;
} kTestCases[] = {
{"android://"
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_"
"@com.example.android",
"android://"
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_"
"@com.example.android",
"com.example.android"},
{"ANDROID://"
"hash@abcdefghijklmnopqrstuvwxyz_0123456789.ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"android://"
"hash@abcdefghijklmnopqrstuvwxyz_0123456789.ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"abcdefghijklmnopqrstuvwxyz_0123456789.ABCDEFGHIJKLMNOPQRSTUVWXYZ"},
{"android://needpadding@com.example.android",
"android://needpadding=@com.example.android",
"com.example.android"},
{"android://needtounescape%3D%3D@com.%65xample.android",
"android://needtounescape==@com.example.android",
"com.example.android"},
{"ANDROID://hash@com.example.android",
"android://hash@com.example.android",
"com.example.android"},
{"android://hash@com.example.android/",
"android://hash@com.example.android",
"com.example.android"},
{"android://hash:@com.example.android",
"android://hash@com.example.android",
"com.example.android"}};
for (const auto& test_case : kTestCases) {
SCOPED_TRACE(testing::Message("URI = ") << test_case.valid_facet_uri);
FacetURI facet_uri =
FacetURI::FromPotentiallyInvalidSpec(test_case.valid_facet_uri);
ASSERT_TRUE(facet_uri.IsValidAndroidFacetURI());
EXPECT_EQ(test_case.expected_canonical_facet_uri,
facet_uri.canonical_spec());
EXPECT_EQ("android", facet_uri.scheme());
EXPECT_EQ(test_case.expected_package_name,
facet_uri.android_package_name());
}
}
TEST(AffiliationUtilsTest, InvalidAndroidFacetURIs) {
const char* kInvalidFacetURIs[]{
// Invalid URL (actually, will be treated as having only a host part).
"Does not look like a valid URL.",
// Path is more than just the root path ('/').
"android://hash@com.example.android/path",
// Empty scheme or not "android" scheme.
"://hash@com.example.android",
"http://hash@com.example.android",
// Package name with illegal characters.
"android://hash@com.$example.android",
"android://hash@com-example-android",
"android://hash@com%2Dexample.android", // Escaped '-'.
"android://hash@com.example.sz\xc3\xb3t\xc3\xa1r", // UTF-8 o' and a'.
// Empty, non-existent and malformed hash part.
"android://@com.example.android",
"android://com.example.android",
"android://badpadding=a@com.example.android",
"android://toolongpaddin===@com.example.android",
"android://invalid+characters@com.example.android",
"android://invalid%2Fcharacters@com.example.android", // Escaped '/'.
// Forbidden non-empty components.
"android://hash:password@com.example.android",
"android://hash@com.example.android:port",
"android://hash@com.example.android/?",
"android://hash@com.example.android/?query",
"android://hash@com.example.android/#",
"android://hash@com.example.android/#ref",
// Valid Web facet URI.
"https://www.example.com/"};
for (const char* uri : kInvalidFacetURIs) {
SCOPED_TRACE(testing::Message("URI = ") << uri);
FacetURI facet_uri = FacetURI::FromPotentiallyInvalidSpec(uri);
EXPECT_FALSE(facet_uri.IsValidAndroidFacetURI());
EXPECT_EQ("", facet_uri.android_package_name());
}
}
TEST(AffiliationUtilsTest, EqualEquivalenceClasses) {
AffiliatedFacets a;
a.push_back(FacetURI::FromCanonicalSpec(kTestFacetURI1));
a.push_back(FacetURI::FromCanonicalSpec(kTestFacetURI2));
a.push_back(FacetURI::FromCanonicalSpec(kTestFacetURI3));
AffiliatedFacets b;
b.push_back(FacetURI::FromCanonicalSpec(kTestFacetURI3));
b.push_back(FacetURI::FromCanonicalSpec(kTestFacetURI1));
b.push_back(FacetURI::FromCanonicalSpec(kTestFacetURI2));
EXPECT_TRUE(AreEquivalenceClassesEqual(a, a));
EXPECT_TRUE(AreEquivalenceClassesEqual(b, b));
EXPECT_TRUE(AreEquivalenceClassesEqual(b, a));
EXPECT_TRUE(AreEquivalenceClassesEqual(a, b));
}
TEST(AffiliationUtilsTest, NotEqualEquivalenceClasses) {
AffiliatedFacets a;
a.push_back(FacetURI::FromCanonicalSpec(kTestFacetURI1));
a.push_back(FacetURI::FromCanonicalSpec(kTestFacetURI2));
AffiliatedFacets b;
a.push_back(FacetURI::FromCanonicalSpec(kTestFacetURI2));
b.push_back(FacetURI::FromCanonicalSpec(kTestFacetURI3));
AffiliatedFacets c;
a.push_back(FacetURI::FromCanonicalSpec(kTestFacetURI1));
a.push_back(FacetURI::FromCanonicalSpec(kTestFacetURI2));
b.push_back(FacetURI::FromCanonicalSpec(kTestFacetURI3));
EXPECT_FALSE(AreEquivalenceClassesEqual(a, b));
EXPECT_FALSE(AreEquivalenceClassesEqual(a, c));
EXPECT_FALSE(AreEquivalenceClassesEqual(b, a));
EXPECT_FALSE(AreEquivalenceClassesEqual(b, c));
EXPECT_FALSE(AreEquivalenceClassesEqual(c, a));
EXPECT_FALSE(AreEquivalenceClassesEqual(c, b));
}
TEST(AffiliationUtilsTest, IsAffiliationBasedMatchingEnabled) {
struct {
const char* field_trial_group;
const char* command_line_switch;
bool expected_enabled;
} kTestCases[] = {
{"", "", false},
{"", switches::kEnableAffiliationBasedMatching, true},
{"", switches::kDisableAffiliationBasedMatching, false},
{"garbage value", "", false},
{"disabled", "", false},
{"disabled2", "", false},
{"Disabled", "", false},
{"Disabled", switches::kDisableAffiliationBasedMatching, false},
{"Disabled", switches::kEnableAffiliationBasedMatching, true},
{"enabled", "", true},
{"enabled2", "", true},
{"Enabled", "", true},
{"Enabled", switches::kDisableAffiliationBasedMatching, false},
{"Enabled", switches::kEnableAffiliationBasedMatching, true}};
for (const auto& test_case : kTestCases) {
SCOPED_TRACE(testing::Message("Command line = ")
<< test_case.command_line_switch);
SCOPED_TRACE(testing::Message("Group name = ")
<< test_case.field_trial_group);
base::FieldTrialList field_trials(nullptr);
base::FieldTrialList::CreateFieldTrial(kFieldTrialName,
test_case.field_trial_group);
base::CommandLine command_line(base::CommandLine::NO_PROGRAM);
command_line.AppendSwitch(test_case.command_line_switch);
EXPECT_EQ(test_case.expected_enabled,
IsAffiliationBasedMatchingEnabled(command_line));
}
}
TEST(AffiliationUtilsTest,
IsPropagatingPasswordChangesToWebCredentialsEnabled) {
const char kExperimentName[] = "DoesNotMatter";
struct {
const char* variation_param;
const char* command_line_switch;
bool expected_enabled;
} kTestCases[] = {
{"", "", false},
{"", switches::kEnableAffiliationBasedMatching, true},
{"", switches::kDisableAffiliationBasedMatching, false},
{"garbage value", "", false},
{"disabled", "", false},
{"Disabled", "", false},
{"Disabled", switches::kDisableAffiliationBasedMatching, false},
{"Disabled", switches::kEnableAffiliationBasedMatching, true},
{"enabled", "", true},
{"Enabled", "", true},
{"Enabled", switches::kDisableAffiliationBasedMatching, false},
{"Enabled", switches::kEnableAffiliationBasedMatching, true}};
for (const auto& test_case : kTestCases) {
SCOPED_TRACE(testing::Message("Command line = ")
<< test_case.command_line_switch);
SCOPED_TRACE(testing::Message("Variation param = ")
<< test_case.variation_param);
variations::testing::ClearAllVariationParams();
base::FieldTrialList field_trials(nullptr);
base::FieldTrialList::CreateFieldTrial(kFieldTrialName, kExperimentName);
std::map<std::string, std::string> variation_params;
variation_params["propagate_password_changes_to_web"] =
test_case.variation_param;
ASSERT_TRUE(variations::AssociateVariationParams(
kFieldTrialName, kExperimentName, variation_params));
base::CommandLine command_line(base::CommandLine::NO_PROGRAM);
command_line.AppendSwitch(test_case.command_line_switch);
EXPECT_EQ(
test_case.expected_enabled,
IsPropagatingPasswordChangesToWebCredentialsEnabled(command_line));
}
}
TEST(AffiliationUtilsTest, IsAffiliationRequestsForDummyFacetsEnabled) {
const char kExperimentName[] = "DoesNotMatter";
struct {
const char* variation_param;
const char* command_line_switch;
bool expected_enabled;
} kTestCases[] = {
{"", "", false},
{"", switches::kEnableAffiliationBasedMatching, true},
{"", switches::kDisableAffiliationBasedMatching, false},
{"garbage value", "", false},
{"disabled", "", false},
{"Disabled", "", false},
{"Disabled", switches::kDisableAffiliationBasedMatching, false},
{"Disabled", switches::kEnableAffiliationBasedMatching, true},
{"enabled", "", true},
{"Enabled", "", true},
{"Enabled", switches::kDisableAffiliationBasedMatching, false},
{"Enabled", switches::kEnableAffiliationBasedMatching, true}};
for (const auto& test_case : kTestCases) {
SCOPED_TRACE(testing::Message("Command line = ")
<< test_case.command_line_switch);
SCOPED_TRACE(testing::Message("Variation param = ")
<< test_case.variation_param);
variations::testing::ClearAllVariationParams();
base::FieldTrialList field_trials(nullptr);
base::FieldTrialList::CreateFieldTrial(kFieldTrialName, kExperimentName);
std::map<std::string, std::string> variation_params;
variation_params["affiliation_requests_for_dummy_facets"] =
test_case.variation_param;
ASSERT_TRUE(variations::AssociateVariationParams(
kFieldTrialName, kExperimentName, variation_params));
base::CommandLine command_line(base::CommandLine::NO_PROGRAM);
command_line.AppendSwitch(test_case.command_line_switch);
EXPECT_EQ(test_case.expected_enabled,
IsAffiliationRequestsForDummyFacetsEnabled(command_line));
}
}
} // namespace password_manager
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
04ed14fdd6de5afb8036731f8d2400eec4ef4152 | 59fb234b179fc08863bdf0df6fc6b4d9fb75c1d6 | /project/paralution-1.1.0/src/utils/allocate_free.cpp | 2713eb735c236b60e2d7da2612aead940502702d | [] | no_license | tanderson92/CS179Labs | d9b873a0cada2f166ad0987da7271028871be4b5 | fb5435e9c154837b1004aa7539144c83c97fe6af | refs/heads/master | 2021-01-20T01:23:04.780629 | 2017-06-09T21:40:26 | 2017-06-09T21:40:26 | 89,268,268 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,921 | cpp | // **************************************************************************
//
// PARALUTION www.paralution.com
//
// Copyright (C) 2015 PARALUTION Labs UG (haftungsbeschränkt) & Co. KG
// Am Hasensprung 6, 76571 Gaggenau
// Handelsregister: Amtsgericht Mannheim, HRA 706051
// Vertreten durch:
// PARALUTION Labs Verwaltungs UG (haftungsbeschränkt)
// Am Hasensprung 6, 76571 Gaggenau
// Handelsregister: Amtsgericht Mannheim, HRB 721277
// Geschäftsführer: Dimitar Lukarski, Nico Trost
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// **************************************************************************
// PARALUTION version 1.1.0
#include "def.hpp"
#include "allocate_free.hpp"
#include "log.hpp"
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <complex>
#include <cstddef>
namespace paralution {
// Check -- if there is no CUDA support
// pinned memory is disabled
#ifndef SUPPORT_CUDA
#undef PARALUTION_CUDA_PINNED_MEMORY
#endif
//#define MEM_ALIGNMENT 64
//#define LONG_PTR size_t
//#define LONG_PTR long
#ifndef PARALUTION_CUDA_PINNED_MEMORY
template <typename DataType>
void allocate_host(const int size, DataType **ptr) {
LOG_DEBUG(0, "allocate_host()",
size);
if (size > 0) {
assert(*ptr == NULL);
// *********************************************************
// C++ style
// *ptr = new DataType[size];
// *********************************************************
// *********************************************************
// C style
// *ptr = (DataType *) malloc(size*sizeof(DataType));
// *********************************************************
// *********************************************************
// C style (zero-set)
// *ptr = (DataType *) calloc(size, sizeof(DatatType));
// *********************************************************
// *********************************************************
// Aligned allocation
// total size = (size*datatype) + (alignment-1) + (void ptr)
// void *non_aligned = malloc(size*sizeof(DataType)+(MEM_ALIGNMENT-1)+sizeof(void*));
// assert(non_aligned != NULL);
// void *aligned = (void*)( ((LONG_PTR)(non_aligned)+MEM_ALIGNMENT+sizeof(void*) ) & ~(MEM_ALIGNMENT-1) );
// *((void**)aligned-1) = non_aligned;
// *ptr = (DataType*) aligned;
// LOG_INFO("A " << *ptr << " " << aligned << " " << non_aligned << " "<< sizeof(DataType) << " " << size);
// *********************************************************
// *********************************************************
// C++ style and error handling
*ptr = new (std::nothrow) DataType[size];
if ((*ptr) == false) { // nullptr
LOG_INFO("Cannot allocate memory");
LOG_VERBOSE_INFO(2, "Size of the requested buffer = " << size*sizeof(DataType));
FATAL_ERROR(__FILE__, __LINE__);
}
// *********************************************************
assert(*ptr != NULL);
LOG_DEBUG(0, "allocate_host()",
*ptr);
}
}
template <typename DataType>
void free_host(DataType **ptr) {
LOG_DEBUG(0, "free_host()",
*ptr);
assert(*ptr != NULL);
// *********************************************************
// C++ style
delete[] *ptr;
// *********************************************************
// *********************************************************
// C style
// free(*ptr);
// *********************************************************
// *********************************************************
// Aligned allocation
// free(*((void **)*ptr-1));
// *********************************************************
*ptr = NULL;
}
#endif
template <typename DataType>
void set_to_zero_host(const int size, DataType *ptr) {
LOG_DEBUG(0, "set_to_zero_host()",
"size =" << size <<
" ptr=" << ptr);
if (size > 0) {
assert(ptr != NULL);
memset(ptr, 0, size*sizeof(DataType));
// for (int i=0; i<size; ++i)
// ptr[i] = DataType(0);
}
}
#ifndef PARALUTION_CUDA_PINNED_MEMORY
template void allocate_host<float >(const int size, float **ptr);
template void allocate_host<double >(const int size, double **ptr);
#ifdef SUPPORT_COMPLEX
template void allocate_host<std::complex<float> >(const int size, std::complex<float> **ptr);
template void allocate_host<std::complex<double> >(const int size, std::complex<double> **ptr);
#endif
template void allocate_host<int >(const int size, int **ptr);
template void allocate_host<unsigned int >(const int size, unsigned int **ptr);
template void allocate_host<char >(const int size, char **ptr);
template void free_host<float >(float **ptr);
template void free_host<double >(double **ptr);
#ifdef SUPPORT_COMPLEX
template void free_host<std::complex<float> >(std::complex<float> **ptr);
template void free_host<std::complex<double> >(std::complex<double> **ptr);
#endif
template void free_host<int >(int **ptr);
template void free_host<unsigned int >(unsigned int **ptr);
template void free_host<char >(char **ptr);
#endif
template void set_to_zero_host<float >(const int size, float *ptr);
template void set_to_zero_host<double >(const int size, double *ptr);
#ifdef SUPPORT_COMPLEX
template void set_to_zero_host<std::complex<float> >(const int size, std::complex<float> *ptr);
template void set_to_zero_host<std::complex<double> >(const int size, std::complex<double> *ptr);
#endif
template void set_to_zero_host<int >(const int size, int *ptr);
template void set_to_zero_host<unsigned int >(const int size, unsigned int *ptr);
template void set_to_zero_host<char >(const int size, char *ptr);
}
| [
"tanderson@caltech.edu"
] | tanderson@caltech.edu |
59186e897825e19d5e9c0f9e194f512168bf5eac | ed6997c8fa4a0197f5275cf1488875ff09622d9f | /PPlate_0_28/PPlate_0_28.ino | 347e48515bcef3398836a3b59528a7d38ffc155c | [] | no_license | wlad1453/ChocoFactory | c9c647937f8a2c939b1428b774450c5a5c4dd4ec | 5a903bf693766fb01f80f076b5fd5b7c9b3fcf48 | refs/heads/master | 2022-07-22T01:00:56.058993 | 2022-07-16T20:37:45 | 2022-07-16T20:37:45 | 154,287,873 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 35,911 | ino | /*
BeltDriveShifterRotator //Rotates the shifter arm up (1) and down (0)
BeltDriveShifterSlider // Slide a peace of chocolate from the belt drive to the right edge of the table
MainPusher // Slide a peace of chocolate to the center of the working zone
LabelKnife // grabs a single lable from the banch
LabelVacuumValve // Switch on the vacuum to stick the lower lable
FoilGreifer // Grasp the adge of the package (foil and lable)
FoilPuller // Pulls the package onto the peace of chocolate
FoilCutter // Cutt a peace of foil
UpperRodeHolder // Holds the upper side of the cocolate
BottomRodeSupport // Heaves the peace of chocolate and the package of foil and lable and pudhes it through the guiding window
SideFolder // Fold together foil wings (front and hind ones)
MainFolder // pushes the right package wing (foil and label) beneath the peace of chocolate
GlueThrower // throws two drops of glue onto the left end of the label
LeftGreiferLifter // greies and shift the ready wrapped peace of chocolate
LeftGreiferShifter
2004 LCD
Version 28.01.2020
Next tasks
0. LCD display and keyboard!!!
1. Pressure sensor implementation - > Alarm signal
2. Launching procedure !!! --> "Ready to Work" signal (To clear the possibility of an automated pressure air valve)
3. Shut-down procedure (should be done as an interrupt routine)
4. Breakdown stop
Version 21.02.20
*/
#include <avr/io.h>
// #include <Arduino.h>
// #include <Wire.h> // Arduino IDE
// #include <PCylinder.h>
// #include <Cyclogramm.h>
#define cycleLength 1000 // Machine cycle length in milliSeconds
#define ProcNumber 26 // Number of processes to be done during the sycle
// #define ElementsNum 14 // Number of elements (units, components) the packing machine consists of
#define VelocityFactor 1 // "2" would mean that the velocity is devided by factor 2
#define sensorA 49 // Hall effect sensor at the fore end of the upper cylinder
#define sensorB 48 // Hall effect sensor in the middle of the U.cylinder
#define sensorC 47 // Hall effect sensor at the back end of the U.cylinder (working chamber)
#define sensorD 46 // Hall effect sensor at the back end of the bottom cylinder (working chamber)
#define sensorE 45 // HES Label Knife front end
#define sensorF 44 // HES Label Knife back end
#define sensorG 43 // HES Foil puller front end
#define sensorH 42 // HES Foil puller back end
#define BRode_work 37 // Bottom rode working chamber. 5/3 NC valve with 2 solenoids
#define BRode_back 36 // Bottom rode back stroke chamber. 5/3 NC valve with 2 solenoids
#define URode_work 35 // Upper rode working chamber. 5/3 NO valve
#define URode_back 34 // Upper rode back stroke chamber. 5/3 NO valve
#define BeltShifter 22 // Belt shifter. Shift the piece of chock. from the belt. 5/2 valve
#define MainPusher 23 // Main Pusher. Pushes the peece of chock. onto the table. 5/2 valve
#define LblKnife_work 24 // Label Knife to the left (work) movement. 5/3 NC valve
#define LblKnife_back 25 // Label Knife to the right (back) movement. 5/3 NC valve
#define FPuller_work 26 // Foil puller ahead (work) movement. 5/3 NC valve
#define FPuller_back 27 // Foil puller back (pull the foil back) 1st and 2nd movement. 5/3 NC valve
#define FoilGraber 28 // Foil Graber On/Off. 3/2 valve
#define BeltShifterSol 29 // Belt Shifter Solenoid
#define FoilCutter 30 // Foil Cutter On/Off. 3/2 valve
#define SideFolders 33
#define FrontFolder 32
#define PackPusher 31
uint8_t btw; // A variable to store the index in the bubble sorting procedure
boolean change;
uint16_t eventTimePnt[52]; // Start and stop time points of various machine processes (event time points)
uint8_t eventSequNum[52]; // Sequence number of events. Appearance of the event within the sycle (trigger points)
unsigned long CycleStart; // Cycle start time
uint8_t slowFac (1); // Slowdown factor
uint16_t Counter (0); // Cycle counter
boolean feed(0), elevator(1), knife(0), foil(0), cutter(0), wrapper(1);
struct machineProc {
int procNum; // Number of the machineProc process (PROCESS NUMBER)
char Name[25]; // Name of the PROCESS
boolean startLow; // Shows if at the cycle start the process isn't active (control signal is LOW)
int Start; // Start time (event) in milliSeconds from the cycle begin
int Duration; // Duration of the process between two appropriate machineProc events
int End; // End time. If !startLow End event comes earlier then the Start (End time value is less then the Start time)
boolean Active; // Shows whether the process is going on.
};
// Initialization of the machine mProcs array. Each line describes a process (element movement, switching etc.)
// Initialization of all mProcs (elements) with data out of the timing diagramm 'ChocoPackMachine v2.2.xml'
// Later should be exchanged through automatic routine, wich read a flat file or CSV with mProcs timing data or just with #include
machineProc mProc[ProcNumber] {
//Nu. Name SLow Start Dur End Active
0, "Belt shifter ahead", true, 0, 180, 0, false, // was 0, 450, 450 Should be changed because of 5/2 valve. 0, 520,
1, "Belt shifter Back", true, 540, 450, 0, false, // Became obsolete because of the simple movement
2, "Belt shifter Up", true, 510, 400, 0, false, // Should be changed due to changes of the process [0] 510, 400 (was 520, 470)
3, "Main pusher left", true, 540, 87, 0, false, // was 480, 500, 980 Should be changed because of 5/2 valve. 480, 450, (was 480,390)
4, "Main pusher right", false, 990, 330, 0, false, // Became obsolete because of the simple movement
5, "Label knife left", true, 540, 430, 0, false,
6, "Glue thrower", true, 900, 8, 0, false, // NOT done. Lack of information - signal level, design
7, "Label knife right", true, 0, 430, 0, false,
8, "Vacum valve", false, 980, 470, 0, false, // NOT done. Lack of information - signal level, design
9, "Foil puller ahead", true, 0, 450, 0, false,
10, "Foil puller 1st move", true, 480, 228, 0, false,
11, "Foil puller 2nd move", true, 760, 100, 0, false,
12, "Foil grabber", true, 450, 410, 0, false, // OK
13, "Foil cutter", true, 700, 152, 0, false, // OK. Cutt/release action. Dur was 52
14, "Upper rode down", true, 720, 270, 0, false,
15, "Upper rode Up 1st", true, 50, 230, 0, false,
16, "Upper rode Up 2nd", true, 440, 110, 0, false, // 490, 90,
17, "Bottom rode Up", true, 50, 290, 0, false, // 50, 290\310\280\320(was ok)
18, "Bottom rode Down", true, 350, 190, 0, false, // 350\330\370 (was 0k), 190, 0,
19, "Side folders", true, 340, 25, 0, false, // Was 320, 88 (20), 30
20, "Front folder", true, 410, 60, 0, false, // was 410, 40, \ 410, 78 \ 370, 40 (was ok)
21, "Package Pusher left", true, 480, 45, 0, false, // was 450, 120, \ 500, 108
22, "Package Pusher back", true, 620, 108, 0, false, // 620, 108,
23, "Package greifer Up", false, 868, 782, 0, false, // For the later implementation
24, "Package greifer left", true, 660, 228, 0, false,
25, "Package greifer right", false, 900, 240, 0, false
};
void setup() {
DDRA = 0xFF; // Port A is set as Output PA0 -> pin 22 ... PA7 -> pin 29
DDRC = 0xFF; // Port C is set as Output PC0 -> pin 37 ... PC7 -> pin 30
DDRL = 0x00; // Port L is set as Input PL0 -> pin 49 ... PL7 -> pin 42
PORTA = 0x00;
PORTB = 0x00;
// PORTL = 0xFF; // in this case it switches on pull up resistors
Serial.begin(115200); // Serial communication with PC
// Stop time calculation (mProc[n].End) and signal level setting at the sycle start
for (int i = 0; i < ProcNumber; i++) {
mProc[i].End = mProc[i].Start + mProc[i].Duration;
if (mProc[i].End > cycleLength) {
mProc[i].startLow = false;
mProc[i].End -= cycleLength;
}
/*Serial.print(i); Serial.print(" "); Serial.print(mProc[i].Name); Serial.print(" "); Serial.print(mProc[i].startLow); Serial.print(" ");
Serial.print(mProc[i].Start); Serial.print(" "); Serial.print(mProc[i].Duration); Serial.print(" ");
Serial.println(mProc[i].End); */
}
// Launching procedure !!! --> "Ready to Work" signal
// Shut-down procedure (should be done as an interrupt routine)
// Breakdown stop
// Trigger points (events time points) calculation. The Start events have even number and the Stop events get odd ones
for (int i = 0; i < ProcNumber * 2; i++) {
if (i % 2 != 0) eventTimePnt[i] = mProc[ (i-1)/2 ].End; // Refer to the mProc table
else eventTimePnt[i] = mProc[i/2].Start;
eventSequNum[i] = i; // All the step indexes are in a row, prepared for the later sorting
// Serial.print(i); Serial.print(" "); Serial.print(eventSequNum[i]); Serial.print(" "); Serial.println(eventTimePnt[i]);
}
// ********** Bubble sorting ****************
// Machine steps sorting. Building of a mapping table where all the steps are timely in a row
do {
change = false;
for (int i = 0; i < (ProcNumber * 2 - 1); i++) { // 0..51 - 52 events. (PrNu * 2 - 1) = 51 - the last Nu in the sequence
//Serial.print(i); Serial.print(" "); Serial.print(eventSequNum[i]); Serial.print(" "); Serial.print(eventSequNum[i+1]); Serial.print(" ");
//Serial.print(eventTimePnt[eventSequNum[i]]); Serial.print(" "); Serial.println(eventTimePnt[eventSequNum[i+1]]);
if ( eventTimePnt[eventSequNum[i]] > eventTimePnt[eventSequNum[i + 1]]) {
btw = eventSequNum[i];
eventSequNum[i] = eventSequNum[i + 1];
eventSequNum[i + 1] = btw;
change = true;
// Serial.print(i); Serial.print(" "); Serial.print(eventSequNum[i]); Serial.print(" "); Serial.println(eventSequNum[i+1]);
}
}
} while (change == true);
MProcTable();
SequenceTable();
StartingSequence();
} // End Setup
void loop() {
// To do:
// Keypad polling module (or interrupt routine)
// In case a key pressed changing the default values (could be done via interrapts)
// Main working sequence for(int i = 0; i < sizeOf(eventSequNum()); i++)
// If some mProcs happen -> FullStop (Stop switch pressed, no chokolate with greifer running-out, not allowed situation etc.)
CycleStart = millis(); // Starting point of each cycles
Counter++; Serial.print("Cycle number: "); Serial.println(Counter); // Number of the cycle from the begin
// Sycle control logic
for (int i = 0; i < ProcNumber * 2; ) { // Call all events in the cycle sequentually.
// EorO = eventSequNum[i] % 2; // Check whether the event number is Even or Odd
// Serial.print(i); Serial.print(" "); Serial.println(eventSequNum[i]);
if (eventSequNum[i] % 2 == 0) { // In case of an EVEN number it is a Process Start event
if ( (millis() - CycleStart) >= mProc[eventSequNum[i] / 2].Start * slowFac){ //If the Start point is reached check for the action
// if ( !(mProc[eventSequNum[i] / 2].Active) ) action(i); // make an action (switch ON) in case the process is stopped
action(i);
i++; // Increments each time the current event is reached. (next time check the next event)
}
//deBugPrintE();
}
else { // In case of ODD numbers it is a Process End event
if ( (millis() - CycleStart) >= mProc[(eventSequNum[i] - 1) / 2].End * slowFac ){ //If the Stop point is reached check for the action
// if ( mProc[(eventSequNum[i] - 1) / 2].Active ) action(i); // make an action (switch OFF) in case the process is going on only
action(i);
i++;
}
//deBugPrintO();
}
//Serial.print(digitalRead(sensorC)); Serial.print(digitalRead(sensorB)); Serial.print(digitalRead(sensorA));
//Serial.print(" PINA: "); Serial.print(PINA, BIN); Serial.print(" PINC: "); Serial.println(PINC, BIN);
// ******************* Sensor reading section. Made once each polling *************************************
if ( mProc[14].Active && !(PINL & ( 1 << (49 - sensorA) ) )) { // SensorA reading, Upper rod down. Stop the movement. All connectors are open
PORTC &= ~( 1 << (37 - URode_work));
mProc[14].Active = false;
// Serial.print(PORTL); Serial.print(" "); Serial.print(PINL); Serial.println (F(" sensorA - > Upper Rode down Stop"));
Serial.print("Sensor A at "); Serial.println( millis() - CycleStart);
}
if ( mProc[17].Active && !( PINL & ( 1 << (49 - sensorB)) )) { // Stops the movement Bottom rode Up 1st.
PORTC &= ~( 1 << (37 - BRode_work)); // "Bottom rode Up" and "Upper rode Up 1st" with a piece of chocolate squeezed inbetween
mProc[17].Active = false;
// Serial.print(PORTL); Serial.print(" "); Serial.print(PINL); Serial.println (F(" sensorB - > Bottom rode Up & Upper Rode Up 1st -> Stop"));
Serial.print("Sensor B at "); Serial.println( millis() - CycleStart);
}
if ( mProc[16].Active && !( PINL & ( 1 << (49 - sensorC) ) )) { // Upper rode Up 2nd. Stop the movement of bottom rode. All connections are open
Serial.print (digitalRead(URode_back)); Serial.print(" "); Serial.print (PINL); Serial.print(" "); Serial.println (mProc[16].Active);
PORTC &= ~( 1 << (37 - URode_back)); // Stop "Upper rode Up 2nd"
mProc[16].Active = false;
/* Serial.print(PORTL); Serial.print(" "); Serial.print(PINL); Serial.println (F(" sensorC - > Upper Rode Up 2nd -> Stop"));
Serial.print (digitalRead(URode_back)); Serial.print(" "); Serial.print (PINL); Serial.print(" "); Serial.println (mProc[16].Active); */
Serial.print("Sensor C at "); Serial.println( millis() - CycleStart);
}
if ( mProc[18].Active && !( PINL & ( 1 << (49 - sensorD))) ) { // Stops the movement Bottom rode down at the lower end of cylinder
Serial.println (digitalRead(BRode_back));
PORTC &= ~( 1 << (37 - BRode_back)); //"Bottom rode down", Stop
mProc[18].Active = false;
// action(37);
/* Serial.print(PORTL); Serial.print(" "); Serial.print(PINL); Serial.print (F(" sensorD - > Bottom Rode down -> Stop "));
Serial.println (digitalRead(BRode_back)); */
Serial.print("Sensor D at "); Serial.println( millis() - CycleStart);
}
//*** New sensors conditions 27.11.19
if ( mProc[5].Active && !(PINL & ( 1 << (49 - sensorE) ) )) { // SensorE reading, Lable Knife ahead. Stop the movement. 5/3 NC
PORTA &= ~( 1 << (LblKnife_work - 22));
mProc[5].Active = false;
Serial.print(PORTL); Serial.print(" "); Serial.print(PINL); Serial.println (F(" sensorE - > Lable Knife ahead -> Stop"));
}
if ( mProc[7].Active && !( PINL & ( 1 << (49 - sensorF)) )) { // SensorE reading, Lable Knife back. Stop the movement. 5/3 NC
PORTA &= ~( 1 << (LblKnife_back - 22));
mProc[7].Active = false;
Serial.print(PORTL); Serial.print(" "); Serial.print(PINL); Serial.println (F(" sensorF - > Lable Knife back -> Stop"));
}
if ( mProc[9].Active && !(PINL & ( 1 << (49 - sensorG) ) )) { // SensorG reading, Foil Grabber ahead. Stop the movement. 5/3 NC
PORTA &= ~( 1 << (FPuller_work - 22));
mProc[9].Active = false;
Serial.print(PORTL); Serial.print(" "); Serial.print(PINL); Serial.println (F(" sensorG - > Foil Grabber ahead -> Stop"));
}
if ( mProc[10].Active && !( PINL & ( 1 << (49 - sensorH)) )) { // SensorH reading, Foil Grabber back 1st move. Stop the movement. 5/3 NC
PORTA &= ~( 1 << (FPuller_back - 22));
mProc[10].Active = false;
Serial.print(PORTL); Serial.print(" "); Serial.print(PINL); Serial.println (F(" sensorH - > Foil Grabber back 1st move -> Stop"));
}
/* New sensors 27.11*/
} // End (i = 0; i < ProcNumber * 2; i++)
// delay(10000); // Delay between cycles
} // End void loop()
void action(int i) {
byte j;
j = eventSequNum[i];
// Serial.print(F("Action: ")); Serial.print(i); Serial.print(" "); Serial.println(eventSequNum[i]);
if( (feed && (j <= 9))
|| ( knife && (j >= 10) && (j <= 15))
|| ( foil && (j >= 18) && (j <= 25))
|| ( cutter && ( (j == 26) || (j == 27) ))
|| ( elevator && (j >= 28) && (j <= 37))
|| ( wrapper && (j >= 38) && (j <= 43)) )
{Serial.print(feed + 2*knife + 4*foil + 8*cutter + 16*elevator + 32*wrapper); Serial.print(" "); Serial.print(i); Serial.print(" "); Serial.println(j);}
else return;
switch (j) {
//*** Feed
case 0: PORTA |= ( 1 << (BeltShifter - 22)); // Belt shifter. Shift the piece of chock. from the belt. 5/2 valve
mProc[0].Active = true;
break;
case 1: PORTA &= ~( 1 << (BeltShifter - 22)); // Belt shifter. Come back to the starting position. Should be raised up
mProc[0].Active = false; // by a solenoid or additional cylinder
break;
case 6: PORTA |= ( 1 << (MainPusher - 22)); // Main Pusher. Pushes the peece of chock. onto the table. 5/2 valve
mProc[3].Active = true;
break;
case 7: PORTA &= ~( 1 << (MainPusher - 22)); // Main Pusher. Come back to the starting pos. Waiting for the next
mProc[3].Active = false; // piece of chock.
break;
//******************* /* */
case 10: PORTA |= ( 1 << (LblKnife_work - 22)); // Start Lable Knife ahead (work) movement.
mProc[5].Active = true;
break;
case 11: PORTA &= ~( 1 << (LblKnife_work - 22)); // Stop Lable Knife ahead (work) movement.
mProc[5].Active = false;
break;
case 12: // Open Glue thrower. To implement later
mProc[6].Active = true;
break;
case 13: // Close Glue thrower. To implement later
mProc[6].Active = false;
break;
case 14: PORTA |= ( 1 << (LblKnife_back - 22)); // Start Lable Knife back movement.
mProc[7].Active = true;
break;
case 15: PORTA &= ~( 1 << (LblKnife_back - 22)); // Stop Lable Knife back movement.
mProc[7].Active = false;
break;
case 18: PORTA |= ( 1 << (FPuller_work - 22)); // Start Foil puller ahead (work) movement.
mProc[9].Active = true;
break;
case 19: PORTA &= ~( 1 << (FPuller_work - 22)); // Stop Foil puller ahead (work) movement.
mProc[9].Active = false;
break;
case 20: PORTA |= ( 1 << (FPuller_back - 22)); // Start Foil puller back (pull) 1st movement.
mProc[10].Active = true;
break;
case 21: PORTA &= ~( 1 << (FPuller_back - 22)); // Stop Foil puller back (pull) 1st movement.
mProc[10].Active = false;
break;
case 22: PORTA |= ( 1 << (FPuller_back - 22)); // Start Foil puller back (pull) 2nd movement.
mProc[11].Active = true;
break;
case 23: PORTA &= ~( 1 << (FPuller_back - 22)); // Stop Foil puller back (pull) 2nd movement.
mProc[11].Active = false;
break;
case 24: PORTA |= ( 1 << (FoilGraber - 22)); // Foil Graber On (clanch).
mProc[12].Active = true;
break;
case 25: PORTA &= ~( 1 << (FoilGraber - 22)); // Foil Graber Off (release).
mProc[12].Active = false;
break;
case 26: PORTC |= ( 1 << (37 - FoilCutter)); // Foil Cutter On (cutt foil).
mProc[13].Active = true;
break;
case 27: PORTC &= ~( 1 << (37 - FoilCutter)); // Foil Cutter Off (release).
mProc[13].Active = false;
break;
case 28: PORTC |= ( 1 << (37 - URode_work)); //Start "Upper rode down"
Serial.print("Start Upper rode down at "); Serial.println( millis() - CycleStart);
mProc[14].Active = true;
break;
case 29: PORTC &= ~( 1 << (37 - URode_work)); //Stop "Upper rode down"
Serial.print("Stop Upper rode down at "); Serial.println( millis() - CycleStart);
mProc[14].Active = false;
break;
case 30: mProc[15].Active = true; break; //"Upper rode Up 1st", Start. No upper rode drives active.
// This movement is being carried out bei the bottom rode
case 31: // if ( mProc[15].Active ) { //"Upper rode Up 1st", Stop
// PORTC &= ~( 1 << (37 - BRode_work)); //Stop "Bottom rode Up"
//mProc[17].Active = false;
mProc[15].Active = false; //}
break;
case 32: PORTC |= ( 1 << (37 - URode_back)); //Start "Upper rode Up 2nd"
Serial.print("Start Upper rode Up 2nd at "); Serial.println( millis() - CycleStart);
mProc[16].Active = true;
//Serial.print("Upper rode Up 2nd, Start "); Serial.print( mProc[eventSequNum[i] / 2].Start); Serial.print(" "); Serial.print ( millis() - CycleStart);
//Serial.print(" "); Serial.print ( mProc[16].Active); Serial.print(" "); Serial.println ( PORTB, BIN);
break;
case 33: if ( mProc[16].Active ) { PORTC &= ~( 1 << (37 - URode_back)); //Stop "Upper rode Up 2nd"
Serial.print("Stop Upper rode Up 2nd at "); Serial.println( millis() - CycleStart);
//Serial.print("Upper rode Up 2nd, Stop1 "); Serial.print( mProc[(eventSequNum[i] - 1)/ 2].End); Serial.print(" "); Serial.println ( PORTB, BIN);
mProc[16].Active = false; }
//Serial.print("Upper rode Up 2nd, Stop "); Serial.print( mProc[(eventSequNum[i] - 1)/ 2].End); Serial.print(" "); Serial.print ( millis() - CycleStart);
//Serial.print(" "); Serial.print ( mProc[16].Active); Serial.print(" "); Serial.println ( PORTB, BIN);
break;
case 34: PORTC |= ( 1 << (37 - BRode_work)); //Start "Bottom rode Up"
Serial.print("Start Bottom rode Up at "); Serial.println( millis() - CycleStart);
mProc[17].Active = true;
// Serial.print("Bottom rode Up -> Start "); Serial.print( mProc[eventSequNum[i] / 2].Start); Serial.print(" "); Serial.println ( millis() - CycleStart);
break;
case 35: if ( mProc[17].Active ) { PORTC &= ~( 1 << (37 - BRode_work)); //Stop "Bottom rode Up"
Serial.print("Stop Bottom rode Up at "); Serial.println( millis() - CycleStart);
mProc[17].Active = false;
//mProc[15].Active = false;
}
// Serial.print("Bottom rode Up -> Stop "); Serial.print( mProc[eventSequNum[i] / 2].End); Serial.print(" "); Serial.println ( millis() - CycleStart);
break;
case 36: PORTC |= ( 1 << (37 - BRode_back)); //Start "Bottom rode Down"
mProc[18].Active = true;
Serial.print("Start Bottom rode Down at "); Serial.println( millis() - CycleStart);
// Serial.print(PORTC); Serial.print(" run "); Serial.println(BRode_back);
// Serial.print("Bottom rode Down -> Start "); Serial.print( mProc[eventSequNum[i] / 2].Start); Serial.print(" "); Serial.println ( millis() - CycleStart);
break;
case 37: if ( mProc[18].Active ) { PORTC &= ~( 1 << (37 - BRode_back)); //Stop "Bottom rode Down"
Serial.print("Stop Bottom rode Down at "); Serial.println( millis() - CycleStart);
mProc[18].Active = false; }
// Serial.print("Bottom rode Down -> Stop "); Serial.print( mProc[eventSequNum[i] / 2].End); Serial.print(" "); Serial.println ( millis() - CycleStart);
break;
case 38: PORTC |= ( 1 << (37 - SideFolders)); //Side Folders ON
mProc[19].Active = true;
// Serial.print("Bottom rode Down -> Start "); Serial.print( mProc[eventSequNum[i] / 2].Start); Serial.print(" "); Serial.println ( millis() - CycleStart);
break;
case 39: if ( mProc[19].Active ) { PORTC &= ~( 1 << (37 - SideFolders)); //Side Folders OFF
mProc[19].Active = false; }
// Serial.print("Bottom rode Down -> Stop "); Serial.print( mProc[eventSequNum[i] / 2].End); Serial.print(" "); Serial.println ( millis() - CycleStart);
break;
case 40: PORTC |= ( 1 << (37 - FrontFolder)); //Front Folder push (ON)
mProc[20].Active = true;
// Serial.print("Bottom rode Down -> Start "); Serial.print( mProc[eventSequNum[i] / 2].Start); Serial.print(" "); Serial.println ( millis() - CycleStart);
break;
case 41: if ( mProc[20].Active ) { PORTC &= ~( 1 << (37 - FrontFolder)); //Front Folder back (OFF)
mProc[20].Active = false; }
// Serial.print("Bottom rode Down -> Stop "); Serial.print( mProc[eventSequNum[i] / 2].End); Serial.print(" "); Serial.println ( millis() - CycleStart);
break;
case 42: PORTC |= ( 1 << (37 - PackPusher)); //Package Pusher (ON)
mProc[21].Active = true;
// Serial.print("Bottom rode Down -> Start "); Serial.print( mProc[eventSequNum[i] / 2].Start); Serial.print(" "); Serial.println ( millis() - CycleStart);
break;
case 43: if ( mProc[21].Active ) { PORTC &= ~( 1 << (37 - PackPusher)); //Package Pusher back (OFF)
mProc[21].Active = false; }
// Serial.print("Bottom rode Down -> Stop "); Serial.print( mProc[eventSequNum[i] / 2].End); Serial.print(" "); Serial.println ( millis() - CycleStart);
break;
}
}
void deBugPrintE() {
delay (100);
// Serial.print(millis() - CycleStart); Serial.print(" "); Serial.print(mProc[eventSequNum[i]/2].Start); Serial.print(" ");
// Serial.print(mProc[eventSequNum[i]/2].Name); Serial.print(" "); Serial.println("Start");
}
void deBugPrintO() {
// Serial.print(millis() - CycleStart); Serial.print(" "); Serial.print(mProc[(eventSequNum[i]-1)/2].End); Serial.print(" ");
// Serial.print(mProc[(eventSequNum[i]-1)/2].Name); Serial.print(" "); Serial.println("Stop");
}
void MProcTable() {
Serial.println();
Serial.println("Event\tProcNo. Name[]\t\t\tStLow\tStart\tDur\tEnd\tActive\tEvntNo.\tEventTimeP");
for (int i = 0; i < ProcNumber * 2; i++) { // To print out results of the sorting
Serial.print(i); Serial.print("\t"); Serial.print(mProc[(int)(i/2)].procNum); Serial.print("\t"); Serial.print(mProc[(int)(i/2)].Name); Serial.print("\t");
Serial.print(mProc[(int)(i/2)].startLow); Serial.print("\t"); Serial.print(mProc[(int)(i/2)].Start); Serial.print("\t");
Serial.print(mProc[(int)(i/2)].Duration); Serial.print("\t"); Serial.print(mProc[(int)(i/2)].End); Serial.print("\t");
Serial.print(mProc[(int)(i/2)].Active); Serial.print("\t"); Serial.print(eventSequNum[i]); Serial.print("\t"); Serial.println(eventTimePnt[i]);
}
}
void SequenceTable() {
Serial.println();
Serial.println("SeqNum\tEvntNo.\tEventTime");
for (int i = 0; i < ProcNumber * 2; i++) { // To print out results of the sorting
Serial.print(i); Serial.print("\t");
Serial.print(eventSequNum[i]); Serial.print("\t");
Serial.println(eventTimePnt[eventSequNum[i]]);
}
}
void StartingSequence() {
Serial.print("Starting Sequence"); Serial.println(" ***************************************** ");
delay(500);
PORTC &= ~( 1 << (37 - FoilCutter)); mProc[13].Active = false; // Case 27. Foil Cutter Off (release).
PORTA &= ~( 1 << (BeltShifter - 22)); mProc[0].Active = false; // Belt shifter. Come back to the starting position.
PORTA &= ~( 1 << (MainPusher - 22)); mProc[3].Active = false; // Main Pusher. Come back to the starting pos.
BRodePrep();
// CylinderStart ( BRode_back, sensorD, 18, 450 ); // Bottom rode down, case 36, 37
/*CycleStart = millis();
PORTC |= ( 1 << (37 - BRode_back)); //case 36: Start "Bottom rode Down"
mProc[18].Active = true;
while( PINL & ( 1 << (49 - sensorD) ) ){
Serial.println("Starting procedure. Waiting for the Sensor D (bottom rod down)");
if (CycleStart < ( millis() - 500 )) break; }
PORTC &= ~( 1 << (37 - BRode_back)); // case 37: Stop "Bottom rode Down"
mProc[18].Active = false; */
CylinderStart ( LblKnife_back, sensorF, 7, 450 ); // Lable Knife back movement. Case 14, 15
/* CycleStart = millis();
PORTA |= ( 1 << (LblKnife_back - 22)); // Case 14. Start Lable Knife back movement.
mProc[7].Active = true;
while( PINL & ( 1 << (49 - sensorF) ) ){
Serial.println("Starting procedure. Waiting for the Sensor F (lable knife to the right)");
if (CycleStart < ( millis() - 1000 )) break; }
PORTA &= ~( 1 << (LblKnife_back - 22)); // Case 15. Stop Lable Knife back (work) movement.
mProc[7].Active = false;*/
PORTA &= ~( 1 << (FoilGraber - 22)); mProc[12].Active = false; // Case 25. Foil Graber Off (release).
CylinderStart ( FPuller_back, sensorH, 11, 450 ); // *** Foil puller back. Case 22, 23
/* CycleStart = millis();
PORTA |= ( 1 << (FPuller_back - 22)); // Case 22. Start Foil puller back (pull) 2nd movement.
mProc[11].Active = true;
while( PINL & ( 1 << (49 - sensorH) ) ){
Serial.println("Starting procedure. Waiting for the Sensor H (foil puller back)");
if (CycleStart < ( millis() - 500 )) break; }
PORTA &= ~( 1 << (FPuller_back - 22)); // Case 23. Stop Foil puller back (pull) 2nd movement.
mProc[11].Active = false; */
CylinderStart ( URode_back, sensorC, 16, 450 ); // Upper rode Up. Case 32, 33
/* CycleStart = millis();
PORTC |= ( 1 << (37 - URode_back)); // case 32: Start "Upper rode Up 2nd"
mProc[16].Active = true;
while( (PINL & ( 1 << (49 - sensorC) )) ){
Serial.println("Starting procedure. Waiting for the Sensor H (foil puller back)");
if (CycleStart < ( millis() - 500 )) break; }
PORTC &= ~( 1 << (37 - URode_back)); //case 33: Stop "Upper rode Up 2nd"
mProc[16].Active = false; */
delay(10000);
CylinderStart ( URode_work, sensorA, 14, 450 ); // Upper rode down, Case 28. 29
/* CycleStart = millis();
PORTC |= ( 1 << (37 - URode_work)); //case 28: Start "Upper rode down"
mProc[14].Active = true;
while( PINL & ( 1 << (49 - sensorA) ) ){
Serial.println("Starting procedure. Waiting for the Sensor A (lower position of the upper road)");
delay(10);
if (CycleStart < ( millis() - 500 )) break; }
PORTC &= ~( 1 << (37 - URode_work)); //case 29: Stop "Upper rode down"
mProc[14].Active = false; */
}
void CylinderStart(uint8_t GPIO_pin, uint8_t sensor, uint8_t proc, uint16_t duration) {
Serial.print("** Cylinder Start "); Serial.print(GPIO_pin); Serial.print(" Sensor: "); Serial.print(sensor); Serial.print(" Procedure: ");
Serial.print(proc); Serial.print(" Dur: ");Serial.print(duration); Serial.println(" ** ");
CycleStart = millis();
if( GPIO_pin > 29) { PORTC |= ( 1 << (37 - GPIO_pin)); } // Start of the movement back
else { PORTA |= ( 1 << (GPIO_pin - 22)); }
mProc[proc].Active = true;
while( (PINL & ( 1 << (49 - sensor))) ) { // waiting till the appropriate sensor give a signal
Serial.print("Starting procedure. Waiting for the Sensor "); Serial.println(sensor);
delay(5);
if (CycleStart < ( millis() - duration )) { // or exit the cycle after 450 mS
Serial.println ("Timeout!");
break; }
}
if( GPIO_pin > 29) { PORTC &= ~( 1 << (37 - GPIO_pin));} // Movement stop
else { PORTA &= ~( 1 << (GPIO_pin - 22)); }
mProc[proc].Active = false;
}
void BRodePrep() {
for(uint8_t i = 0; i < 3; i++) {
CylinderStart ( BRode_work, sensorC, 17, 80 ); // Bottom rode Up, case 34, 35
delay(10);
CylinderStart ( BRode_back, sensorD, 18, 450 ); // Bottom rode down, case 36, 37
// delay(15);
// CylinderStart ( BRode_work, sensorB, 17, 20 ); // Bottom rode Up, case 34, 35
}
}
| [
"noreply@github.com"
] | wlad1453.noreply@github.com |
94df69fbf2d869697c6169da2e00bd8dc1f7408c | 42e40486bf709a62e7ca53706d629788c4177fc7 | /src/core/core_module.cc | 020a214466237601719e35c8661d7ca9f0accfff | [
"Unlicense"
] | permissive | archilleu/muinx | 66af5155ab796594839add5e66ff86be48c89b11 | 5b9cae589a0b3b1ca126912ca7bbda6c9f8d8e35 | refs/heads/master | 2021-06-05T02:40:48.116742 | 2020-04-21T06:53:39 | 2020-04-21T06:53:39 | 145,510,759 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 914 | cc | //---------------------------------------------------------------------------
#include <cassert>
#include "core_module.h"
#include "defines.h"
//---------------------------------------------------------------------------
namespace core
{
//---------------------------------------------------------------------------
CoreModule::CoreModule()
{
this->type_ = CORE;
}
//---------------------------------------------------------------------------
CoreModule::~CoreModule()
{
}
//---------------------------------------------------------------------------
const CoreModule::CoreModuleCtx* CoreModule::ctx() const
{
void* ctx = this->ctx_.get();
assert(((void)"ctx is nullptr", ctx));
return static_cast<CoreModuleCtx*>(ctx);
}
//---------------------------------------------------------------------------
}//namespace core
//---------------------------------------------------------------------------
| [
"archilleu9527@gmail.com"
] | archilleu9527@gmail.com |
8ee8f61cc297ebc561acb21472dbedf10d0e3fff | 6f5d2ce3db4cce5b4ff12840c9cccc20be350063 | /code/LiliEngine/VKBuffer.cpp | 90177fb9062bc2d72f4214c7dca511d671ff14a7 | [
"MIT"
] | permissive | deltafran/Tiny3DRPG | 51cffbacf49126a04fee0e24f6af9cfbe71cbb37 | 59aab39bd844b3f242d14a739622d481e7e83283 | refs/heads/main | 2023-03-31T17:45:08.129827 | 2021-04-14T02:42:23 | 2021-04-14T02:42:23 | 324,893,810 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,976 | cpp | #include "stdafx.h"
#include "VKBuffer.h"
#include "VulkanDevice.h"
#include "VulkanMemory.h"
//-----------------------------------------------------------------------------
VKBuffer::~VKBuffer()
{
if (m_buffer != VK_NULL_HANDLE)
{
vkDestroyBuffer(m_device, m_buffer, nullptr);
m_buffer = VK_NULL_HANDLE;
}
if (m_memory != VK_NULL_HANDLE)
{
vkFreeMemory(m_device, m_memory, nullptr);
m_memory = VK_NULL_HANDLE;
}
}
//-----------------------------------------------------------------------------
VkResult VKBuffer::Map(VkDeviceSize size, VkDeviceSize offset) noexcept
{
if (m_mapped)
return VK_SUCCESS;
return vkMapMemory(m_device, m_memory, offset, size, 0, &m_mapped);
}
//-----------------------------------------------------------------------------
void VKBuffer::UnMap() noexcept
{
if (!m_mapped)
return;
vkUnmapMemory(m_device, m_memory);
m_mapped = nullptr;
}
//-----------------------------------------------------------------------------
VkResult VKBuffer::Bind(VkDeviceSize offset) noexcept
{
return vkBindBufferMemory(m_device, m_buffer, m_memory, offset);
}
//-----------------------------------------------------------------------------
void VKBuffer::SetupDescriptor(VkDeviceSize size, VkDeviceSize offset) noexcept
{
m_descriptor.offset = offset;
m_descriptor.buffer = m_buffer;
m_descriptor.range = size;
}
//-----------------------------------------------------------------------------
void VKBuffer::CopyFrom(void* data, VkDeviceSize size) noexcept
{
if (!m_mapped)
return;
memcpy(m_mapped, data, size);
}
//-----------------------------------------------------------------------------
VkResult VKBuffer::Flush(VkDeviceSize size, VkDeviceSize offset) noexcept
{
VkMappedMemoryRange mappedRange = {};
mappedRange.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
mappedRange.memory = m_memory;
mappedRange.offset = offset;
mappedRange.size = size;
return vkFlushMappedMemoryRanges(m_device, 1, &mappedRange);
}
//-----------------------------------------------------------------------------
VkResult VKBuffer::Invalidate(VkDeviceSize size, VkDeviceSize offset) noexcept
{
VkMappedMemoryRange mappedRange = {};
mappedRange.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
mappedRange.memory = m_memory;
mappedRange.offset = offset;
mappedRange.size = size;
return vkInvalidateMappedMemoryRanges(m_device, 1, &mappedRange);
}
//-----------------------------------------------------------------------------
bool VKBuffer::createBuffer(std::shared_ptr<VulkanDevice> vulkanDevice, VkBufferUsageFlags usageFlags, VkMemoryPropertyFlags memoryPropertyFlags, VkDeviceSize size, void* data) noexcept
{
m_device = vulkanDevice->GetInstanceHandle();
uint32_t memoryTypeIndex = 0;
VkMemoryRequirements memReqs = {};
VkMemoryAllocateInfo memAlloc;
ZeroVulkanStruct(memAlloc, VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO);
VkBufferCreateInfo bufferCreateInfo;
ZeroVulkanStruct(bufferCreateInfo, VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO);
bufferCreateInfo.usage = usageFlags;
bufferCreateInfo.size = size;
vkCreateBuffer(m_device, &bufferCreateInfo, nullptr, &(m_buffer));
vkGetBufferMemoryRequirements(m_device, m_buffer, &memReqs);
vulkanDevice->GetMemoryManager().GetMemoryTypeFromProperties(memReqs.memoryTypeBits, memoryPropertyFlags, &memoryTypeIndex);
memAlloc.allocationSize = memReqs.size;
memAlloc.memoryTypeIndex = memoryTypeIndex;
vkAllocateMemory(m_device, &memAlloc, nullptr, &m_memory);
m_size = memAlloc.allocationSize;
m_alignment = memReqs.alignment;
m_usageFlags = usageFlags;
m_memoryPropertyFlags = memoryPropertyFlags;
if (data != nullptr)
{
Map();
memcpy(m_mapped, data, size);
if ((memoryPropertyFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) == 0)
Flush();
UnMap();
}
SetupDescriptor();
Bind();
// TODO: проверки на ошибки
return true;
}
//----------------------------------------------------------------------------- | [
"deltafran@mail.ru"
] | deltafran@mail.ru |
5586897f1238684221267fb5b174f5ec9489a83a | 18761b78d3b3dee8d43b978a0e0fa79102622780 | /18127259_w06/18127259_Week06_03/18127259_Ex03/cLibrary.cpp | 70dc43e0d83a07a566229de1dec18255596057b1 | [] | no_license | kieuconghau/oop-lab | ed2cedfb4d253b71c67682a2079d033cee7bf0f6 | b3f2dd6fbf6796878e9a1fc2c6f1442bebe0985d | refs/heads/master | 2022-01-16T18:43:40.829618 | 2019-08-01T13:04:41 | 2019-08-01T13:04:41 | 188,341,760 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,946 | cpp | #include "cLibrary.h"
cLibrary::cLibrary() {}
cLibrary::~cLibrary()
{
int n = this->Readers.size();
for (int i = 0; i < n; i++)
delete this->Readers[i];
}
void cLibrary::input()
{
string opt;
while (true)
{
cout << "Choose: 1. Normal Reader, 2. VIP Reader, 0. <Exit> ";
getline(cin, opt);
if (opt != "1" && opt != "2")
break;
cReader* reader;
if (opt == "1")
{
reader = new cNormalReader;
}
else if (opt == "2")
{
reader = new cVipReader;
}
else
throw;
reader->input_info();
this->Readers.push_back(reader);
}
}
void cLibrary::show()
{
int n = this->Readers.size();
for (int i = 0; i < n; i++)
{
cout << "#" << i + 1 << endl;
this->Readers[i]->show_info();
cout << endl;
}
}
float cLibrary::calc_sum_fees()
{
int n = this->Readers.size();
float sum = 0;
for (int i = 0; i < n; i++)
{
sum += this->Readers[i]->calc_fees();
}
return sum;
}
vector<cReader*> cLibrary::find_readers_having_the_highest_fees()
{
int n = this->Readers.size();
float max = this->Readers[0]->calc_fees();
float cur;
for (int i = 1; i < n; i++)
{
cur = this->Readers[i]->calc_fees();
if (cur > max)
max = cur;
}
vector<cReader*> res;
for (int i = 0; i < n; i++)
{
if (fabs(this->Readers[i]->calc_fees() - max) <= 0.00001)
res.push_back(this->Readers[i]);
}
return res;
}
int cLibrary::count_normal_readers()
{
int n = this->Readers.size();
int count = 0;
for (int i = 0; i < n; i++)
{
if (this->Readers[i]->has_type(cReader::ecType::NORMAL))
++count;
}
return count;
}
int cLibrary::count_vip_readers()
{
int n = this->Readers.size();
int count = 0;
for (int i = 0; i < n; i++)
{
if (this->Readers[i]->has_type(cReader::ecType::VIP))
++count;
}
return count;
}
float cLibrary::calc_average_salary()
{
return this->calc_sum_fees() / this->Readers.size();
}
vector<cReader*> cLibrary::find_readers_having_fees_more_than(float fees)
{
int n = this->Readers.size();
vector<cReader*> res;
for (int i = 0; i < n; i++)
{
if (this->Readers[i]->calc_fees() > fees)
res.push_back(this->Readers[i]);
}
return res;
}
cReader* cLibrary::find_a_reader_with_id()
{
string id;
cout << "Input ID:";
getline(cin, id);
int n = this->Readers.size();
for (int i = 0; i < n; i++)
{
if (this->Readers[i]->has_id(id))
return this->Readers[i];
}
return nullptr;
}
vector<cReader*> cLibrary::find_readers_with_full_name()
{
string fullName;
cout << "Input full name: ";
getline(cin, fullName);
int n = this->Readers.size();
vector<cReader*> res;
for (int i = 0; i < n; i++)
{
if (this->Readers[i]->has_full_name(fullName))
res.push_back(this->Readers[i]);
}
return res;
}
int cLibrary::count_readers_having_expiration_date_in_year(int year)
{
int n = this->Readers.size();
int count = 0;
for (int i = 0; i < n; i++)
{
if (this->Readers[i]->has_expiration_date_in_year(year))
++count;
}
return count;
}
| [
"kieuconghau.it@gmail.com"
] | kieuconghau.it@gmail.com |
7c5032e0373df446867d9703882e0272693dcf23 | 6ca9a23524c2ef60530b5b398e1b6ce63b78808f | /MySDL/azChoicePage.cpp | cce0b70c6d5064d4560fc55d8cbedba499772e64 | [] | no_license | a876565/MySDL-azPlayer | a772789ed05882f07c68f142d10bd4c4091680e9 | a25ac64e5a7261d4a218a002f6e50e3c70849c8a | refs/heads/master | 2021-01-19T10:48:05.872011 | 2017-04-12T06:50:50 | 2017-04-12T06:50:50 | 87,899,630 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,240 | cpp | #include "azChoicePage.h"
void azChoicePage::on_list_click(azvList &list, int id)
{
if (onChoose)
onChoose(id);
shown = 0;
}
azChoicePage::azChoicePage(azView * p):azPage(p)
{
shown = 0;
list = new azvListbox(this);
}
void azChoicePage::show()
{
shown = 1;
area = parent->area;
area.x = area.y = 0;
list->OnItemClick=[this](azvList&,int id)
{
if (this->onChoose)
this->onChoose(id);
};
}
void azChoicePage::end()
{
shown = 0;
list->OnItemClick = nullptr;
area.w = area.h = 0;
}
void azChoicePage::draw()
{
if (shown)
azPage::draw();
}
int azChoicePage::onMoveIn(int x, int y)
{
azPage::onMoveIn(x, y);
return 1;
}
int azChoicePage::onMoveOut(int x, int y)
{
azPage::onMoveOut(x, y);
return 1;
}
int azChoicePage::onMoving(int x, int y, int dx, int dy)
{
azPage::onMoving(x, y, dx, dy);
return 1;
}
int azChoicePage::onPress(int x, int y, Uint32 flag)
{
azPage::onPress(x, y, flag);
return 1;
}
int azChoicePage::onRelease(int x, int y, Uint32 flag)
{
azPage::onRelease(x, y, flag);
end();
return 1;
}
int azChoicePage::onWheel(int dx, int dy)
{
azPage::onWheel(dx, dy);
return 1;
}
azChoicePage::~azChoicePage()
{
if (shown&&onChoose)
{
shown = 0;
list->OnItemClick = nullptr;
}
}
| [
"swa67193@gmail.com"
] | swa67193@gmail.com |
39b89efd62fde207f0f5a8f209653a3536770cc6 | cac416b3169d097ba46b14a391a5000b6676cc0f | /src/core/utils/helpers/tensor_transform.cpp | a4bce5da5a7ee04b15b22bcfddcff666e3de3b44 | [
"MIT"
] | permissive | prasan001/ComputeLibrary | b6d5078da03e452ed5523fc7a258686ec372392b | 4afff8347a9931f201c142e5f9195ae2bb5e2e89 | refs/heads/master | 2023-04-15T16:14:28.022152 | 2023-04-10T05:09:28 | 2023-04-10T05:09:28 | 163,144,659 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,510 | cpp | /*
* Copyright (c) 2018 ARM Limited.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "arm_compute/core/utils/helpers/tensor_transform.h"
namespace arm_compute
{
namespace helpers
{
namespace tensor_transform
{
Coordinates slice_absolute_end_coords(TensorShape input_shape, Coordinates ends)
{
// Create end mask
int32_t end_mask = 0;
for(unsigned int i = 0; i < ends.num_dimensions(); ++i)
{
if(ends[i] < 0)
{
end_mask |= 1 << i;
}
}
// Get unit strides
const BiStrides unit_strides = strided_slice_strides(input_shape, BiStrides());
return strided_slice_absolute_end_coords(input_shape, Coordinates(), ends, unit_strides, end_mask);
}
TensorShape compute_slice_output_shape(TensorShape input_shape, Coordinates starts, Coordinates ends_abs)
{
// Get unit strides
const BiStrides unit_strides = strided_slice_strides(input_shape, BiStrides());
return compute_strided_slice_output_shape(input_shape, starts, ends_abs, unit_strides);
}
Coordinates strided_slice_absolute_start_coords(TensorShape input_shape, Coordinates starts, Coordinates strides, int32_t begin_mask)
{
Coordinates starts_abs;
for(unsigned int i = 0; i < starts.num_dimensions(); ++i)
{
// Get start index
int start_i = starts[i];
// Reset in case of begin mask present
if((begin_mask & 1 << i) != 0)
{
start_i = strides[i] > 0 ? std::numeric_limits<int>::lowest() : std::numeric_limits<int>::max();
}
// Account negative start points
const int dim_size = input_shape[i];
if(start_i < 0)
{
start_i += dim_size;
}
// Final clamp
start_i = utility::clamp(start_i, 0, dim_size - 1);
starts_abs.set(i, start_i);
}
// Fill remaining
for(unsigned int i = starts_abs.num_dimensions(); i < input_shape.num_dimensions(); ++i)
{
starts_abs.set(i, 0);
}
return starts_abs;
}
Coordinates strided_slice_absolute_end_coords(TensorShape input_shape, Coordinates starts_abs, Coordinates ends, Coordinates strides,
int32_t end_mask, int32_t shrink_axis_mask)
{
Coordinates ends_abs;
for(unsigned int i = 0; i < ends.num_dimensions(); ++i)
{
// Get end index
int stop_i = ends[i];
// Shrink dimension
if((shrink_axis_mask & (1 << i)) != 0)
{
stop_i = starts_abs[i] + 1;
}
// Reset in case of begin mask present
if((end_mask & 1 << i) != 0)
{
stop_i = (strides[i] > 0) ? std::numeric_limits<int>::max() : std::numeric_limits<int>::lowest();
}
// Account negative end points
const int dim_size = input_shape[i];
if(stop_i < 0)
{
stop_i += dim_size;
}
// Final clamp
stop_i = (strides[i] > 0) ? utility::clamp(stop_i, 0, dim_size) : utility::clamp(stop_i, -1, dim_size - 1);
ends_abs.set(i, stop_i);
}
// Fill remaining ends
for(unsigned int i = ends_abs.num_dimensions(); i < input_shape.num_dimensions(); ++i)
{
ends_abs.set(i, input_shape[i]);
}
return ends_abs;
}
Coordinates strided_slice_strides(TensorShape input_shape, Coordinates strides)
{
for(unsigned int i = strides.num_dimensions(); i < input_shape.num_dimensions(); ++i)
{
strides.set(i, 1);
}
return strides;
}
TensorShape compute_strided_slice_output_shape(TensorShape input_shape, Coordinates starts_abs, Coordinates ends_abs, Coordinates final_strides)
{
TensorShape output_shape = input_shape;
for(unsigned int i = 0; i < input_shape.num_dimensions(); ++i)
{
const int stride_i = final_strides[i];
const int range = ends_abs[i] - starts_abs[i];
if((range == 0) || // Zero range
(range < 0 && stride_i >= 0) || // Negative range with positive stride
(range > 0 && stride_i <= 0)) // Positive range with negative stride
{
output_shape.set(i, 0);
return output_shape;
}
else
{
int dim = range / stride_i + (range % stride_i != 0 ? 1 : 0);
output_shape.set(i, dim);
}
}
return output_shape;
}
} // namespace tensor_transform
} // namespace helpers
} // namespace arm_compute
| [
"bsgcomp@arm.com"
] | bsgcomp@arm.com |
f0c1ee56fe6013ff5a8fe6551303bff50ff249fe | 916527f1a976fc2140028c4d76caf0e47c4f4a77 | /OneElectron_class.cpp | ea3246b41ca31cfc3cfcc8e840f8b34e69959ddc | [] | no_license | clvirik/Project2 | 05c77cb7fa82cdba5b3389bfef3accaa8bbf3e18 | c9984331aa0238c1fb29ef33292077844bc38efb | refs/heads/master | 2022-12-18T18:11:34.127149 | 2020-09-30T18:04:08 | 2020-09-30T18:04:08 | 298,308,560 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 862 | cpp | #include "project2.hpp"
#include <iostream>
#include <armadillo>
#include <iomanip>
using namespace std;
using namespace arma;
void OneElectron::Initialize(int N, double rho_max, bool test)
{
Solver_class::Initialize(N, test);
m_rho_max = rho_max;
m_h = m_rho_max/(m_N-1.0);
m_Diag = 2.0/(m_h*m_h);
m_nDiag = -1.0/(m_h*m_h);
m_A = Dmatrix(m_Nmat, m_Nmat);
m_R = Dmatrix(m_Nmat, m_Nmat);
for (int i = 0; i < m_Nmat; i++) {
for (int j = 0; j < m_Nmat; j++) {
if (i == j) {
m_A[i][j] = m_Diag + (i+1.0)*(i+1.0)*m_h*m_h;
m_R[i][j] = 1.0;
}
else {
m_R[i][j] = 0.0;
if (i+1==j or i-1==j)
m_A[i][j] = m_nDiag;
else
m_A[i][j] = 0;
}
}
}
if (m_test)
EigenCompare();
}
void OneElectron::Jacobi(double tolerance, int maxiter)
{
Solver_class::Jacobi(tolerance, maxiter);
if (m_test)
Jacobi_TEST();
}
| [
"christlv@student.matnat.uio.no"
] | christlv@student.matnat.uio.no |
1bc39229bcb5c71d0624d5c3134560cc865ac591 | 9fdba15a3b58c286b9980552e3e9018f868eb1fa | /t_chash.cpp | 04665bb440576f30fd367acefe75f05e9fbfd1c4 | [] | no_license | nordlow/justcxx | 370a1a400796f0febb99788eeea4c4feea2b33ab | 1876bb4ffa108f03bddda9d65948226f12a59388 | refs/heads/master | 2021-06-09T04:33:42.152922 | 2020-10-22T19:37:23 | 2020-10-22T19:37:23 | 20,072,735 | 1 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 4,397 | cpp | #include <chrono>
#include <array>
#include "chash.hpp"
#include "enforce.hpp"
#include "timed.hpp"
#include "show_all.hpp"
typedef std::chrono::high_resolution_clock hrc;
/*! Show Benchmark Result. */
template<class Time, class T, size_t N>
void view(std::ostream& os,
const char* name,
const std::array<T,N>& dig,
Time duration)
{
auto count = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
os << name << " took " << count << " milliseconds" << std::endl;
}
void test_chash(bool show = false, size_t data_length = 4*1024*1024)
{
typedef uint8_t T;
using std::cout;
using std::endl;
using std::array;
using namespace chash;
T mdat[data_length]; const size_t mlen = sizeof(mdat); // 4 Megabytes of data
auto fct = 111; // fill constant
pnw::timed tm; tm.m_n_tries = 5;
// \todo: Call tests in async
// SHA-1
{
array<T,SHA1_DIGEST_SIZE> dA; dA.fill(fct);
view(cout, "SHA1-160 Nettle ", dA, tm.call([&mdat, mlen, &dA]() { nettle::SHA1_160 ch(mdat, mlen); ch.final(dA.data()); }));
array<T,SHA1_DIGEST_SIZE> dB; dB.fill(fct);
view(cout, "SHA1-160 OpenSSL (EVP)", dB, tm.call([&mdat, mlen, &dB]() { openssl::CHash ch(mdat, mlen); ch.final(dB.data()); }));
array<T,SHA1_DIGEST_SIZE> dC; dC.fill(fct);
view(cout, "SHA1-160 OpenSSL", dC, tm.call([&mdat, mlen, &dC]() { openssl::SHA1_160 ch_ssl(mdat, mlen); ch_ssl.final(dC.data()); }));
enforce_eq3(dA, dB, dC);
}
cout << endl;
// SHA-224
{
array<T,SHA224_DIGEST_SIZE> dA; dA.fill(fct);
if (show) { view(cout, "SHA2-224 Nettle ", dA, tm.call([&mdat, mlen, &dA]() { nettle::SHA2_224 ch(mdat, mlen); ch.final(dA.data());})); }
array<T,SHA224_DIGEST_SIZE> dB; dB.fill(fct);
if (show) { view(cout, "SHA2-224 OpenSSL ", dB, tm.call([&mdat, mlen, &dB]() { openssl::SHA2_224 ch(mdat, mlen); ch.final(dB.data()); })); }
array<T,SHA224_DIGEST_SIZE> dC; dC.fill(fct);
if (show) { view(cout, "SHA3-224 Nettle ", dC, tm.call([&mdat, mlen, &dC]() { nettle::SHA3_224 ch(mdat, mlen); ch.final(dC.data()); })); }
enforce_eq(dA, dB);
}
cout << endl;
// SHA-256
{
array<T,SHA256_DIGEST_SIZE> dA; dA.fill(fct);
if (show) { view(cout, "SHA2-256 Nettle ", dA, tm.call([&mdat, mlen, &dA]() { nettle::SHA2_256 ch(mdat, mlen); ch.final(dA.data());})); }
array<T,SHA256_DIGEST_SIZE> dB; dB.fill(fct);
if (show) { view(cout, "SHA2-256 OpenSSL ", dB, tm.call([&mdat, mlen, &dB]() { openssl::SHA2_256 ch(mdat, mlen); ch.final(dB.data());})); }
array<T,SHA256_DIGEST_SIZE> dC; dC.fill(fct);
if (show) { view(cout, "SHA3-256 OpenSSL ", dC, tm.call([&mdat, mlen, &dC]() { nettle::SHA3_256 ch(mdat, mlen); ch.final(dC.data());})); }
enforce_eq(dA, dB);
}
cout << endl;
// SHA-384
{
array<T,SHA384_DIGEST_SIZE> dA; dA.fill(fct);
if (show) { view(cout, "SHA2-384 Nettle ", dA, tm.call([&mdat, mlen, &dA]() { nettle::SHA2_384 ch(mdat, mlen); ch.final(dA.data());})); }
array<T,SHA384_DIGEST_SIZE> dB; dB.fill(fct);
if (show) { view(cout, "SHA2-384 OpenSSL ", dB, tm.call([&mdat, mlen, &dB]() { openssl::SHA2_384 ch(mdat, mlen); ch.final(dB.data());})); }
array<T,SHA384_DIGEST_SIZE> dC; dC.fill(fct);
if (show) { view(cout, "SHA3-384 OpenSSL ", dC, tm.call([&mdat, mlen, &dC]() { nettle::SHA3_384 ch(mdat, mlen); ch.final(dC.data());})); }
enforce_eq(dA, dB);
}
cout << endl;
// SHA-512
{
array<T,SHA512_DIGEST_SIZE> dA; dA.fill(fct);
if (show) { view(cout, "SHA2-512 Nettle ", dA, tm.call([&mdat, mlen, &dA]() { nettle::SHA2_512 ch(mdat, mlen); ch.final(dA.data());})); }
array<T,SHA512_DIGEST_SIZE> dB; dB.fill(fct);
if (show) { view(cout, "SHA2-512 OpenSSL ", dB, tm.call([&mdat, mlen, &dB]() { openssl::SHA2_512 ch(mdat, mlen); ch.final(dB.data());})); }
array<T,SHA512_DIGEST_SIZE> dC; dC.fill(fct);
if (show) { view(cout, "SHA3-512 OpenSSL ", dC, tm.call([&mdat, mlen, &dC]() { nettle::SHA3_512 ch(mdat, mlen); ch.final(dC.data());})); }
enforce_eq(dA, dB);
}
cout << endl;
}
int main(int argc, char* argv[])
{
test_chash(true);
return 0;
}
| [
"per.nordlow@gmail.com"
] | per.nordlow@gmail.com |
6f42d77180ea0f27fcd3bc7b153afe9de98cdb56 | 2ea91f4b2d4a44f36f9b8cea1b0d1a3c8da0b27f | /engine/src/Loaders/AssimpModelInfo.cpp | 99ab1ad043d03942f349d6973e5c05c26cf78ec2 | [] | no_license | knut0815/MoonEngine | 4ed46ab414efef7ac4b499d6da2b0a3b86b7401a | 243cce7988ee089d0fc51d817e2736501e019702 | refs/heads/master | 2021-06-12T19:51:46.802997 | 2017-03-24T23:58:20 | 2017-03-24T23:58:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,572 | cpp | #include "AssimpModelInfo.h"
using namespace MoonEngine;
bool AssimpModelInfo::hasNormals() const
{
return _hasNormals;
}
bool AssimpModelInfo::hasTangentBitangent() const
{
return _hasTangentBitangent;
}
bool AssimpModelInfo::hasTextureCoordinates() const
{
return _hasTextureCoordinates;
}
bool AssimpModelInfo::hasBones() const
{
return _hasBones;
}
const std::vector<AssimpMeshInfo> & AssimpModelInfo::getMeshInfo() const
{
return _meshInfo;
}
int AssimpModelInfo::stride() const
{
return 3 +
(int)hasNormals()* 3 +
(int)hasTextureCoordinates() * 2 +
(int)hasTangentBitangent() * 6 +
(int)hasBones() * 8;
}
int AssimpModelInfo::addBone(const AssimpBoneInfo & boneInfo)
{
_hasBones = true;
_boneInfo.push_back(boneInfo);
_boneToIndexMap[boneInfo.boneName] = _boneInfo.size() - 1;
return _boneInfo.size() - 1;
}
std::vector<std::string> AssimpModelInfo::getAllTextures() const
{
std::vector<std::string> retVals;
for(const auto & mesh : _meshInfo)
{
for(const auto texStrPair : mesh.textures)
{
retVals.push_back(texStrPair.second);
}
}
return retVals;
}
void AssimpModelInfo::addMeshInfo(AssimpMeshInfo & ami)
{
ami.meshInfo.setVertexArrayObject(vertexObjectPtr);
_meshInfo.push_back(ami);
boundingBox = boundingBox.merge(ami.box);
}
int AssimpModelInfo::getBoneId(const std::string & string)
{
const auto & itr = _boneToIndexMap.find(string);
if(itr != _boneToIndexMap.end())
{
return itr->second;
}
else
{
LOG(ERROR, "Could not find bone of name " + string);
assert(false);
return -1;
}
}
| [
"kpiddy@gmail.com"
] | kpiddy@gmail.com |
8c7f218b64b3753d0c6191eb239c174dd98d3b64 | f7b21ddf913902d4961d5b6411aa1958a4633cc9 | /chapter-06/bitwise-operator-q2-3.cpp | a9f76b4326668cd3c96664d3502686584c3dc105 | [] | no_license | live-abhishek/cpp-practice | 98df2278d3e1504755f880f790662b717a79012c | 615b45721bace72520692dcfdcde430fdda62ee4 | refs/heads/master | 2020-04-13T22:37:23.316260 | 2020-01-14T02:30:40 | 2020-01-14T02:30:40 | 163,483,850 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 638 | cpp | #include <iostream>
#include <bitset>
std::bitset<4> rotlUsingFunctions(std::bitset<4> bits) {
bool leftBit = bits.test(3);
bits = bits << 1;
if (leftBit) {
bits.set(0);
}
return bits;
}
std::bitset<4> rotlCustom(std::bitset<4> bits) {
return (bits << 1) | (bits >> 3);
}
std::bitset<4> rotl(std::bitset<4> bits) {
// return rotlUsingFunctions(bits);
return rotlCustom(bits);
}
int main() {
std::bitset<4> bits1{0b0001};
std::cout << rotl(bits1) << "\n"; // should print 0010
std::bitset<4> bits2{0b1001};
std::cout << rotl(bits2) << "\n"; // should print 0011
return 0;
} | [
"abhisheksimla@google.com"
] | abhisheksimla@google.com |
5428bc385c6ff0d21cff277877536aaebf0723f7 | 6ac5389ca32c5a27c91228b80d53abe30b7b5ad7 | /MyElectron.h | e3f1891a7b60ca1cd2af556a377399d7d073c552 | [] | no_license | Simon-macht-Software/topquark | 8479cbeba86a9b9e4373dfde8a4bf14dc51c5438 | fe417c655af99ae2a08baee545852a6f614ee7f3 | refs/heads/master | 2022-07-08T22:20:47.257324 | 2020-05-13T17:53:43 | 2020-05-13T17:53:43 | 263,416,490 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 836 | h | /*
* MyElectron.h
*
* Created on: Feb 1, 2012
* Author: csander
*/
#ifndef MYELECTRON_H_
#define MYELECTRON_H_
#include <TLorentzVector.h>
class MyElectron: public TLorentzVector {
public:
MyElectron();
MyElectron(double px, double py, double pz, double e) {
SetPxPyPzE(px, py, pz, e);
}
;
virtual ~MyElectron();
void SetIsolation(double x) {
isolation = x;
}
;
void SetCharge(int q) {
charge = q;
}
;
const double GetIsolation() {
return isolation;
}
;
const bool IsIsolated() {
return (isolation < 1.);
}
;
const int GetCharge() {
return charge;
}
;
private:
double isolation;
int charge;
};
#endif /* MYELECTRON_H_ */
| [
"noreply@github.com"
] | Simon-macht-Software.noreply@github.com |
537569c0719221686c504e1e63877a79294eb8cb | b45439c51203c4654e7d3fa4f6c1fc82a6a0bcf6 | /LineCamera/LoginData.cpp | 0aead5ffea657ec4463596fbfbe34da1e5d92ac5 | [] | no_license | gzj1997/LineCamera | 2d67450bd0751081ba88a14ae62abbea77be6ceb | 87f78d3ca0a3efddfb967ac383091471bafbd96b | refs/heads/master | 2020-04-01T16:35:10.269069 | 2019-01-14T01:48:52 | 2019-01-14T01:48:52 | 153,388,088 | 2 | 2 | null | null | null | null | GB18030 | C++ | false | false | 1,201 | cpp | #include "LoginData.h"
LoginData::LoginData(QWidget *parent)
: QDialog(parent)
{
ui.setupUi(this);
addproductname();
}
LoginData::~LoginData()
{
}
void LoginData::addproductname()
{
vector<QString> folder;
PathHelper::GetAllFileFolder(folder);
for each (QString var in folder)
{
ui.comboBox->addItem(var);
}
//qDebug() << QString::fromStdString(Dpath);
}
void LoginData::newproduct()
{
QString title = u8"新产品名称";
QString Tlabel = u8"请输入新产品名称";
bool ok = false;
QString name = QInputDialog::getText(this, title, Tlabel, QLineEdit::Normal, u8"新产品名称", &ok);
if (ok && !name.isEmpty())
{
if (PathHelper::newproduct(name))
{
/* Sdatapath = (QDir::currentPath() + "/data").toStdString();
Sproduct = name.toStdString();*/
this->accept();
//emit sendsignal();
//this->hide();
}
else {
QMessageBox::warning(this, "warning", u8"产品名已存在");
}
}
}
void LoginData::getproductname()
{
PathHelper::initial();
PathHelper::setproductname( ui.comboBox->currentText());
this->accept();
//Sdatapath1 = (QDir::currentPath() + "/data").toStdString();
//Sproduct = productname;
//emit sendsignal();
//this->hide();
}
| [
"894702351@qq.com"
] | 894702351@qq.com |
a0b07f14e2ec1f3a902c5ca34fb2ba16e9b00e86 | 01f6fe3f7b5a00a2767c63c8712033921e11ffc0 | /adventureOpenWorld/snowcrash/src/ResourceParser.h | f6c52fb9c7a0b07be2f6934835d3bded1b1e4456 | [
"MIT"
] | permissive | limbo0312/egsFramework | 9dac681cc5b3a8190781a22de54c24b864763f58 | f859b938d105382d64054ffb7bebfd94163fc5d6 | refs/heads/master | 2022-01-24T16:20:46.446605 | 2022-01-20T13:53:53 | 2022-01-20T13:53:53 | 18,937,303 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 25,701 | h | //
// ResourceParser.h
// snowcrash
//
// Created by Zdenek Nemec on 5/4/13.
// Copyright (c) 2013 Apiary Inc. All rights reserved.
//
#ifndef SNOWCRASH_RESOURCEPARSER_H
#define SNOWCRASH_RESOURCEPARSER_H
#include <sstream>
#include "BlueprintParserCore.h"
#include "Blueprint.h"
#include "ActionParser.h"
#include "RegexMatch.h"
#include "StringUtility.h"
#include "ParametersParser.h"
#include "DescriptionSectionUtility.h"
namespace snowcrashconst {
/** Nameless resource matching regex */
const char* const ResourceHeaderRegex = "^[[:blank:]]*(" HTTP_REQUEST_METHOD "[[:blank:]]+)?" URI_TEMPLATE "$";
/** Named resource matching regex */
const char* const NamedResourceHeaderRegex = "^[[:blank:]]*" SYMBOL_IDENTIFIER "[[:blank:]]+\\[" URI_TEMPLATE "]$";
}
namespace snowcrash {
// Resource signature
enum ResourceSignature {
UndefinedResourceSignature,
NoResourceSignature,
URIResourceSignature,
MethodURIResourceSignature,
NamedResourceSignature
};
// Query resource signature
FORCEINLINE ResourceSignature GetResourceSignature(const MarkdownBlock& block,
Name& name,
URITemplate& uri,
HTTPMethod& method) {
if (block.type != HeaderBlockType ||
block.content.empty())
return NoResourceSignature;
CaptureGroups captureGroups;
// Nameless resource
if (RegexCapture(block.content, snowcrashconst::ResourceHeaderRegex, captureGroups, 4)) {
method = captureGroups[2];
uri = captureGroups[3];
return (method.empty()) ? URIResourceSignature : MethodURIResourceSignature;
}
else if (RegexCapture(block.content, snowcrashconst::NamedResourceHeaderRegex, captureGroups, 4)) {
method.clear();
name = captureGroups[1];
TrimString(name);
uri = captureGroups[2];
return NamedResourceSignature;
}
return NoResourceSignature;
}
// Returns true if block has resource header signature, false otherwise
FORCEINLINE bool HasResourceSignature(const MarkdownBlock& block) {
Name name;
URITemplate uri;
HTTPMethod method;
return GetResourceSignature(block, name, uri, method) != NoResourceSignature;
}
// Resource iterator in its containment group
typedef Collection<Resource>::const_iterator ResourceIterator;
// Finds a resource in resource group by its URI template
FORCEINLINE ResourceIterator FindResource(const ResourceGroup& group,
const Resource& resource) {
return std::find_if(group.resources.begin(),
group.resources.end(),
std::bind2nd(MatchResource(), resource));
}
// Resource iterator pair: its containment group and resource iterator itself
typedef std::pair<Collection<ResourceGroup>::const_iterator, ResourceIterator> ResourceIteratorPair;
// Finds a resource in blueprint by its URI template
FORCEINLINE ResourceIteratorPair FindResource(const Blueprint& blueprint,
const Resource& resource) {
for (Collection<ResourceGroup>::const_iterator it = blueprint.resourceGroups.begin();
it != blueprint.resourceGroups.end();
++it) {
Collection<Resource>::const_iterator match = FindResource(*it, resource);
if (match != it->resources.end())
return std::make_pair(it, match);
}
return std::make_pair(blueprint.resourceGroups.end(), Collection<Resource>::iterator());
}
//
// Classifier of internal list items, Resource context
//
template <>
FORCEINLINE SectionType ClassifyInternaListBlock<Resource>(const BlockIterator& begin,
const BlockIterator& end) {
if (HasHeaderSignature(begin, end))
return HeadersSectionType;
if (HasParametersSignature(begin, end))
return ParametersSectionType;
Name name;
SourceData mediaType;
PayloadSignature payloadSignature = GetPayloadSignature(begin, end, name, mediaType);
if (payloadSignature == ObjectPayloadSignature)
return ObjectSectionType;
else if (payloadSignature == ModelPayloadSignature)
return ModelSectionType;
return UndefinedSectionType;
}
/** Children blocks classifier */
template <>
FORCEINLINE SectionType ClassifyChildrenListBlock<Resource>(const BlockIterator& begin,
const BlockIterator& end) {
SectionType type = ClassifyInternaListBlock<Resource>(begin, end);
if (type != UndefinedSectionType)
return type;
type = ClassifyChildrenListBlock<HeaderCollection>(begin, end);
if (type != UndefinedSectionType)
return type;
type = ClassifyChildrenListBlock<ParameterCollection>(begin, end);
if (type != UndefinedSectionType)
return type;
type = ClassifyChildrenListBlock<Payload>(begin, end);
if (type != UndefinedSectionType)
return type;
return UndefinedSectionType;
}
//
// Block Classifier, Resource Context
//
template <>
FORCEINLINE SectionType ClassifyBlock<Resource>(const BlockIterator& begin,
const BlockIterator& end,
const SectionType& context) {
if (HasResourceGroupSignature(*begin))
return UndefinedSectionType;
Name name;
URITemplate uri;
HTTPMethod method;
ResourceSignature resourceSignature = GetResourceSignature(*begin, name, uri, method);
if (resourceSignature != NoResourceSignature) {
return (context == UndefinedSectionType) ?
((resourceSignature == MethodURIResourceSignature) ? ResourceMethodSectionType : ResourceSectionType) :
UndefinedSectionType;
}
if (HasActionSignature(*begin))
return (context != ResourceMethodSectionType) ? ActionSectionType : UndefinedSectionType;
SectionType listSection = ClassifyInternaListBlock<Resource>(begin, end);
if (listSection != UndefinedSectionType)
return listSection;
// Unrecognized list item at this level
if (begin->type == ListItemBlockBeginType)
return ForeignSectionType;
return (context == ResourceSectionType) ? context : UndefinedSectionType;
}
//
// Resource SectionType Parser
//
template<>
struct SectionParser<Resource> {
static ParseSectionResult ParseSection(const BlueprintSection& section,
const BlockIterator& cur,
BlueprintParserCore& parser,
Resource& resource) {
ParseSectionResult result = std::make_pair(Result(), cur);
switch (section.type) {
case ResourceSectionType:
result = HandleResourceDescriptionBlock(section, cur, parser, resource);
break;
case ResourceMethodSectionType:
result = HandleResourceMethod(section, cur, parser, resource);
break;
case ModelSectionType:
case ObjectSectionType:
result = HandleModel(section, cur, parser, resource);
break;
case ParametersSectionType:
result = HandleParameters(section, cur, parser, resource);
break;
case HeadersSectionType:
result = HandleDeprecatedHeaders(section, cur, parser, resource);
break;
case ActionSectionType:
result = HandleAction(section, cur, parser, resource);
break;
case UndefinedSectionType:
CheckAmbiguousMethod(section, cur, resource, parser.sourceData, result.first);
result.second = CloseList(cur, section.bounds.second);
break;
case ForeignSectionType:
result = HandleForeignSection<Resource>(section, cur, parser.sourceData);
break;
default:
result.first.error = UnexpectedBlockError(section, cur, parser.sourceData);
break;
}
return result;
}
static void Finalize(const SectionBounds& bounds,
BlueprintParserCore& parser,
Resource& resource,
Result& result)
{
// Consolidate depraceted headers into subsequent payloads
if (!resource.headers.empty()) {
for (Collection<Action>::iterator it = resource.actions.begin();
it != resource.actions.end();
++it) {
InjectDeprecatedHeaders(resource.headers, it->examples);
}
resource.headers.clear();
}
}
static ParseSectionResult HandleResourceDescriptionBlock(const BlueprintSection& section,
const BlockIterator& cur,
BlueprintParserCore& parser,
Resource& resource) {
ParseSectionResult result = std::make_pair(Result(), cur);
BlockIterator sectionCur(cur);
// Retrieve URI
if (cur->type == HeaderBlockType &&
cur == section.bounds.first) {
HTTPMethod method;
GetResourceSignature(*cur, resource.name, resource.uriTemplate, method);
result.second = ++sectionCur;
return result;
}
result = ParseDescriptionBlock<Resource>(section,
sectionCur,
parser.sourceData,
resource);
return result;
}
static ParseSectionResult HandleModel(const BlueprintSection& section,
const BlockIterator& cur,
BlueprintParserCore& parser,
Resource& resource)
{
Payload payload;
ParseSectionResult result = PayloadParser::Parse(cur,
section.bounds.second,
section,
parser,
payload);
if (result.first.error.code != Error::OK)
return result;
// Check whether there isnt a model already
if (!resource.model.name.empty()) {
// WARN: Model already defined
std::stringstream ss;
ss << "overshadowing previous model definiton for '";
if (!resource.name.empty())
ss << resource.name << "(" << resource.uriTemplate << ")";
else
ss << resource.uriTemplate;
ss << "' resource, a resource can be represented by a single model only";
BlockIterator nameBlock = ListItemNameBlock(cur, section.bounds.second);
SourceCharactersBlock sourceBlock = CharacterMapForBlock(nameBlock, cur, section.bounds, parser.sourceData);
result.first.warnings.push_back(Warning(ss.str(),
DuplicateWarning,
sourceBlock));
return result;
}
// Check symbol name
if (payload.name.empty()) {
if (!resource.name.empty()) {
payload.name = resource.name;
}
else {
// ERR: No name specified for resource model
std::stringstream ss;
ss << "resource model can be specified only for a named resource";
ss << ", name your resource, e.g. '# <resource name> [" << resource.uriTemplate << "]'";
BlockIterator nameBlock = ListItemNameBlock(cur, section.bounds.second);
SourceCharactersBlock sourceBlock = CharacterMapForBlock(nameBlock, cur, section.bounds, parser.sourceData);
result.first.error = Error(ss.str(),
SymbolError,
sourceBlock);
}
}
// Check whether symbol isn't already defined
ResourceModelSymbolTable::const_iterator it = parser.symbolTable.resourceModels.find(payload.name);
if (it == parser.symbolTable.resourceModels.end()) {
parser.symbolTable.resourceModels[payload.name] = payload;
}
else {
// ERR: Symbol already defined
std::stringstream ss;
ss << "symbol '" << payload.name << "' already defined";
BlockIterator nameBlock = ListItemNameBlock(cur, section.bounds.second);
SourceCharactersBlock sourceBlock = CharacterMapForBlock(nameBlock, cur, section.bounds, parser.sourceData);
result.first.error = Error(ss.str(),
SymbolError,
sourceBlock);
}
// Assign model
resource.model = payload;
return result;
}
/** Parse Parameters section */
static ParseSectionResult HandleParameters(const BlueprintSection& section,
const BlockIterator& cur,
BlueprintParserCore& parser,
Resource& resource) {
ParameterCollection parameters;
ParseSectionResult result = ParametersParser::Parse(cur,
section.bounds.second,
section,
parser,
parameters);
if (result.first.error.code != Error::OK)
return result;
if (parameters.empty()) {
BlockIterator nameBlock = ListItemNameBlock(cur, section.bounds.second);
SourceCharactersBlock sourceBlock = CharacterMapForBlock(nameBlock, cur, section.bounds, parser.sourceData);
result.first.warnings.push_back(Warning(snowcrashconst::NoParametersMessage,
FormattingWarning,
sourceBlock));
}
else {
// Check Eligibility
BlockIterator nameBlock = ListItemNameBlock(cur, section.bounds.second);
CheckParametersEligibility(resource, parameters, nameBlock->sourceMap, parser.sourceData, result.first);
// Insert
resource.parameters.insert(resource.parameters.end(), parameters.begin(), parameters.end());
}
return result;
}
/** Check parameter eligibility, reporting if a parameter is not specified in URI template */
static void CheckParametersEligibility(const Resource& resource,
const ParameterCollection& parameters,
const SourceDataBlock& location,
const SourceData& sourceData,
Result& result)
{
for (ParameterCollection::const_iterator it = parameters.begin();
it != parameters.end();
++it) {
// Naive check whether parameter is present in URI Template
if (resource.uriTemplate.find(it->name) == std::string::npos) {
// WARN: parameter name not present
std::stringstream ss;
ss << "parameter '" << it->name << "' not specified in ";
if (!resource.name.empty())
ss << "'" << resource.name << "' ";
ss << "its '" << resource.uriTemplate << "' URI template";
result.warnings.push_back(Warning(ss.str(),
LogicalErrorWarning,
MapSourceDataBlock(location, sourceData)));
}
}
}
static ParseSectionResult HandleResourceMethod(const BlueprintSection& section,
const BlockIterator& cur,
BlueprintParserCore& parser,
Resource& resource) {
// Retrieve URI template
HTTPMethod method;
GetResourceSignature(*cur, resource.name, resource.uriTemplate, method);
// Parse as a resource action abbreviation
return HandleAction(section, cur, parser, resource, true);
}
static ParseSectionResult HandleAction(const BlueprintSection& section,
const BlockIterator& cur,
BlueprintParserCore& parser,
Resource& resource,
bool abbrev = false)
{
Action action;
ParseSectionResult result = ActionParser::Parse(cur,
section.bounds.second,
section,
parser,
action);
if (result.first.error.code != Error::OK)
return result;
if (!abbrev) {
Name name;
HTTPMethod httpMethod;
ActionSignature actionSignature = GetActionSignature(*cur, name, httpMethod);
if (actionSignature == MethodURIActionSignature) {
// WARN: ignoring extraneous content in action header
std::stringstream ss;
ss << "ignoring additional content in method header '" << cur->content << "'";
ss << ", expected method-only e.g. '# " << action.method << "'";
SourceCharactersBlock sourceBlock = CharacterMapForBlock(cur, section.bounds.second, section.bounds, parser.sourceData);
result.first.warnings.push_back(Warning(ss.str(),
IgnoringWarning,
sourceBlock));
}
}
Collection<Action>::iterator duplicate = FindAction(resource, action);
if (duplicate != resource.actions.end()) {
// WARN: duplicate method
std::stringstream ss;
ss << "action with method '" << action.method << "' already defined for resource '";
ss << resource.uriTemplate << "'";
SourceCharactersBlock sourceBlock = CharacterMapForBlock(cur, section.bounds.second, section.bounds, parser.sourceData);
result.first.warnings.push_back(Warning(ss.str(),
DuplicateWarning,
sourceBlock));
}
// Check Eligibility
if (!action.parameters.empty())
CheckParametersEligibility(resource, action.parameters, cur->sourceMap, parser.sourceData, result.first);
// Check for header duplictes
DeepCheckHeaderDuplicates(resource, action, cur->sourceMap, parser.sourceData, result.first);
if (action.examples.empty() ||
action.examples.front().responses.empty()) {
// WARN: method has no response
std::stringstream ss;
ss << "no response defined for '" << action.method << " " << resource.uriTemplate << "'";
SourceCharactersBlock sourceBlock = CharacterMapForBlock(cur, section.bounds.second, section.bounds, parser.sourceData);
result.first.warnings.push_back(Warning(ss.str(),
EmptyDefinitionWarning,
sourceBlock));
}
resource.actions.push_back(action);
return result;
}
static void DeepCheckHeaderDuplicates(const Resource& resource,
const Action& action,
const SourceDataBlock& sourceMap,
const SourceData& sourceData,
Result& result) {
if (action.examples.empty())
return;
CheckHeaderDuplicates(resource, action, sourceMap, sourceData, result);
for (Collection<Request>::const_iterator it = action.examples.front().requests.begin();
it != action.examples.front().requests.end();
++it) {
CheckHeaderDuplicates(resource, *it, sourceMap, sourceData, result);
}
for (Collection<Response>::const_iterator it = action.examples.front().responses.begin();
it != action.examples.front().responses.end();
++it) {
CheckHeaderDuplicates(resource, *it, sourceMap, sourceData, result);
}
}
// Check whether abbreviated resource action isn't followed by an
// action header which would imply possible additional method intended.
static void CheckAmbiguousMethod(const BlueprintSection& section,
const BlockIterator& cur,
const Resource& resource,
const SourceData& sourceData,
Result& result) {
if (cur == section.bounds.second ||
cur->type != HeaderBlockType)
return;
Name name;
HTTPMethod method;
ActionSignature actionSignature = GetActionSignature(*cur, name, method);
if (actionSignature == MethodActionSignature ||
actionSignature == NamedActionSignature) {
// WARN: ignoring possible method header
std::stringstream ss;
ss << "unexpected action '" << cur->content << "', ";
ss << "to the define muliple actions for the '" << resource.uriTemplate << "' resource omit the HTTP method in its definition, ";
ss << "e.g. '# " << resource.uriTemplate << "'";
SourceCharactersBlock sourceBlock = CharacterMapForBlock(cur, section.bounds.second, section.bounds, sourceData);
result.warnings.push_back(Warning(ss.str(),
IgnoringWarning,
sourceBlock));
}
}
};
typedef BlockParser<Resource, SectionParser<Resource> > ResourceParser;
}
#endif
| [
"limbo0312@foxmail.com"
] | limbo0312@foxmail.com |
1f2d5d66b8024134b83304f8d48ca63714d2f667 | 7332ffbff3d0addab34256935e260a597aa70c95 | /kernel/graphics/virtiogpu/Console.h | b40ab981620c5e794f372f0a57b19a6a31c87bac | [
"BSD-2-Clause"
] | permissive | emacodes/pranaOS | 3a4d187998e892bc8b32998fb0da08b5406018b4 | 963f2b5940ea94b153cf36780097740654fe6acd | refs/heads/master | 2023-07-08T06:15:51.533719 | 2021-08-11T11:46:55 | 2021-08-11T11:46:55 | 394,933,991 | 0 | 0 | BSD-2-Clause | 2021-08-11T09:25:54 | 2021-08-11T09:25:53 | null | UTF-8 | C++ | false | false | 1,363 | h | /*
* Copyright (c) 2021, Krisna Pranav
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
// includes
#include <kernel/graphics/console/GenericFramebufferConsole.h>
#include <kernel/graphics/virtiogpu/GPU.h>
#include <kernel/TimerQueue.h>
namespace Kernel::Graphics::VirtIOGPU {
class DirtyRect {
public:
void union_rect(size_t x, size_t y, size_t width, size_t height);
bool is_dirty() const { return m_is_dirty; }
size_t x() const { return m_x0; }
size_t y() const { return m_y0; }
size_t width() const { return m_x1 - m_x0; }
size_t height() const { return m_y1 - m_y0; }
void clear() { m_is_dirty = false; }
private:
bool m_is_dirty { false };
size_t m_x0 { 0 };
size_t m_y0 { 0 };
size_t m_x1 { 0 };
size_t m_y1 { 0 };
};
class Console final : public GenericFramebufferConsole {
public:
static NonnullRefPtr<Console> initialize(RefPtr<FrameBufferDevice> const&);
virtual void set_resolution(size_t width, size_t height, size_t pitch) override;
virtual void flush(size_t x, size_t y, size_t width, size_t height) override;
virtual void enable() override;
private:
void enqueue_refresh_timer();
virtual u8* framebuffer_data() override;
Console(RefPtr<FrameBufferDevice> const&);
RefPtr<FrameBufferDevice> m_framebuffer_device;
DirtyRect m_dirty_rect;
};
}
| [
"krisna.pranav@gmail.com"
] | krisna.pranav@gmail.com |
6d57fae3d983f25fbddc2f5ac41c25db4a8c899a | 29609b94d70ca16b173ebbe4d86d7795786a1bff | /HW 4 - practicum/4/PendulumCard.cpp | e40c5118de1710e8033541cedf45f7e4985c9653 | [] | no_license | RadoslavSV/Object-Oriented_Programming | 84af4d65d9ab857312efc5bc7d55872ff2edb493 | e781422ec7243f38ca2f87c848c885c74bb6acba | refs/heads/main | 2023-06-07T06:35:04.059771 | 2021-07-01T07:49:09 | 2021-07-01T07:49:09 | 381,949,621 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,143 | cpp | /**
* Solution to homework assignment 4
* Object Oriented Programming Course
* Faculty of Mathematics and Informatics of Sofia University
* Summer semester 2020/2021
*
* @author Radoslav Velkov
* @idnumber 62528
* @task 4
* @compiler GCC
*/
#include <iostream>
#include <string>
using namespace std;
#include "PendulumCard.hpp"
int PendulumCard::getPendulumScale() const
{
return this->pendulumScale;
}
void PendulumCard::setPendulumScale(int pendulumScale)
{
this->pendulumScale = pendulumScale;
}
PendulumCard::PendulumCard(std::string name, std::string effect, unsigned int rarity, unsigned int attPts, unsigned int defPts,
int pendulumScale, CardType type)
{
setName(name);
setEffect(effect);
setRarity(rarity);
setAttPts(attPts);
setDefPts(defPts);
setPendulumScale(pendulumScale);
setType(type);
}
void PendulumCard::printCard()
{
std::cout<<"Name:"<<getName()<<" Effect:"<<getEffect()<<" Rarity:"<<getRarity()<<" ATT:"<<getAttPts()<<" DEF:"<<getDefPts()
<<" PendulumScale:"<<getPendulumScale()<<" Type:"<<static_cast<int>(getType())<<std::endl;
}
| [
"noreply@github.com"
] | RadoslavSV.noreply@github.com |
6ef785d0da5eaf53807051129c53eaecb80e8bb0 | 299648a8c633728662d0b7651cd98afdc28db902 | /src/thirdparty/cefbinary_72/libcef_dll/cpptoc/request_handler_cpptoc.cc | df15fa1fe3ad9acc91941f6104a504fd8f2a86e9 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown"
] | permissive | aardvarkxr/aardvark | 2978277b34c2c3894d6aafc4c590f3bda50f4d43 | 300d0d5e9b872ed839fae932c56eff566967d24b | refs/heads/master | 2023-01-12T18:42:10.705028 | 2021-08-18T04:09:02 | 2021-08-18T04:09:02 | 182,431,653 | 183 | 25 | BSD-3-Clause | 2023-01-07T12:42:14 | 2019-04-20T16:55:30 | TypeScript | UTF-8 | C++ | false | false | 22,753 | cc | // Copyright (c) 2019 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
//
// ---------------------------------------------------------------------------
//
// This file was generated by the CEF translator tool. If making changes by
// hand only do so within the body of existing method and function
// implementations. See the translator.README.txt file in the tools directory
// for more information.
//
// $hash=4476db944b857d3233fe82f63a7b0373bcc9196a$
//
#include "libcef_dll/cpptoc/request_handler_cpptoc.h"
#include "libcef_dll/cpptoc/resource_handler_cpptoc.h"
#include "libcef_dll/cpptoc/response_filter_cpptoc.h"
#include "libcef_dll/ctocpp/auth_callback_ctocpp.h"
#include "libcef_dll/ctocpp/browser_ctocpp.h"
#include "libcef_dll/ctocpp/frame_ctocpp.h"
#include "libcef_dll/ctocpp/request_callback_ctocpp.h"
#include "libcef_dll/ctocpp/request_ctocpp.h"
#include "libcef_dll/ctocpp/response_ctocpp.h"
#include "libcef_dll/ctocpp/select_client_certificate_callback_ctocpp.h"
#include "libcef_dll/ctocpp/sslinfo_ctocpp.h"
#include "libcef_dll/ctocpp/x509certificate_ctocpp.h"
namespace {
// MEMBER FUNCTIONS - Body may be edited by hand.
int CEF_CALLBACK
request_handler_on_before_browse(struct _cef_request_handler_t* self,
cef_browser_t* browser,
cef_frame_t* frame,
cef_request_t* request,
int user_gesture,
int is_redirect) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return 0;
// Verify param: browser; type: refptr_diff
DCHECK(browser);
if (!browser)
return 0;
// Verify param: frame; type: refptr_diff
DCHECK(frame);
if (!frame)
return 0;
// Verify param: request; type: refptr_diff
DCHECK(request);
if (!request)
return 0;
// Execute
bool _retval = CefRequestHandlerCppToC::Get(self)->OnBeforeBrowse(
CefBrowserCToCpp::Wrap(browser), CefFrameCToCpp::Wrap(frame),
CefRequestCToCpp::Wrap(request), user_gesture ? true : false,
is_redirect ? true : false);
// Return type: bool
return _retval;
}
int CEF_CALLBACK request_handler_on_open_urlfrom_tab(
struct _cef_request_handler_t* self,
cef_browser_t* browser,
cef_frame_t* frame,
const cef_string_t* target_url,
cef_window_open_disposition_t target_disposition,
int user_gesture) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return 0;
// Verify param: browser; type: refptr_diff
DCHECK(browser);
if (!browser)
return 0;
// Verify param: frame; type: refptr_diff
DCHECK(frame);
if (!frame)
return 0;
// Verify param: target_url; type: string_byref_const
DCHECK(target_url);
if (!target_url)
return 0;
// Execute
bool _retval = CefRequestHandlerCppToC::Get(self)->OnOpenURLFromTab(
CefBrowserCToCpp::Wrap(browser), CefFrameCToCpp::Wrap(frame),
CefString(target_url), target_disposition, user_gesture ? true : false);
// Return type: bool
return _retval;
}
cef_return_value_t CEF_CALLBACK
request_handler_on_before_resource_load(struct _cef_request_handler_t* self,
cef_browser_t* browser,
cef_frame_t* frame,
cef_request_t* request,
cef_request_callback_t* callback) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return RV_CONTINUE;
// Verify param: browser; type: refptr_diff
DCHECK(browser);
if (!browser)
return RV_CONTINUE;
// Verify param: frame; type: refptr_diff
DCHECK(frame);
if (!frame)
return RV_CONTINUE;
// Verify param: request; type: refptr_diff
DCHECK(request);
if (!request)
return RV_CONTINUE;
// Verify param: callback; type: refptr_diff
DCHECK(callback);
if (!callback)
return RV_CONTINUE;
// Execute
cef_return_value_t _retval =
CefRequestHandlerCppToC::Get(self)->OnBeforeResourceLoad(
CefBrowserCToCpp::Wrap(browser), CefFrameCToCpp::Wrap(frame),
CefRequestCToCpp::Wrap(request),
CefRequestCallbackCToCpp::Wrap(callback));
// Return type: simple
return _retval;
}
struct _cef_resource_handler_t* CEF_CALLBACK
request_handler_get_resource_handler(struct _cef_request_handler_t* self,
cef_browser_t* browser,
cef_frame_t* frame,
cef_request_t* request) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return NULL;
// Verify param: browser; type: refptr_diff
DCHECK(browser);
if (!browser)
return NULL;
// Verify param: frame; type: refptr_diff
DCHECK(frame);
if (!frame)
return NULL;
// Verify param: request; type: refptr_diff
DCHECK(request);
if (!request)
return NULL;
// Execute
CefRefPtr<CefResourceHandler> _retval =
CefRequestHandlerCppToC::Get(self)->GetResourceHandler(
CefBrowserCToCpp::Wrap(browser), CefFrameCToCpp::Wrap(frame),
CefRequestCToCpp::Wrap(request));
// Return type: refptr_same
return CefResourceHandlerCppToC::Wrap(_retval);
}
void CEF_CALLBACK
request_handler_on_resource_redirect(struct _cef_request_handler_t* self,
cef_browser_t* browser,
cef_frame_t* frame,
cef_request_t* request,
struct _cef_response_t* response,
cef_string_t* new_url) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return;
// Verify param: browser; type: refptr_diff
DCHECK(browser);
if (!browser)
return;
// Verify param: frame; type: refptr_diff
DCHECK(frame);
if (!frame)
return;
// Verify param: request; type: refptr_diff
DCHECK(request);
if (!request)
return;
// Verify param: response; type: refptr_diff
DCHECK(response);
if (!response)
return;
// Verify param: new_url; type: string_byref
DCHECK(new_url);
if (!new_url)
return;
// Translate param: new_url; type: string_byref
CefString new_urlStr(new_url);
// Execute
CefRequestHandlerCppToC::Get(self)->OnResourceRedirect(
CefBrowserCToCpp::Wrap(browser), CefFrameCToCpp::Wrap(frame),
CefRequestCToCpp::Wrap(request), CefResponseCToCpp::Wrap(response),
new_urlStr);
}
int CEF_CALLBACK
request_handler_on_resource_response(struct _cef_request_handler_t* self,
cef_browser_t* browser,
cef_frame_t* frame,
cef_request_t* request,
struct _cef_response_t* response) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return 0;
// Verify param: browser; type: refptr_diff
DCHECK(browser);
if (!browser)
return 0;
// Verify param: frame; type: refptr_diff
DCHECK(frame);
if (!frame)
return 0;
// Verify param: request; type: refptr_diff
DCHECK(request);
if (!request)
return 0;
// Verify param: response; type: refptr_diff
DCHECK(response);
if (!response)
return 0;
// Execute
bool _retval = CefRequestHandlerCppToC::Get(self)->OnResourceResponse(
CefBrowserCToCpp::Wrap(browser), CefFrameCToCpp::Wrap(frame),
CefRequestCToCpp::Wrap(request), CefResponseCToCpp::Wrap(response));
// Return type: bool
return _retval;
}
struct _cef_response_filter_t* CEF_CALLBACK
request_handler_get_resource_response_filter(
struct _cef_request_handler_t* self,
cef_browser_t* browser,
cef_frame_t* frame,
cef_request_t* request,
struct _cef_response_t* response) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return NULL;
// Verify param: browser; type: refptr_diff
DCHECK(browser);
if (!browser)
return NULL;
// Verify param: frame; type: refptr_diff
DCHECK(frame);
if (!frame)
return NULL;
// Verify param: request; type: refptr_diff
DCHECK(request);
if (!request)
return NULL;
// Verify param: response; type: refptr_diff
DCHECK(response);
if (!response)
return NULL;
// Execute
CefRefPtr<CefResponseFilter> _retval =
CefRequestHandlerCppToC::Get(self)->GetResourceResponseFilter(
CefBrowserCToCpp::Wrap(browser), CefFrameCToCpp::Wrap(frame),
CefRequestCToCpp::Wrap(request), CefResponseCToCpp::Wrap(response));
// Return type: refptr_same
return CefResponseFilterCppToC::Wrap(_retval);
}
void CEF_CALLBACK
request_handler_on_resource_load_complete(struct _cef_request_handler_t* self,
cef_browser_t* browser,
cef_frame_t* frame,
cef_request_t* request,
struct _cef_response_t* response,
cef_urlrequest_status_t status,
int64 received_content_length) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return;
// Verify param: browser; type: refptr_diff
DCHECK(browser);
if (!browser)
return;
// Verify param: frame; type: refptr_diff
DCHECK(frame);
if (!frame)
return;
// Verify param: request; type: refptr_diff
DCHECK(request);
if (!request)
return;
// Verify param: response; type: refptr_diff
DCHECK(response);
if (!response)
return;
// Execute
CefRequestHandlerCppToC::Get(self)->OnResourceLoadComplete(
CefBrowserCToCpp::Wrap(browser), CefFrameCToCpp::Wrap(frame),
CefRequestCToCpp::Wrap(request), CefResponseCToCpp::Wrap(response),
status, received_content_length);
}
int CEF_CALLBACK
request_handler_get_auth_credentials(struct _cef_request_handler_t* self,
cef_browser_t* browser,
cef_frame_t* frame,
int isProxy,
const cef_string_t* host,
int port,
const cef_string_t* realm,
const cef_string_t* scheme,
cef_auth_callback_t* callback) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return 0;
// Verify param: browser; type: refptr_diff
DCHECK(browser);
if (!browser)
return 0;
// Verify param: frame; type: refptr_diff
DCHECK(frame);
if (!frame)
return 0;
// Verify param: host; type: string_byref_const
DCHECK(host);
if (!host)
return 0;
// Verify param: callback; type: refptr_diff
DCHECK(callback);
if (!callback)
return 0;
// Unverified params: realm, scheme
// Execute
bool _retval = CefRequestHandlerCppToC::Get(self)->GetAuthCredentials(
CefBrowserCToCpp::Wrap(browser), CefFrameCToCpp::Wrap(frame),
isProxy ? true : false, CefString(host), port, CefString(realm),
CefString(scheme), CefAuthCallbackCToCpp::Wrap(callback));
// Return type: bool
return _retval;
}
int CEF_CALLBACK
request_handler_can_get_cookies(struct _cef_request_handler_t* self,
cef_browser_t* browser,
cef_frame_t* frame,
cef_request_t* request) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return 0;
// Verify param: browser; type: refptr_diff
DCHECK(browser);
if (!browser)
return 0;
// Verify param: frame; type: refptr_diff
DCHECK(frame);
if (!frame)
return 0;
// Verify param: request; type: refptr_diff
DCHECK(request);
if (!request)
return 0;
// Execute
bool _retval = CefRequestHandlerCppToC::Get(self)->CanGetCookies(
CefBrowserCToCpp::Wrap(browser), CefFrameCToCpp::Wrap(frame),
CefRequestCToCpp::Wrap(request));
// Return type: bool
return _retval;
}
int CEF_CALLBACK
request_handler_can_set_cookie(struct _cef_request_handler_t* self,
cef_browser_t* browser,
cef_frame_t* frame,
cef_request_t* request,
const struct _cef_cookie_t* cookie) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return 0;
// Verify param: browser; type: refptr_diff
DCHECK(browser);
if (!browser)
return 0;
// Verify param: frame; type: refptr_diff
DCHECK(frame);
if (!frame)
return 0;
// Verify param: request; type: refptr_diff
DCHECK(request);
if (!request)
return 0;
// Verify param: cookie; type: struct_byref_const
DCHECK(cookie);
if (!cookie)
return 0;
// Translate param: cookie; type: struct_byref_const
CefCookie cookieObj;
if (cookie)
cookieObj.Set(*cookie, false);
// Execute
bool _retval = CefRequestHandlerCppToC::Get(self)->CanSetCookie(
CefBrowserCToCpp::Wrap(browser), CefFrameCToCpp::Wrap(frame),
CefRequestCToCpp::Wrap(request), cookieObj);
// Return type: bool
return _retval;
}
int CEF_CALLBACK
request_handler_on_quota_request(struct _cef_request_handler_t* self,
cef_browser_t* browser,
const cef_string_t* origin_url,
int64 new_size,
cef_request_callback_t* callback) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return 0;
// Verify param: browser; type: refptr_diff
DCHECK(browser);
if (!browser)
return 0;
// Verify param: origin_url; type: string_byref_const
DCHECK(origin_url);
if (!origin_url)
return 0;
// Verify param: callback; type: refptr_diff
DCHECK(callback);
if (!callback)
return 0;
// Execute
bool _retval = CefRequestHandlerCppToC::Get(self)->OnQuotaRequest(
CefBrowserCToCpp::Wrap(browser), CefString(origin_url), new_size,
CefRequestCallbackCToCpp::Wrap(callback));
// Return type: bool
return _retval;
}
void CEF_CALLBACK
request_handler_on_protocol_execution(struct _cef_request_handler_t* self,
cef_browser_t* browser,
const cef_string_t* url,
int* allow_os_execution) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return;
// Verify param: browser; type: refptr_diff
DCHECK(browser);
if (!browser)
return;
// Verify param: url; type: string_byref_const
DCHECK(url);
if (!url)
return;
// Verify param: allow_os_execution; type: bool_byref
DCHECK(allow_os_execution);
if (!allow_os_execution)
return;
// Translate param: allow_os_execution; type: bool_byref
bool allow_os_executionBool =
(allow_os_execution && *allow_os_execution) ? true : false;
// Execute
CefRequestHandlerCppToC::Get(self)->OnProtocolExecution(
CefBrowserCToCpp::Wrap(browser), CefString(url), allow_os_executionBool);
// Restore param: allow_os_execution; type: bool_byref
if (allow_os_execution)
*allow_os_execution = allow_os_executionBool ? true : false;
}
int CEF_CALLBACK
request_handler_on_certificate_error(struct _cef_request_handler_t* self,
cef_browser_t* browser,
cef_errorcode_t cert_error,
const cef_string_t* request_url,
struct _cef_sslinfo_t* ssl_info,
cef_request_callback_t* callback) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return 0;
// Verify param: browser; type: refptr_diff
DCHECK(browser);
if (!browser)
return 0;
// Verify param: request_url; type: string_byref_const
DCHECK(request_url);
if (!request_url)
return 0;
// Verify param: ssl_info; type: refptr_diff
DCHECK(ssl_info);
if (!ssl_info)
return 0;
// Verify param: callback; type: refptr_diff
DCHECK(callback);
if (!callback)
return 0;
// Execute
bool _retval = CefRequestHandlerCppToC::Get(self)->OnCertificateError(
CefBrowserCToCpp::Wrap(browser), cert_error, CefString(request_url),
CefSSLInfoCToCpp::Wrap(ssl_info),
CefRequestCallbackCToCpp::Wrap(callback));
// Return type: bool
return _retval;
}
int CEF_CALLBACK request_handler_on_select_client_certificate(
struct _cef_request_handler_t* self,
cef_browser_t* browser,
int isProxy,
const cef_string_t* host,
int port,
size_t certificatesCount,
struct _cef_x509certificate_t* const* certificates,
cef_select_client_certificate_callback_t* callback) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return 0;
// Verify param: browser; type: refptr_diff
DCHECK(browser);
if (!browser)
return 0;
// Verify param: host; type: string_byref_const
DCHECK(host);
if (!host)
return 0;
// Verify param: certificates; type: refptr_vec_diff_byref_const
DCHECK(certificatesCount == 0 || certificates);
if (certificatesCount > 0 && !certificates)
return 0;
// Verify param: callback; type: refptr_diff
DCHECK(callback);
if (!callback)
return 0;
// Translate param: certificates; type: refptr_vec_diff_byref_const
std::vector<CefRefPtr<CefX509Certificate>> certificatesList;
if (certificatesCount > 0) {
for (size_t i = 0; i < certificatesCount; ++i) {
CefRefPtr<CefX509Certificate> certificatesVal =
CefX509CertificateCToCpp::Wrap(certificates[i]);
certificatesList.push_back(certificatesVal);
}
}
// Execute
bool _retval = CefRequestHandlerCppToC::Get(self)->OnSelectClientCertificate(
CefBrowserCToCpp::Wrap(browser), isProxy ? true : false, CefString(host),
port, certificatesList,
CefSelectClientCertificateCallbackCToCpp::Wrap(callback));
// Return type: bool
return _retval;
}
void CEF_CALLBACK
request_handler_on_plugin_crashed(struct _cef_request_handler_t* self,
cef_browser_t* browser,
const cef_string_t* plugin_path) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return;
// Verify param: browser; type: refptr_diff
DCHECK(browser);
if (!browser)
return;
// Verify param: plugin_path; type: string_byref_const
DCHECK(plugin_path);
if (!plugin_path)
return;
// Execute
CefRequestHandlerCppToC::Get(self)->OnPluginCrashed(
CefBrowserCToCpp::Wrap(browser), CefString(plugin_path));
}
void CEF_CALLBACK
request_handler_on_render_view_ready(struct _cef_request_handler_t* self,
cef_browser_t* browser) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return;
// Verify param: browser; type: refptr_diff
DCHECK(browser);
if (!browser)
return;
// Execute
CefRequestHandlerCppToC::Get(self)->OnRenderViewReady(
CefBrowserCToCpp::Wrap(browser));
}
void CEF_CALLBACK request_handler_on_render_process_terminated(
struct _cef_request_handler_t* self,
cef_browser_t* browser,
cef_termination_status_t status) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return;
// Verify param: browser; type: refptr_diff
DCHECK(browser);
if (!browser)
return;
// Execute
CefRequestHandlerCppToC::Get(self)->OnRenderProcessTerminated(
CefBrowserCToCpp::Wrap(browser), status);
}
} // namespace
// CONSTRUCTOR - Do not edit by hand.
CefRequestHandlerCppToC::CefRequestHandlerCppToC() {
GetStruct()->on_before_browse = request_handler_on_before_browse;
GetStruct()->on_open_urlfrom_tab = request_handler_on_open_urlfrom_tab;
GetStruct()->on_before_resource_load =
request_handler_on_before_resource_load;
GetStruct()->get_resource_handler = request_handler_get_resource_handler;
GetStruct()->on_resource_redirect = request_handler_on_resource_redirect;
GetStruct()->on_resource_response = request_handler_on_resource_response;
GetStruct()->get_resource_response_filter =
request_handler_get_resource_response_filter;
GetStruct()->on_resource_load_complete =
request_handler_on_resource_load_complete;
GetStruct()->get_auth_credentials = request_handler_get_auth_credentials;
GetStruct()->can_get_cookies = request_handler_can_get_cookies;
GetStruct()->can_set_cookie = request_handler_can_set_cookie;
GetStruct()->on_quota_request = request_handler_on_quota_request;
GetStruct()->on_protocol_execution = request_handler_on_protocol_execution;
GetStruct()->on_certificate_error = request_handler_on_certificate_error;
GetStruct()->on_select_client_certificate =
request_handler_on_select_client_certificate;
GetStruct()->on_plugin_crashed = request_handler_on_plugin_crashed;
GetStruct()->on_render_view_ready = request_handler_on_render_view_ready;
GetStruct()->on_render_process_terminated =
request_handler_on_render_process_terminated;
}
template <>
CefRefPtr<CefRequestHandler> CefCppToCRefCounted<
CefRequestHandlerCppToC,
CefRequestHandler,
cef_request_handler_t>::UnwrapDerived(CefWrapperType type,
cef_request_handler_t* s) {
NOTREACHED() << "Unexpected class type: " << type;
return NULL;
}
#if DCHECK_IS_ON()
template <>
base::AtomicRefCount CefCppToCRefCounted<CefRequestHandlerCppToC,
CefRequestHandler,
cef_request_handler_t>::DebugObjCt
ATOMIC_DECLARATION;
#endif
template <>
CefWrapperType CefCppToCRefCounted<CefRequestHandlerCppToC,
CefRequestHandler,
cef_request_handler_t>::kWrapperType =
WT_REQUEST_HANDLER;
| [
"joe@valvesoftware.com"
] | joe@valvesoftware.com |
bc974d38c692580b2a8a3a99e071d50f05c3b5d1 | 32329c4cd2a56850a68c145ccc62e6faaae9ccec | /Ana_ADC_Data/include/Rect.h | e5d332e3d7467051bb9f9e03beaab028ad55ce2e | [] | no_license | yuanzx10/Two_Step_ADC | 076d55561aa7b54e08c4658f2f3bce884f9525f7 | c84213c62e7e472ef89dd9a9a4c260136abd7249 | refs/heads/master | 2021-04-29T11:20:12.305309 | 2017-01-08T18:41:21 | 2017-01-08T18:41:21 | 77,822,375 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 222 | h | // this is the test program
#include <iostream>
using namespace std;
#ifndef RECT_H
#define RECT_H
class Rect{
public:
double width;
double length;
Rect(double wid, double len);
double get_Area();
};
#endif
| [
"yuanzx@laptop"
] | yuanzx@laptop |
826cf768572ac0f69162aea87c7f937f64f8391d | cfb439b21edce6fd2891889a07faf212e5c997b0 | /include/XCOMETConstruction.h | 5afecf355f026528906eedec85994dd40f05a0a2 | [] | no_license | kyushu-yyang/Ts1MagSys | a45cbe99c68fce020bc4fe4bbaeed4de8b4b3329 | 98c1f91d3287eef837df85954789a3d906872a0b | refs/heads/master | 2021-01-01T06:35:05.141203 | 2017-07-18T02:56:27 | 2017-07-18T02:56:27 | 97,458,047 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,776 | h | /**
* @file XCOMETConstruction.h
* @author Y.Yang (Kyushu University)
* @date 16 Jul 2017
**/
#ifndef XCOMETConstruction_HH
#include "XThermalSolver.hpp"
#include "XFieldHandle.hpp"
#include "XCoilHandle.hpp"
#include "XQuenchTransient.hpp"
using namespace Quench;
class XCOMETConstruction : public XQuenchTransient
{
public:
/// constructor
XCOMETConstruction();
/// deconstructor
~XCOMETConstruction();
/// @brief calculate the coil total resistance
double GetCoilResistance(XThermalSolver* solver);
/// @brief construct central coil
void ConstructTs1a();
void ConstructTs1b();
/// @brief update the resistance of conductor
/// @detail please use this function after SetMaterial() and the current decay calculation
void UpdateQuench(XThermalSolver* solve, const double time);
void UpdateQuench2(XThermalSolver* solve, const double time);
/// @brief begin of run
virtual void Begin();
/// @brief run
virtual void Run();
/// @brief end of run
virtual void End();
protected:
/// @brief setup conductor size
XCoilBase* GetConductor();
/// @brief setup strip size
XCoilBase* GetStrip();
XCoilBase* GetFirstStrip();
/// @brief setup shell size
XCoilBase* GetShell();
/// @brief construct magnetic field
void ConstructField(XFieldHandle* fld);
void SetQuenchHeating(XThermalSolver* solve);
/// @brief connection of shell
void ConnectShell(XThermalSolver* mag1, XThermalSolver* mag2, const double l, const double dt);
void ConnectMagnet(XThermalSolver* mag1, XThermalSolver* mag2, const double l, const double dt);
private:
XFieldHandle* fFld;
XThermalSolver* fTs1a;
XThermalSolver* fTs1b;
};
#endif
| [
"yangyefactor@gmail.com"
] | yangyefactor@gmail.com |
98c9c375c84c654d2d016f83a4bdf0b9d57a42ad | 70c05ceb72b15494f7237bd2f1f1aa4fd97aa54d | /teste SFML/include/Collider.h | 4a6c81ac4415fb29e598f7ff006d72f8d7c8851b | [] | no_license | GuiSSantos/Corrida-ao-Oeste | de1356357d58795ec4a5f542f774b8d480b8a7bb | c70afd869f1ddeddaf83983f6ce64f75e220ed18 | refs/heads/master | 2020-04-06T16:53:00.896624 | 2018-11-19T02:05:53 | 2018-11-19T02:05:53 | 157,638,096 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 473 | h | #ifndef COLLIDER_H
#define COLLIDER_H
#include <SFML/Graphics.hpp>
using namespace sf;
class Collider
{
public:
Collider(RectangleShape& corpo);
~Collider();
void Move(float dx, float dy);
bool CheckCollision(Collider& other, Vector2f& direction, float push);
Vector2f getPosition();
Vector2f getHalfSize();
protected:
private:
RectangleShape& corpo;
};
#endif // COLLIDER_H
| [
"noreply@github.com"
] | GuiSSantos.noreply@github.com |
8c416ed45edf30f2c1591b67fabd797ca9e52123 | 05e60ff430f8961077e1cd69849c252ec25c899b | /kanna/src/context.cpp | 58161996ad4a771cb2ae2ebdf91f8cd6a28e1467 | [] | no_license | CallmeNezha/KANNA | 4d8203724d2dd7998f98910b433a3090e42495ee | 60ef6dee47d3f97ba23e58244208ba7028269905 | refs/heads/master | 2021-01-02T08:55:08.140606 | 2017-08-06T05:37:10 | 2017-08-06T05:37:10 | 99,097,944 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 157 | cpp | #include "context.h"
namespace KANNA
{
Context::Context()
{
}
Context::~Context()
{
}
uint32_t Context::frame(bool _capture)
{
return 1;
}
}
| [
"783627014@qq.com"
] | 783627014@qq.com |
1ac8f41613c11e48c8b534a1dbaaf6fba1627824 | 0ae33b95d6af7bd6a54b2747a2cd2d67d795c146 | /samples/aws-samples/amazon-dynamodb-getting-started-for-game-developers/Common/common.h | c5f9d549a9b3850a07db0e2e372ed7e7e9bf27f4 | [
"MIT-0"
] | permissive | briancabbott/programming-sandbox-dynamodb | 13907ad51603546b8c0896b019df917e5ca73ba1 | d017b8dbb6b157f924b0f624842a885b8ce50ad3 | refs/heads/main | 2023-02-04T21:12:49.640976 | 2020-12-21T11:36:56 | 2020-12-21T11:36:56 | 322,939,056 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,607 | h | namespace AmazingRPG
{
// per player data
struct PlayerDesc
{
std::string id;
int level{ 1 };
int strength{ 0 };
int intellect{ 0 };
std::string GetString()
{
std::stringstream sstrm;
sstrm << "Player ID: " << id << std::endl;
sstrm << "\tLevel: " << level << std::endl;
sstrm << "\tStrength: " << strength << std::endl;
sstrm << "\tIntellect: " << intellect << std::endl;
return sstrm.str();
}
};
// shared socket settings
const u_short PORT{ 27015 };
const size_t SOCKET_BUFFER_SIZE = 8192;
// size of the ID strings
const int ID_SIZE{ 30 };
// protocol
// all control codes will be followed by 30 characters of ID
// for the demo the client doesn't send any integers for the stats
// to keep the protocol simple
const char VIEW{ 'V' }; // view player info
const char STR{ 'S' }; // increment strength by 1
const char INT{ 'I' }; // increment intellect by 1
inline std::string GetPlayerIDForInt(int id)
{
std::stringstream name;
name << std::setfill('0') << std::setw(ID_SIZE) << id;
return name.str();
}
inline std::string AskForPlayerID()
{
std::cout << "Type the player ID as a positive integer: ";
int id{ 0 };
std::cin >> id;
if (std::cin.fail() || id < 0)
{
id = 0;
std::cout << "You didn't enter a positive integer" << std::endl;
}
return GetPlayerIDForInt(id);
}
} | [
"briancabbott@gmail.com"
] | briancabbott@gmail.com |
7ea0f00550b8898d059d4e61b2d733e061ed6b0e | 875a9c7cfc77740cde671709ace2106dd5d42268 | /tests/test_serialization_final.cpp | 0673b698516573bdf90e8f413c969d5d01069c0e | [
"MIT"
] | permissive | virgiliofornazin/FastBinaryEncoding | eb8507b16c020e63676ac882021bc9ba97f24e28 | c718c750510b1823c43e90ddcc0c76b2e3f20a72 | refs/heads/master | 2022-11-08T22:12:21.340594 | 2020-07-04T01:20:43 | 2020-07-04T01:20:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 53,869 | cpp | //
// Created by Ivan Shynkarenka on 09.07.2018
//
#include "test.h"
#include "../proto/proto_models.h"
#include "../proto/test_models.h"
TEST_CASE("Serialization (Final): domain", "[FBE]")
{
// Create a new account with some orders
proto::Account account1 = { 1, "Test", proto::State::good, { "USD", 1000.0 }, std::make_optional<proto::Balance>({ "EUR", 100.0 }), {} };
account1.orders.emplace_back(1, "EURUSD", proto::OrderSide::buy, proto::OrderType::market, 1.23456, 1000.0);
account1.orders.emplace_back(2, "EURUSD", proto::OrderSide::sell, proto::OrderType::limit, 1.0, 100.0);
account1.orders.emplace_back(3, "EURUSD", proto::OrderSide::buy, proto::OrderType::stop, 1.5, 10.0);
// Serialize the account to the FBE stream
FBE::proto::AccountFinalModel<FBE::WriteBuffer> writer;
size_t serialized = writer.serialize(account1);
REQUIRE(serialized == writer.buffer().size());
REQUIRE(writer.verify());
writer.next(serialized);
// Check the serialized FBE size
REQUIRE(writer.buffer().size() == 152);
// Deserialize the account from the FBE stream
proto::Account account2;
FBE::proto::AccountFinalModel<FBE::ReadBuffer> reader;
reader.attach(writer.buffer());
REQUIRE(reader.verify());
size_t deserialized = reader.deserialize(account2);
REQUIRE(deserialized == reader.buffer().size());
reader.next(deserialized);
REQUIRE(account2.id == 1);
REQUIRE(account2.name == "Test");
REQUIRE((account2.state | proto::State::good));
REQUIRE(std::string(account2.wallet.currency) == "USD");
REQUIRE(account2.wallet.amount == 1000.0);
REQUIRE(account2.asset.has_value());
REQUIRE(std::string(account2.asset.value().currency) == "EUR");
REQUIRE(account2.asset.value().amount == 100.0);
REQUIRE(account2.orders.size() == 3);
REQUIRE(account2.orders[0].id == 1);
REQUIRE(std::string(account2.orders[0].symbol) == "EURUSD");
REQUIRE(account2.orders[0].side == proto::OrderSide::buy);
REQUIRE(account2.orders[0].type == proto::OrderType::market);
REQUIRE(account2.orders[0].price == 1.23456);
REQUIRE(account2.orders[0].volume == 1000.0);
REQUIRE(account2.orders[1].id == 2);
REQUIRE(std::string(account2.orders[1].symbol) == "EURUSD");
REQUIRE(account2.orders[1].side == proto::OrderSide::sell);
REQUIRE(account2.orders[1].type == proto::OrderType::limit);
REQUIRE(account2.orders[1].price == 1.0);
REQUIRE(account2.orders[1].volume == 100.0);
REQUIRE(account2.orders[2].id == 3);
REQUIRE(std::string(account2.orders[2].symbol) == "EURUSD");
REQUIRE(account2.orders[2].side == proto::OrderSide::buy);
REQUIRE(account2.orders[2].type == proto::OrderType::stop);
REQUIRE(account2.orders[2].price == 1.5);
REQUIRE(account2.orders[2].volume == 10.0);
}
TEST_CASE("Serialization (Final): struct simple", "[FBE]")
{
// Create a new struct
test::StructSimple struct1;
// Serialize the struct to the FBE stream
FBE::test::StructSimpleFinalModel<FBE::WriteBuffer> writer;
REQUIRE(writer.fbe_type() == 110);
size_t serialized = writer.serialize(struct1);
REQUIRE(serialized == writer.buffer().size());
REQUIRE(writer.verify());
writer.next(serialized);
// Check the serialized FBE size
REQUIRE(writer.buffer().size() == 304);
// Deserialize the struct from the FBE stream
test::StructSimple struct2;
FBE::test::StructSimpleFinalModel<FBE::ReadBuffer> reader;
REQUIRE(reader.fbe_type() == 110);
reader.attach(writer.buffer());
REQUIRE(reader.verify());
size_t deserialized = reader.deserialize(struct2);
REQUIRE(deserialized == reader.buffer().size());
reader.next(deserialized);
REQUIRE(struct2.f1 == false);
REQUIRE(struct2.f2 == true);
REQUIRE(struct2.f3 == 0);
REQUIRE(struct2.f4 == 0xFF);
REQUIRE(struct2.f5 == '\0');
REQUIRE(struct2.f6 == '!');
REQUIRE(struct2.f7 == 0);
REQUIRE(struct2.f8 == 0x0444);
REQUIRE(struct2.f9 == 0);
REQUIRE(struct2.f10 == 127);
REQUIRE(struct2.f11 == 0);
REQUIRE(struct2.f12 == 0xFF);
REQUIRE(struct2.f13 == 0);
REQUIRE(struct2.f14 == 32767);
REQUIRE(struct2.f15 == 0);
REQUIRE(struct2.f16 == 0xFFFF);
REQUIRE(struct2.f17 == 0);
REQUIRE(struct2.f18 == 2147483647);
REQUIRE(struct2.f19 == 0);
REQUIRE(struct2.f20 == 0xFFFFFFFF);
REQUIRE(struct2.f21 == 0);
REQUIRE(struct2.f22 == 9223372036854775807ll);
REQUIRE(struct2.f23 == 0);
REQUIRE(struct2.f24 == 0xFFFFFFFFFFFFFFFFull);
REQUIRE(struct2.f25 == 0.0f);
REQUIRE(std::abs(struct2.f26 - 123.456f) < 0.0001);
REQUIRE(struct2.f27 == 0.0);
REQUIRE(std::abs(struct2.f28 - -123.567e+123) < 1e+123);
REQUIRE(struct2.f29 == 0.0);
REQUIRE(struct2.f30 == 123456.123456);
REQUIRE(struct2.f31 == "");
REQUIRE(struct2.f32 == "Initial string!");
REQUIRE(struct2.f33 == 0);
REQUIRE(struct2.f34 == 0);
REQUIRE(struct2.f35 > 1514764800000000000);
REQUIRE(struct2.f36 == FBE::uuid_t());
REQUIRE(struct2.f37 != FBE::uuid_t());
REQUIRE(struct2.f38 == FBE::uuid_t("123e4567-e89b-12d3-a456-426655440000"));
REQUIRE(struct2.f1 == struct1.f1);
REQUIRE(struct2.f2 == struct1.f2);
REQUIRE(struct2.f3 == struct1.f3);
REQUIRE(struct2.f4 == struct1.f4);
REQUIRE(struct2.f5 == struct1.f5);
REQUIRE(struct2.f6 == struct1.f6);
REQUIRE(struct2.f7 == struct1.f7);
REQUIRE(struct2.f8 == struct1.f8);
REQUIRE(struct2.f9 == struct1.f9);
REQUIRE(struct2.f10 == struct1.f10);
REQUIRE(struct2.f11 == struct1.f11);
REQUIRE(struct2.f12 == struct1.f12);
REQUIRE(struct2.f13 == struct1.f13);
REQUIRE(struct2.f14 == struct1.f14);
REQUIRE(struct2.f15 == struct1.f15);
REQUIRE(struct2.f16 == struct1.f16);
REQUIRE(struct2.f17 == struct1.f17);
REQUIRE(struct2.f18 == struct1.f18);
REQUIRE(struct2.f19 == struct1.f19);
REQUIRE(struct2.f20 == struct1.f20);
REQUIRE(struct2.f21 == struct1.f21);
REQUIRE(struct2.f22 == struct1.f22);
REQUIRE(struct2.f23 == struct1.f23);
REQUIRE(struct2.f24 == struct1.f24);
REQUIRE(struct2.f25 == struct1.f25);
REQUIRE(struct2.f26 == struct1.f26);
REQUIRE(struct2.f27 == struct1.f27);
REQUIRE(struct2.f28 == struct1.f28);
REQUIRE(struct2.f29 == struct1.f29);
REQUIRE(struct2.f30 == struct1.f30);
REQUIRE(struct2.f31 == struct1.f31);
REQUIRE(struct2.f32 == struct1.f32);
REQUIRE(struct2.f33 == struct1.f33);
REQUIRE(struct2.f34 == struct1.f34);
REQUIRE(struct2.f35 == struct1.f35);
REQUIRE(struct2.f36 == struct1.f36);
REQUIRE(struct2.f37 == struct1.f37);
REQUIRE(struct2.f38 == struct1.f38);
REQUIRE(struct2.f39 == struct1.f39);
REQUIRE(struct2.f40 == struct1.f40);
}
TEST_CASE("Serialization (Final): struct optional", "[FBE]")
{
// Create a new struct
test::StructOptional struct1;
// Serialize the struct to the FBE stream
FBE::test::StructOptionalFinalModel<FBE::WriteBuffer> writer;
REQUIRE(writer.fbe_type() == 111);
size_t serialized = writer.serialize(struct1);
REQUIRE(serialized == writer.buffer().size());
REQUIRE(writer.verify());
writer.next(serialized);
// Check the serialized FBE size
REQUIRE(writer.buffer().size() == 478);
// Deserialize the struct from the FBE stream
test::StructOptional struct2;
FBE::test::StructOptionalFinalModel<FBE::ReadBuffer> reader;
REQUIRE(reader.fbe_type() == 111);
reader.attach(writer.buffer());
REQUIRE(reader.verify());
size_t deserialized = reader.deserialize(struct2);
REQUIRE(deserialized == reader.buffer().size());
reader.next(deserialized);
REQUIRE(struct2.f1 == false);
REQUIRE(struct2.f2 == true);
REQUIRE(struct2.f3 == 0);
REQUIRE(struct2.f4 == 0xFF);
REQUIRE(struct2.f5 == '\0');
REQUIRE(struct2.f6 == '!');
REQUIRE(struct2.f7 == 0);
REQUIRE(struct2.f8 == 0x0444);
REQUIRE(struct2.f9 == 0);
REQUIRE(struct2.f10 == 127);
REQUIRE(struct2.f11 == 0);
REQUIRE(struct2.f12 == 0xFF);
REQUIRE(struct2.f13 == 0);
REQUIRE(struct2.f14 == 32767);
REQUIRE(struct2.f15 == 0);
REQUIRE(struct2.f16 == 0xFFFF);
REQUIRE(struct2.f17 == 0);
REQUIRE(struct2.f18 == 2147483647);
REQUIRE(struct2.f19 == 0);
REQUIRE(struct2.f20 == 0xFFFFFFFF);
REQUIRE(struct2.f21 == 0);
REQUIRE(struct2.f22 == 9223372036854775807ll);
REQUIRE(struct2.f23 == 0);
REQUIRE(struct2.f24 == 0xFFFFFFFFFFFFFFFFull);
REQUIRE(struct2.f25 == 0.0f);
REQUIRE(std::abs(struct2.f26 - 123.456f) < 0.0001);
REQUIRE(struct2.f27 == 0.0);
REQUIRE(std::abs(struct2.f28 - -123.567e+123) < 1e+123);
REQUIRE(struct2.f29 == 0.0);
REQUIRE(struct2.f30 == 123456.123456);
REQUIRE(struct2.f31 == "");
REQUIRE(struct2.f32 == "Initial string!");
REQUIRE(struct2.f33 == 0);
REQUIRE(struct2.f34 == 0);
REQUIRE(struct2.f35 > 1514764800000000000);
REQUIRE(struct2.f36 == FBE::uuid_t());
REQUIRE(struct2.f37 != FBE::uuid_t());
REQUIRE(struct2.f38 == FBE::uuid_t("123e4567-e89b-12d3-a456-426655440000"));
REQUIRE(!struct2.f100.has_value());
REQUIRE(struct2.f101.has_value());
REQUIRE(struct2.f101.value() == true);
REQUIRE(!struct2.f102.has_value());
REQUIRE(!struct2.f103.has_value());
REQUIRE(struct2.f104.has_value());
REQUIRE(struct2.f104.value() == 0xFF);
REQUIRE(!struct2.f105.has_value());
REQUIRE(!struct2.f106.has_value());
REQUIRE(struct2.f107.has_value());
REQUIRE(struct2.f107.value() == '!');
REQUIRE(!struct2.f108.has_value());
REQUIRE(!struct2.f109.has_value());
REQUIRE(struct2.f110.has_value());
REQUIRE(struct2.f110.value() == 0x0444);
REQUIRE(!struct2.f111.has_value());
REQUIRE(!struct2.f112.has_value());
REQUIRE(struct2.f113.has_value());
REQUIRE(struct2.f113.value() == 127);
REQUIRE(!struct2.f114.has_value());
REQUIRE(!struct2.f115.has_value());
REQUIRE(struct2.f116.has_value());
REQUIRE(struct2.f116.value() == 0xFF);
REQUIRE(!struct2.f117.has_value());
REQUIRE(!struct2.f118.has_value());
REQUIRE(struct2.f119.has_value());
REQUIRE(struct2.f119.value() == 32767);
REQUIRE(!struct2.f120.has_value());
REQUIRE(!struct2.f121.has_value());
REQUIRE(struct2.f122.has_value());
REQUIRE(struct2.f122.value() == 0xFFFF);
REQUIRE(!struct2.f123.has_value());
REQUIRE(!struct2.f124.has_value());
REQUIRE(struct2.f125.has_value());
REQUIRE(struct2.f125.value() == 2147483647);
REQUIRE(!struct2.f126.has_value());
REQUIRE(!struct2.f127.has_value());
REQUIRE(struct2.f128.has_value());
REQUIRE(struct2.f128.value() == 0xFFFFFFFF);
REQUIRE(!struct2.f129.has_value());
REQUIRE(!struct2.f130.has_value());
REQUIRE(struct2.f131.has_value());
REQUIRE(struct2.f131.value() == 9223372036854775807ll);
REQUIRE(!struct2.f132.has_value());
REQUIRE(!struct2.f133.has_value());
REQUIRE(struct2.f131.has_value());
REQUIRE(struct2.f134.value() == 0xFFFFFFFFFFFFFFFFull);
REQUIRE(!struct2.f135.has_value());
REQUIRE(!struct2.f136.has_value());
REQUIRE(struct2.f137.has_value());
REQUIRE(std::abs(struct2.f137.value() - 123.456f) < 0.0001);
REQUIRE(!struct2.f138.has_value());
REQUIRE(!struct2.f139.has_value());
REQUIRE(struct2.f140.has_value());
REQUIRE(std::abs(struct2.f140.value() - -123.567e+123) < 1e+123);
REQUIRE(!struct2.f141.has_value());
REQUIRE(!struct2.f142.has_value());
REQUIRE(struct2.f143.has_value());
REQUIRE(struct2.f143.value() == 123456.123456);
REQUIRE(!struct2.f144.has_value());
REQUIRE(!struct2.f145.has_value());
REQUIRE(struct2.f146.has_value());
REQUIRE(struct2.f146.value() == "Initial string!");
REQUIRE(!struct2.f147.has_value());
REQUIRE(!struct2.f148.has_value());
REQUIRE(struct2.f149.has_value());
REQUIRE(struct2.f149.value() > 1514764800000000000);
REQUIRE(!struct2.f150.has_value());
REQUIRE(!struct2.f151.has_value());
REQUIRE(struct2.f152.has_value());
REQUIRE(struct2.f152.value() == FBE::uuid_t("123e4567-e89b-12d3-a456-426655440000"));
REQUIRE(!struct2.f153.has_value());
REQUIRE(!struct2.f154.has_value());
REQUIRE(!struct2.f155.has_value());
REQUIRE(!struct2.f156.has_value());
REQUIRE(!struct2.f157.has_value());
REQUIRE(!struct2.f158.has_value());
REQUIRE(!struct2.f159.has_value());
REQUIRE(!struct2.f160.has_value());
REQUIRE(!struct2.f161.has_value());
REQUIRE(!struct2.f162.has_value());
REQUIRE(!struct2.f163.has_value());
REQUIRE(!struct2.f164.has_value());
REQUIRE(!struct2.f165.has_value());
REQUIRE(struct2.f1 == struct1.f1);
REQUIRE(struct2.f2 == struct1.f2);
REQUIRE(struct2.f3 == struct1.f3);
REQUIRE(struct2.f4 == struct1.f4);
REQUIRE(struct2.f5 == struct1.f5);
REQUIRE(struct2.f6 == struct1.f6);
REQUIRE(struct2.f7 == struct1.f7);
REQUIRE(struct2.f8 == struct1.f8);
REQUIRE(struct2.f9 == struct1.f9);
REQUIRE(struct2.f10 == struct1.f10);
REQUIRE(struct2.f11 == struct1.f11);
REQUIRE(struct2.f12 == struct1.f12);
REQUIRE(struct2.f13 == struct1.f13);
REQUIRE(struct2.f14 == struct1.f14);
REQUIRE(struct2.f15 == struct1.f15);
REQUIRE(struct2.f16 == struct1.f16);
REQUIRE(struct2.f17 == struct1.f17);
REQUIRE(struct2.f18 == struct1.f18);
REQUIRE(struct2.f19 == struct1.f19);
REQUIRE(struct2.f20 == struct1.f20);
REQUIRE(struct2.f21 == struct1.f21);
REQUIRE(struct2.f22 == struct1.f22);
REQUIRE(struct2.f23 == struct1.f23);
REQUIRE(struct2.f24 == struct1.f24);
REQUIRE(struct2.f25 == struct1.f25);
REQUIRE(struct2.f26 == struct1.f26);
REQUIRE(struct2.f27 == struct1.f27);
REQUIRE(struct2.f28 == struct1.f28);
REQUIRE(struct2.f29 == struct1.f29);
REQUIRE(struct2.f30 == struct1.f30);
REQUIRE(struct2.f31 == struct1.f31);
REQUIRE(struct2.f32 == struct1.f32);
REQUIRE(struct2.f33 == struct1.f33);
REQUIRE(struct2.f34 == struct1.f34);
REQUIRE(struct2.f35 == struct1.f35);
REQUIRE(struct2.f36 == struct1.f36);
REQUIRE(struct2.f37 == struct1.f37);
REQUIRE(struct2.f38 == struct1.f38);
REQUIRE(struct2.f39 == struct1.f39);
REQUIRE(struct2.f40 == struct1.f40);
REQUIRE(struct2.f100 == struct1.f100);
REQUIRE(struct2.f101 == struct1.f101);
REQUIRE(struct2.f102 == struct1.f102);
REQUIRE(struct2.f103 == struct1.f103);
REQUIRE(struct2.f104 == struct1.f104);
REQUIRE(struct2.f105 == struct1.f105);
REQUIRE(struct2.f106 == struct1.f106);
REQUIRE(struct2.f107 == struct1.f107);
REQUIRE(struct2.f108 == struct1.f108);
REQUIRE(struct2.f109 == struct1.f109);
REQUIRE(struct2.f110 == struct1.f110);
REQUIRE(struct2.f111 == struct1.f111);
REQUIRE(struct2.f112 == struct1.f112);
REQUIRE(struct2.f113 == struct1.f113);
REQUIRE(struct2.f114 == struct1.f114);
REQUIRE(struct2.f115 == struct1.f115);
REQUIRE(struct2.f116 == struct1.f116);
REQUIRE(struct2.f117 == struct1.f117);
REQUIRE(struct2.f118 == struct1.f118);
REQUIRE(struct2.f119 == struct1.f119);
REQUIRE(struct2.f120 == struct1.f120);
REQUIRE(struct2.f121 == struct1.f121);
REQUIRE(struct2.f122 == struct1.f122);
REQUIRE(struct2.f123 == struct1.f123);
REQUIRE(struct2.f124 == struct1.f124);
REQUIRE(struct2.f125 == struct1.f125);
REQUIRE(struct2.f126 == struct1.f126);
REQUIRE(struct2.f127 == struct1.f127);
REQUIRE(struct2.f128 == struct1.f128);
REQUIRE(struct2.f129 == struct1.f129);
REQUIRE(struct2.f130 == struct1.f130);
REQUIRE(struct2.f131 == struct1.f131);
REQUIRE(struct2.f132 == struct1.f132);
REQUIRE(struct2.f133 == struct1.f133);
REQUIRE(struct2.f134 == struct1.f134);
REQUIRE(struct2.f135 == struct1.f135);
REQUIRE(struct2.f136 == struct1.f136);
REQUIRE(struct2.f137 == struct1.f137);
REQUIRE(struct2.f138 == struct1.f138);
REQUIRE(struct2.f139 == struct1.f139);
REQUIRE(struct2.f140 == struct1.f140);
REQUIRE(struct2.f141 == struct1.f141);
REQUIRE(struct2.f142 == struct1.f142);
REQUIRE(struct2.f143 == struct1.f143);
REQUIRE(struct2.f144 == struct1.f144);
REQUIRE(struct2.f145 == struct1.f145);
REQUIRE(struct2.f146 == struct1.f146);
REQUIRE(struct2.f147 == struct1.f147);
REQUIRE(struct2.f148 == struct1.f148);
REQUIRE(struct2.f149 == struct1.f149);
REQUIRE(struct2.f150 == struct1.f150);
REQUIRE(struct2.f151 == struct1.f151);
REQUIRE(struct2.f152 == struct1.f152);
REQUIRE(struct2.f153 == struct1.f153);
REQUIRE(struct2.f154 == struct1.f154);
REQUIRE(struct2.f155 == struct1.f155);
REQUIRE(struct2.f156 == struct1.f156);
REQUIRE(struct2.f157 == struct1.f157);
}
TEST_CASE("Serialization (Final): struct nested", "[FBE]")
{
// Create a new struct
test::StructNested struct1;
// Serialize the struct to the FBE stream
FBE::test::StructNestedFinalModel<FBE::WriteBuffer> writer;
REQUIRE(writer.fbe_type() == 112);
size_t serialized = writer.serialize(struct1);
REQUIRE(serialized == writer.buffer().size());
REQUIRE(writer.verify());
writer.next(serialized);
// Check the serialized FBE size
REQUIRE(writer.buffer().size() == 1267);
// Deserialize the struct from the FBE stream
test::StructNested struct2;
FBE::test::StructNestedFinalModel<FBE::ReadBuffer> reader;
REQUIRE(reader.fbe_type() == 112);
reader.attach(writer.buffer());
REQUIRE(reader.verify());
size_t deserialized = reader.deserialize(struct2);
REQUIRE(deserialized == reader.buffer().size());
reader.next(deserialized);
REQUIRE(struct2.f1 == false);
REQUIRE(struct2.f2 == true);
REQUIRE(struct2.f3 == 0);
REQUIRE(struct2.f4 == 0xFF);
REQUIRE(struct2.f5 == '\0');
REQUIRE(struct2.f6 == '!');
REQUIRE(struct2.f7 == 0);
REQUIRE(struct2.f8 == 0x0444);
REQUIRE(struct2.f9 == 0);
REQUIRE(struct2.f10 == 127);
REQUIRE(struct2.f11 == 0);
REQUIRE(struct2.f12 == 0xFF);
REQUIRE(struct2.f13 == 0);
REQUIRE(struct2.f14 == 32767);
REQUIRE(struct2.f15 == 0);
REQUIRE(struct2.f16 == 0xFFFF);
REQUIRE(struct2.f17 == 0);
REQUIRE(struct2.f18 == 2147483647);
REQUIRE(struct2.f19 == 0);
REQUIRE(struct2.f20 == 0xFFFFFFFF);
REQUIRE(struct2.f21 == 0);
REQUIRE(struct2.f22 == 9223372036854775807ll);
REQUIRE(struct2.f23 == 0);
REQUIRE(struct2.f24 == 0xFFFFFFFFFFFFFFFFull);
REQUIRE(struct2.f25 == 0.0f);
REQUIRE(std::abs(struct2.f26 - 123.456f) < 0.0001);
REQUIRE(struct2.f27 == 0.0);
REQUIRE(std::abs(struct2.f28 - -123.567e+123) < 1e+123);
REQUIRE(struct2.f29 == 0.0);
REQUIRE(struct2.f30 == 123456.123456);
REQUIRE(struct2.f31 == "");
REQUIRE(struct2.f32 == "Initial string!");
REQUIRE(struct2.f33 == 0);
REQUIRE(struct2.f34 == 0);
REQUIRE(struct2.f35 > 1514764800000000000);
REQUIRE(struct2.f36 == FBE::uuid_t());
REQUIRE(struct2.f37 != FBE::uuid_t());
REQUIRE(struct2.f38 == FBE::uuid_t("123e4567-e89b-12d3-a456-426655440000"));
REQUIRE(!struct2.f100.has_value());
REQUIRE(struct2.f101.has_value());
REQUIRE(struct2.f101.value() == true);
REQUIRE(!struct2.f102.has_value());
REQUIRE(!struct2.f103.has_value());
REQUIRE(struct2.f104.has_value());
REQUIRE(struct2.f104.value() == 0xFF);
REQUIRE(!struct2.f105.has_value());
REQUIRE(!struct2.f106.has_value());
REQUIRE(struct2.f107.has_value());
REQUIRE(struct2.f107.value() == '!');
REQUIRE(!struct2.f108.has_value());
REQUIRE(!struct2.f109.has_value());
REQUIRE(struct2.f110.has_value());
REQUIRE(struct2.f110.value() == 0x0444);
REQUIRE(!struct2.f111.has_value());
REQUIRE(!struct2.f112.has_value());
REQUIRE(struct2.f113.has_value());
REQUIRE(struct2.f113.value() == 127);
REQUIRE(!struct2.f114.has_value());
REQUIRE(!struct2.f115.has_value());
REQUIRE(struct2.f116.has_value());
REQUIRE(struct2.f116.value() == 0xFF);
REQUIRE(!struct2.f117.has_value());
REQUIRE(!struct2.f118.has_value());
REQUIRE(struct2.f119.has_value());
REQUIRE(struct2.f119.value() == 32767);
REQUIRE(!struct2.f120.has_value());
REQUIRE(!struct2.f121.has_value());
REQUIRE(struct2.f122.has_value());
REQUIRE(struct2.f122.value() == 0xFFFF);
REQUIRE(!struct2.f123.has_value());
REQUIRE(!struct2.f124.has_value());
REQUIRE(struct2.f125.has_value());
REQUIRE(struct2.f125.value() == 2147483647);
REQUIRE(!struct2.f126.has_value());
REQUIRE(!struct2.f127.has_value());
REQUIRE(struct2.f128.has_value());
REQUIRE(struct2.f128.value() == 0xFFFFFFFF);
REQUIRE(!struct2.f129.has_value());
REQUIRE(!struct2.f130.has_value());
REQUIRE(struct2.f131.has_value());
REQUIRE(struct2.f131.value() == 9223372036854775807ll);
REQUIRE(!struct2.f132.has_value());
REQUIRE(!struct2.f133.has_value());
REQUIRE(struct2.f131.has_value());
REQUIRE(struct2.f134.value() == 0xFFFFFFFFFFFFFFFFull);
REQUIRE(!struct2.f135.has_value());
REQUIRE(!struct2.f136.has_value());
REQUIRE(struct2.f137.has_value());
REQUIRE(std::abs(struct2.f137.value() - 123.456f) < 0.0001);
REQUIRE(!struct2.f138.has_value());
REQUIRE(!struct2.f139.has_value());
REQUIRE(struct2.f140.has_value());
REQUIRE(std::abs(struct2.f140.value() - -123.567e+123) < 1e+123);
REQUIRE(!struct2.f141.has_value());
REQUIRE(!struct2.f142.has_value());
REQUIRE(struct2.f143.has_value());
REQUIRE(struct2.f143.value() == 123456.123456);
REQUIRE(!struct2.f144.has_value());
REQUIRE(!struct2.f145.has_value());
REQUIRE(struct2.f146.has_value());
REQUIRE(struct2.f146.value() == "Initial string!");
REQUIRE(!struct2.f147.has_value());
REQUIRE(!struct2.f148.has_value());
REQUIRE(struct2.f149.has_value());
REQUIRE(struct2.f149.value() > 1514764800000000000);
REQUIRE(!struct2.f150.has_value());
REQUIRE(!struct2.f151.has_value());
REQUIRE(struct2.f152.has_value());
REQUIRE(struct2.f152.value() == FBE::uuid_t("123e4567-e89b-12d3-a456-426655440000"));
REQUIRE(!struct2.f153.has_value());
REQUIRE(!struct2.f154.has_value());
REQUIRE(!struct2.f155.has_value());
REQUIRE(!struct2.f156.has_value());
REQUIRE(!struct2.f157.has_value());
REQUIRE(!struct2.f158.has_value());
REQUIRE(!struct2.f159.has_value());
REQUIRE(!struct2.f160.has_value());
REQUIRE(!struct2.f161.has_value());
REQUIRE(!struct2.f162.has_value());
REQUIRE(!struct2.f163.has_value());
REQUIRE(!struct2.f164.has_value());
REQUIRE(!struct2.f165.has_value());
REQUIRE(struct2.f1000 == test::EnumSimple::ENUM_VALUE_0);
REQUIRE(!struct2.f1001.has_value());
REQUIRE(struct2.f1002 == test::EnumTyped::ENUM_VALUE_2);
REQUIRE(!struct2.f1003.has_value());
REQUIRE(struct2.f1004 == test::FlagsSimple::FLAG_VALUE_0);
REQUIRE(!struct2.f1005.has_value());
REQUIRE(struct2.f1006 == (test::FlagsTyped::FLAG_VALUE_2 | test::FlagsTyped::FLAG_VALUE_4 | test::FlagsTyped::FLAG_VALUE_6));
REQUIRE(!struct2.f1007.has_value());
REQUIRE(!struct2.f1009.has_value());
REQUIRE(!struct2.f1011.has_value());
REQUIRE(struct2.f1 == struct1.f1);
REQUIRE(struct2.f2 == struct1.f2);
REQUIRE(struct2.f3 == struct1.f3);
REQUIRE(struct2.f4 == struct1.f4);
REQUIRE(struct2.f5 == struct1.f5);
REQUIRE(struct2.f6 == struct1.f6);
REQUIRE(struct2.f7 == struct1.f7);
REQUIRE(struct2.f8 == struct1.f8);
REQUIRE(struct2.f9 == struct1.f9);
REQUIRE(struct2.f10 == struct1.f10);
REQUIRE(struct2.f11 == struct1.f11);
REQUIRE(struct2.f12 == struct1.f12);
REQUIRE(struct2.f13 == struct1.f13);
REQUIRE(struct2.f14 == struct1.f14);
REQUIRE(struct2.f15 == struct1.f15);
REQUIRE(struct2.f16 == struct1.f16);
REQUIRE(struct2.f17 == struct1.f17);
REQUIRE(struct2.f18 == struct1.f18);
REQUIRE(struct2.f19 == struct1.f19);
REQUIRE(struct2.f20 == struct1.f20);
REQUIRE(struct2.f21 == struct1.f21);
REQUIRE(struct2.f22 == struct1.f22);
REQUIRE(struct2.f23 == struct1.f23);
REQUIRE(struct2.f24 == struct1.f24);
REQUIRE(struct2.f25 == struct1.f25);
REQUIRE(struct2.f26 == struct1.f26);
REQUIRE(struct2.f27 == struct1.f27);
REQUIRE(struct2.f28 == struct1.f28);
REQUIRE(struct2.f29 == struct1.f29);
REQUIRE(struct2.f30 == struct1.f30);
REQUIRE(struct2.f31 == struct1.f31);
REQUIRE(struct2.f32 == struct1.f32);
REQUIRE(struct2.f33 == struct1.f33);
REQUIRE(struct2.f34 == struct1.f34);
REQUIRE(struct2.f35 == struct1.f35);
REQUIRE(struct2.f36 == struct1.f36);
REQUIRE(struct2.f37 == struct1.f37);
REQUIRE(struct2.f38 == struct1.f38);
REQUIRE(struct2.f39 == struct1.f39);
REQUIRE(struct2.f40 == struct1.f40);
REQUIRE(struct2.f100 == struct1.f100);
REQUIRE(struct2.f101 == struct1.f101);
REQUIRE(struct2.f102 == struct1.f102);
REQUIRE(struct2.f103 == struct1.f103);
REQUIRE(struct2.f104 == struct1.f104);
REQUIRE(struct2.f105 == struct1.f105);
REQUIRE(struct2.f106 == struct1.f106);
REQUIRE(struct2.f107 == struct1.f107);
REQUIRE(struct2.f108 == struct1.f108);
REQUIRE(struct2.f109 == struct1.f109);
REQUIRE(struct2.f110 == struct1.f110);
REQUIRE(struct2.f111 == struct1.f111);
REQUIRE(struct2.f112 == struct1.f112);
REQUIRE(struct2.f113 == struct1.f113);
REQUIRE(struct2.f114 == struct1.f114);
REQUIRE(struct2.f115 == struct1.f115);
REQUIRE(struct2.f116 == struct1.f116);
REQUIRE(struct2.f117 == struct1.f117);
REQUIRE(struct2.f118 == struct1.f118);
REQUIRE(struct2.f119 == struct1.f119);
REQUIRE(struct2.f120 == struct1.f120);
REQUIRE(struct2.f121 == struct1.f121);
REQUIRE(struct2.f122 == struct1.f122);
REQUIRE(struct2.f123 == struct1.f123);
REQUIRE(struct2.f124 == struct1.f124);
REQUIRE(struct2.f125 == struct1.f125);
REQUIRE(struct2.f126 == struct1.f126);
REQUIRE(struct2.f127 == struct1.f127);
REQUIRE(struct2.f128 == struct1.f128);
REQUIRE(struct2.f129 == struct1.f129);
REQUIRE(struct2.f130 == struct1.f130);
REQUIRE(struct2.f131 == struct1.f131);
REQUIRE(struct2.f132 == struct1.f132);
REQUIRE(struct2.f133 == struct1.f133);
REQUIRE(struct2.f134 == struct1.f134);
REQUIRE(struct2.f135 == struct1.f135);
REQUIRE(struct2.f136 == struct1.f136);
REQUIRE(struct2.f137 == struct1.f137);
REQUIRE(struct2.f138 == struct1.f138);
REQUIRE(struct2.f139 == struct1.f139);
REQUIRE(struct2.f140 == struct1.f140);
REQUIRE(struct2.f141 == struct1.f141);
REQUIRE(struct2.f142 == struct1.f142);
REQUIRE(struct2.f143 == struct1.f143);
REQUIRE(struct2.f144 == struct1.f144);
REQUIRE(struct2.f145 == struct1.f145);
REQUIRE(struct2.f146 == struct1.f146);
REQUIRE(struct2.f147 == struct1.f147);
REQUIRE(struct2.f148 == struct1.f148);
REQUIRE(struct2.f149 == struct1.f149);
REQUIRE(struct2.f150 == struct1.f150);
REQUIRE(struct2.f151 == struct1.f151);
REQUIRE(struct2.f152 == struct1.f152);
REQUIRE(struct2.f153 == struct1.f153);
REQUIRE(struct2.f154 == struct1.f154);
REQUIRE(struct2.f155 == struct1.f155);
REQUIRE(struct2.f156 == struct1.f156);
REQUIRE(struct2.f157 == struct1.f157);
REQUIRE(struct2.f1000 == struct1.f1000);
REQUIRE(struct2.f1001 == struct1.f1001);
REQUIRE(struct2.f1002 == struct1.f1002);
REQUIRE(struct2.f1003 == struct1.f1003);
REQUIRE(struct2.f1004 == struct1.f1004);
REQUIRE(struct2.f1005 == struct1.f1005);
REQUIRE(struct2.f1006 == struct1.f1006);
REQUIRE(struct2.f1007 == struct1.f1007);
}
TEST_CASE("Serialization (Final): struct bytes", "[FBE]")
{
const char* f1 = "ABC";
const char* f2 = "test";
// Create a new struct
test::StructBytes struct1;
struct1.f1.assign((const uint8_t*)f1, (const uint8_t*)f1 + strlen(f1));
struct1.f2.emplace();
struct1.f2.value().assign((const uint8_t*)f2, (const uint8_t*)f2 + strlen(f2));
// Serialize the struct to the FBE stream
FBE::test::StructBytesFinalModel<FBE::WriteBuffer> writer;
REQUIRE(writer.fbe_type() == 120);
size_t serialized = writer.serialize(struct1);
REQUIRE(serialized == writer.buffer().size());
REQUIRE(writer.verify());
writer.next(serialized);
// Check the serialized FBE size
REQUIRE(writer.buffer().size() == 25);
// Deserialize the struct from the FBE stream
test::StructBytes struct2;
FBE::test::StructBytesFinalModel<FBE::ReadBuffer> reader;
REQUIRE(reader.fbe_type() == 120);
reader.attach(writer.buffer());
REQUIRE(reader.verify());
size_t deserialized = reader.deserialize(struct2);
REQUIRE(deserialized == reader.buffer().size());
reader.next(deserialized);
REQUIRE(struct2.f1.size() == 3);
REQUIRE(memcmp(f1, struct2.f1.data(), struct2.f1.size()) == 0);
REQUIRE(struct2.f2.has_value());
REQUIRE(struct2.f2.value().size() == 4);
REQUIRE(memcmp(f2, struct2.f2.value().data(), struct2.f2.value().size()) == 0);
REQUIRE(!struct2.f3.has_value());
}
TEST_CASE("Serialization (Final): struct array", "[FBE]")
{
// Create a new struct
test::StructArray struct1;
struct1.f1[0] = (uint8_t)48;
struct1.f1[1] = (uint8_t)65;
struct1.f2[0] = (uint8_t)97;
struct1.f2[1] = std::nullopt;
struct1.f3[0] = std::vector<uint8_t>(3, 48);
struct1.f3[1] = std::vector<uint8_t>(3, 65);
struct1.f4[0] = std::vector<uint8_t>(3, 97);
struct1.f4[1] = std::nullopt;
struct1.f5[0] = test::EnumSimple::ENUM_VALUE_1;
struct1.f5[1] = test::EnumSimple::ENUM_VALUE_2;
struct1.f6[0] = test::EnumSimple::ENUM_VALUE_1;
struct1.f6[1] = std::nullopt;
struct1.f7[0] = test::FlagsSimple::FLAG_VALUE_1 | test::FlagsSimple::FLAG_VALUE_2;
struct1.f7[1] = test::FlagsSimple::FLAG_VALUE_1 | test::FlagsSimple::FLAG_VALUE_2 | test::FlagsSimple::FLAG_VALUE_3;
struct1.f8[0] = test::FlagsSimple::FLAG_VALUE_1 | test::FlagsSimple::FLAG_VALUE_2;
struct1.f8[1] = std::nullopt;
struct1.f9[0] = test::StructSimple();
struct1.f9[1] = test::StructSimple();
struct1.f10[0] = test::StructSimple();
struct1.f10[1] = std::nullopt;
// Serialize the struct to the FBE stream
FBE::test::StructArrayFinalModel<FBE::WriteBuffer> writer;
REQUIRE(writer.fbe_type() == 125);
size_t serialized = writer.serialize(struct1);
REQUIRE(serialized == writer.buffer().size());
REQUIRE(writer.verify());
writer.next(serialized);
// Check the serialized FBE size
REQUIRE(writer.buffer().size() == 954);
// Deserialize the struct from the FBE stream
test::StructArray struct2;
FBE::test::StructArrayFinalModel<FBE::ReadBuffer> reader;
REQUIRE(reader.fbe_type() == 125);
reader.attach(writer.buffer());
REQUIRE(reader.verify());
size_t deserialized = reader.deserialize(struct2);
REQUIRE(deserialized == reader.buffer().size());
reader.next(deserialized);
REQUIRE(struct2.f1.size() == 2);
REQUIRE(struct2.f1[0] == 48);
REQUIRE(struct2.f1[1] == 65);
REQUIRE(struct2.f2.size() == 2);
REQUIRE(struct2.f2[0].value() == 97);
REQUIRE(struct2.f2[1] == std::nullopt);
REQUIRE(struct2.f3.size() == 2);
REQUIRE(struct2.f3[0].size() == 3);
REQUIRE(struct2.f3[0][0] == 48);
REQUIRE(struct2.f3[0][1] == 48);
REQUIRE(struct2.f3[0][2] == 48);
REQUIRE(struct2.f3[1].size() == 3);
REQUIRE(struct2.f3[1][0] == 65);
REQUIRE(struct2.f3[1][1] == 65);
REQUIRE(struct2.f3[1][2] == 65);
REQUIRE(struct2.f4.size() == 2);
REQUIRE(struct2.f4[0].has_value());
REQUIRE(struct2.f4[0].value().size() == 3);
REQUIRE(struct2.f4[0].value()[0] == 97);
REQUIRE(struct2.f4[0].value()[1] == 97);
REQUIRE(struct2.f4[0].value()[2] == 97);
REQUIRE(struct2.f4[1] == std::nullopt);
REQUIRE(struct2.f5.size() == 2);
REQUIRE(struct2.f5[0] == test::EnumSimple::ENUM_VALUE_1);
REQUIRE(struct2.f5[1] == test::EnumSimple::ENUM_VALUE_2);
REQUIRE(struct2.f6.size() == 2);
REQUIRE(struct2.f6[0].value() == test::EnumSimple::ENUM_VALUE_1);
REQUIRE(struct2.f6[1] == std::nullopt);
REQUIRE(struct2.f7.size() == 2);
REQUIRE(struct2.f7[0] == (test::FlagsSimple::FLAG_VALUE_1 | test::FlagsSimple::FLAG_VALUE_2));
REQUIRE(struct2.f7[1] == (test::FlagsSimple::FLAG_VALUE_1 | test::FlagsSimple::FLAG_VALUE_2 | test::FlagsSimple::FLAG_VALUE_3));
REQUIRE(struct2.f8.size() == 2);
REQUIRE(struct2.f8[0].value() == (test::FlagsSimple::FLAG_VALUE_1 | test::FlagsSimple::FLAG_VALUE_2));
REQUIRE(struct2.f8[1] == std::nullopt);
REQUIRE(struct2.f9.size() == 2);
REQUIRE(struct2.f9[0].f2 == true);
REQUIRE(struct2.f9[0].f12 == 255);
REQUIRE(struct2.f9[0].f32 == "Initial string!");
REQUIRE(struct2.f9[1].f2 == true);
REQUIRE(struct2.f9[1].f12 == 255);
REQUIRE(struct2.f9[1].f32 == "Initial string!");
REQUIRE(struct2.f10.size() == 2);
REQUIRE(struct2.f10[0].has_value());
REQUIRE(struct2.f10[0].value().f2 == true);
REQUIRE(struct2.f10[0].value().f12 == 255);
REQUIRE(struct2.f10[0].value().f32 == "Initial string!");
REQUIRE(struct2.f10[1] == std::nullopt);
}
TEST_CASE("Serialization (Final): struct vector", "[FBE]")
{
// Create a new struct
test::StructVector struct1;
struct1.f1.emplace_back((uint8_t)48);
struct1.f1.emplace_back((uint8_t)65);
struct1.f2.emplace_back((uint8_t)97);
struct1.f2.emplace_back(std::nullopt);
struct1.f3.emplace_back(std::vector<uint8_t>(3, 48));
struct1.f3.emplace_back(std::vector<uint8_t>(3, 65));
struct1.f4.emplace_back(std::vector<uint8_t>(3, 97));
struct1.f4.emplace_back(std::nullopt);
struct1.f5.emplace_back(test::EnumSimple::ENUM_VALUE_1);
struct1.f5.emplace_back(test::EnumSimple::ENUM_VALUE_2);
struct1.f6.emplace_back(test::EnumSimple::ENUM_VALUE_1);
struct1.f6.emplace_back(std::nullopt);
struct1.f7.emplace_back(test::FlagsSimple::FLAG_VALUE_1 | test::FlagsSimple::FLAG_VALUE_2);
struct1.f7.emplace_back(test::FlagsSimple::FLAG_VALUE_1 | test::FlagsSimple::FLAG_VALUE_2 | test::FlagsSimple::FLAG_VALUE_3);
struct1.f8.emplace_back(test::FlagsSimple::FLAG_VALUE_1 | test::FlagsSimple::FLAG_VALUE_2);
struct1.f8.emplace_back(std::nullopt);
struct1.f9.emplace_back(test::StructSimple());
struct1.f9.emplace_back(test::StructSimple());
struct1.f10.emplace_back(test::StructSimple());
struct1.f10.emplace_back(std::nullopt);
// Serialize the struct to the FBE stream
FBE::test::StructVectorFinalModel<FBE::WriteBuffer> writer;
REQUIRE(writer.fbe_type() == 130);
size_t serialized = writer.serialize(struct1);
REQUIRE(serialized == writer.buffer().size());
REQUIRE(writer.verify());
writer.next(serialized);
// Check the serialized FBE size
REQUIRE(writer.buffer().size() == 994);
// Deserialize the struct from the FBE stream
test::StructVector struct2;
FBE::test::StructVectorFinalModel<FBE::ReadBuffer> reader;
REQUIRE(reader.fbe_type() == 130);
reader.attach(writer.buffer());
REQUIRE(reader.verify());
size_t deserialized = reader.deserialize(struct2);
REQUIRE(deserialized == reader.buffer().size());
reader.next(deserialized);
REQUIRE(struct2.f1.size() == 2);
REQUIRE(struct2.f1[0] == 48);
REQUIRE(struct2.f1[1] == 65);
REQUIRE(struct2.f2.size() == 2);
REQUIRE(struct2.f2[0].value() == 97);
REQUIRE(struct2.f2[1] == std::nullopt);
REQUIRE(struct2.f3.size() == 2);
REQUIRE(struct2.f3[0].size() == 3);
REQUIRE(struct2.f3[0][0] == 48);
REQUIRE(struct2.f3[0][1] == 48);
REQUIRE(struct2.f3[0][2] == 48);
REQUIRE(struct2.f3[1].size() == 3);
REQUIRE(struct2.f3[1][0] == 65);
REQUIRE(struct2.f3[1][1] == 65);
REQUIRE(struct2.f3[1][2] == 65);
REQUIRE(struct2.f4.size() == 2);
REQUIRE(struct2.f4[0].has_value());
REQUIRE(struct2.f4[0].value().size() == 3);
REQUIRE(struct2.f4[0].value()[0] == 97);
REQUIRE(struct2.f4[0].value()[1] == 97);
REQUIRE(struct2.f4[0].value()[2] == 97);
REQUIRE(struct2.f4[1] == std::nullopt);
REQUIRE(struct2.f5.size() == 2);
REQUIRE(struct2.f5[0] == test::EnumSimple::ENUM_VALUE_1);
REQUIRE(struct2.f5[1] == test::EnumSimple::ENUM_VALUE_2);
REQUIRE(struct2.f6.size() == 2);
REQUIRE(struct2.f6[0].value() == test::EnumSimple::ENUM_VALUE_1);
REQUIRE(struct2.f6[1] == std::nullopt);
REQUIRE(struct2.f7.size() == 2);
REQUIRE(struct2.f7[0] == (test::FlagsSimple::FLAG_VALUE_1 | test::FlagsSimple::FLAG_VALUE_2));
REQUIRE(struct2.f7[1] == (test::FlagsSimple::FLAG_VALUE_1 | test::FlagsSimple::FLAG_VALUE_2 | test::FlagsSimple::FLAG_VALUE_3));
REQUIRE(struct2.f8.size() == 2);
REQUIRE(struct2.f8[0].value() == (test::FlagsSimple::FLAG_VALUE_1 | test::FlagsSimple::FLAG_VALUE_2));
REQUIRE(struct2.f8[1] == std::nullopt);
REQUIRE(struct2.f9.size() == 2);
REQUIRE(struct2.f9[0].f2 == true);
REQUIRE(struct2.f9[0].f12 == 255);
REQUIRE(struct2.f9[0].f32 == "Initial string!");
REQUIRE(struct2.f9[1].f2 == true);
REQUIRE(struct2.f9[1].f12 == 255);
REQUIRE(struct2.f9[1].f32 == "Initial string!");
REQUIRE(struct2.f10.size() == 2);
REQUIRE(struct2.f10[0].has_value());
REQUIRE(struct2.f10[0].value().f2 == true);
REQUIRE(struct2.f10[0].value().f12 == 255);
REQUIRE(struct2.f10[0].value().f32 == "Initial string!");
REQUIRE(struct2.f10[1] == std::nullopt);
}
TEST_CASE("Serialization (Final): struct list", "[FBE]")
{
// Create a new struct
test::StructList struct1;
struct1.f1.emplace_back((uint8_t)48);
struct1.f1.emplace_back((uint8_t)65);
struct1.f2.emplace_back((uint8_t)97);
struct1.f2.emplace_back(std::nullopt);
struct1.f3.emplace_back(std::vector<uint8_t>(3, 48));
struct1.f3.emplace_back(std::vector<uint8_t>(3, 65));
struct1.f4.emplace_back(std::vector<uint8_t>(3, 97));
struct1.f4.emplace_back(std::nullopt);
struct1.f5.emplace_back(test::EnumSimple::ENUM_VALUE_1);
struct1.f5.emplace_back(test::EnumSimple::ENUM_VALUE_2);
struct1.f6.emplace_back(test::EnumSimple::ENUM_VALUE_1);
struct1.f6.emplace_back(std::nullopt);
struct1.f7.emplace_back(test::FlagsSimple::FLAG_VALUE_1 | test::FlagsSimple::FLAG_VALUE_2);
struct1.f7.emplace_back(test::FlagsSimple::FLAG_VALUE_1 | test::FlagsSimple::FLAG_VALUE_2 | test::FlagsSimple::FLAG_VALUE_3);
struct1.f8.emplace_back(test::FlagsSimple::FLAG_VALUE_1 | test::FlagsSimple::FLAG_VALUE_2);
struct1.f8.emplace_back(std::nullopt);
struct1.f9.emplace_back(test::StructSimple());
struct1.f9.emplace_back(test::StructSimple());
struct1.f10.emplace_back(test::StructSimple());
struct1.f10.emplace_back(std::nullopt);
// Serialize the struct to the FBE stream
FBE::test::StructListFinalModel<FBE::WriteBuffer> writer;
REQUIRE(writer.fbe_type() == 131);
size_t serialized = writer.serialize(struct1);
REQUIRE(serialized == writer.buffer().size());
REQUIRE(writer.verify());
writer.next(serialized);
// Check the serialized FBE size
REQUIRE(writer.buffer().size() == 994);
// Deserialize the struct from the FBE stream
test::StructList struct2;
FBE::test::StructListFinalModel<FBE::ReadBuffer> reader;
REQUIRE(reader.fbe_type() == 131);
reader.attach(writer.buffer());
REQUIRE(reader.verify());
size_t deserialized = reader.deserialize(struct2);
REQUIRE(deserialized == reader.buffer().size());
reader.next(deserialized);
REQUIRE(struct2.f1.size() == 2);
REQUIRE(struct2.f1.front() == 48);
REQUIRE(struct2.f1.back() == 65);
REQUIRE(struct2.f2.size() == 2);
REQUIRE(struct2.f2.front().value() == 97);
REQUIRE(struct2.f2.back() == std::nullopt);
REQUIRE(struct2.f3.size() == 2);
REQUIRE(struct2.f3.front().size() == 3);
REQUIRE(struct2.f3.front()[0] == 48);
REQUIRE(struct2.f3.front()[1] == 48);
REQUIRE(struct2.f3.front()[2] == 48);
REQUIRE(struct2.f3.back().size() == 3);
REQUIRE(struct2.f3.back()[0] == 65);
REQUIRE(struct2.f3.back()[1] == 65);
REQUIRE(struct2.f3.back()[2] == 65);
REQUIRE(struct2.f4.size() == 2);
REQUIRE(struct2.f4.front().has_value());
REQUIRE(struct2.f4.front().value().size() == 3);
REQUIRE(struct2.f4.front().value()[0] == 97);
REQUIRE(struct2.f4.front().value()[1] == 97);
REQUIRE(struct2.f4.front().value()[2] == 97);
REQUIRE(struct2.f4.back() == std::nullopt);
REQUIRE(struct2.f5.size() == 2);
REQUIRE(struct2.f5.front() == test::EnumSimple::ENUM_VALUE_1);
REQUIRE(struct2.f5.back() == test::EnumSimple::ENUM_VALUE_2);
REQUIRE(struct2.f6.size() == 2);
REQUIRE(struct2.f6.front().value() == test::EnumSimple::ENUM_VALUE_1);
REQUIRE(struct2.f6.back() == std::nullopt);
REQUIRE(struct2.f7.size() == 2);
REQUIRE(struct2.f7.front() == (test::FlagsSimple::FLAG_VALUE_1 | test::FlagsSimple::FLAG_VALUE_2));
REQUIRE(struct2.f7.back() == (test::FlagsSimple::FLAG_VALUE_1 | test::FlagsSimple::FLAG_VALUE_2 | test::FlagsSimple::FLAG_VALUE_3));
REQUIRE(struct2.f8.size() == 2);
REQUIRE(struct2.f8.front().value() == (test::FlagsSimple::FLAG_VALUE_1 | test::FlagsSimple::FLAG_VALUE_2));
REQUIRE(struct2.f8.back() == std::nullopt);
REQUIRE(struct2.f9.size() == 2);
REQUIRE(struct2.f9.front().f2 == true);
REQUIRE(struct2.f9.front().f12 == 255);
REQUIRE(struct2.f9.front().f32 == "Initial string!");
REQUIRE(struct2.f9.back().f2 == true);
REQUIRE(struct2.f9.back().f12 == 255);
REQUIRE(struct2.f9.back().f32 == "Initial string!");
REQUIRE(struct2.f10.size() == 2);
REQUIRE(struct2.f10.front().has_value());
REQUIRE(struct2.f10.front().value().f2 == true);
REQUIRE(struct2.f10.front().value().f12 == 255);
REQUIRE(struct2.f10.front().value().f32 == "Initial string!");
REQUIRE(struct2.f10.back() == std::nullopt);
}
TEST_CASE("Serialization (Final): struct set", "[FBE]")
{
// Create a new struct
test::StructSet struct1;
struct1.f1.emplace((uint8_t)48);
struct1.f1.emplace((uint8_t)65);
struct1.f1.emplace((uint8_t)97);
struct1.f2.emplace(test::EnumSimple::ENUM_VALUE_1);
struct1.f2.emplace(test::EnumSimple::ENUM_VALUE_2);
struct1.f3.emplace(test::FlagsSimple::FLAG_VALUE_1 | test::FlagsSimple::FLAG_VALUE_2);
struct1.f3.emplace(test::FlagsSimple::FLAG_VALUE_1 | test::FlagsSimple::FLAG_VALUE_2 | test::FlagsSimple::FLAG_VALUE_3);
test::StructSimple s1;
s1.id = 48;
struct1.f4.emplace(s1);
test::StructSimple s2;
s2.id = 65;
struct1.f4.emplace(s2);
// Serialize the struct to the FBE stream
FBE::test::StructSetFinalModel<FBE::WriteBuffer> writer;
REQUIRE(writer.fbe_type() == 132);
size_t serialized = writer.serialize(struct1);
REQUIRE(serialized == writer.buffer().size());
REQUIRE(writer.verify());
writer.next(serialized);
// Check the serialized FBE size
REQUIRE(writer.buffer().size() == 635);
// Deserialize the struct from the FBE stream
test::StructSet struct2;
FBE::test::StructSetFinalModel<FBE::ReadBuffer> reader;
REQUIRE(reader.fbe_type() == 132);
reader.attach(writer.buffer());
REQUIRE(reader.verify());
size_t deserialized = reader.deserialize(struct2);
REQUIRE(deserialized == reader.buffer().size());
reader.next(deserialized);
REQUIRE(struct2.f1.size() == 3);
REQUIRE(struct2.f1.find((uint8_t)48) != struct2.f1.end());
REQUIRE(struct2.f1.find((uint8_t)65) != struct2.f1.end());
REQUIRE(struct2.f1.find((uint8_t)97) != struct2.f1.end());
REQUIRE(struct2.f2.size() == 2);
REQUIRE(struct2.f2.find(test::EnumSimple::ENUM_VALUE_1) != struct2.f2.end());
REQUIRE(struct2.f2.find(test::EnumSimple::ENUM_VALUE_2) != struct2.f2.end());
REQUIRE(struct2.f3.size() == 2);
REQUIRE(struct2.f3.find(test::FlagsSimple::FLAG_VALUE_1 | test::FlagsSimple::FLAG_VALUE_2) != struct2.f3.end());
REQUIRE(struct2.f3.find(test::FlagsSimple::FLAG_VALUE_1 | test::FlagsSimple::FLAG_VALUE_2 | test::FlagsSimple::FLAG_VALUE_3) != struct2.f3.end());
REQUIRE(struct2.f4.size() == 2);
REQUIRE(struct2.f4.find(s1) != struct2.f4.end());
REQUIRE(struct2.f4.find(s2) != struct2.f4.end());
}
TEST_CASE("Serialization (Final): struct map", "[FBE]")
{
// Create a new struct
test::StructMap struct1;
struct1.f1.emplace(10, (uint8_t)48);
struct1.f1.emplace(20, (uint8_t)65);
struct1.f2.emplace(10, (uint8_t)97);
struct1.f2.emplace(20, std::nullopt);
struct1.f3.emplace(10, std::vector<uint8_t>(3, 48));
struct1.f3.emplace(20, std::vector<uint8_t>(3, 65));
struct1.f4.emplace(10, std::vector<uint8_t>(3, 97));
struct1.f4.emplace(20, std::nullopt);
struct1.f5.emplace(10, test::EnumSimple::ENUM_VALUE_1);
struct1.f5.emplace(20, test::EnumSimple::ENUM_VALUE_2);
struct1.f6.emplace(10, test::EnumSimple::ENUM_VALUE_1);
struct1.f6.emplace(20, std::nullopt);
struct1.f7.emplace(10, test::FlagsSimple::FLAG_VALUE_1 | test::FlagsSimple::FLAG_VALUE_2);
struct1.f7.emplace(20, test::FlagsSimple::FLAG_VALUE_1 | test::FlagsSimple::FLAG_VALUE_2 | test::FlagsSimple::FLAG_VALUE_3);
struct1.f8.emplace(10, test::FlagsSimple::FLAG_VALUE_1 | test::FlagsSimple::FLAG_VALUE_2);
struct1.f8.emplace(20, std::nullopt);
test::StructSimple s1;
s1.id = 48;
struct1.f9.emplace(10, s1);
test::StructSimple s2;
s2.id = 65;
struct1.f9.emplace(20, s2);
struct1.f10.emplace(10, s1);
struct1.f10.emplace(20, std::nullopt);
// Serialize the struct to the FBE stream
FBE::test::StructMapFinalModel<FBE::WriteBuffer> writer;
REQUIRE(writer.fbe_type() == 140);
size_t serialized = writer.serialize(struct1);
REQUIRE(serialized == writer.buffer().size());
REQUIRE(writer.verify());
writer.next(serialized);
// Check the serialized FBE size
REQUIRE(writer.buffer().size() == 1074);
// Deserialize the struct from the FBE stream
test::StructMap struct2;
FBE::test::StructMapFinalModel<FBE::ReadBuffer> reader;
REQUIRE(reader.fbe_type() == 140);
reader.attach(writer.buffer());
REQUIRE(reader.verify());
size_t deserialized = reader.deserialize(struct2);
REQUIRE(deserialized == reader.buffer().size());
reader.next(deserialized);
REQUIRE(struct2.f1.size() == 2);
REQUIRE(struct2.f1.find(10)->second == 48);
REQUIRE(struct2.f1.find(20)->second == 65);
REQUIRE(struct2.f2.size() == 2);
REQUIRE(struct2.f2.find(10)->second.value() == 97);
REQUIRE(struct2.f2.find(20)->second == std::nullopt);
REQUIRE(struct2.f3.size() == 2);
REQUIRE(struct2.f3.find(10)->second.size() == 3);
REQUIRE(struct2.f3.find(20)->second.size() == 3);
REQUIRE(struct2.f4.size() == 2);
REQUIRE(struct2.f4.find(10)->second.value().size() == 3);
REQUIRE(struct2.f4.find(20)->second == std::nullopt);
REQUIRE(struct2.f5.size() == 2);
REQUIRE(struct2.f5.find(10)->second == test::EnumSimple::ENUM_VALUE_1);
REQUIRE(struct2.f5.find(20)->second == test::EnumSimple::ENUM_VALUE_2);
REQUIRE(struct2.f6.size() == 2);
REQUIRE(struct2.f6.find(10)->second.value() == test::EnumSimple::ENUM_VALUE_1);
REQUIRE(struct2.f6.find(20)->second == std::nullopt);
REQUIRE(struct2.f7.size() == 2);
REQUIRE(struct2.f7.find(10)->second == (test::FlagsSimple::FLAG_VALUE_1 | test::FlagsSimple::FLAG_VALUE_2));
REQUIRE(struct2.f7.find(20)->second == (test::FlagsSimple::FLAG_VALUE_1 | test::FlagsSimple::FLAG_VALUE_2 | test::FlagsSimple::FLAG_VALUE_3));
REQUIRE(struct2.f8.size() == 2);
REQUIRE(struct2.f8.find(10)->second.value() == (test::FlagsSimple::FLAG_VALUE_1 | test::FlagsSimple::FLAG_VALUE_2));
REQUIRE(struct2.f8.find(20)->second == std::nullopt);
REQUIRE(struct2.f9.size() == 2);
REQUIRE(struct2.f9.find(10)->second.id == 48);
REQUIRE(struct2.f9.find(20)->second.id == 65);
REQUIRE(struct2.f10.size() == 2);
REQUIRE(struct2.f10.find(10)->second.value().id == 48);
REQUIRE(struct2.f10.find(20)->second == std::nullopt);
}
TEST_CASE("Serialization (Final): struct hash", "[FBE]")
{
// Create a new struct
test::StructHash struct1;
struct1.f1.emplace("10", (uint8_t)48);
struct1.f1.emplace("20", (uint8_t)65);
struct1.f2.emplace("10", (uint8_t)97);
struct1.f2.emplace("20", std::nullopt);
struct1.f3.emplace("10", std::vector<uint8_t>(3, 48));
struct1.f3.emplace("20", std::vector<uint8_t>(3, 65));
struct1.f4.emplace("10", std::vector<uint8_t>(3, 97));
struct1.f4.emplace("20", std::nullopt);
struct1.f5.emplace("10", test::EnumSimple::ENUM_VALUE_1);
struct1.f5.emplace("20", test::EnumSimple::ENUM_VALUE_2);
struct1.f6.emplace("10", test::EnumSimple::ENUM_VALUE_1);
struct1.f6.emplace("20", std::nullopt);
struct1.f7.emplace("10", test::FlagsSimple::FLAG_VALUE_1 | test::FlagsSimple::FLAG_VALUE_2);
struct1.f7.emplace("20", test::FlagsSimple::FLAG_VALUE_1 | test::FlagsSimple::FLAG_VALUE_2 | test::FlagsSimple::FLAG_VALUE_3);
struct1.f8.emplace("10", test::FlagsSimple::FLAG_VALUE_1 | test::FlagsSimple::FLAG_VALUE_2);
struct1.f8.emplace("20", std::nullopt);
test::StructSimple s1;
s1.id = 48;
struct1.f9.emplace("10", s1);
test::StructSimple s2;
s2.id = 65;
struct1.f9.emplace("20", s2);
struct1.f10.emplace("10", s1);
struct1.f10.emplace("20", std::nullopt);
// Serialize the struct to the FBE stream
FBE::test::StructHashFinalModel<FBE::WriteBuffer> writer;
REQUIRE(writer.fbe_type() == 141);
size_t serialized = writer.serialize(struct1);
REQUIRE(serialized == writer.buffer().size());
REQUIRE(writer.verify());
writer.next(serialized);
// Check the serialized FBE size
REQUIRE(writer.buffer().size() == 1114);
// Deserialize the struct from the FBE stream
test::StructHash struct2;
FBE::test::StructHashFinalModel<FBE::ReadBuffer> reader;
REQUIRE(reader.fbe_type() == 141);
reader.attach(writer.buffer());
REQUIRE(reader.verify());
size_t deserialized = reader.deserialize(struct2);
REQUIRE(deserialized == reader.buffer().size());
reader.next(deserialized);
REQUIRE(struct2.f1.size() == 2);
REQUIRE(struct2.f1.find("10")->second == 48);
REQUIRE(struct2.f1.find("20")->second == 65);
REQUIRE(struct2.f2.size() == 2);
REQUIRE(struct2.f2.find("10")->second.value() == 97);
REQUIRE(struct2.f2.find("20")->second == std::nullopt);
REQUIRE(struct2.f3.size() == 2);
REQUIRE(struct2.f3.find("10")->second.size() == 3);
REQUIRE(struct2.f3.find("20")->second.size() == 3);
REQUIRE(struct2.f4.size() == 2);
REQUIRE(struct2.f4.find("10")->second.value().size() == 3);
REQUIRE(struct2.f4.find("20")->second == std::nullopt);
REQUIRE(struct2.f5.size() == 2);
REQUIRE(struct2.f5.find("10")->second == test::EnumSimple::ENUM_VALUE_1);
REQUIRE(struct2.f5.find("20")->second == test::EnumSimple::ENUM_VALUE_2);
REQUIRE(struct2.f6.size() == 2);
REQUIRE(struct2.f6.find("10")->second.value() == test::EnumSimple::ENUM_VALUE_1);
REQUIRE(struct2.f6.find("20")->second == std::nullopt);
REQUIRE(struct2.f7.size() == 2);
REQUIRE(struct2.f7.find("10")->second == (test::FlagsSimple::FLAG_VALUE_1 | test::FlagsSimple::FLAG_VALUE_2));
REQUIRE(struct2.f7.find("20")->second == (test::FlagsSimple::FLAG_VALUE_1 | test::FlagsSimple::FLAG_VALUE_2 | test::FlagsSimple::FLAG_VALUE_3));
REQUIRE(struct2.f8.size() == 2);
REQUIRE(struct2.f8.find("10")->second.value() == (test::FlagsSimple::FLAG_VALUE_1 | test::FlagsSimple::FLAG_VALUE_2));
REQUIRE(struct2.f8.find("20")->second == std::nullopt);
REQUIRE(struct2.f9.size() == 2);
REQUIRE(struct2.f9.find("10")->second.id == 48);
REQUIRE(struct2.f9.find("20")->second.id == 65);
REQUIRE(struct2.f10.size() == 2);
REQUIRE(struct2.f10.find("10")->second.value().id == 48);
REQUIRE(struct2.f10.find("20")->second == std::nullopt);
}
TEST_CASE("Serialization (Final): struct hash extended", "[FBE]")
{
// Create a new struct
test::StructHashEx struct1;
test::StructSimple s1;
s1.id = 48;
struct1.f1.emplace(s1, test::StructNested());
test::StructSimple s2;
s2.id = 65;
struct1.f1.emplace(s2, test::StructNested());
struct1.f2.emplace(s1, test::StructNested());
struct1.f2.emplace(s2, std::nullopt);
// Serialize the struct to the FBE stream
FBE::test::StructHashExFinalModel<FBE::WriteBuffer> writer;
REQUIRE(writer.fbe_type() == 142);
size_t serialized = writer.serialize(struct1);
REQUIRE(serialized == writer.buffer().size());
REQUIRE(writer.verify());
writer.next(serialized);
// Check the serialized FBE size
REQUIRE(writer.buffer().size() == 4979);
// Deserialize the struct from the FBE stream
test::StructHashEx struct2;
FBE::test::StructHashExFinalModel<FBE::ReadBuffer> reader;
REQUIRE(reader.fbe_type() == 142);
reader.attach(writer.buffer());
REQUIRE(reader.verify());
size_t deserialized = reader.deserialize(struct2);
REQUIRE(deserialized == reader.buffer().size());
reader.next(deserialized);
REQUIRE(struct2.f1.size() == 2);
REQUIRE(struct2.f1.find(s1)->second.f1002 == test::EnumTyped::ENUM_VALUE_2);
REQUIRE(struct2.f1.find(s2)->second.f1002 == test::EnumTyped::ENUM_VALUE_2);
REQUIRE(struct2.f2.size() == 2);
REQUIRE(struct2.f2.find(s1)->second.value().f1002 == test::EnumTyped::ENUM_VALUE_2);
REQUIRE(struct2.f2.find(s2)->second == std::nullopt);
}
| [
"chronoxor@gmail.com"
] | chronoxor@gmail.com |
52a745ad470e1de7ab1c29900bfaa28291b4bb7d | c982fa18c907d94e797f2b5c0d0fec67b766f726 | /code/C++/CSES-Solutions/Graph Algorithms/Building Roads (1666)/catkl.cpp | c6fd657e4fc1f7bee7d7b01c0b1e17312d145501 | [] | no_license | hieupm123/Hieu | 203e87d4a37813bcc0d1e2d04e791b3e92e1b007 | 3611a7c9c24690747b48610c5fbce2acc1a2c0ce | refs/heads/main | 2023-06-10T23:22:03.816539 | 2021-06-30T01:29:12 | 2021-06-30T01:29:12 | 381,540,974 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,381 | cpp | #include <bits/stdc++.h>
using namespace std;
#define rep(i, a, b) for(int i = a; i < (b); ++i)
#define trav(a, x) for(auto& a : x)
#define all(x) begin(x), end(x)
#define sz(x) (int)(x).size()
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;
vi val, comp, z, cont;
int Time, ncomps;
template<class G, class F> int dfs(int j, G& g, F& f) {
int low = val[j] = ++Time, x; z.push_back(j);
trav(e,g[j]) if (comp[e] < 0)
low = min(low, val[e] ?: dfs(e,g,f));
if (low == val[j]) {
do {
x = z.back(); z.pop_back();
comp[x] = ncomps;
cont.push_back(x);
} while (x != j);
f(cont); cont.clear();
ncomps++;
}
return val[j] = low;
}
template<class G, class F> void scc(G& g, F f) {
int n = sz(g);
val.assign(n, 0); comp.assign(n, -1);
Time = ncomps = 0;
rep(i,0,n) if (comp[i] < 0) dfs(i, g, f);
}
int main() {
cin.sync_with_stdio(0); cin.tie(0);
cin.exceptions(cin.failbit);
int n, m;
cin >> n >> m;
vector<vi> g(n);
while (m--) {
int a, b;
cin >> a >> b;
a--, b--;
g[a].push_back(b);
g[b].push_back(a);
}
vi r;
scc(g, [&](vi &c) { r.push_back(c[0]); });
cout << sz(r)-1 << '\n';
rep(i, 1, sz(r))
cout << r[0]+1 << " " << r[i]+1 << '\n';
return 0;
}
| [
"hieu@hieu"
] | hieu@hieu |
28688b881e47bfe79d00e436ab56f31bb709886d | 0e8d57f10639b0bdcab2c89b307029697c909863 | /lib/main/ds/sqrt-decomposition/main-max-query.cpp | c816b69f8d67ed00a5f5e317c219488e8c43684b | [
"Apache-2.0"
] | permissive | xirc/cp-algorithm | 07a6faf5228e07037920f5011326c16091a9157d | e83ea891e9f8994fdd6f704819c0c69f5edd699a | refs/heads/main | 2021-12-25T16:19:57.617683 | 2021-12-22T12:06:49 | 2021-12-22T12:06:49 | 226,591,291 | 15 | 1 | Apache-2.0 | 2021-12-22T12:06:50 | 2019-12-07T23:53:18 | C++ | UTF-8 | C++ | false | false | 1,725 | cpp | #include <iostream>
#include <vector>
#include <map>
#include <string>
#include <random>
#include <numeric>
#include <algorithm>
#include "template/template-main.hpp"
#include "cpalgo/ds/sqrt-decomposition.hpp"
using namespace std;
struct Maximum {
const long long id = std::numeric_limits<long long>::lowest();
long long operator()(const long long& lhs, const long long& rhs) const {
return max(lhs, rhs);
}
};
SqrtDecomposition<int> container({}, Maximum());
void action_init() {
int n, _min, _max;
random_device random;
cin >> n >> _min >> _max;
if (n < 0) {
cout << "false" << endl;
return;
}
vector<int> array(n, 0);
for (int i = 0 ; i < n; ++i) {
array[i] = random() % (_max - _min) + _min;
}
container.build(array);
cout << "true" << endl;
}
void action_query() {
int l, r;
cin >> l >> r;
int ans = container.query(l, r);
cout << ans << endl;
}
void action_update() {
int i, v;
cin >> i >> v;
if (i < 0 || i > container.size()) {
cout << "false" << endl;
return;
}
container.update(i, v);
cout << "true" << endl;
}
void action_dump() {
vector<int> buffer;
container.dump(buffer);
for (int i = 0; i < buffer.size(); ++i) {
if (i > 0) cout << " ";
cout << buffer[i];
}
cout << endl;
}
void setup(string& header, map<string,Command>& commands) {
header = "Sum Query using Sqrt Decomposition";
commands["init"] = { "init {size} {min} {max}", action_init };
commands["max"] = { "max {l} {r}", action_query };
commands["update"] = { "update {index} {value}", action_update };
commands["dump"] = { "dump", action_dump };
} | [
"xirckey@gmail.com"
] | xirckey@gmail.com |
5a67258e72d51680589fdce4a3514a73b787667b | a871da148c720bc4d0962900712dba2df432243f | /Week_06/322.零钱兑换--动态规划.cpp | 752db491eb00b7dd4a7a978445fabd4fe387d6b9 | [] | no_license | stephenhe/algorithm016 | 452687da68055598a188a7c869da455cf15fbfdc | a1de418fec29b3704a82d1aa749c87454ebce203 | refs/heads/master | 2023-01-27T20:47:15.452813 | 2020-12-08T13:41:45 | 2020-12-08T13:41:45 | 293,403,372 | 0 | 0 | null | 2020-09-07T02:32:38 | 2020-09-07T02:32:37 | null | UTF-8 | C++ | false | false | 1,601 | cpp | /*
* @lc app=leetcode.cn id=322 lang=cpp
*
* [322] 零钱兑换
*
* https://leetcode-cn.com/problems/coin-change/description/
*
* algorithms
* Medium (41.65%)
* Likes: 873
* Dislikes: 0
* Total Accepted: 144.9K
* Total Submissions: 347.9K
* Testcase Example: '[1,2,5]\n11'
*
* 给定不同面额的硬币 coins 和一个总金额
* amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。
*
* 你可以认为每种硬币的数量是无限的。
*
*
*
* 示例 1:
*
*
* 输入:coins = [1, 2, 5], amount = 11
* 输出:3
* 解释:11 = 5 + 5 + 1
*
* 示例 2:
*
*
* 输入:coins = [2], amount = 3
* 输出:-1
*
* 示例 3:
*
*
* 输入:coins = [1], amount = 0
* 输出:0
*
*
* 示例 4:
*
*
* 输入:coins = [1], amount = 1
* 输出:1
*
*
* 示例 5:
*
*
* 输入:coins = [1], amount = 2
* 输出:2
*
*
*
*
* 提示:
*
*
* 1
* 1
* 0
*
*
*/
// @lc code=start
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
if (amount == 0) return 0;
if (coins.size() == 0) return -1;
vector<int> dp(amount+1, amount+1);
dp[0] = 0;
for (int i = 1; i <= amount; i++) {
for (int coin : coins) {
if (i - coin >= 0)
dp[i] = min(dp[i], dp[i - coin] + 1);
}
}
return dp[amount] == amount + 1 ? -1 : dp[amount];
}
};
// @lc code=end
| [
"songlinhe@hotmail.com"
] | songlinhe@hotmail.com |
62e3fd3620c27d8fa02edaf2be61c14d77e3653a | 21ab8235a1deadbd3914c15645226ca45978b1ad | /binary_string_to_subsequences.cpp | 9193c27119f7f3ace8d35a42b0a6b872fd4398be | [] | no_license | surarijit/DSA_ALGO | 8a9079c71444928f88995679d16dafb50df8be5b | 1e1a1e189c9cd11b222150df2aa89952cb15de8d | refs/heads/master | 2023-01-29T04:36:49.892183 | 2020-12-07T07:01:47 | 2020-12-07T07:01:47 | 281,638,964 | 0 | 4 | null | 2021-10-01T10:58:11 | 2020-07-22T09:50:53 | C++ | UTF-8 | C++ | false | false | 1,336 | cpp | //Tell your code to believe in God
//@surcode
#include<bits/stdc++.h>
#define max(a,b) (a>b?a:b)
#define min(a,b) (a<b?a:b)
#define abs(a) (a>0?a:-a)
#define all(a) a.begin(),a.end()
#define pb push_back
#define sort(a) sort(all(a))
#define display(a) {for(int i=0;i<a.size();i++) cout<<a[i]<<" "; cout<<endl;}
#define IOS ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
using namespace std;
typedef long long ll;
int main()
{
IOS
int t,n;
cin>>t;
while(t--){
cin>>n;
string s;
cin>>s;
unordered_map<int,char> ma;
//cout<<ma.size()<<endl;continue;
vector<int> ans;
int j=0,i;
while(j<n){
if(s[j++]=='0'){
for(i=1;i<=ma.size();i++){
if(ma[i]=='1'){
ma[i] = '0';
break;
}
}
if(i==ma.size()+1) ma[i] = '0';
}
else{
for( i=1;i<=ma.size();i++){
if(ma[i]=='0'){
ma[i] = '1';
break;
}
}
if(i==ma.size()+1) ma[i] = '0';
}
ans.pb(i);
}
cout<<ma.size()<<endl;
display(ans);
}
return 0;
} | [
"arijit.sur1998@gmail.com"
] | arijit.sur1998@gmail.com |
41725e4dcb95f599db745fcfd84c3de9b2eac77b | f16a32a85f2f94e8d54f5fffe7f3381100bd879f | /src/test/multisig_tests.cpp | b3d0fd3a7c05fce6dcd389a8cbe0b2e97424b0c3 | [
"MIT"
] | permissive | Babocoin/Babocoin | 978ea6d2a4b7eb400b9d83bb7da99419f71c8f51 | 5dc79c49efb13851eb55436d05fd18a8bbafad78 | refs/heads/main | 2023-03-21T10:24:29.294544 | 2021-03-11T01:09:14 | 2021-03-11T01:09:14 | 339,209,313 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,592 | cpp | // Copyright (c) 2011-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <key.h>
#include <keystore.h>
#include <policy/policy.h>
#include <script/script.h>
#include <script/script_error.h>
#include <script/interpreter.h>
#include <script/sign.h>
#include <script/ismine.h>
#include <uint256.h>
#include <test/test_babocoin.h>
#include <boost/test/unit_test.hpp>
BOOST_FIXTURE_TEST_SUITE(multisig_tests, BasicTestingSetup)
static CScript
sign_multisig(const CScript& scriptPubKey, const std::vector<CKey>& keys, const CTransaction& transaction, int whichIn)
{
uint256 hash = SignatureHash(scriptPubKey, transaction, whichIn, SIGHASH_ALL, 0, SigVersion::BASE);
CScript result;
result << OP_0; // CHECKMULTISIG bug workaround
for (const CKey &key : keys)
{
std::vector<unsigned char> vchSig;
BOOST_CHECK(key.Sign(hash, vchSig));
vchSig.push_back((unsigned char)SIGHASH_ALL);
result << vchSig;
}
return result;
}
BOOST_AUTO_TEST_CASE(multisig_verify)
{
unsigned int flags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC;
ScriptError err;
CKey key[4];
CAmount amount = 0;
for (int i = 0; i < 4; i++)
key[i].MakeNewKey(true);
CScript a_and_b;
a_and_b << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG;
CScript a_or_b;
a_or_b << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG;
CScript escrow;
escrow << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << ToByteVector(key[2].GetPubKey()) << OP_3 << OP_CHECKMULTISIG;
CMutableTransaction txFrom; // Funding transaction
txFrom.vout.resize(3);
txFrom.vout[0].scriptPubKey = a_and_b;
txFrom.vout[1].scriptPubKey = a_or_b;
txFrom.vout[2].scriptPubKey = escrow;
CMutableTransaction txTo[3]; // Spending transaction
for (int i = 0; i < 3; i++)
{
txTo[i].vin.resize(1);
txTo[i].vout.resize(1);
txTo[i].vin[0].prevout.n = i;
txTo[i].vin[0].prevout.hash = txFrom.GetHash();
txTo[i].vout[0].nValue = 1;
}
std::vector<CKey> keys;
CScript s;
// Test a AND b:
keys.assign(1,key[0]);
keys.push_back(key[1]);
s = sign_multisig(a_and_b, keys, txTo[0], 0);
BOOST_CHECK(VerifyScript(s, a_and_b, nullptr, flags, MutableTransactionSignatureChecker(&txTo[0], 0, amount), &err));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
for (int i = 0; i < 4; i++)
{
keys.assign(1,key[i]);
s = sign_multisig(a_and_b, keys, txTo[0], 0);
BOOST_CHECK_MESSAGE(!VerifyScript(s, a_and_b, nullptr, flags, MutableTransactionSignatureChecker(&txTo[0], 0, amount), &err), strprintf("a&b 1: %d", i));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_INVALID_STACK_OPERATION, ScriptErrorString(err));
keys.assign(1,key[1]);
keys.push_back(key[i]);
s = sign_multisig(a_and_b, keys, txTo[0], 0);
BOOST_CHECK_MESSAGE(!VerifyScript(s, a_and_b, nullptr, flags, MutableTransactionSignatureChecker(&txTo[0], 0, amount), &err), strprintf("a&b 2: %d", i));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
}
// Test a OR b:
for (int i = 0; i < 4; i++)
{
keys.assign(1,key[i]);
s = sign_multisig(a_or_b, keys, txTo[1], 0);
if (i == 0 || i == 1)
{
BOOST_CHECK_MESSAGE(VerifyScript(s, a_or_b, nullptr, flags, MutableTransactionSignatureChecker(&txTo[1], 0, amount), &err), strprintf("a|b: %d", i));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
}
else
{
BOOST_CHECK_MESSAGE(!VerifyScript(s, a_or_b, nullptr, flags, MutableTransactionSignatureChecker(&txTo[1], 0, amount), &err), strprintf("a|b: %d", i));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
}
}
s.clear();
s << OP_0 << OP_1;
BOOST_CHECK(!VerifyScript(s, a_or_b, nullptr, flags, MutableTransactionSignatureChecker(&txTo[1], 0, amount), &err));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_SIG_DER, ScriptErrorString(err));
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
{
keys.assign(1,key[i]);
keys.push_back(key[j]);
s = sign_multisig(escrow, keys, txTo[2], 0);
if (i < j && i < 3 && j < 3)
{
BOOST_CHECK_MESSAGE(VerifyScript(s, escrow, nullptr, flags, MutableTransactionSignatureChecker(&txTo[2], 0, amount), &err), strprintf("escrow 1: %d %d", i, j));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
}
else
{
BOOST_CHECK_MESSAGE(!VerifyScript(s, escrow, nullptr, flags, MutableTransactionSignatureChecker(&txTo[2], 0, amount), &err), strprintf("escrow 2: %d %d", i, j));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
}
}
}
BOOST_AUTO_TEST_CASE(multisig_IsStandard)
{
CKey key[4];
for (int i = 0; i < 4; i++)
key[i].MakeNewKey(true);
txnouttype whichType;
CScript a_and_b;
a_and_b << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG;
BOOST_CHECK(::IsStandard(a_and_b, whichType));
CScript a_or_b;
a_or_b << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG;
BOOST_CHECK(::IsStandard(a_or_b, whichType));
CScript escrow;
escrow << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << ToByteVector(key[2].GetPubKey()) << OP_3 << OP_CHECKMULTISIG;
BOOST_CHECK(::IsStandard(escrow, whichType));
CScript one_of_four;
one_of_four << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << ToByteVector(key[2].GetPubKey()) << ToByteVector(key[3].GetPubKey()) << OP_4 << OP_CHECKMULTISIG;
BOOST_CHECK(!::IsStandard(one_of_four, whichType));
CScript malformed[6];
malformed[0] << OP_3 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG;
malformed[1] << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_3 << OP_CHECKMULTISIG;
malformed[2] << OP_0 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG;
malformed[3] << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_0 << OP_CHECKMULTISIG;
malformed[4] << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_CHECKMULTISIG;
malformed[5] << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey());
for (int i = 0; i < 6; i++)
BOOST_CHECK(!::IsStandard(malformed[i], whichType));
}
BOOST_AUTO_TEST_CASE(multisig_Sign)
{
// Test SignSignature() (and therefore the version of Solver() that signs transactions)
CBasicKeyStore keystore;
CKey key[4];
for (int i = 0; i < 4; i++)
{
key[i].MakeNewKey(true);
keystore.AddKey(key[i]);
}
CScript a_and_b;
a_and_b << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG;
CScript a_or_b;
a_or_b << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG;
CScript escrow;
escrow << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << ToByteVector(key[2].GetPubKey()) << OP_3 << OP_CHECKMULTISIG;
CMutableTransaction txFrom; // Funding transaction
txFrom.vout.resize(3);
txFrom.vout[0].scriptPubKey = a_and_b;
txFrom.vout[1].scriptPubKey = a_or_b;
txFrom.vout[2].scriptPubKey = escrow;
CMutableTransaction txTo[3]; // Spending transaction
for (int i = 0; i < 3; i++)
{
txTo[i].vin.resize(1);
txTo[i].vout.resize(1);
txTo[i].vin[0].prevout.n = i;
txTo[i].vin[0].prevout.hash = txFrom.GetHash();
txTo[i].vout[0].nValue = 1;
}
for (int i = 0; i < 3; i++)
{
BOOST_CHECK_MESSAGE(SignSignature(keystore, txFrom, txTo[i], 0, SIGHASH_ALL), strprintf("SignSignature %d", i));
}
}
BOOST_AUTO_TEST_SUITE_END()
| [
"36169687+blockinator@users.noreply.github.com"
] | 36169687+blockinator@users.noreply.github.com |
a0e752fbd506141043fdf75792590808145f4ecd | 0e2b9eca49091b288666e4d7db9110758cd7520b | /Lab5/task3.cpp | af1cac374bd2aa7ebab93387cefb3336ba3b08f7 | [] | no_license | Labnann/OS_Lab | c2d42c917ea73c07ffe0da34d5217e4a1e0f42d3 | a92dec975f842042e02a60cac42c87ceb77ca967 | refs/heads/main | 2023-07-09T17:00:33.858896 | 2021-08-18T15:31:37 | 2021-08-18T15:31:37 | 391,399,002 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,960 | cpp | //SJF NP
#include <iostream>
#include <map>
#include <queue>
using namespace std;
class Process {
private:
int burstTime;
int priority;
string name;
int startTime = -1;
int arrivalTime;
int lastTime = 0;
private:
void work(int currentTime){
int timePassed = currentTime - lastTime+1;
this->burstTime--;
this->lastTime += timePassed;
}
public:
int getPriority() const {
return priority;
}
int getArrivalTime(){
return this->arrivalTime;
}
Process(int burstTime, int priority, string name, int arrivalTime) {
this->burstTime = burstTime;
this->priority = priority;
this->name = name;
this->arrivalTime = arrivalTime;
}
int getBurstTime() const {
return this->burstTime;
}
int getFinishTime(){
return lastTime;
}
int getStartTime() const{
return this->startTime;
}
int getResponseTime(){
return startTime - arrivalTime;
}
int getWaitingTime(){
return startTime-arrivalTime;
}
bool done(){
return this->burstTime<=0;
}
string getName(){
return this->name;
}
void execute(int currentTime){
this->startTime = (this->startTime == -1) ? currentTime : this->startTime;
work(currentTime);
}
};
class JobQueue {
map<int, queue<Process *>> processQueue;
public:
auto getProcess(int time) {
return processQueue[time];
}
void addProcess(int time, Process *process) {
processQueue[time].push(process);
}
};
void executeProcess();
void propagateToReadyQueue(queue<Process *> &processes);
void printStatus();
void defineTasks(JobQueue *taskArrival) {
auto* p1 = new Process(13,3,"P1",2);
taskArrival->addProcess(2,p1);
auto* p2 = new Process(1,1,"P2",0);
taskArrival->addProcess(0,p2);
auto* p3 = new Process(2,3,"P3",1);
taskArrival->addProcess(1,p3);
auto* p4 = new Process(16,4,"P4",3);
taskArrival->addProcess(3,p4);
auto* p5 = new Process(7,2,"P5",5);
taskArrival->addProcess(7,p5);
}
struct LessBurst
{
bool operator()(const Process * lhs, const Process * rhs) const
{
return lhs->getBurstTime() > rhs->getBurstTime();
}
};
#define SIMULATION_TIME 1000
priority_queue <Process*, vector<Process*>, LessBurst> readyQueue;
queue <Process*> finishedQueue;
auto *pJobQueue = new JobQueue();
int worldTime = 0;
int main() {
defineTasks(pJobQueue);
for ( worldTime = 0; worldTime < SIMULATION_TIME; worldTime++) {
auto processes =pJobQueue->getProcess(worldTime);
propagateToReadyQueue(processes);
executeProcess();
}
printStatus();
return 0;
}
void printStatus() {
while (!finishedQueue.empty()){
auto finished = finishedQueue.front();
finishedQueue.pop();
cout << "\n";
cout << "Process "<< finished->getName() <<":\n";
cout << "Start Time "<< finished->getStartTime() <<":\n";
cout << "Finish Time "<< finished->getFinishTime() <<":\n";
cout << "Response Time "<< finished->getResponseTime() <<":\n";
cout << "Waiting Time "<< finished->getWaitingTime() <<":\n";
}
}
void propagateToReadyQueue(queue<Process *> &processes) {
while(!processes.empty()){
auto *process = processes.front();
readyQueue.push(process);
processes.pop();
}
}
Process *currentProcess = nullptr;
void executeProcess() {
if (readyQueue.empty() && currentProcess== nullptr)
return;
if (currentProcess == nullptr) {
currentProcess = readyQueue.top();
readyQueue.pop();
}
auto process = currentProcess;
process->execute(worldTime);
if (process->done()) {
cout << "-->" << process->getName();
finishedQueue.push(process);
currentProcess = nullptr;
}
} | [
"khalidmasum@iut-dhaka.edu"
] | khalidmasum@iut-dhaka.edu |
0e21f1ffb9a8ebcd25fd5549ec352c5f6196c36d | 711e5c8b643dd2a93fbcbada982d7ad489fb0169 | /XPSP1/NT/com/ole32/ih/rothint.hxx | 6accdd368d77dfeab5cd87a55762cdcd7e9952fe | [] | no_license | aurantst/windows-XP-SP1 | 629a7763c082fd04d3b881e0d32a1cfbd523b5ce | d521b6360fcff4294ae6c5651c539f1b9a6cbb49 | refs/heads/master | 2023-03-21T01:08:39.870106 | 2020-09-28T08:10:11 | 2020-09-28T08:10:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,439 | hxx | //+-------------------------------------------------------------------------
//
// Microsoft Windows
// Copyright (C) Microsoft Corporation, 1992 - 1993.
//
// File: rothint.hxx
//
// Contents: Base class for ROT hint table used in NT
//
// History: 24-Jan-95 Ricksa Created
//
//--------------------------------------------------------------------------
#ifndef __ROTHINT_HXX__
#define __ROTHINT_HXX__
// Size of the hint table and size of the SCM's hash table for the ROT.
#define SCM_HASH_SIZE 251
// Name of hint table for non-NT1X
#define ROTHINT_NAME L"Global\\RotHintTable"
#if 1 // #ifndef _CHICAGO_
//+-------------------------------------------------------------------------
//
// Class: CRotHintTable (rht)
//
// Purpose: Base class for hint table shared between SCM and OLE32.
// It is designed to abstract what is fundamental an array
// of on/off switches.
//
// Interface: SetIndicator - set indicator byte
// ClearIndicator - clear indicator byte
// GetIndicator - get indicator byte.
//
// History: 24-Jan-93 Ricksa Created
//
// Notes:
//
//--------------------------------------------------------------------------
class CRotHintTable
{
public:
CRotHintTable(void);
void SetIndicator(DWORD dwOffset);
void ClearIndicator(DWORD dwOffset);
BOOL GetIndicator(DWORD dwOffset);
protected:
// This memory is allocated by the derived class.
// The SCM actually creates the memory while the
// client just opens the memory.
BYTE * _pbHintArray;
};
//+-------------------------------------------------------------------------
//
// Member: CRotHintTable::CRotHintTable
//
// Synopsis: Initialize object
//
// History: 24-Jan-95 Ricksa Created
//
//--------------------------------------------------------------------------
inline CRotHintTable::CRotHintTable(void) : _pbHintArray(NULL)
{
// Header does all the work
}
//+-------------------------------------------------------------------------
//
// Member: CRotHintTable::SetIndicator
//
// Synopsis: Turn switch on
//
// History: 24-Jan-95 Ricksa Created
//
//--------------------------------------------------------------------------
inline void CRotHintTable::SetIndicator(DWORD dwOffset)
{
_pbHintArray[dwOffset] = TRUE;
}
//+-------------------------------------------------------------------------
//
// Member: CRotHintTable::ClearIndicator
//
// Synopsis: Turn switch off
//
// History: 24-Jan-95 Ricksa Created
//
//--------------------------------------------------------------------------
inline void CRotHintTable::ClearIndicator(DWORD dwOffset)
{
_pbHintArray[dwOffset] = FALSE;
}
//+-------------------------------------------------------------------------
//
// Member: CRotHintTable::GetIndicator
//
// Synopsis: Get the state of the switch
//
// History: 24-Jan-95 Ricksa Created
//
//--------------------------------------------------------------------------
inline BOOL CRotHintTable::GetIndicator(DWORD dwOffset)
{
return _pbHintArray[dwOffset];
}
#endif // !_CHICAGO_
#endif // __ROTHINT_HXX__
| [
"112426112@qq.com"
] | 112426112@qq.com |
95f51953913ae0ed01e65ba5dd11d732fb3733f0 | 83c140de645a85462429e3fd5af775a789551dda | /CourseBid/bid10192015 FINAL MERGE/Shenkar_CourseBidSystem/CourseBid_SecretaryTerminal/SecretaryMainScreen.h | 3238d1b4ce5b54cd93a62928ce1a6ac9a2622dd5 | [] | no_license | moshe31sh/Course_Bid_C-_Project | 1d6456676d78a1e484a13add431d15e8faf28caf | 1bbedd1f0b4100e14d7e9ff8a6ebd6ab99ff6a63 | refs/heads/master | 2021-01-10T06:10:00.993904 | 2015-11-05T16:41:39 | 2015-11-05T16:41:39 | 45,624,303 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,031 | h | /* ---------------------------------------------------------------------------
** This software is Shenkar College for Engineering and Design final submission
** for course "Tools of Software Engineering".
** Authors: <Ohad Sasson, Moshe Shimon, Yaron Israeli, Maor Toubian, Yossi Gleyzer
**
** SecretaryMainScreen.h
** <very brief file description>
**
** Author: <original author>
** -------------------------------------------------------------------------*/
#ifndef SECRETARYMAINSCREEN_H
#define SECRETARYMAINSCREEN_H
#include <iostream>
#include <cstdint>
#include <vector>
using namespace std;
#include "UIMainScreen.h"
#include "Course.h"
#include "Student.h"
#include "SetExpressionScreen.h"
#include "LockRegistrationScreen.h"
#include "TerminalObj.h"
#include "Terminal.h"
#include "CourseEditScreen.h"
#include <time.h>
#include "StudentAddNewScreen.h"
#include "StudentEditScreen.h"
#include "CourseAddNewScreen.h"
#include "AssignmentCalculator.h"
#include "SystemTime.h"
#include "SetRegistrationStartDateScreen.h"
//#include "Expression.h"
#define CLEAN cout<<"\nPlease press any key to continue"<<endl; fflush(stdin); getchar(); system("cls");
#define CLEAN1 cout<<"\nPlease press any key to continue"<<endl; fflush(stdin); getchar();
#define lOGO cout<<"\t\t\t----Course bid - Shenkar----\n"<<endl;
class SecretaryMainScreen : public UIMainScreen {
private:
SystemTime::CourseBidTime changeScreen;
void changeSrceenByTime();
void preRegistrationMenu(FileStorage *);
void registrationMenu(FileStorage *);
void postRegistrationMenu(FileStorage *);
public:
SecretaryMainScreen();
vector<Course*> getCourseList();
vector<Student*> getStudentList();
void getAssignitionResultsCourses();
void getAssignitionResultsStudents();
bool lockTerminal(bool status);
string getRegistrationStartDate();
bool releaseTerminalScreen();
bool studentUnlockScreen();
bool studentResetPassScreen();
void show();
};
#endif SECRETARYMAINSCREEN_H | [
"moshe31sh@gmail.com"
] | moshe31sh@gmail.com |
a79537cfac3dd965acef7bc1c33b3bb383e4fbed | 584fb69896f39590bbf43e3d4221dbbeb07b5a5d | /source/LibFgWin/FgGuiWinRadio.cpp | a53fe7359e36b699c2b9fc244372a72042a70f75 | [
"MIT"
] | permissive | leo92613/FaceGenBaseLibrary | d94bf9f67cc2bc95e05b368945b5a6cdb58e24b7 | 97c9a80a232dc10281d8fc52c11f1b6d0b17552a | refs/heads/master | 2022-03-15T04:44:31.948009 | 2019-11-28T13:21:55 | 2019-11-28T13:21:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,326 | cpp | //
// Copyright (c) 2019 Singular Inversions Inc. (facegen.com)
// Use, modification and distribution is subject to the MIT License,
// see accompanying file LICENSE.txt or facegen.com/base_library_license.txt
//
//
#include "stdafx.h"
#include "FgGuiApiRadio.hpp"
#include "FgGuiWin.hpp"
#include "FgThrowWindows.hpp"
using namespace std;
namespace Fg {
static Vec2UI s_pad(40,12);
struct GuiRadioWin : public GuiBaseImpl
{
GuiRadio m_api;
DfgFPtr updateFlag;
HWND hwndThis;
vector<HWND> m_hwnds;
vector<Vec2UI> m_sizes;
GuiRadioWin(const GuiRadio & api)
: m_api(api), updateFlag(makeUpdateFlag(m_api.selection))
{}
virtual void
create(HWND parentHwnd,int ident,Ustring const &,DWORD extStyle,bool visible)
{
//fgout << fgnl << "GuiRadioWin::create " << m_api.labels[0];
WinCreateChild cc;
cc.extStyle = extStyle;
cc.visible = visible;
winCreateChild(parentHwnd,ident,this,cc);
}
virtual void
destroy()
{
// Automatically destroys children first:
DestroyWindow(hwndThis);
}
virtual Vec2UI
getMinSize() const
{
Vec2UI sz;
uint dimAcc = (m_api.horiz ? 0 : 1),
dimMax = 1 - dimAcc;
for (size_t ii=0; ii<m_sizes.size(); ++ii) {
setIfGreater(sz[dimMax],m_sizes[ii][dimMax]);
sz[dimAcc] += m_sizes[ii][dimAcc] + s_pad[dimAcc];
}
sz[dimMax] += s_pad[dimMax];
return sz;
}
virtual Vec2B
wantStretch() const
{return Vec2B(false,false); }
virtual void
updateIfChanged()
{
if (updateFlag->checkUpdate())
updateRadio();
}
virtual void
moveWindow(Vec2I lo,Vec2I sz)
{
//fgout << fgnl << "GuiRadioWin::moveWindow " << lo << " , " << sz;
MoveWindow(hwndThis,lo[0],lo[1],sz[0],sz[1],FALSE);
}
virtual void
showWindow(bool s)
{ShowWindow(hwndThis,s ? SW_SHOW : SW_HIDE); }
LRESULT
wndProc(HWND hwnd,UINT message,WPARAM wParam,LPARAM lParam)
{
switch (message)
{
case WM_CREATE:
{
//fgout << fgnl << "GuiRadioWin::WM_CREATE " << m_api.labels[0];
hwndThis = hwnd;
m_sizes.resize(m_api.labels.size());
m_hwnds.resize(m_api.labels.size());
for (size_t ii=0; ii<m_api.labels.size(); ++ii) {
wstring wstr = m_api.labels[ii].as_wstring();
m_hwnds[ii] =
CreateWindowEx(0,
TEXT("button"),
wstr.c_str(),
WS_CHILD | WS_VISIBLE | BS_RADIOBUTTON,
0,0,0,0, // Generates WM_SIZE 0 message
hwnd,
HMENU(ii),
s_guiWin.hinst,
NULL); // No WM_CREATE parameter
FGASSERTWIN(m_hwnds[ii] != 0);
// I couldn't get the 'Button_GetIdealSize' macro to work; here, in WM_SIZE,
// with GuiButtonWin, with starting size arguments, whatever. This approach
// is more universal than just buttons anyway.
// Still only an approximate I think ... docs are complex:
SIZE sz;
GetTextExtentPoint32(GetDC(hwndThis),wstr.c_str(),int(wstr.size()),&sz);
m_sizes[ii] = Vec2UI(sz.cx,sz.cy);
}
updateRadio();
return 0;
}
case WM_SIZE:
{
//fgout << fgnl << "GuiRadioWin::WM_SIZE " << m_api.labels[0];
// Don't care what size params are since these controls stick to min size,
// but we still need to ignore Windows' initial zero-size message:
if (LOWORD(lParam) * HIWORD(lParam) == 0)
return 0;
Vec2UI szTot = getMinSize(),
pos,sz;
uint dimAcc = (m_api.horiz ? 0 : 1),
dimMax = 1 - dimAcc;
sz[dimMax] = szTot[dimMax];
for (uint ii=0; ii<m_hwnds.size(); ++ii) {
sz[dimAcc] = m_sizes[ii][dimAcc] + s_pad[dimAcc];
MoveWindow(m_hwnds[ii],pos[0],pos[1],sz[0],sz[1],TRUE);
pos[dimAcc] += sz[dimAcc];
}
return 0;
}
case WM_COMMAND:
{
WORD ident = LOWORD(wParam);
WORD code = HIWORD(wParam);
if (code == 0) { // radio box clicked
//fgout << fgnl << "GuiRadioWin::WM_COMMAND clicked " << m_api.labels[0];
size_t sel = ident;
if (sel >= m_api.labels.size())
sel = 0;
//fgout << " val: " << sel << " m_api.selection " << m_api.selection;
m_api.selection.set(sel);
//fgout << fgnl << "Update screen: " << flush << fgpush;
winUpdateScreen();
//fgout << fgpop << fgnl << "Updated " << flush;
}
return 0;
}
}
return DefWindowProc(hwnd,message,wParam,lParam);
}
void
updateRadio()
{
size_t val = m_api.selection.val();
if (val >= m_api.labels.size())
val = 0;
for (size_t ii=0; ii<m_hwnds.size(); ++ii) {
if (ii == val)
SendMessage(m_hwnds[ii],BM_SETCHECK,BST_CHECKED,0);
else
SendMessage(m_hwnds[ii],BM_SETCHECK,BST_UNCHECKED,0);
}
}
};
GuiImplPtr
guiGetOsImpl(const GuiRadio & def)
{return GuiImplPtr(new GuiRadioWin(def)); }
}
| [
"abeatty@facegen.com"
] | abeatty@facegen.com |
a2b198127e40d1398be97e438f3de83f570e8e46 | 8af639477e1b2747429671dc3124826c75950747 | /pftp.h | 44b8be869f4dbd8e5e1b88201cccd7c83f9360ab | [] | no_license | xlfdlihailong/pftp | 1d2e6212fd5215320e0cfd71cd4a3402420d5b7a | 19998b89ce012f448fdb75febeb7ec46e4c0136b | refs/heads/master | 2020-06-19T02:05:57.283269 | 2019-07-12T07:05:10 | 2019-07-12T07:05:10 | 196,526,995 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,912 | h | #ifndef PFTP_H
#define PFTP_H
#include "Ftp.h"
#include "../plib/plib.h"
#define CMD_BUF_SIZE 256
int GetRetCodeWithRecv(int iSock, int iCorrectCode,char* arrchRecv);
int SendFtpCmdWithRecv(int iSock, const char *pchCmd, char *arrchRecv);
class pftp
{
int sockStatus;//状态连接
string strIp;
string strUser;
string strPwd;
int iPort;
public:
//realip先设置为连接的ip,默认虚拟ip
string strRealIp;
//被动模式返回的端口
int iPortPasv;
pftp();
~pftp();
int connect(string ip, string user, string pwd,int port=21);
int reconnect();//一直重连,1s一次
int sendcmd(string cmd);
string pwd();
//相对路径
int cd(string strdes);
int quit();
//<0表示失败
long long getLength(string path);
int recvres(char* dataRecv,int len);
int isExsistDir(string path);
//被动模式,同时获取真实ip和端口,要在能访问的地方连接虚拟ip,否则不返回真实ip
int setPASV();
//默认自带断点续传,无限次数,直到传完才返回,支持服务端的断点续传
//支持递归文件夹传输,且支持递归文件夹的各个文件的断点续传
int upload(string strPathLocal, string strPathRemote);
//默认自带断点续传,无限次数,直到传完才返回,仅支持服务端的断点续传
//支持递归文件夹传输,且支持递归文件夹的各个文件的断点续传
int download(string strPathLocal, string strPathRemote, long lpos=0);
int UploadWithSpeedUpdateByXlfdInner(const char *pchLocalPath, const char *pchFtpPath, const char *pchPostfix , const int iPostfixFlag);
int DownloadWithSpeedUpdateByXlfdInner(const char *pchLocalPath, const char *pchFtpPath, const char *pchPostfix , const int iPostfixFlag);
};
#endif // PFTP_H
| [
"root@localhost.localdomain"
] | root@localhost.localdomain |
1293eb1727d8e7d9297dbe99af04d3819a122f2c | fa53215c65feeca53ecf48979db129b9eec77086 | /extensions/CocoStudio/Reader/WidgetReader/LabelBMFontReader/LabelBMFontReader.h | 6220b21891b92f70cab00b8b3aae7c88a8d81811 | [] | no_license | stubma/cocos2dx-classical | 66d57304dc1cc8834d672a087f2b979d0e1a993c | 42da4ee120ce9a0a97da344117c48e91c146c56d | refs/heads/master | 2021-01-24T08:17:10.706511 | 2018-05-30T03:04:10 | 2018-05-30T03:04:10 | 26,906,938 | 138 | 57 | null | null | null | null | UTF-8 | C++ | false | false | 1,922 | h | /****************************************************************************
Copyright (c) 2014 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __TestCpp__LabelBMFontReader__
#define __TestCpp__LabelBMFontReader__
#include "../WidgetReader.h"
NS_CC_EXT_BEGIN
class CC_DLL LabelBMFontReader : public WidgetReader
{
public:
DECLARE_CLASS_WIDGET_READER_INFO
LabelBMFontReader();
virtual ~LabelBMFontReader();
static LabelBMFontReader* getInstance();
static void purge();
virtual void setPropsFromJsonDictionary(ui::Widget* widget, const rapidjson::Value& options);
virtual void setPropsFromBinary(cocos2d::ui::Widget* widget, CocoLoader* pCocoLoader, stExpCocoNode* pCocoNode) ;
};
NS_CC_EXT_END
#endif /* defined(__TestCpp__LabelBMFontReader__) */
| [
"stubma@gmail.com"
] | stubma@gmail.com |
577dc283a5993a86cdc681a98a0335acca4d326c | e53e52b47df3798d8402bc6f2ee15d2a4e0c8326 | /cpp_cp_simd/main.cpp | 91f3137f6aad2e578b57039918e6b8f7758921d1 | [] | no_license | oalign/cpp_cp_simd | a9be8ff69094e28cb557aa7d2416149741bf6fc8 | bfac7da202d21788e5e350d32b01e6c6214b568a | refs/heads/master | 2020-04-12T11:20:28.709663 | 2018-12-19T15:27:55 | 2018-12-19T15:27:55 | 162,456,115 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 88 | cpp | #include <cstdio>
int main()
{
printf("hello from cpp_cp_simd!\n");
return 0;
} | [
"oferalign@gmail.com"
] | oferalign@gmail.com |
43c9c7b2aa735eb39ca8712d1a34e2ad7305d2a2 | 3be2ea1ba22256d9c5bb331b9fe053372bbfef2d | /TC-programs/OLD_CIS3D/PACKETS/mk_init_wav.cc | 39dff43e426015f8b5e2a7b1f8cd6f33c2e7b64b | [
"MIT"
] | permissive | sklinkusch/scripts | 5f6561974bf7ca1525ce4b6ddcc61bc21dca7313 | 91cad6f21d0fe4498fe591bce8ce8d52f4ffc4b2 | refs/heads/master | 2022-05-24T18:14:47.897169 | 2022-05-10T09:51:42 | 2022-05-10T09:51:42 | 153,755,308 | 0 | 0 | null | 2019-07-24T09:12:44 | 2018-10-19T09:00:45 | C++ | UTF-8 | C++ | false | false | 10,381 | cc | /********************************************************************************
* CIS3(D) Program suite *
* *
* file: mk_init_wav.cc *
* *
* computes initial wave function in *
* *
* 1. Eigenstate basis *
* 2. CSF basis *
* 3. Projected-MO CSFs *
* *
* Tillmann Klamroth 2005 *
********************************************************************************/
#include <fstream>
#include <math.h>
#include <limits.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <stdio.h>
#include <ctype.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <iostream>
#include <sstream>
#include <complex>
#include <stdlib.h>
using namespace std;
#define Complex complex<double>
//Functions
void check_range(int tomuch, int current_number, ofstream *outf);
//Extern Functions
extern int rem_com(char* filename, char* streamstring, int string_length);
extern void status(ofstream* outf);
extern void get_sys_size(char* sysfile, int* nroao, int* nroa, long long int* nrofint);
extern void read_sys_1el(char* sysfile, double* coord, double* charges, double* mass,
double* Hmat, double* Tmat, double* Smat, double* Dx, double* Dy,
double *Dz);
extern void read_wav_HF(char* wavfile, int nroao, double* MOens, double* MOs);
extern int pos_i_a(int i, int a, int omo, int umo, int llim);
extern void pmv(double* mat, double* vi, double* vo, int nroao);
int main(int argc, char* argv[]){
if(argc != 3){
cerr << "Need input-file output-prefix\n";
exit(1);
}
char dumc[2048];
sprintf(dumc,"%s.log",argv[2]);
ofstream outf(dumc);
outf << "MK_INI_WAV [CIS3(D) Suite]\n";
outf << "Execution started on/at:\n";
status(&outf);
outf << "-------------------------------------------------------------------------------\n";
outf << "Reading input form " << argv[1] << "\n\n";
//INPUT VARIABLES
//SYSTEM
char bcsfile[256]; //binary system file (CIS space)
//INITAL WAVE FUNCTION
int iwav_mode; //Mode for inital wave function creation
// 0 -> Eigenstate basis
// 1 -> CSF basis
// 2 -> Projected-MO CSFs
int buff_length = 65536;
char* file_buff = new char[buff_length];
rem_com(argv[1], file_buff, buff_length);
istringstream ist(file_buff);
ist >> bcsfile;
outf << "Binary system file (CIS space): " << bcsfile << "\n";
//CIS-VARIABLES
outf << "\nREADING CIS-SPACE\n";
int nroao;
int nroe; //Nr of electrons
int llim; //first MO used for correlation
int ulim; //last MO used for correlation
ifstream datf(bcsfile);
datf.read((char*) &nroao, sizeof(int));
datf.read((char*) &nroe, sizeof(int));
datf.read((char*) &llim, sizeof(int));
datf.read((char*) &ulim, sizeof(int));
outf << "CIS data read: \n";
int nrof = ulim - llim +1;
int omo = nroe/2 - llim;
int umo = ulim - nroe/2+1;
outf << "# MOs for correlation : " << nrof << "\n";
outf << "limits (l,u) : " << llim << " , " << ulim << "\n";
outf << "occupied : " << omo << "\n";
outf << "virtual : " << umo << "\n";
int cis_size = omo*umo+1;
long long int Cis_size = cis_size;
outf << "nr of CSF : " << cis_size << "\n";
outf << "Allocating Memory\n";
double* cisvecs = new double[(long long int) cis_size* (long long int) cis_size];
double* cis_vals = new double[cis_size]; //CIS (or CIS(D) eigenvalues)
double* dumv = new double[cis_size]; //temporary space
Complex* wav = new Complex[cis_size]; //Time dependent wave function (eigen state basis)
Complex* SEwav = new Complex[cis_size]; //Time dependent wave function (CSF basis)
for(int x = 0; x < cis_size; x++)
wav[x] = SEwav[x] = 0.;
outf << "Reading data\n";
datf.read((char *) cis_vals, cis_size * sizeof(double));
datf.read((char *) cisvecs, (long long int) cis_size * (long long int) cis_size * sizeof(double));
outf << "-------------------------------------------------------------------------------\n";
datf.close();
ist >> iwav_mode;
outf << "iwav_mode is " << iwav_mode << "\n";
outf << "-------------------------------------------------------------------------------\n";
if(iwav_mode == 0){
outf << "Constructing inital wave in eigenstate basis\n";
//Eigenstate basis
int i_state; //inital state
ist >> i_state;
outf << "Initial state is " << i_state << "\n";
wav[i_state] = 1.;
}
if(iwav_mode == 1){
//CSF basis
int nroin; //Number of initial states
ist >> nroin;
int i_MO, f_MO; //Numbers of initial and final MOs
outf << "Constructing inital wave in CSF basis\n";
for(int j = 0; j < nroin; j++){
ist >> i_MO >> f_MO;
ist >> SEwav[pos_i_a(i_MO, f_MO, omo, umo, llim)];
outf << "Inital MO is " << i_MO << " with coefficient " << SEwav[pos_i_a(i_MO, f_MO, omo, umo, llim)] << "\n";
outf << "Final MO is " << f_MO << "\n";}
for(long long int x = 0; x < Cis_size; x++){
for(long long int y = 0; y < Cis_size; y++){
wav[x] += cisvecs[x*Cis_size+y]*SEwav[y];
}
}
}
if(iwav_mode == 2){
//Projected-MO CSFs
char sysfile[256];
char hfwfile[256];
int nroa;
ist >> sysfile >> hfwfile;
outf << "Sysfile: " << sysfile << "\n";
outf << "HF-wavefunction: " << hfwfile << "\n";
double* i_MO = new double[nroao];
double* f_MO = new double[nroao];
double* pro_i = new double[nroao]; //Projections on HF orbitals
double* pro_f = new double[nroao]; //Projections on HF orbitals
for(int x = 0; x < nroao; x++)
i_MO[x] = f_MO[x] = pro_i[x] = pro_f[x] = 0.;
long long int nrofint; //Nr of two electron Integrals (not used here)
get_sys_size( sysfile, &nroao, &nroa, &nrofint);
outf << "System sizes read from " << sysfile << "\n";
outf << "Nr of basis functions: " << nroao << "\n";
outf << "Nr of atoms: " << nroa << "\n";
outf << "Allocating Memory\n";
double* MOs = new double[nroao*nroao];
double* Smat = new double[nroao*nroao];
double* dumvec = new double[nroao];
outf.flush();
read_sys_1el(sysfile, MOs, MOs, MOs, MOs, MOs, Smat, MOs, MOs, MOs);
read_wav_HF(hfwfile, nroao, dumvec, MOs);
int nc_i, nc_f;
int nc;
double pop;
ist >> nc_i;
outf << "Reading " << nc_i << " coeffs for the inital Orbital\n";
for(int x = 0; x < nc_i; x ++){
ist >> nc;
ist >> i_MO[nc];
outf << nc << " " << i_MO[nc] << "\n";
}
ist >> nc_f;
outf << "Reading " << nc_f << " coeffs for the final Orbital\n";
for(int x = 0; x < nc_f; x ++){
ist >> nc;
ist >> f_MO[nc];
outf << nc << " " << f_MO[nc] << "\n";
}
outf << "\n\n Calculationg projections on HF orbitals\n";
pmv(Smat, i_MO , dumvec, nroao);
for(int x = 0; x < nroao; x++){
for(int y = 0; y < nroao; y++)
pro_i[x] += dumvec[y]*MOs[x*nroao+y];
}
pmv(Smat, f_MO , dumvec, nroao);
for(int x = 0; x < nroao; x++){
for(int y = 0; y < nroao; y++)
pro_f[x] += dumvec[y]*MOs[x*nroao+y];
}
outf << "-------------------------------------------------------------------------------\n";
for(int x = 0; x < nroao; x++)
outf << x << "\t" << pro_i[x] << "\t" << pro_f[x] << "\n";
pop = 0.; for(int x = 0; x < nroao; x++) pop += pow( pro_i[x],2);
outf << "\nTotal population of inital MO in HF-MOs: " << pop << "\n";
pop = 0.; for(int x = 0; x < nroe/2; x++) pop += pow( pro_i[x],2);
outf << "Population of inital MO in occ-HF-MOs: " << pop << "\n";
pop = 0.; for(int x = llim; x < nroe/2; x++) pop += pow( pro_i[x],2);
outf << "Population of inital MO in active occ-HF-MOs: " << pop << "\n";
pop = 0.; for(int x = 0; x < nroao; x++) pop += pow( pro_f[x],2);
outf << "\nTotal population of final MO in HF-MOs: " << pop << "\n";
pop = 0.; for(int x = nroe/2; x < nroao; x++) pop += pow( pro_f[x],2);
outf << "Population of final MO in virt-HF-MOs: " << pop << "\n";
pop = 0.; for(int x = nroe/2; x <= ulim; x++) pop += pow( pro_f[x],2);
outf << "Population of inital MO in active virt-HF-MOs: " << pop << "\n";
outf << "\nConstructing inital wave function\n";
double wav_norm = 0.;
for(int x = 1; x < cis_size; x++){
int i1 = (x-1)/umo+llim;
int f1 = (x-1)%umo+omo+llim;
SEwav[x] = pro_i[i1]*pro_f[f1];
wav_norm += norm(SEwav[x]);
}
outf << "Initial norm is: " << wav_norm << "\n";
outf << "Renorming.\n";
for(int x = 0; x < cis_size; x++)
SEwav[x] /= sqrt(wav_norm);
for(long long int x = 0; x < Cis_size; x++){
for(long long int y = 0; y < Cis_size; y++){
wav[x] += cisvecs[x*Cis_size+y]*SEwav[y];
}
}
}
outf << "-------------------------------------------------------------------------------\n";
double curr_time = 0.;
sprintf(dumc,"%s.iwav",argv[2]);
ofstream wavf(dumc);
outf << "Writing initial wave function to " << dumc << "\n";
wavf.write((char* ) &curr_time, sizeof(double));
wavf.write((char* ) wav, sizeof(Complex)*cis_size);
wavf.flush();
}
void check_range(int tomuch, int current_number, ofstream *outf){
if( current_number < 0 || current_number >= tomuch){
*outf << "Invalid input: " << current_number << "\n";
outf->flush(); exit(1);
}
}
| [
"stefan.klinkusch@googlemail.com"
] | stefan.klinkusch@googlemail.com |
1f27027191e0f97eb58dba77f6509121685d1dab | 10ed683bcd2ba0ade6095975014f5c43d6ad55e6 | /Algorithms/MaterialMapping/include/ACTFW/MaterialMapping/MaterialMapping.hpp | ecd719027f05c99f94de1b78a5a6fd431fd3c472 | [] | no_license | Sharad24/acts-framework | a922dabeaa3abc548b3fd3c7852f273227323e67 | 452fdc841a3fd31d6b76baabfd6ca529647baa12 | refs/heads/master | 2022-12-13T01:31:22.160636 | 2020-03-11T08:52:08 | 2020-03-11T08:52:08 | 204,444,776 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,536 | hpp | // This file is part of the Acts project.
//
// Copyright (C) 2017 Acts project team
//
// 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 ACTFW_ALGORITHMS_MATERIALMAPPING_MATERIALMAPPING_H
#define ACTFW_ALGORITHMS_MATERIALMAPPING_MATERIALMAPPING_H
#include <climits>
#include <memory>
#include "ACTFW/Framework/BareAlgorithm.hpp"
#include "ACTFW/Framework/ProcessCode.hpp"
#include "ACTFW/Readers/IReaderT.hpp"
#include "ACTFW/Writers/IWriterT.hpp"
#include "Acts/Layers/Layer.hpp"
#include "Acts/Material/SurfaceMaterial.hpp"
#include "Acts/Plugins/MaterialMapping/MaterialMapper.hpp"
#include "Acts/Plugins/MaterialMapping/MaterialTrack.hpp"
#include "Acts/Utilities/Logger.hpp"
namespace FW {
class WhiteBoard;
}
namespace Acts {
class TrackingGeometry;
}
namespace FW {
/// @class MaterialMapping
///
/// @brief Initiates material mapping
///
/// The MaterialMapping reads in the MaterialTrack with a dedicated
/// reader and uses the material mapper to project the material onto
/// the tracking geometry
///
/// In a final step, the material maps are written out for further usage
class MaterialMapping : public FW::BareAlgorithm
{
public:
/// @class nested Config class
/// of the MaterialMapping algorithm
struct Config
{
public:
/// The reader to read in the MaterialTrack entities
std::shared_ptr<FW::IReaderT<Acts::MaterialTrack>> materialTrackReader
= nullptr;
/// The ACTS material mapper
std::shared_ptr<Acts::MaterialMapper> materialMapper = nullptr;
/// The validation writer of the material
std::shared_ptr<FW::IWriterT<Acts::MaterialTrack>> materialTrackWriter
= nullptr;
/// The writer of the material
std::shared_ptr<FW::IWriterT<Acts::IndexedSurfaceMaterial>>
indexedMaterialWriter = nullptr;
/// The TrackingGeometry to be mapped on
std::shared_ptr<const Acts::TrackingGeometry> trackingGeometry = nullptr;
/// mapping conditions
size_t maximumTrackRecords = std::numeric_limits<size_t>::infinity();
};
/// Constructor
MaterialMapping(const Config& cfg,
Acts::Logging::Level level = Acts::Logging::INFO);
/// Framework execute method
FW::ProcessCode
execute(const AlgorithmContext& context) const final override;
private:
Config m_cfg;
};
} // namespace FW
#endif // ACTFW_ALGORITHMS_MATERIALMAPPING_MATERIALMAPPING_H
| [
"f20170472@goa.bits-pilani.ac.in"
] | f20170472@goa.bits-pilani.ac.in |
5fa83fefcbd729bb9e77bff91006f7667b5de71f | c982493958badefd13ebecf0f8523c3d3ac414bd | /Plugins/TextureHelper/Private/TextureRuntimeImporter/RTIBlueprintFunctionLibrary.cpp | 3404f0f1d6e244c6100e3e31832c21cc18a4d329 | [] | no_license | XavierLynn/SmartCity | 5e44eee8660b67bec53b69762bff00f0bc3e7bc1 | 1102a5c5bc4c3bb626d1103ae6ea5451fa6de90e | refs/heads/master | 2023-05-09T16:16:48.564967 | 2021-06-04T10:10:52 | 2021-06-04T10:10:52 | 330,520,955 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 750 | cpp | // Copyright 2020 byTangs, All Rights Reserved.
#include "RTIBlueprintFunctionLibrary.h"
#include "TextureImporter.h"
#include "Kismet/KismetStringLibrary.h"
UTexture2D* URTIBlueprintFunctionLibrary::ImportTexture(const FString& Filename)
{
return EMEngine::FTextureImporter::Get()->ImportTexture(Filename);
}
UTexture2D* URTIBlueprintFunctionLibrary::LoadTextureFormContentPath(UObject* Outer,const FString& TexturePath)
{
if(TexturePath.IsEmpty())
return nullptr;
int32 FirstIndex = 0;
FirstIndex = TexturePath.Find(TEXT("/"));
const FString ObjectPath = UKismetStringLibrary::GetSubstring(TexturePath,FirstIndex,TexturePath.Len() - 1 - FirstIndex);
return LoadObject<UTexture2D>(Outer,*ObjectPath);
}
| [
"Administrator@DESKTOP-CKU0KSV"
] | Administrator@DESKTOP-CKU0KSV |
7ea5744d68062c9db77488f2034e2b28ac2f6acf | f371a1e57b354cc1b985dbfc17f057c186d9f7a0 | /acmicpc.net/source/9654.cpp | dc1ae5e29fd77ff6570ba7634c43df7fe0cef87d | [
"MIT"
] | permissive | tdm1223/Algorithm | 7ea3d79eaa7244a1cfe8a420e25d89b783465e8f | c773ab0338e5a606ad0fc7d8989b0ee7cc1bf3fa | refs/heads/master | 2022-11-14T01:34:08.955376 | 2022-10-30T11:00:54 | 2022-10-30T11:00:54 | 143,304,153 | 8 | 9 | null | 2019-08-06T02:41:24 | 2018-08-02T14:16:00 | C++ | UTF-8 | C++ | false | false | 578 | cpp | // 9654. 나부 함대 데이터
// 2020.10.11
// 구현
#include<iostream>
using namespace std;
int main()
{
cout << "SHIP NAME CLASS DEPLOYMENT IN SERVICE" << endl;
cout << "N2 Bomber Heavy Fighter Limited 21 " << endl;
cout << "J-Type 327 Light Combat Unlimited 1 " << endl;
cout << "NX Cruiser Medium Fighter Limited 18 " << endl;
cout << "N1 Starfighter Medium Fighter Unlimited 25 " << endl;
cout << "Royal Cruiser Light Combat Limited 4 " << endl;
return 0;
}
| [
"tdm1223@naver.com"
] | tdm1223@naver.com |
9912fbd59923784eaf3419ab99e8f5c88641dcd0 | a35b30a7c345a988e15d376a4ff5c389a6e8b23a | /boost/smart_ptr/detail/lwm_nop.hpp | 08ec11bbc64e021494ecbb3f772502f7ebb33a79 | [] | no_license | huahang/thirdparty | 55d4cc1c8a34eff1805ba90fcbe6b99eb59a7f0b | 07a5d64111a55dda631b7e8d34878ca5e5de05ab | refs/heads/master | 2021-01-15T14:29:26.968553 | 2014-02-06T07:35:22 | 2014-02-06T07:35:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 70 | hpp | #include "thirdparty/boost_1_55_0/boost/smart_ptr/detail/lwm_nop.hpp"
| [
"liuhuahang@xiaomi.com"
] | liuhuahang@xiaomi.com |
7c82059289e2495ed5efc0edba3d58157ca69cd5 | 9aa576523ebaab4cf2060abcd9146482cef40c4a | /project-3-mason-and-wang-master/src/Node.hpp | 80313634c4023cbd1b7a0deb959c185d3e79de18 | [] | no_license | Mason961201/CS100-project3 | 3dcb16c2acd77b608a2eed3aae4b2e294c64550f | 9ae326c3d8d76dd7dac1a67e3a9e6c24f7fae68d | refs/heads/main | 2023-07-06T19:44:57.978012 | 2021-08-14T00:04:08 | 2021-08-14T00:04:08 | 395,834,294 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 843 | hpp | #ifndef NODE_HPP
#define NODE_HPP
#include <iostream>
#include <vector>
#include <limits>
using namespace std;
/*
* Node class has four fields:
* id is the id for the person
* adj is the vector of all friends the person has
* dist is the distance between this node with others (we used in findpath)
* prev is the the previous nodes it comes from
*/
class Node{
public:
int const id;
vector<int> adj;
int dist;
Node* prev;
int degree;
bool visit;
bool visit1;
Node(const int & d): id(d) {
adj = {};
visit1 = false;
dist = numeric_limits<int>::max();
prev = nullptr;
degree = 0;
visit = false;
}
bool operator<(const Node& other);
bool operator==(const Node& other);
bool operator!=(const Node& other);
void push (int a);
};
#endif // NODE_HPP
| [
"noreply@github.com"
] | Mason961201.noreply@github.com |
1c162cb0703e37870d4dd5cb16f6c0e1b2142937 | 63f42c100ca2bab04d0f24a5b77392a21fb1a82f | /Bada-Boom!!/Testing Box/Bada-Boom!! Project/Code/SpriteMan.h | f56b5c313b2f5e279a19f08400698fc91a9971d1 | [] | no_license | LuisRangel-person/Bada-Boom | 9ec19190fff4c1284e0b50fca43e75ea0fd79238 | dd426cd03895c14d9ee0bd3125d66e5050d72346 | refs/heads/master | 2021-01-21T07:00:20.279198 | 2019-04-21T16:35:50 | 2019-04-21T16:35:50 | 82,877,879 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 826 | h | /// \file SpriteMan.h
/// \brief Interface for the sprite manager class CSpriteManager.
#pragma once
#include "defines.h"
#include "sprite.h"
/// \brief The sprite manager.
///
/// The sprite manager is responsible for managing sprites.
class CSpriteManager{
private:
C3DSprite* m_pSprite[NUM_OBJECT_TYPES]; ///< Sprite pointers.
char m_pBuffer[MAX_PATH]; ///< File name buffer.
C3DSprite* Load(ObjectType object,
const char* file, const char* ext, int frames); ///< Load sprite.
public:
CSpriteManager(); ///< Constructor.
~CSpriteManager(); ///< Destructor.
void Load(ObjectType object, char* name); ///< Load sprite.
C3DSprite* GetSprite(ObjectType object); ///< Get sprite for object.
void Release(); ///< Release all sprites.
}; //CSpriteManager
| [
"luisrangel.person@gmail.com"
] | luisrangel.person@gmail.com |
b94bf569f8544befcd8b26055b2454c1cddb8ee2 | cc19192f1773fd5bcb0869a61171e865ed20aa94 | /ElementalRoguelite/ECS/Components/Headers/GraphicComponent.hpp | 2cb3e5e9e0eff38b449864a660dee5d7afc64a89 | [] | no_license | DBurden1997/ElementalRoguelite | 27b7912b65a6407edb7edfc19fd5eece29ef53db | 62b95de9b473c27c46e1bc017d360ce6f989e85f | refs/heads/master | 2020-04-15T05:22:51.943121 | 2019-03-12T02:13:24 | 2019-03-12T02:13:24 | 164,419,277 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 854 | hpp | //
// GraphicComponent.hpp
// ElementalRoguelite
//
// Created by Dylan Burden on 2018-09-30.
// Copyright © 2018 ElementalRoguelike. All rights reserved.
//
#ifndef GraphicComponent_hpp
#define GraphicComponent_hpp
#include <string>
#include <memory>
#include <SDL2/SDL.h>
#include "IComponent.hpp"
class GraphicComponent: public Component< GraphicComponent >
{
public:
// The name of the sprite sheet this component uses
std::string m_spriteSheet;
// Current clip of sprite sheet being used
SDL_Rect m_spriteClip;
// Constructor
GraphicComponent( EntityID ownerId, const std::string& sheetName, int clipX, int clipY, int clipW, int clipH );
GraphicComponent( EntityID ownerId, const std::string& sheetName, SDL_Rect& clip );
virtual void toString() override;
};
#endif /* GraphicComponent_hpp */
| [
"dylanburden@Dylans-MacBook-Air.local"
] | dylanburden@Dylans-MacBook-Air.local |
480c8a1c7b7d00077d983b8072f0397ee4336b86 | dd9a8b7e730895df3ad7748116d0d0eb20f2189e | /MPI_MaxInMat/mat.h | fc539f4bd8cb69e1f426ae3f66482fff580b83b4 | [] | no_license | kkoryun/ParallelProg | ee599b417c0f8b247ee72b440f954a8c9af25e8a | d4bf04725bfe27a9cbbea604cb942e6aedc73695 | refs/heads/master | 2022-01-10T04:31:44.118620 | 2019-06-12T18:51:45 | 2019-06-12T18:51:45 | 90,050,688 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 865 | h | #pragma once
template<typename TYPE>
class mat
{
public:
TYPE * data;
size_t size, remaind ;
TYPE ** datapnt;
mat(size_t w = 1, size_t h = 1) {
size = w*h;
data = new TYPE [size];
for (size_t i = 0; i < size; i++)
{
srand(5);
data[i] =rand()%10;
}
datapnt = new TYPE * [h];
for (size_t i = 0; i < h; i++)
datapnt[i] = data + w*i;
remaind = 0;
};
void resize(size_t pn){
if (data != 0 && datapnt!=0) {
delete[] datapnt;
pnt = new TYPE*[pn];
size_t len = size / pn;
remaind = size % pn;
for (size_t i = 0; i < pn; i++)
pnt[i] = m + len*i;
}
}
size_t getRemaund() {
return remaind;
}
void showmatr(int** m, size_t w, size_t h)
{
for (int i = 0; i < h; i++)
{
for (int j = 0; j < w; j++)
cout << m[i][j] << " ";
cout << endl;
}
}
~mat() {
delete[] data;
delete[] pnt;
}
};
| [
"Koryun Khachatryan"
] | Koryun Khachatryan |
89211040c714e0fd88d49cc5aa8fe429870edf73 | 5df66b7c0cf0241831ea7d8345aa4102f77eba03 | /Carberp Botnet/source - absource/pro/all source/BJWJ/include/dom/nsIDOMNSXBLFormControl.h | 38a1041402dd42aa1d627e98c86f89e6093a9ebd | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | bengalm/fireroothacker | e8f20ae69f4246fc4fe8c48bbb107318f7a79265 | ceb71ba972caca198524fe91a45d1e53b80401f6 | refs/heads/main | 2023-04-02T03:00:41.437494 | 2021-04-06T00:26:28 | 2021-04-06T00:26:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,744 | h | /*
* DO NOT EDIT. THIS FILE IS GENERATED FROM e:/builds/moz2_slave/mozilla-1.9.1-win32-xulrunner/build/dom/public/idl/html/nsIDOMNSXBLFormControl.idl
*/
#ifndef __gen_nsIDOMNSXBLFormControl_h__
#define __gen_nsIDOMNSXBLFormControl_h__
#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif
/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
class nsIBoxObject; /* forward declaration */
/* starting interface: nsIDOMNSXBLFormControl */
#define NS_IDOMNSXBLFORMCONTROL_IID_STR "1c28ed66-1dd2-11b2-95af-e2cf10931adb"
#define NS_IDOMNSXBLFORMCONTROL_IID \
{0x1c28ed66, 0x1dd2, 0x11b2, \
{ 0x95, 0xaf, 0xe2, 0xcf, 0x10, 0x93, 0x1a, 0xdb }}
class NS_NO_VTABLE NS_SCRIPTABLE nsIDOMNSXBLFormControl : public nsISupports {
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDOMNSXBLFORMCONTROL_IID)
/* readonly attribute nsIBoxObject boxObject; */
NS_SCRIPTABLE NS_IMETHOD GetBoxObject(nsIBoxObject * *aBoxObject) = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsIDOMNSXBLFormControl, NS_IDOMNSXBLFORMCONTROL_IID)
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIDOMNSXBLFORMCONTROL \
NS_SCRIPTABLE NS_IMETHOD GetBoxObject(nsIBoxObject * *aBoxObject);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIDOMNSXBLFORMCONTROL(_to) \
NS_SCRIPTABLE NS_IMETHOD GetBoxObject(nsIBoxObject * *aBoxObject) { return _to GetBoxObject(aBoxObject); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIDOMNSXBLFORMCONTROL(_to) \
NS_SCRIPTABLE NS_IMETHOD GetBoxObject(nsIBoxObject * *aBoxObject) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetBoxObject(aBoxObject); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsDOMNSXBLFormControl : public nsIDOMNSXBLFormControl
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIDOMNSXBLFORMCONTROL
nsDOMNSXBLFormControl();
private:
~nsDOMNSXBLFormControl();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS1(nsDOMNSXBLFormControl, nsIDOMNSXBLFormControl)
nsDOMNSXBLFormControl::nsDOMNSXBLFormControl()
{
/* member initializers and constructor code */
}
nsDOMNSXBLFormControl::~nsDOMNSXBLFormControl()
{
/* destructor code */
}
/* readonly attribute nsIBoxObject boxObject; */
NS_IMETHODIMP nsDOMNSXBLFormControl::GetBoxObject(nsIBoxObject * *aBoxObject)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
#endif /* __gen_nsIDOMNSXBLFormControl_h__ */
| [
"ludi@ps.ac.cn"
] | ludi@ps.ac.cn |
072fd1fbeba7759278e43baa3d42c250471b5335 | 6540ac51373d533fc6bd88ff2b22c4e26f9960c3 | /src/utility/Endian.h | 78c6158e3bc24935c79590391f9569542101faaa | [
"MIT"
] | permissive | mccdaq/uldaq | 92e09dbe3d189f35156731ce09cf74a56d5336aa | 1d8404159c0fb6d2665461b80acca5bbef5c610a | refs/heads/master | 2022-05-02T14:49:01.623605 | 2022-03-22T01:52:43 | 2022-03-22T01:52:43 | 131,733,031 | 88 | 38 | MIT | 2020-05-11T21:48:24 | 2018-05-01T15:59:13 | C | UTF-8 | C++ | false | false | 5,635 | h | /*
* Endian.h
*
* Author: Measurement Computing Corporation
*/
#ifndef _ENDIAN_H_
#define _ENDIAN_H_
#include "../ul_internal.h"
namespace ul
{
class UL_LOCAL Endian
{
public:
static Endian& Instance()
{
static Endian mInstance;
return mInstance;
}
static inline unsigned short cpu_to_le_ui16(const unsigned short x)
{
union
{
unsigned char b8[2];
unsigned short b16;
} _tmp;
_tmp.b8[1] = (unsigned char) (x >> 8);
_tmp.b8[0] = (unsigned char) (x & 0xff);
return _tmp.b16;
}
#define le_ui16_to_cpu cpu_to_le_ui16
static inline short cpu_to_le_i16(const short x)
{
union
{
unsigned char b8[2];
short b16;
} _tmp;
_tmp.b8[1] = (unsigned char) (x >> 8);
_tmp.b8[0] = (unsigned char) (x & 0xff);
return _tmp.b16;
}
#define le_i16_to_cpu cpu_to_le_i16
static inline unsigned int cpu_to_le_ui32(const unsigned int x)
{
union
{
unsigned char b8[4];
unsigned int b32;
} _tmp;
_tmp.b8[3] = (unsigned char) (x >> 24);
_tmp.b8[2] = (unsigned char) (x >> 16 & 0xff);
_tmp.b8[1] = (unsigned char) (x >> 8 & 0xff);
_tmp.b8[0] = (unsigned char) (x & 0xff);
return _tmp.b32;
}
#define le_ui32_to_cpu cpu_to_le_ui32
static inline unsigned long long cpu_to_le_ui64(const unsigned long long x)
{
union
{
unsigned char b8[8];
unsigned long long b64;
} _tmp;
_tmp.b8[7] = (unsigned char) (x >> 56);
_tmp.b8[6] = (unsigned char) (x >> 48 & 0xff);
_tmp.b8[5] = (unsigned char) (x >> 40 & 0xff);
_tmp.b8[4] = (unsigned char) (x >> 32 & 0xff);
_tmp.b8[3] = (unsigned char) (x >> 24 & 0xff);
_tmp.b8[2] = (unsigned char) (x >> 16 & 0xff);
_tmp.b8[1] = (unsigned char) (x >> 8 & 0xff);
_tmp.b8[0] = (unsigned char) (x & 0xff);
return _tmp.b64;
}
#define le_ui64_to_cpu cpu_to_le_ui64
static inline int isLittleEndian()
{
unsigned short i = 1;
char *ptr = (char *) &i;
return (*ptr);
}
inline short le_ptr_to_cpu_i16(const unsigned char* x)
{
union
{
unsigned char b8[2];
short b16;
} _tmp;
if(mLittleEndian)
_tmp.b16 = *((short*)x);
else
{
_tmp.b8[1] = x[0];
_tmp.b8[0] = x[1];
}
return _tmp.b16;
}
inline int le_ptr_to_cpu_i32(const unsigned char x[4])
{
union
{
unsigned char b8[4];
int b32;
} _tmp;
if(mLittleEndian)
_tmp.b32 = *((int*)x);
else
{
_tmp.b8[3] = x[0];
_tmp.b8[2] = x[1];
_tmp.b8[1] = x[2];
_tmp.b8[0] = x[3];
}
return _tmp.b32;
}
inline unsigned int le_ptr_to_cpu_ui32(const unsigned char x[4])
{
union
{
unsigned char b8[4];
unsigned int b32;
} _tmp;
if(mLittleEndian)
_tmp.b32 = *((int*)x);
else
{
_tmp.b8[3] = x[0];
_tmp.b8[2] = x[1];
_tmp.b8[1] = x[2];
_tmp.b8[0] = x[3];
}
return _tmp.b32;
}
inline int be_ptr_to_cpu_i32(const unsigned char x[4])
{
union
{
unsigned char b8[4];
int b32;
} _tmp;
if(!mLittleEndian)
_tmp.b32 = *((int*)x);
else
{
_tmp.b8[3] = x[0];
_tmp.b8[2] = x[1];
_tmp.b8[1] = x[2];
_tmp.b8[0] = x[3];
}
return _tmp.b32;
}
inline unsigned int be_ptr_to_cpu_ui32(const unsigned char x[4])
{
union
{
unsigned char b8[4];
unsigned int b32;
} _tmp;
if(!mLittleEndian)
_tmp.b32 = *((unsigned int*)x);
else
{
_tmp.b8[3] = x[0];
_tmp.b8[2] = x[1];
_tmp.b8[1] = x[2];
_tmp.b8[0] = x[3];
}
return _tmp.b32;
}
inline float le_ptr_to_cpu_f32(const unsigned char x[4])
{
union
{
unsigned char b8[4];
float b32;
} _tmp;
if(mLittleEndian)
_tmp.b32 = *((float*)x);
else
{
_tmp.b8[3] = x[0];
_tmp.b8[2] = x[1];
_tmp.b8[1] = x[2];
_tmp.b8[0] = x[3];
}
return _tmp.b32;
}
inline void cpu_f32_to_le_ptr(float f32, unsigned char x[4])
{
union
{
unsigned char b8[4];
float b32;
} _tmp;
if(mLittleEndian)
std::memcpy((void*)&f32, (void*)x, sizeof(float));
else
{
_tmp.b32 = f32;
x[0] = _tmp.b8[3];
x[1] = _tmp.b8[2];
x[2] = _tmp.b8[1];
x[3] = _tmp.b8[0];
}
}
inline unsigned long long be_ptr_to_cpu_u64(const unsigned char x[8])
{
union
{
unsigned char b8[8];
unsigned long long b64;
} _tmp;
if(!mLittleEndian)
_tmp.b64 = *((unsigned long long*)x);
else
{
_tmp.b8[7] = x[0];
_tmp.b8[6] = x[1];
_tmp.b8[5] = x[2];
_tmp.b8[4] = x[3];
_tmp.b8[3] = x[4];
_tmp.b8[2] = x[5];
_tmp.b8[1] = x[6];
_tmp.b8[0] = x[7];
}
return _tmp.b64;
}
static inline unsigned short cpu_to_be_ui16(const unsigned short x)
{
union
{
unsigned char b8[2];
unsigned short b16;
} _tmp;
_tmp.b8[0] = (unsigned char) (x >> 8);
_tmp.b8[1] = (unsigned char) (x & 0xff);
return _tmp.b16;
}
#define be_ui16_to_cpu cpu_to_be_ui16
inline double le_ptr_to_cpu_f64(const unsigned char x[8])
{
union
{
unsigned char b8[8];
double b64;
} _tmp;
if(mLittleEndian)
_tmp.b64 = *((double*)x);
else
{
_tmp.b8[7] = x[0];
_tmp.b8[6] = x[1];
_tmp.b8[5] = x[2];
_tmp.b8[4] = x[3];
_tmp.b8[3] = x[4];
_tmp.b8[2] = x[5];
_tmp.b8[1] = x[6];
_tmp.b8[0] = x[7];
}
return _tmp.b64;
}
inline void cpu_f64_to_le_ptr(double f64, unsigned char x[8])
{
union
{
unsigned char b8[8];
double b64;
} _tmp;
if(mLittleEndian)
std::memcpy((void*)&f64, (void*)x, sizeof(double));
else
{
_tmp.b64 = f64;
x[0] = _tmp.b8[7];
x[1] = _tmp.b8[6];
x[2] = _tmp.b8[5];
x[3] = _tmp.b8[4];
x[4] = _tmp.b8[3];
x[5] = _tmp.b8[2];
x[6] = _tmp.b8[1];
x[8] = _tmp.b8[0];
}
}
protected:
Endian();
private:
bool mLittleEndian;
};
} /* namespace ul */
#endif /* UTILITY_ENDIAN_H_ */
| [
"measurementcomputingcorp@gmail.com"
] | measurementcomputingcorp@gmail.com |
7f708ec1e8466fb6f9707ece4cfa2e2e4dfd80fa | 73aa1c94c67958e27982e65de46461364172f503 | /Classes/Definitions.h | 768a13178f2642b012109e1f5cfe3c2c2fd54995 | [] | no_license | sspatari/SquareJump | c88bd901c59a2c0f37839996c747d2b2548bb08d | cfc334710f642c5de5be9fdb23fbbdfd55a837d6 | refs/heads/master | 2021-07-13T00:50:07.852814 | 2018-09-06T17:03:55 | 2018-09-06T18:19:31 | 101,523,299 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,513 | h | #ifndef __DEFINITIONS_H__
#define __DEFINITIONS_H__
//triangle
const float GAME_SPEED_COEF = 0.25f;
const float MIN_SECOND_TILL_INIT_TRIANGLE = 1.0f;
const float MAX_SECOND_TILL_INIT_TRIANGLE = 3.0f;
const int MIN_TRIANGLES_TILL_NEXT_SAME_SIDE = 1;
const int MAX_TRIANGLES_TILL_NEXT_SAME_SIDE = MIN_TRIANGLES_TILL_NEXT_SAME_SIDE + 8;
const int MIN_TRIANGLES_TILL_NEXT_DIFF_SIDE = 1;
const int MAX_TRIANGLES_TILL_NEXT_DIFF_SIDE = MIN_TRIANGLES_TILL_NEXT_DIFF_SIDE + 8;
const int TRIANGLE_COLLISION_BITMASK = 0x00000001;
//rain
const int RAIN_DROP_SCALE_RANGES = 3;
const float RAIN_SPEED = 0.9f;
const float RAIN_SPEED_SCALE_COEF = 0.35f; //0->1, 0 means rainDrop with smaller scale move slower, 1 means rainDrops have same speed
const int RAIN_DROPS_NUMBER = 150;
const float RAIN_DROP_SCALE_STANDARD_DEVIATION = 5.0f;
const float MIN_RAIN_DROP_SCALE = 0.5f;
const float MAX_RAIN_DROP_SCALE = 2.8f;
const GLubyte RAIN_DROP_OPACITY = 140; //(0 -> 255) unsigned char
const float RAIN_ANGLE = 15.0f;
//square
const int ROTATION_NUMBER = 1;
const float SQUARE_ANIMATION_TIME = 0.5f;
const int SQUARE_COLLISION_BITMASK = 0x00000002;
//score
const float SCORE_FONT_SIZE = 99.35f;
const std::string MAIN_FONT = "fonts/AldotheApache.ttf";
const int MAIN_FONT_COLOR_RED = 19;
const int MAIN_FONT_COLOR_GREEN= 43;
const int MAIN_FONT_COLOR_BLUE = 91;
const int SCORING_LINE_COLLISION_BITMASK = 0x00000003;
const float SCORE_POSITION_X_COEF = 0.75f;
const float SCORE_POSITION_Y_COEF = 0.85f;
#endif// __DEFINITIONS_H__
| [
"spatari.stanislav@gmail.com"
] | spatari.stanislav@gmail.com |
5e8a6742d550820df34361f10761d49ae1cf5f90 | ae45359c86a0e91364127824050de9894a614392 | /environment/build/3rdParty/gdal/frmts/wms/wmsdriver.h | 8d919389ba0dbf7117e5c38ad7febaf3acba3a62 | [
"LicenseRef-scancode-info-zip-2005-02",
"LicenseRef-scancode-warranty-disclaimer",
"MIT",
"LicenseRef-scancode-public-domain"
] | permissive | hope815/osgEarthX | 6d6d084f907aaa0e6b832781dfc51a2f0c184eb9 | 7b7c5e98f82c82571cd1d0f306cecf05452315d5 | refs/heads/master | 2023-03-15T21:49:20.588996 | 2018-03-29T10:51:34 | 2018-03-29T10:51:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,721 | h | /******************************************************************************
* $Id: wmsdriver.h 21997 2011-03-20 22:17:31Z rouault $
*
* Project: WMS Client Driver
* Purpose: Implementation of Dataset and RasterBand classes for WMS
* and other similar services.
* Author: Adam Nowacki, nowak@xpam.de
*
******************************************************************************
* Copyright (c) 2007, Adam Nowacki
*
* 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.
****************************************************************************/
class GDALWMSDataset;
class GDALWMSRasterBand;
CPLString MD5String(const char *s);
CPLString ProjToWKT(const CPLString &proj);
void URLAppend(CPLString *url, const char *s);
void URLAppendF(CPLString *url, const char *s, ...);
void URLAppend(CPLString *url, const CPLString &s);
CPLString BufferToVSIFile(GByte *buffer, size_t size);
CPLErr MakeDirs(const char *path);
int StrToBool(const char *p);
int URLSearchAndReplace (CPLString *base, const char *search, const char *fmt, ...);
/* Convert a.b.c.d to a * 0x1000000 + b * 0x10000 + c * 0x100 + d */
int VersionStringToInt(const char *version);
class GDALWMSImageRequestInfo {
public:
double m_x0, m_y0;
double m_x1, m_y1;
int m_sx, m_sy;
};
class GDALWMSDataWindow {
public:
double m_x0, m_y0;
double m_x1, m_y1;
int m_sx, m_sy;
int m_tx, m_ty, m_tlevel;
enum { BOTTOM = -1, DEFAULT = 0, TOP = 1 } m_y_origin;
GDALWMSDataWindow() : m_x0(-180), m_y0(90), m_x1(180), m_y1(-90),
m_sx(-1), m_sy(-1), m_tx(0), m_ty(0),
m_tlevel(-1), m_y_origin(DEFAULT) {}
};
class GDALWMSTiledImageRequestInfo {
public:
int m_x, m_y;
int m_level;
};
class GDALWMSRasterIOHint {
public:
int m_x0, m_y0;
int m_sx, m_sy;
int m_overview;
bool m_valid;
};
class GDALWMSMiniDriverCapabilities {
public:
/* Version N capabilities require all version N and earlier variables to be set to correct values */
int m_capabilities_version;
/* Version 1 capabilities */
int m_has_image_request; // 1 if ImageRequest method is implemented
int m_has_tiled_image_requeset; // 1 if TiledImageRequest method is implemented
int m_has_arb_overviews; // 1 if ImageRequest method supports arbitrary overviews / resolutions
int m_max_overview_count; // Maximum number of overviews supported if known, -1 otherwise
};
/* All data returned by mini-driver as pointer should remain valid for mini-driver lifetime
and should be freed by mini-driver destructor unless otherwise specified. */
class GDALWMSMiniDriver {
friend class GDALWMSDataset;
public:
GDALWMSMiniDriver();
virtual ~GDALWMSMiniDriver();
public:
/* Read mini-driver specific configuration. */
virtual CPLErr Initialize(CPLXMLNode *config);
public:
virtual void GetCapabilities(GDALWMSMiniDriverCapabilities *caps);
virtual void ImageRequest(CPLString *url, const GDALWMSImageRequestInfo &iri);
virtual void TiledImageRequest(CPLString *url, const GDALWMSImageRequestInfo &iri, const GDALWMSTiledImageRequestInfo &tiri);
/* Return data projection in WKT format, NULL or empty string if unknown */
virtual const char *GetProjectionInWKT();
protected:
GDALWMSDataset *m_parent_dataset;
};
class GDALWMSMiniDriverFactory {
public:
GDALWMSMiniDriverFactory();
virtual ~GDALWMSMiniDriverFactory();
public:
virtual GDALWMSMiniDriver* New() = 0;
virtual void Delete(GDALWMSMiniDriver *instance) = 0;
public:
const CPLString &GetName() {
return m_name;
}
protected:
CPLString m_name;
};
class GDALWMSMiniDriverManager {
public:
GDALWMSMiniDriverManager();
~GDALWMSMiniDriverManager();
public:
void Register(GDALWMSMiniDriverFactory *mdf);
GDALWMSMiniDriverFactory *Find(const CPLString &name);
protected:
std::list<GDALWMSMiniDriverFactory *> m_mdfs;
};
#define H_GDALWMSMiniDriverFactory(name) \
class GDALWMSMiniDriverFactory_##name : public GDALWMSMiniDriverFactory { \
public: \
GDALWMSMiniDriverFactory_##name(); \
virtual ~GDALWMSMiniDriverFactory_##name(); \
\
public: \
virtual GDALWMSMiniDriver* New(); \
virtual void Delete(GDALWMSMiniDriver *instance); \
};
#define CPP_GDALWMSMiniDriverFactory(name) \
GDALWMSMiniDriverFactory_##name::GDALWMSMiniDriverFactory_##name() { \
m_name = #name;\
} \
\
GDALWMSMiniDriverFactory_##name::~GDALWMSMiniDriverFactory_##name() { \
} \
\
GDALWMSMiniDriver* GDALWMSMiniDriverFactory_##name::New() { \
return new GDALWMSMiniDriver_##name(); \
} \
\
void GDALWMSMiniDriverFactory_##name::Delete(GDALWMSMiniDriver *instance) { \
delete instance; \
}
class GDALWMSCache {
public:
GDALWMSCache();
~GDALWMSCache();
public:
CPLErr Initialize(CPLXMLNode *config);
CPLErr Write(const char *key, const CPLString &file_name);
CPLErr Read(const char *key, CPLString *file_name);
protected:
CPLString KeyToCacheFile(const char *key);
protected:
CPLString m_cache_path;
CPLString m_postfix;
int m_cache_depth;
};
class GDALWMSDataset : public GDALPamDataset {
friend class GDALWMSRasterBand;
public:
GDALWMSDataset();
virtual ~GDALWMSDataset();
virtual const char *GetProjectionRef();
virtual CPLErr SetProjection(const char *proj);
virtual CPLErr GetGeoTransform(double *gt);
virtual CPLErr SetGeoTransform(double *gt);
virtual CPLErr AdviseRead(int x0, int y0, int sx, int sy, int bsx, int bsy, GDALDataType bdt, int band_count, int *band_map, char **options);
virtual const char *GetMetadataItem( const char * pszName,
const char * pszDomain = "" );
const GDALWMSDataWindow *WMSGetDataWindow() const;
void WMSSetClamp(bool flag);
void WMSSetOverviewCount(int count);
void WMSSetBlockSize(int x, int y);
void WMSSetRasterSize(int x, int y);
void WMSSetDataType(GDALDataType type);
void WMSSetDataWindow(GDALWMSDataWindow &window);
void WMSSetBandsCount(int count);
void mSetBand(int i, GDALRasterBand *band) { SetBand(i,band); };
GDALWMSRasterBand *mGetBand(int i) { return reinterpret_cast<GDALWMSRasterBand *>(GetRasterBand(i)); };
void WMSSetDefaultDataWindowCoordinates(double x0, double y0, double x1, double y1);
void WMSSetDefaultTileLevel(int tlevel);
void WMSSetDefaultTileCount(int tilecountx, int tilecounty);
void WMSSetDefaultBlockSize(int x, int y);
void WMSSetDefaultOverviewCount(int overview_count);
void WMSSetNeedsDataWindow(int flag);
static GDALDataset* Open(GDALOpenInfo *poOpenInfo);
static int Identify(GDALOpenInfo *poOpenInfo);
static GDALDataset *CreateCopy( const char * pszFilename,
GDALDataset *poSrcDS,
int bStrict, char ** papszOptions,
GDALProgressFunc pfnProgress,
void * pProgressData );
protected:
virtual CPLErr IRasterIO(GDALRWFlag rw, int x0, int y0, int sx, int sy, void *buffer, int bsx, int bsy, GDALDataType bdt, int band_count, int *band_map, int pixel_space, int line_space, int band_space);
CPLErr Initialize(CPLXMLNode *config);
GDALWMSDataWindow m_data_window;
GDALWMSMiniDriver *m_mini_driver;
GDALWMSMiniDriverCapabilities m_mini_driver_caps;
GDALWMSCache *m_cache;
CPLString m_projection;
int m_overview_count;
GDALDataType m_data_type;
int m_block_size_x, m_block_size_y;
GDALWMSRasterIOHint m_hint;
int m_use_advise_read;
int m_verify_advise_read;
int m_offline_mode;
int m_http_max_conn;
int m_http_timeout;
int m_clamp_requests;
int m_unsafeSsl;
CPLString m_osUserAgent;
CPLString m_osReferer;
GDALWMSDataWindow m_default_data_window;
int m_default_block_size_x, m_default_block_size_y;
int m_default_tile_count_x, m_default_tile_count_y;
int m_default_overview_count;
int m_bNeedsDataWindow;
CPLString m_osXML;
};
class GDALWMSRasterBand : public GDALPamRasterBand {
friend class GDALWMSDataset;
public:
GDALWMSRasterBand(GDALWMSDataset *parent_dataset, int band, double scale);
virtual ~GDALWMSRasterBand();
void AddOverview(double scale);
virtual CPLErr AdviseRead(int x0, int y0, int sx, int sy, int bsx, int bsy, GDALDataType bdt, char **options);
virtual GDALColorInterp GetColorInterpretation();
virtual CPLErr SetColorInterpretation( GDALColorInterp );
virtual CPLErr IReadBlock(int x, int y, void *buffer);
virtual CPLErr IRasterIO(GDALRWFlag rw, int x0, int y0, int sx, int sy, void *buffer, int bsx, int bsy, GDALDataType bdt, int pixel_space, int line_space);
virtual int HasArbitraryOverviews();
virtual int GetOverviewCount();
virtual GDALRasterBand *GetOverview(int n);
protected:
CPLErr ReadBlocks(int x, int y, void *buffer, int bx0, int by0, int bx1, int by1, int advise_read);
bool IsBlockInCache(int x, int y);
void AskMiniDriverForBlock(CPLString *url, int x, int y);
CPLErr ReadBlockFromFile(int x, int y, const char *file_name, int to_buffer_band, void *buffer, int advise_read);
CPLErr ZeroBlock(int x, int y, int to_buffer_band, void *buffer);
CPLErr ReportWMSException(const char *file_name);
protected:
GDALWMSDataset *m_parent_dataset;
double m_scale;
std::vector<GDALWMSRasterBand *> m_overviews;
int m_overview;
GDALColorInterp m_color_interp;
};
GDALWMSMiniDriverManager *GetGDALWMSMiniDriverManager();
void DestroyWMSMiniDriverManager(void);
| [
"luohao@hacksome.org"
] | luohao@hacksome.org |
e8751063de1531491466761f4a7a05aac2f56213 | ee341d52015d9895b3cff2590bc78871f43f2d7b | /ChristmasGift/ChristmasGift/ModelController.cpp | 24105dc5e8d30936ecce3c8034e1a5ba858b2f86 | [] | no_license | jackball2008/ACW | 24fa77586c316ad836c975d44c2a3432e9a34287 | 427450c888e0a4fc7e758bebaabd522e20bd99e2 | refs/heads/master | 2021-01-19T08:11:27.205779 | 2012-05-22T16:18:42 | 2012-05-22T16:18:42 | 2,802,051 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 29,467 | cpp | #include "ModelController.h"
ModelController ModelController::_modelController;
ModelController::ModelController(void)
{
}
ModelController::~ModelController(void)
{
}
ModelController* ModelController::GetInstance(){
return &_modelController;
}
/************************************************************************/
/* Read a 3Dmodel file, and transfer data to model instance */
/************************************************************************/
void ModelController::AssemblyModelFromFile(IDisplayObject* model, const char* path, GLuint texarr)
{
ifstream fin(path);
if(!fin){
cout<<"file open error\n";
return;
}
else{
cout<<"read ok"<<endl;
}
char buffer[100];
int rA,rB,rv,rn,ru,rc;
int numofvertex;
float tempfloat;
int tempindex;
bool hasuv,hascol;
hasuv = false;
hascol = false;
Vertex (*_vertices);
GLuint *_indices;
while(!fin.eof()){
//analyze each line
fin.getline(buffer, sizeof(buffer));
int lengthOfLine = fin.gcount();
istrstream sin (buffer, lengthOfLine-1);
string word;
sin>>word;
rA = rB = rv = rn = ru = rc = -2;
rA = word.compare("A");
rB = word.compare("B");
rv = word.compare("v");
rn = word.compare("n");
ru = word.compare("u");
rc = word.compare("c");
if(rA == 0){
sin>>word;
numofvertex = (int)atof(word.c_str());
_vertices = new Vertex[numofvertex];
}
if(rB == 0){
sin>>word;
cout<<"fn = "<<atof(word.c_str())<<endl;
}
if(rv == 0){
sin>>word;
tempindex = (int)atof(word.c_str());
//x
sin>>word;
tempfloat = atof(word.c_str());
_vertices[tempindex].position[X_POS] = tempfloat;
//y
sin>>word;
tempfloat = atof(word.c_str());
_vertices[tempindex].position[Y_POS] = tempfloat;
//z
sin>>word;
tempfloat = atof(word.c_str());
_vertices[tempindex].position[Z_POS] = tempfloat;
}
if(rn == 0){
sin>>word;
tempindex = (int)atof(word.c_str());
sin>>word;
tempfloat = atof(word.c_str());
_vertices[tempindex].normal[X_POS] = tempfloat;
sin>>word;
tempfloat = atof(word.c_str());
_vertices[tempindex].normal[Y_POS] = tempfloat;
sin>>word;
tempfloat = atof(word.c_str());
_vertices[tempindex].normal[Z_POS] = tempfloat;
}
if(ru == 0){
sin>>word;
tempindex = (int)atof(word.c_str());
sin>>word;
tempfloat = atof(word.c_str());
_vertices[tempindex].texture[U_POS] = tempfloat;
sin>>word;
tempfloat = atof(word.c_str());
_vertices[tempindex].texture[V_POS] = tempfloat;
hasuv = true;
}
if(rc == 0){
sin>>word;
tempindex = (int)atof(word.c_str());
sin>>word;
tempfloat = atof(word.c_str());
_vertices[tempindex].colour[R_POS] = tempfloat;
sin>>word;
tempfloat = atof(word.c_str());
_vertices[tempindex].colour[G_POS] = tempfloat;
sin>>word;
tempfloat = atof(word.c_str());
_vertices[tempindex].colour[B_POS] = tempfloat;
sin>>word;
tempfloat = atof(word.c_str());
_vertices[tempindex].colour[A_POS] = tempfloat;
hascol = true;
}
}
fin.close();
if(!hasuv){
for(int i = 0; i<numofvertex;i++)
{
_vertices[i].texture[U_POS] = 0.0;
_vertices[i].texture[V_POS] = 0.0;
}
}
if(!hascol){
for(int i = 0; i<numofvertex;i++){
_vertices[i].colour[R_POS] = 0.5;
_vertices[i].colour[G_POS] = 0.5;
_vertices[i].colour[B_POS] = 0.5;
_vertices[i].colour[A_POS] = 1.0;
}
}
/**
if(model->getEnableTransparency()){
for(int i = 0; i<numofvertex;i++){
_vertices[i].colour[A_POS] =model->getColorApalha();;
}
}
**/
_indices = new GLuint[numofvertex];
for(int i = 0; i<numofvertex;i++){
_indices[i] = i;
}
/**
model->setVertexes((_vertices),(_indices), numofvertex, numofvertex ,texarr,GL_TRIANGLES);
model->Initialize();
*/
}
void ModelController::AssemblyModelFromHeightFieldFile(IDisplayObject* model, const char* mappath,GLuint texarr){
//1. generate vertex array
//vertex array
Vertex (*_vertices);
//index array
GLuint (*_indices);
//////////////////////////////////////////////////////////////////////////
float (*_vertexarray)[3];
float (*_normalarray)[3];
//GLuint
GLuint *_indexarray;
float (*_texarray)[2];
//////////////////////////////////////////////////////////////////////////
int bitsperpixel;
unsigned char* rowpointer;
int vertex_index;
int current_vertex;
//////////////////////////////////////////////////////////////////////////
Image _heightfield;
int _width,_height,numofvertex,numofindex;
_heightfield.Load(mappath);
_height =_heightfield.Height();
_width = _heightfield.Width();
/************************************************************************/
/* generate vertex array, used later */
/************************************************************************/
numofvertex = _height*_width;
//////////////////////////////////////////////////////////////////////////
bitsperpixel = _heightfield.GetPixelSize();
_vertexarray = new float[_height*_width][3];
_normalarray = new float[_height*_width][3];
_indexarray = new GLuint[_height*_width*2];
_texarray = new float[_height*_width][2];
//generate veretx data
vertex_index = 0;
for(int j=0;j<_height;j++) {
rowpointer =_heightfield.GetRowData(j);
// if(j == 100){
// cout<<""<<endl;
// }
for(int i = 0; i <_width; i++) {
_texarray[vertex_index][0] = (float)i/(_width-1);
_texarray[vertex_index][1] = (float)j/(_height-1);
_vertexarray[vertex_index][0] = -2.0f + 4.0f*_texarray[vertex_index][0];
_vertexarray[vertex_index][1] = -2.0f + 4.0f*_texarray[vertex_index][1];
_vertexarray[vertex_index][2] = (float)rowpointer[i*bitsperpixel]/255.0f;
vertex_index++;
};
};
//cout<<""<<endl;
//copy vertex and uv
_vertices = new Vertex[numofvertex];
for(int i = 0; i< numofvertex; i++){
//veretx
_vertices[i].position[X_POS] = _vertexarray[i][0];
_vertices[i].position[Y_POS] = _vertexarray[i][1];
_vertices[i].position[Z_POS] = _vertexarray[i][2];
//uv
_vertices[i].texture[U_POS] = _texarray[i][0];
_vertices[i].texture[V_POS] = _texarray[i][1];
}
// need to generate the index array
vertex_index = 0;
for(int j=0;j<_height-1;j++) {
for(int i = 0; i<_width;i++) {
current_vertex = j*_width+i;
_indexarray[vertex_index++] = current_vertex + _width;
_indexarray[vertex_index++] = current_vertex;
};
};
//copy index array
numofindex = vertex_index;
_indices = new GLuint[numofindex];
for(int i = 0;i<numofindex;i++){
_indices[i] = _indexarray[i];
}
//here , it is the hardest part of this program
//generate the normal of each vertex
vertex_index = 0;
_normalarray[vertex_index][0] = -_vertexarray[vertex_index][2];
_normalarray[vertex_index][1] = -_vertexarray[vertex_index+_width][2];
_normalarray[vertex_index][2] = 8.0f/(_width-1);
vertex_index++;
for(int i = 1; i<_width-1;i++) {
_normalarray[vertex_index][0] = _vertexarray[vertex_index-1][2]-_vertexarray[vertex_index+1][2];
_normalarray[vertex_index][1] = -_vertexarray[vertex_index+_width][2];
_normalarray[vertex_index][2] = 8.0f/(_width-1);
vertex_index++;
};
_normalarray[vertex_index][0] = _vertexarray[vertex_index-1][2];
_normalarray[vertex_index][1] = -_vertexarray[vertex_index+_width][2];
_normalarray[vertex_index][2] = 8.0f/(_width-1);
vertex_index++;
for(int j=1;j<_height-1;j++) {
_normalarray[vertex_index][0] = -_vertexarray[vertex_index][2];
_normalarray[vertex_index][1] = -_vertexarray[vertex_index+_width][2];
_normalarray[vertex_index][2] = 8.0f/(_width-1);
vertex_index++;
for(int i=1;i<_width-1;i++) {
_normalarray[vertex_index][0] = _vertexarray[vertex_index-1][2]-_vertexarray[vertex_index+1][2];
_normalarray[vertex_index][1] = _vertexarray[vertex_index-_width][2]-_vertexarray[vertex_index+_width][2];
_normalarray[vertex_index][2] = 8.0f/(_width-1);
vertex_index++;
}
_normalarray[vertex_index][0] = _vertexarray[vertex_index-1][2];
_normalarray[vertex_index][1] = -_vertexarray[vertex_index+_width][2];
_normalarray[vertex_index][2] = 8.0f/(_width-1);
vertex_index++;
}
_normalarray[vertex_index][0] = -_vertexarray[vertex_index][2];
_normalarray[vertex_index][1] = _vertexarray[vertex_index-_width][2];
_normalarray[vertex_index][2] = 8.0f/(_width-1);
vertex_index++;
for(int i = 1; i<_width-1;i++) {
_normalarray[vertex_index][0] = _vertexarray[vertex_index-1][2]-_vertexarray[vertex_index+1][2];
_normalarray[vertex_index][1] = _vertexarray[vertex_index-_width][2];
_normalarray[vertex_index][2] = 8.0f/(_width-1);
vertex_index++;
};
_normalarray[vertex_index][0] = _vertexarray[vertex_index-1][2];
_normalarray[vertex_index][1] = -_vertexarray[vertex_index-_width][2];
_normalarray[vertex_index][2] = 8.0f/(_width-1);
// make normals unit
float temp;
for(int j=0;j<_height*_width;j++) {
temp = _normalarray[j][0]*_normalarray[j][0]+_normalarray[j][1]*_normalarray[j][1]+_normalarray[j][2]*_normalarray[j][2];
temp = sqrt(temp);
_normalarray[j][0] /= temp;
_normalarray[j][1] /= temp;
_normalarray[j][2] /= temp;
};
//copy normal data
for(int i = 0;i<numofvertex;i++){
_vertices[i].normal[X_POS] = _normalarray[i][0];
_vertices[i].normal[Y_POS] = _normalarray[i][1];
_vertices[i].normal[Z_POS] = _normalarray[i][2];
}
//delete
delete [] _normalarray;
//free old data
delete [] _indexarray;
//free old data
delete [] _vertexarray;
delete [] _texarray;
_heightfield.Free();
//assembly vertex color
for(int i = 0; i<numofvertex;i++){
_vertices[i].colour[R_POS] = 0.5;
_vertices[i].colour[G_POS] = 0.5;
_vertices[i].colour[B_POS] = 0.5;
_vertices[i].colour[A_POS] = 1.0;
// if(model->getEnableTransparency()){
// _vertices[i].colour[A_POS] = model->getColorApalha();
// }
}
//_indexarray
//model->setVertexes((_vertices),(_indices), numofvertex,numofindex, texarr,GL_TRIANGLE_STRIP);
model->Initialize();
}
void ModelController::LoadTexture(){
_images[0].Load("house2.jpg");
_images[1].Load("seattexture.jpg");
_images[2].Load("seattexture_grass.jpg");
_images[3].Load("seattexture2.jpg");
_images[4].Load("SnowFlake2.tga");
_images[5].Load("trunk_skin.tga");
_images[6].Load("leaf_texture.tga");
_images[7].Load("leaf_nor_texture.tga");
glGenTextures(TEXTURENUM, &_textures[0]);
// build 2D mip-maps from image
for (int i = 0; i<TEXTURENUM; i++) {
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glBindTexture(GL_TEXTURE_2D, _textures[i]);
_images[i].gluBuild2DMipmaps();
_images[i].Free();
};
//last texture
// glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_CLAMP);
// glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_CLAMP);
// _images[TEXTURENUM-1].gluBuild2DMipmaps();
// _images[TEXTURENUM-1].Free();
}
void ModelController::AssemblyModelFromHeightFieldFile2(IDisplayObject* model, const char* mappath,GLuint texarr){
//1. generate vertex array
//vertex array
Vertex (*_vertices);
//index array
GLuint (*_indices);
//////////////////////////////////////////////////////////////////////////
float (*_vertexarray)[3];
float (*_normalarray)[3];
//GLuint
GLuint *_indexarray;
float (*_texarray)[2];
//////////////////////////////////////////////////////////////////////////
int (*_incycle)[1];
//////////////////////////////////////////////////////////////////////////
int bitsperpixel;
unsigned char* rowpointer;
int vertex_index;
int current_vertex;
//////////////////////////////////////////////////////////////////////////
Image _heightfield;
int _width,_height,numofvertex,numofindex;
_heightfield.Load(mappath);
_height =_heightfield.Height();
_width = _heightfield.Width();
/************************************************************************/
/* generate vertex array, used later */
/************************************************************************/
numofvertex = _height*_width;
//////////////////////////////////////////////////////////////////////////
bitsperpixel = _heightfield.GetPixelSize();
_vertexarray = new float[_height*_width][3];
_normalarray = new float[_height*_width][3];
_indexarray = new GLuint[_height*_width*2];
_texarray = new float[_height*_width][2];
_incycle = new int[_width*_height][1];
//generate veretx data
vertex_index = 0;
for(int j=0;j<_height;j++) {
rowpointer =_heightfield.GetRowData(j);
for(int i = 0; i <_width; i++) {
_texarray[vertex_index][0] = (float)i/(_width-1);
_texarray[vertex_index][1] = (float)j/(_height-1);
_vertexarray[vertex_index][0] = -2.0f + 4.0f*_texarray[vertex_index][0];
_vertexarray[vertex_index][1] = -2.0f + 4.0f*_texarray[vertex_index][1];
_vertexarray[vertex_index][2] = (float)rowpointer[i*bitsperpixel]/255.0f;
vertex_index++;
};
};
//cout<<""<<endl;
//copy vertex and uv
_vertices = new Vertex[numofvertex];
for(int i = 0; i< numofvertex; i++){
//veretx
_vertices[i].position[X_POS] = _vertexarray[i][0];
_vertices[i].position[Y_POS] = _vertexarray[i][1];
_vertices[i].position[Z_POS] = _vertexarray[i][2];
//uv
_vertices[i].texture[U_POS] = _texarray[i][0];
_vertices[i].texture[V_POS] = _texarray[i][1];
}
// need to generate the index array
vertex_index = 0;
for(int j=0;j<_height-1;j++) {
for(int i = 0; i<_width;i++) {
current_vertex = j*_width+i;
_indexarray[vertex_index++] = current_vertex + _width;
_indexarray[vertex_index++] = current_vertex;
};
};
//copy index array
numofindex = vertex_index;
_indices = new GLuint[numofindex];
for(int i = 0;i<numofindex;i++){
_indices[i] = _indexarray[i];
}
//here , it is the hardest part of this program
//generate the normal of each vertex
vertex_index = 0;
_normalarray[vertex_index][0] = -_vertexarray[vertex_index][2];
_normalarray[vertex_index][1] = -_vertexarray[vertex_index+_width][2];
_normalarray[vertex_index][2] = 8.0f/(_width-1);
vertex_index++;
for(int i = 1; i<_width-1;i++) {
_normalarray[vertex_index][0] = _vertexarray[vertex_index-1][2]-_vertexarray[vertex_index+1][2];
_normalarray[vertex_index][1] = -_vertexarray[vertex_index+_width][2];
_normalarray[vertex_index][2] = 8.0f/(_width-1);
vertex_index++;
};
_normalarray[vertex_index][0] = _vertexarray[vertex_index-1][2];
_normalarray[vertex_index][1] = -_vertexarray[vertex_index+_width][2];
_normalarray[vertex_index][2] = 8.0f/(_width-1);
vertex_index++;
for(int j=1;j<_height-1;j++) {
_normalarray[vertex_index][0] = -_vertexarray[vertex_index][2];
_normalarray[vertex_index][1] = -_vertexarray[vertex_index+_width][2];
_normalarray[vertex_index][2] = 8.0f/(_width-1);
vertex_index++;
for(int i=1;i<_width-1;i++) {
_normalarray[vertex_index][0] = _vertexarray[vertex_index-1][2]-_vertexarray[vertex_index+1][2];
_normalarray[vertex_index][1] = _vertexarray[vertex_index-_width][2]-_vertexarray[vertex_index+_width][2];
_normalarray[vertex_index][2] = 8.0f/(_width-1);
vertex_index++;
}
_normalarray[vertex_index][0] = _vertexarray[vertex_index-1][2];
_normalarray[vertex_index][1] = -_vertexarray[vertex_index+_width][2];
_normalarray[vertex_index][2] = 8.0f/(_width-1);
vertex_index++;
}
_normalarray[vertex_index][0] = -_vertexarray[vertex_index][2];
_normalarray[vertex_index][1] = _vertexarray[vertex_index-_width][2];
_normalarray[vertex_index][2] = 8.0f/(_width-1);
vertex_index++;
for(int i = 1; i<_width-1;i++) {
_normalarray[vertex_index][0] = _vertexarray[vertex_index-1][2]-_vertexarray[vertex_index+1][2];
_normalarray[vertex_index][1] = _vertexarray[vertex_index-_width][2];
_normalarray[vertex_index][2] = 8.0f/(_width-1);
vertex_index++;
};
_normalarray[vertex_index][0] = _vertexarray[vertex_index-1][2];
_normalarray[vertex_index][1] = -_vertexarray[vertex_index-_width][2];
_normalarray[vertex_index][2] = 8.0f/(_width-1);
// make normals unit
float temp;
for(int j=0;j<_height*_width;j++) {
temp = _normalarray[j][0]*_normalarray[j][0]+_normalarray[j][1]*_normalarray[j][1]+_normalarray[j][2]*_normalarray[j][2];
temp = sqrt(temp);
_normalarray[j][0] /= temp;
_normalarray[j][1] /= temp;
_normalarray[j][2] /= temp;
};
//copy normal data
for(int i = 0;i<numofvertex;i++){
_vertices[i].normal[X_POS] = _normalarray[i][0];
_vertices[i].normal[Y_POS] = _normalarray[i][1];
_vertices[i].normal[Z_POS] = _normalarray[i][2];
}
//delete
delete [] _normalarray;
//free old data
delete [] _indexarray;
//free old data
delete [] _vertexarray;
delete [] _texarray;
_heightfield.Free();
//assembly vertex color
for(int i = 0; i<numofvertex;i++){
_vertices[i].colour[R_POS] = 0.5;
_vertices[i].colour[G_POS] = 0.5;
_vertices[i].colour[B_POS] = 0.5;
_vertices[i].colour[A_POS] = 1.0;
// if(model->getEnableTransparency()){
// _vertices[i].colour[A_POS] = model->getColorApalha();
// }
}
//_indexarray
//model->setVertexes((_vertices),(_indices), numofvertex,numofindex, texarr,GL_TRIANGLE_STRIP);
model->Initialize();
}
#define PI (float)3.1415926
void ModelController::AssemblyTransparencyPartSphere(IDisplayObject* model,GLfloat radius, int slices, int stacks, GLuint texarr){
float (*_vertexarray)[3]; // contains the vertices
float (*_normalarray)[3]; // contains the normals to each vertex
GLuint *_indexarray; // index array that defines the polygons
float (*_texarray)[2]; // texture coordinates for each vertex
int _stacks, _slices;
//////////////////////////////
int array_size;
float stack_inc;
float slice_inc;
float x, y , z;
int vertex_count;
int index_count;
int temp_vc;
float temp_tex;
float temp_rad;
stacks = stacks;
_slices = slices;
//////////////////////////////
array_size = (slices+1)*(stacks-1)+2; // +2 is for the top and bottom vertex
_vertexarray = new float[array_size][3];
_normalarray = new float[array_size][3];
_indexarray = new GLuint[2+(stacks-1)*(slices+1)*2];
_texarray = new float[array_size][2];
stack_inc = 1.0f/(float)stacks;
slice_inc = PI*2.0f/slices;
// define the vertex array
// top point
vertex_count = 0;
_vertexarray[vertex_count][0] = 0.0f;
_vertexarray[vertex_count][1] = radius;
_vertexarray[vertex_count][2] = 0.0f;
_normalarray[vertex_count][0] = 0.0f;
_normalarray[vertex_count][1] = 1.0f;
_normalarray[vertex_count][2] = 0.0f;
_texarray[vertex_count][0] = 0;
_texarray[vertex_count++][1] = 1;
// bottom point
_vertexarray[vertex_count][0] = 0.0f;
_vertexarray[vertex_count][1] = -radius;
_vertexarray[vertex_count][2] = 0.0f;
_normalarray[vertex_count][0] = 0.0f;
_normalarray[vertex_count][1] = -1.0f;
_normalarray[vertex_count][2] = 0.0f;
_texarray[vertex_count][0] = 0;
_texarray[vertex_count++][1] = 0;
for (int i = 1; i < stacks; i++) {
y = sin(PI*(1/2.0f - stack_inc*(float)i));
temp_rad = cos(PI*(1/2.0f - stack_inc*(float)i));
temp_vc = vertex_count;
temp_tex = 1.0f - stack_inc*(float)i;
for(int j = 0; j < slices; j++) {
x = cos((float)j*slice_inc);
z = -sin((float)j*slice_inc);
_vertexarray[vertex_count][0] = radius*temp_rad*x;
_vertexarray[vertex_count][1] = radius*y;
_vertexarray[vertex_count][2] = radius*temp_rad*z;
_normalarray[vertex_count][0] = temp_rad*x;
_normalarray[vertex_count][1] = y;
_normalarray[vertex_count][2] = temp_rad*z;
_texarray[vertex_count][0] = (float)j/(float)slices;
_texarray[vertex_count++][1] = temp_tex;
};
_vertexarray[vertex_count][0] = _vertexarray[temp_vc][0];
_vertexarray[vertex_count][1] = _vertexarray[temp_vc][1];
_vertexarray[vertex_count][2] = _vertexarray[temp_vc][2];
_normalarray[vertex_count][0] = _normalarray[temp_vc][0];
_normalarray[vertex_count][1] = _normalarray[temp_vc][1];
_normalarray[vertex_count][2] = _normalarray[temp_vc][2];
_texarray[vertex_count][0] = 1;
_texarray[vertex_count++][1] = temp_tex;
};
// now generate the index array
// start with triangle fans for the top
index_count = 0;
vertex_count =2;
_indexarray[index_count++] = 0; // very top vertex
for(int j = 0; j<= slices; j++) {
_indexarray[index_count++] = vertex_count++;
};
vertex_count -= (slices+1);
// now do the main strips
for(int i = 0; i< (stacks-2-8); i++) {
for(int j = 0; j<= slices; j++) {
_indexarray[index_count++] = vertex_count++;
_indexarray[index_count++] = slices+vertex_count;
};
};
// very bottom vertex
/**
_indexarray[index_count++] = 1;
for(int j = 0; j<= slices; j++) {
_indexarray[index_count++] = vertex_count+slices-j;
};
*/
//copy data
//vertex array
Vertex (*_vertices);
//index array
GLuint (*_indices);
int numofvertex = array_size;
_vertices = new Vertex[numofvertex];
for(int i = 0; i< numofvertex; i++){
//veretx
_vertices[i].position[X_POS] = _vertexarray[i][0];
_vertices[i].position[Y_POS] = _vertexarray[i][1];
_vertices[i].position[Z_POS] = _vertexarray[i][2];
//normal
_vertices[i].normal[X_POS] = _normalarray[i][0];
_vertices[i].normal[Y_POS] = _normalarray[i][1];
_vertices[i].normal[Z_POS] = _normalarray[i][2];
//uv
_vertices[i].texture[U_POS] = _texarray[i][0];
_vertices[i].texture[V_POS] = _texarray[i][1];
_vertices[i].colour[R_POS] = 0.5;
_vertices[i].colour[G_POS] = 0.5;
_vertices[i].colour[B_POS] = 0.5;
_vertices[i].colour[A_POS] = 1.0;
// if(model->getEnableTransparency()){
// _vertices[i].colour[A_POS] = model->getColorApalha();
// }
}
//index
//copy index array
int numofindex = index_count;
_indices = new GLuint[numofindex];
for(int i = 0;i<numofindex;i++){
_indices[i] = _indexarray[i];
}
delete [] _vertexarray;
delete [] _normalarray;
delete [] _indexarray;
delete [] _texarray;
//model->setVertexes((_vertices),(_indices), numofvertex,numofindex, texarr,GL_TRIANGLE_STRIP);
model->Initialize();
}
void ModelController::AssemblyBasicTreeData(IDisplayObject*,GLfloat radius, int slices, int stacks){
float (*_vertexarray)[3]; // contains the vertices
float (*_normalarray)[3]; // contains the normals to each vertex
GLuint *_indexarray; // index array that defines the polygons
float (*_texarray)[2]; // texture coordinates for each vertex
int _stacks, _slices;
int array_size;
float stack_inc;
float slice_inc;
int vertex_count;
float x, y , z;
int index_count;
int temp_vc;
float temp_tex;
float temp_rad;
_stacks = stacks;
_slices = slices;
array_size = (slices+1)*(stacks-1)+2; // +2 is for the top and bottom vertex
_vertexarray = new float[array_size][3];
_normalarray = new float[array_size][3];
_indexarray = new GLuint[2+(stacks-1)*(slices+1)*2];
_texarray = new float[array_size][2];
stack_inc = 1.0f/(float)stacks;
slice_inc = PI*2.0f/slices;
// define the vertex array
// top point
vertex_count = 0;
_vertexarray[vertex_count][0] = 0.0f;
_vertexarray[vertex_count][1] = radius;
_vertexarray[vertex_count][2] = 0.0f;
_normalarray[vertex_count][0] = 0.0f;
_normalarray[vertex_count][1] = 1.0f;
_normalarray[vertex_count][2] = 0.0f;
_texarray[vertex_count][0] = 0;
_texarray[vertex_count++][1] = 1;
// bottom point
_vertexarray[vertex_count][0] = 0.0f;
_vertexarray[vertex_count][1] = -radius;
_vertexarray[vertex_count][2] = 0.0f;
_normalarray[vertex_count][0] = 0.0f;
_normalarray[vertex_count][1] = -1.0f;
_normalarray[vertex_count][2] = 0.0f;
_texarray[vertex_count][0] = 0;
_texarray[vertex_count++][1] = 0;
for (int i = 1; i < stacks; i++) {
y = sin(PI*(1/2.0f - stack_inc*(float)i));
temp_rad = cos(PI*(1/2.0f - stack_inc*(float)i));
temp_vc = vertex_count;
temp_tex = 1.0f - stack_inc*(float)i;
for(int j = 0; j < slices; j++) {
x = cos((float)j*slice_inc);
z = -sin((float)j*slice_inc);
_vertexarray[vertex_count][0] = radius*temp_rad*x;
_vertexarray[vertex_count][1] = radius*y;
_vertexarray[vertex_count][2] = radius*temp_rad*z;
_normalarray[vertex_count][0] = temp_rad*x;
_normalarray[vertex_count][1] = y;
_normalarray[vertex_count][2] = temp_rad*z;
_texarray[vertex_count][0] = (float)j/(float)slices;
_texarray[vertex_count++][1] = temp_tex;
};
_vertexarray[vertex_count][0] = _vertexarray[temp_vc][0];
_vertexarray[vertex_count][1] = _vertexarray[temp_vc][1];
_vertexarray[vertex_count][2] = _vertexarray[temp_vc][2];
_normalarray[vertex_count][0] = _normalarray[temp_vc][0];
_normalarray[vertex_count][1] = _normalarray[temp_vc][1];
_normalarray[vertex_count][2] = _normalarray[temp_vc][2];
_texarray[vertex_count][0] = 1;
_texarray[vertex_count++][1] = temp_tex;
};
// now generate the index array
// start with triangle fans for the top
index_count = 0;
vertex_count =2;
_indexarray[index_count++] = 0; // very top vertex
for(int j = 0; j<= slices; j++) {
_indexarray[index_count++] = vertex_count++;
};
vertex_count -= (slices+1);
// now do the main strips
for(int i = 0; i< (stacks-2); i++) {
for(int j = 0; j<= slices; j++) {
_indexarray[index_count++] = vertex_count++;
_indexarray[index_count++] = slices+vertex_count;
};
};
_indexarray[index_count++] = 1; // very bottom vertex
for(int j = 0; j<= slices; j++) {
_indexarray[index_count++] = vertex_count+slices-j;
};
}
void ModelController::AssemblyModelFromFile2(DisplayObjectModel* model, const char* path, GLuint texarr){
ifstream fin(path);
if(!fin){
cout<<"file open error\n";
return;
}
else{
cout<<"read ok"<<endl;
}
char buffer[100];
int rA,rB,rv,rn,ru,rc;
int numofvertex;
float tempfloat;
int tempindex;
bool hasuv,hascol;
hasuv = false;
hascol = false;
Vertex (*_vertices);
GLuint *_indices;
vertex* vp;
vertex* vn;
color* vc;
uvcoord* vt;
while(!fin.eof()){
//analyze each line
fin.getline(buffer, sizeof(buffer));
int lengthOfLine = fin.gcount();
istrstream sin (buffer, lengthOfLine-1);
string word;
sin>>word;
rA = rB = rv = rn = ru = rc = -2;
rA = word.compare("A");
rB = word.compare("B");
rv = word.compare("v");
rn = word.compare("n");
ru = word.compare("u");
rc = word.compare("c");
if(rA == 0){
sin>>word;
numofvertex = (int)atof(word.c_str());
_vertices = new Vertex[numofvertex];
}
if(rB == 0){
sin>>word;
cout<<"fn = "<<atof(word.c_str())<<endl;
}
if(rv == 0){
sin>>word;
tempindex = (int)atof(word.c_str());
//x
sin>>word;
tempfloat = atof(word.c_str());
_vertices[tempindex].position[X_POS] = tempfloat;
//y
sin>>word;
tempfloat = atof(word.c_str());
_vertices[tempindex].position[Y_POS] = tempfloat;
//z
sin>>word;
tempfloat = atof(word.c_str());
_vertices[tempindex].position[Z_POS] = tempfloat;
}
if(rn == 0){
sin>>word;
tempindex = (int)atof(word.c_str());
sin>>word;
tempfloat = atof(word.c_str());
_vertices[tempindex].normal[X_POS] = tempfloat;
sin>>word;
tempfloat = atof(word.c_str());
_vertices[tempindex].normal[Y_POS] = tempfloat;
sin>>word;
tempfloat = atof(word.c_str());
_vertices[tempindex].normal[Z_POS] = tempfloat;
}
if(ru == 0){
sin>>word;
tempindex = (int)atof(word.c_str());
sin>>word;
tempfloat = atof(word.c_str());
_vertices[tempindex].texture[U_POS] = tempfloat;
sin>>word;
tempfloat = atof(word.c_str());
_vertices[tempindex].texture[V_POS] = tempfloat;
hasuv = true;
}
if(rc == 0){
sin>>word;
tempindex = (int)atof(word.c_str());
sin>>word;
tempfloat = atof(word.c_str());
_vertices[tempindex].colour[R_POS] = tempfloat;
sin>>word;
tempfloat = atof(word.c_str());
_vertices[tempindex].colour[G_POS] = tempfloat;
sin>>word;
tempfloat = atof(word.c_str());
_vertices[tempindex].colour[B_POS] = tempfloat;
sin>>word;
tempfloat = atof(word.c_str());
_vertices[tempindex].colour[A_POS] = tempfloat;
hascol = true;
}
}
fin.close();
if(!hasuv){
for(int i = 0; i<numofvertex;i++)
{
_vertices[i].texture[U_POS] = 0.0;
_vertices[i].texture[V_POS] = 0.0;
}
}
if(!hascol){
for(int i = 0; i<numofvertex;i++){
_vertices[i].colour[R_POS] = 0.5;
_vertices[i].colour[G_POS] = 0.5;
_vertices[i].colour[B_POS] = 0.5;
_vertices[i].colour[A_POS] = 1.0;
}
}
// if(model->getEnableTransparency()){
// for(int i = 0; i<numofvertex;i++){
// _vertices[i].colour[A_POS] =model->getColorApalha();;
// }
// }
_indices = new GLuint[numofvertex];
for(int i = 0; i<numofvertex;i++){
_indices[i] = i;
}
vp = new vertex[numofvertex];
vn = new vertex[numofvertex];
vc = new color[numofvertex];
vt = new uvcoord[numofvertex];
for(int i = 0; i< numofvertex; i++){
vp[i].x = _vertices[i].position[X_POS];
vp[i].y = _vertices[i].position[Y_POS];
vp[i].z = _vertices[i].position[Z_POS];
vn[i].x = _vertices[i].normal[X_POS];
vn[i].y = _vertices[i].normal[Y_POS];
vn[i].z = _vertices[i].normal[Z_POS];
vc[i].r = _vertices[i].colour[R_POS];
vc[i].g = _vertices[i].colour[G_POS];
vc[i].b = _vertices[i].colour[B_POS];
vc[i].a = _vertices[i].colour[A_POS];
vt[i].x = _vertices[i].texture[X_POS];
vt[i].y = _vertices[i].texture[Y_POS];
}
/*delete [] _vertices;*/
//model->setVertexes((_vertices),(_indices), numofvertex, numofvertex ,texarr,GL_TRIANGLES);
model->Initialize();
// model->SetVBOData(vp,vn,vc,vt,(_indices),numofvertex,numofvertex);
// model->Initialize2();
}
| [
"maxiaoyuzdz@gmail.com"
] | maxiaoyuzdz@gmail.com |
3ff9328bfc4f6be04b478f2ba08e5ee55c90ed53 | 6b368ed5b18adf40b744d2fd7f067f09b4240bb9 | /SheepGame/Classes/RunningWolf.cpp | 6474815d88e3806b6637c495218838130fc2adcf | [] | no_license | asarazan/SheepGame | 7149f1a39a3f982777c8d91a490c9f8e83a80e54 | 9fc75053c6b6a6b71821f475ce544a83fc653522 | refs/heads/master | 2021-01-23T07:02:47.689468 | 2012-04-29T20:57:05 | 2012-04-29T20:57:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,870 | cpp | //
// RunningWolf.cpp
// SheepGame
//
// Created by Aaron Sarazan on 4/29/12.
// Copyright (c) 2012 Greplin, Inc. All rights reserved.
//
#include "RunningWolf.h"
#include "Stage.h"
bool RunningWolf::init(CCSpriteBatchNode * batch) {
if (!CCSprite::initWithSpriteFrameName("wolf_0.png")) {
return false;
}
m_speed = 50;
m_batch = batch;
m_batch->retain();
m_batch->addChild(this);
// Set up running animation
CCMutableArray<CCSpriteFrame*> runFrames;
for (int i = 0; i < 5; ++i) {
char name[11];
sprintf(name, "wolf_%i.png",i);
name[10] = '\0';
runFrames.addObject(CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(name));
}
CCAnimation * runAnim = CCAnimation::animationWithFrames(&runFrames, 0.1f);
m_runAction = CCRepeatForever::actionWithAction(CCAnimate::actionWithAnimation(runAnim, true));
m_runAction->retain();
// Set up jumping animation
CCMutableArray<CCSpriteFrame*> jumpFrames;
jumpFrames.addObject(CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("wolf_0.png"));
jumpFrames.addObject(CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("wolf_1.png"));
CCAnimation * jumpAnim = CCAnimation::animationWithFrames(&jumpFrames, 0.5f);
m_jumpAction =
CCSequence::actionOneTwo(
CCAnimate::actionWithDuration(1.0f, jumpAnim, false),
CCCallFunc::actionWithTarget(this, callfunc_selector(RunningWolf::finishJumping)));
m_jumpAction->retain();
CCSize winSize = CCDirector::sharedDirector()->getWinSize();
m_batch->getTexture()->setAliasTexParameters();
getTexture()->setAliasTexParameters();
run();
scheduleUpdate();
return true;
}
RunningWolf * RunningWolf::wolfWithStage(Stage *stage) {
CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("Chase.plist");
CCSpriteBatchNode * batch = CCSpriteBatchNode::batchNodeWithFile("Chase.png");
RunningWolf * pRet = new RunningWolf();
pRet->init(batch);
stage->cocos2d::CCNode::addChild(pRet->m_batch);
pRet->autorelease();
return pRet;
}
void RunningWolf::finishJumping() {
m_isJumping = false;
}
bool RunningWolf::isJumping() {
return m_isJumping;
}
CCPoint RunningWolf::destWithDest(const CCPoint & dest, ccTime dt) {
bool backward = dest.x < getPosition().x;
float d = m_speed * dt * (backward ? -1 : 1);
CCPoint pos = getPosition();
pos.x += d;
if ((!backward && pos.x > dest.x) ||
(backward && pos.x < dest.x)) {
pos.x = dest.x;
}
return pos;
}
bool RunningWolf::jump(const CCPoint & dest) {
if (isJumping()) {
return false;
}
m_isJumping = true;
runAction(m_jumpAction);
CCSize winSize = CCDirector::sharedDirector()->getWinSize();
CCPoint pos = getPosition();
CCPoint finalDest = destWithDest(dest, 1);
CCAction * jumpHeightAction =
CCJumpTo::actionWithDuration(1.0f, finalDest, winSize.height * 0.1f, 1);
runAction(jumpHeightAction);
return true;
}
bool RunningWolf::run() {
if (isJumping()) {
return false;
}
runAction(m_runAction);
return true;
}
void RunningWolf::moveTowardPoint(const CCPoint &point) {
m_pursueDest = !CCPoint::CCPointEqualToPoint(point,CCPointZero);
m_dest = point;
}
void RunningWolf::update(ccTime dt) {
if (!m_pursueDest) {
return;
}
if (fabsf(m_dest.x - getPosition().x) < 5) {
return;
}
CCPoint dest = destWithDest(m_dest, dt);
setPosition(dest);
}
RunningWolf::~RunningWolf() {
m_jumpAction->release();
m_runAction->release();
m_batch->release();
} | [
"aaron@sarazan.net"
] | aaron@sarazan.net |
3a47c907d4e0ec5278bde1017ba27567f7ebe40c | ce89a061003f60dfb5071fa7468643acc36518a8 | /Texturing/Texture.cpp | 6092ec6cea77d947b828a61fb1d7946c1333e580 | [] | no_license | MikaGoetze/Relic | 28dd8ee7a558cda10c6ec2b2d7b1f2e0a269e3b7 | 71e51469c336bf06d0541130957a3a4c1e90656d | refs/heads/master | 2020-03-18T17:07:53.685123 | 2018-06-13T11:57:35 | 2018-06-13T11:57:35 | 135,008,194 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 870 | cpp | #define STB_IMAGE_IMPLEMENTATION
#include "Texture.h"
#include "stb_image.h"
#include <GL/glew.h>
Texture::Texture()
{
}
Texture::Texture(std::string path, unsigned int source_type)
{
int nrChannels;
stbi_set_flip_vertically_on_load(true);
unsigned char * data = stbi_load(path.c_str(), &width, &height, &nrChannels, source_type == GL_RGBA ? 4 : 3);
glGenTextures(1, &id);
glBindTexture(GL_TEXTURE_2D, id);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, source_type, width, height, 0, source_type, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
stbi_image_free(data);
}
Texture::~Texture()
{
}
| [
"mika.goetze@mightykingdom.com"
] | mika.goetze@mightykingdom.com |
5910d10f72622092e3fb143ed15d3a0aee2e770f | 184f587f54f8551f1d457d11659188b2bf15d64b | /α版/α-GalaxyShooter/BlackBoardBase.h | f338ff178f8c1661fa3fc3cb4407ecffd6bd384c | [] | no_license | GameBuilderEngineer/ShainingStarTest001 | 42f7154d73448bf535ed3662835276d5ee3b5ef2 | 8687593395a2fc55972b50509ab68db56c4efd0a | refs/heads/master | 2022-02-22T15:54:01.597817 | 2019-09-12T12:29:30 | 2019-09-12T12:29:30 | 186,948,784 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 611 | h | //-----------------------------------------------------------------------------
// ブラックボード基底処理 [BlackBoardBase.h]
// Author:GP12A332 32 中込和輝
// 作成日:2019/6/15
//-----------------------------------------------------------------------------
#pragma once
//*****************************************************************************
// クラス定義
//*****************************************************************************
class BlackBoardBase {
protected:
// Data
public:
// Method
BlackBoardBase(void);
virtual void initialize(void); // 初期化処理
}; | [
"astora.home@gmail.com"
] | astora.home@gmail.com |
cd09205777818acee21d9414931994e644ce8442 | 6ced41da926682548df646099662e79d7a6022c5 | /aws-cpp-sdk-auditmanager/include/aws/auditmanager/model/CreateControlMappingSource.h | ffdc4054c054f3da9a55763d37ea0e067e865f05 | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | irods/aws-sdk-cpp | 139104843de529f615defa4f6b8e20bc95a6be05 | 2c7fb1a048c96713a28b730e1f48096bd231e932 | refs/heads/main | 2023-07-25T12:12:04.363757 | 2022-08-26T15:33:31 | 2022-08-26T15:33:31 | 141,315,346 | 0 | 1 | Apache-2.0 | 2022-08-26T17:45:09 | 2018-07-17T16:24:06 | C++ | UTF-8 | C++ | false | false | 12,262 | h | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/auditmanager/AuditManager_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/auditmanager/model/SourceSetUpOption.h>
#include <aws/auditmanager/model/SourceType.h>
#include <aws/auditmanager/model/SourceKeyword.h>
#include <aws/auditmanager/model/SourceFrequency.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace AuditManager
{
namespace Model
{
/**
* <p> The control mapping fields that represent the source for evidence
* collection, along with related parameters and metadata. This doesn't contain
* <code>mappingID</code>. </p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/CreateControlMappingSource">AWS
* API Reference</a></p>
*/
class AWS_AUDITMANAGER_API CreateControlMappingSource
{
public:
CreateControlMappingSource();
CreateControlMappingSource(Aws::Utils::Json::JsonView jsonValue);
CreateControlMappingSource& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p> The name of the control mapping data source. </p>
*/
inline const Aws::String& GetSourceName() const{ return m_sourceName; }
/**
* <p> The name of the control mapping data source. </p>
*/
inline bool SourceNameHasBeenSet() const { return m_sourceNameHasBeenSet; }
/**
* <p> The name of the control mapping data source. </p>
*/
inline void SetSourceName(const Aws::String& value) { m_sourceNameHasBeenSet = true; m_sourceName = value; }
/**
* <p> The name of the control mapping data source. </p>
*/
inline void SetSourceName(Aws::String&& value) { m_sourceNameHasBeenSet = true; m_sourceName = std::move(value); }
/**
* <p> The name of the control mapping data source. </p>
*/
inline void SetSourceName(const char* value) { m_sourceNameHasBeenSet = true; m_sourceName.assign(value); }
/**
* <p> The name of the control mapping data source. </p>
*/
inline CreateControlMappingSource& WithSourceName(const Aws::String& value) { SetSourceName(value); return *this;}
/**
* <p> The name of the control mapping data source. </p>
*/
inline CreateControlMappingSource& WithSourceName(Aws::String&& value) { SetSourceName(std::move(value)); return *this;}
/**
* <p> The name of the control mapping data source. </p>
*/
inline CreateControlMappingSource& WithSourceName(const char* value) { SetSourceName(value); return *this;}
/**
* <p> The description of the data source that determines where Audit Manager
* collects evidence from for the control. </p>
*/
inline const Aws::String& GetSourceDescription() const{ return m_sourceDescription; }
/**
* <p> The description of the data source that determines where Audit Manager
* collects evidence from for the control. </p>
*/
inline bool SourceDescriptionHasBeenSet() const { return m_sourceDescriptionHasBeenSet; }
/**
* <p> The description of the data source that determines where Audit Manager
* collects evidence from for the control. </p>
*/
inline void SetSourceDescription(const Aws::String& value) { m_sourceDescriptionHasBeenSet = true; m_sourceDescription = value; }
/**
* <p> The description of the data source that determines where Audit Manager
* collects evidence from for the control. </p>
*/
inline void SetSourceDescription(Aws::String&& value) { m_sourceDescriptionHasBeenSet = true; m_sourceDescription = std::move(value); }
/**
* <p> The description of the data source that determines where Audit Manager
* collects evidence from for the control. </p>
*/
inline void SetSourceDescription(const char* value) { m_sourceDescriptionHasBeenSet = true; m_sourceDescription.assign(value); }
/**
* <p> The description of the data source that determines where Audit Manager
* collects evidence from for the control. </p>
*/
inline CreateControlMappingSource& WithSourceDescription(const Aws::String& value) { SetSourceDescription(value); return *this;}
/**
* <p> The description of the data source that determines where Audit Manager
* collects evidence from for the control. </p>
*/
inline CreateControlMappingSource& WithSourceDescription(Aws::String&& value) { SetSourceDescription(std::move(value)); return *this;}
/**
* <p> The description of the data source that determines where Audit Manager
* collects evidence from for the control. </p>
*/
inline CreateControlMappingSource& WithSourceDescription(const char* value) { SetSourceDescription(value); return *this;}
/**
* <p> The setup option for the data source, which reflects if the evidence
* collection is automated or manual. </p>
*/
inline const SourceSetUpOption& GetSourceSetUpOption() const{ return m_sourceSetUpOption; }
/**
* <p> The setup option for the data source, which reflects if the evidence
* collection is automated or manual. </p>
*/
inline bool SourceSetUpOptionHasBeenSet() const { return m_sourceSetUpOptionHasBeenSet; }
/**
* <p> The setup option for the data source, which reflects if the evidence
* collection is automated or manual. </p>
*/
inline void SetSourceSetUpOption(const SourceSetUpOption& value) { m_sourceSetUpOptionHasBeenSet = true; m_sourceSetUpOption = value; }
/**
* <p> The setup option for the data source, which reflects if the evidence
* collection is automated or manual. </p>
*/
inline void SetSourceSetUpOption(SourceSetUpOption&& value) { m_sourceSetUpOptionHasBeenSet = true; m_sourceSetUpOption = std::move(value); }
/**
* <p> The setup option for the data source, which reflects if the evidence
* collection is automated or manual. </p>
*/
inline CreateControlMappingSource& WithSourceSetUpOption(const SourceSetUpOption& value) { SetSourceSetUpOption(value); return *this;}
/**
* <p> The setup option for the data source, which reflects if the evidence
* collection is automated or manual. </p>
*/
inline CreateControlMappingSource& WithSourceSetUpOption(SourceSetUpOption&& value) { SetSourceSetUpOption(std::move(value)); return *this;}
/**
* <p> Specifies one of the five types of data sources for evidence collection.
* </p>
*/
inline const SourceType& GetSourceType() const{ return m_sourceType; }
/**
* <p> Specifies one of the five types of data sources for evidence collection.
* </p>
*/
inline bool SourceTypeHasBeenSet() const { return m_sourceTypeHasBeenSet; }
/**
* <p> Specifies one of the five types of data sources for evidence collection.
* </p>
*/
inline void SetSourceType(const SourceType& value) { m_sourceTypeHasBeenSet = true; m_sourceType = value; }
/**
* <p> Specifies one of the five types of data sources for evidence collection.
* </p>
*/
inline void SetSourceType(SourceType&& value) { m_sourceTypeHasBeenSet = true; m_sourceType = std::move(value); }
/**
* <p> Specifies one of the five types of data sources for evidence collection.
* </p>
*/
inline CreateControlMappingSource& WithSourceType(const SourceType& value) { SetSourceType(value); return *this;}
/**
* <p> Specifies one of the five types of data sources for evidence collection.
* </p>
*/
inline CreateControlMappingSource& WithSourceType(SourceType&& value) { SetSourceType(std::move(value)); return *this;}
inline const SourceKeyword& GetSourceKeyword() const{ return m_sourceKeyword; }
inline bool SourceKeywordHasBeenSet() const { return m_sourceKeywordHasBeenSet; }
inline void SetSourceKeyword(const SourceKeyword& value) { m_sourceKeywordHasBeenSet = true; m_sourceKeyword = value; }
inline void SetSourceKeyword(SourceKeyword&& value) { m_sourceKeywordHasBeenSet = true; m_sourceKeyword = std::move(value); }
inline CreateControlMappingSource& WithSourceKeyword(const SourceKeyword& value) { SetSourceKeyword(value); return *this;}
inline CreateControlMappingSource& WithSourceKeyword(SourceKeyword&& value) { SetSourceKeyword(std::move(value)); return *this;}
/**
* <p> The frequency of evidence collection for the control mapping source. </p>
*/
inline const SourceFrequency& GetSourceFrequency() const{ return m_sourceFrequency; }
/**
* <p> The frequency of evidence collection for the control mapping source. </p>
*/
inline bool SourceFrequencyHasBeenSet() const { return m_sourceFrequencyHasBeenSet; }
/**
* <p> The frequency of evidence collection for the control mapping source. </p>
*/
inline void SetSourceFrequency(const SourceFrequency& value) { m_sourceFrequencyHasBeenSet = true; m_sourceFrequency = value; }
/**
* <p> The frequency of evidence collection for the control mapping source. </p>
*/
inline void SetSourceFrequency(SourceFrequency&& value) { m_sourceFrequencyHasBeenSet = true; m_sourceFrequency = std::move(value); }
/**
* <p> The frequency of evidence collection for the control mapping source. </p>
*/
inline CreateControlMappingSource& WithSourceFrequency(const SourceFrequency& value) { SetSourceFrequency(value); return *this;}
/**
* <p> The frequency of evidence collection for the control mapping source. </p>
*/
inline CreateControlMappingSource& WithSourceFrequency(SourceFrequency&& value) { SetSourceFrequency(std::move(value)); return *this;}
/**
* <p> The instructions for troubleshooting the control. </p>
*/
inline const Aws::String& GetTroubleshootingText() const{ return m_troubleshootingText; }
/**
* <p> The instructions for troubleshooting the control. </p>
*/
inline bool TroubleshootingTextHasBeenSet() const { return m_troubleshootingTextHasBeenSet; }
/**
* <p> The instructions for troubleshooting the control. </p>
*/
inline void SetTroubleshootingText(const Aws::String& value) { m_troubleshootingTextHasBeenSet = true; m_troubleshootingText = value; }
/**
* <p> The instructions for troubleshooting the control. </p>
*/
inline void SetTroubleshootingText(Aws::String&& value) { m_troubleshootingTextHasBeenSet = true; m_troubleshootingText = std::move(value); }
/**
* <p> The instructions for troubleshooting the control. </p>
*/
inline void SetTroubleshootingText(const char* value) { m_troubleshootingTextHasBeenSet = true; m_troubleshootingText.assign(value); }
/**
* <p> The instructions for troubleshooting the control. </p>
*/
inline CreateControlMappingSource& WithTroubleshootingText(const Aws::String& value) { SetTroubleshootingText(value); return *this;}
/**
* <p> The instructions for troubleshooting the control. </p>
*/
inline CreateControlMappingSource& WithTroubleshootingText(Aws::String&& value) { SetTroubleshootingText(std::move(value)); return *this;}
/**
* <p> The instructions for troubleshooting the control. </p>
*/
inline CreateControlMappingSource& WithTroubleshootingText(const char* value) { SetTroubleshootingText(value); return *this;}
private:
Aws::String m_sourceName;
bool m_sourceNameHasBeenSet;
Aws::String m_sourceDescription;
bool m_sourceDescriptionHasBeenSet;
SourceSetUpOption m_sourceSetUpOption;
bool m_sourceSetUpOptionHasBeenSet;
SourceType m_sourceType;
bool m_sourceTypeHasBeenSet;
SourceKeyword m_sourceKeyword;
bool m_sourceKeywordHasBeenSet;
SourceFrequency m_sourceFrequency;
bool m_sourceFrequencyHasBeenSet;
Aws::String m_troubleshootingText;
bool m_troubleshootingTextHasBeenSet;
};
} // namespace Model
} // namespace AuditManager
} // namespace Aws
| [
"aws-sdk-cpp-automation@github.com"
] | aws-sdk-cpp-automation@github.com |
325b82eb96ef050131ea2fd1ca2dbfd8362c7240 | 77f13ade1c7a6455ba9eb1d62136bf8961fb5aa0 | /src/server/server.cpp | 20cac40b631ceb6c38b0b767bf3dfa2478a2162c | [] | no_license | eshad/simplechat | 207859dd75635af9de0cca772cf0b0f404ad4eb1 | 281a900860a52be41bf914258c760949ed200a81 | refs/heads/master | 2020-09-16T14:48:25.756700 | 2015-04-21T18:28:13 | 2015-04-21T18:28:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,462 | cpp | #include "server.hpp"
#include "client.hpp"
#if defined(_WIN32)
#include <winsock.h>
#else
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#endif
#include <iostream>
Server::Server() : m_port(0), m_running(false), m_socket(-1), m_listener(nullptr), m_clients()
{
memset(m_buffer, 0, 1024);
}
Server::~Server()
{
delete m_listener;
}
void Server::SetPortNumber(unsigned short port)
{
m_port = port;
}
void Server::ClearBuffer()
{
memset(m_buffer, 0, 1024);
}
bool Server::ParseCommand(Client *client, const std::string& msg)
{
const char *string = msg.c_str();
char c_command[255];
if((string[0] >= 0 && string[0] <= 31) || string[0] < 0) return true;
if(string[0] != '/') return false;
sscanf(string, "/%s\r\n", c_command);
sscanf(string, "/%*s %1024[0-9a-zA-Z. ]s\r\n", m_buffer);
if(strcmp(c_command, "exit") == 0) {
client->Disconnect();
} else if(strcmp(c_command, "name") == 0) {
if(strlen(m_buffer) <= 10) {
std::string old_name = client->GetName();
client->SetName(m_buffer);
m_nicks[client->GetIP()] = client->GetName();
this->Broadcast("User " + old_name +" changed his nick to " + client->GetName() + "\n");
} else {
client->SendData("The name can't be longer than 10 characters\n");
}
} else {
if(client->GetGroup() != GROUP::ADMINISTRATOR) {
client->SendData("You don't have sufficient permissions.\n");
return true;
}
if(strcmp(c_command, "kick") == 0) {
bool found = false;
for(Client& c : m_clients) {
if(strcmp(m_buffer, c.GetName().c_str()) == 0) {
this->Broadcast(c.GetName() + " with IP " + c.GetIP() + " has been kicked.\n");
c.Disconnect("Kicked");
this->Broadcast(m_buffer);
found = true;
break;
}
}
if(!found) {
std::string username = std::string(m_buffer);
client->SendData("Couldn't find the user " + username + ".\n");
}
}
else if(strcmp(c_command, "ban") == 0) {
bool found = false;
for(Client& c : m_clients) {
if(strcmp(m_buffer, c.GetName().c_str()) == 0) {
this->Broadcast(c.GetName() + " with IP " + c.GetIP() + " has been banned.\n");
c.Disconnect("Banned");
m_bans.push_back(c.GetIP());
found = true;
break;
}
}
if(!found) {
std::string username = std::string(m_buffer);
client->SendData("Could not find the user " + username + ".\n");
}
}
else if(strcmp(c_command, "unban") == 0) {
bool found = false;
for(auto i = m_bans.begin(); i != m_bans.end(); ++i) {
if(strcmp(m_buffer, (*i).c_str()) == 0) {
found = true;
m_bans.erase(i);
break;
}
}
if(!found) {
this->ClearBuffer();
sprintf(m_buffer, "This IP is not banned.\n");
client->SendData(m_buffer);
}
}
else if(strcmp(c_command, "shutdown") == 0) {
this->ClearBuffer();
client->SendData("The server is closing\n");
m_running = false;
} else {
this->ClearBuffer();
client->SendData("Unrecognized command\n");
return true;
}
}
std::cout << "[CMD] " << msg;
this->ClearBuffer();
return true;
}
void Server::ReadNicknames()
{
char ip[255];
FILE *f = fopen(NICKNAMES, "rb");
if(!f) return;
while(!feof(f)) {
if(fscanf(f, "%s %1024[0-9a-zA-Z. ]s\n", ip, m_buffer) != 2)
continue;
m_nicks.insert(std::make_pair(std::string(ip), std::string(m_buffer)));
}
fclose(f);
}
void Server::WriteNicknames()
{
FILE *f = fopen(NICKNAMES, "wb+");
for(auto i = m_nicks.begin(); i != m_nicks.end(); ++i) {
fprintf(f, "%s %s\n", i->first.c_str(), i->second.c_str());
}
fclose(f);
}
std::string Server::GetNickname(std::string ip)
{
auto i = m_nicks.find(ip);
if(i != m_nicks.end()) return i->second;
else return "noname";
}
bool Server::Start() {
try {
#if defined(_WIN32)
WSADATA wsadata;
if(WSAStartup(MAKEWORD(2,2), &wsadata) != 0)
throw "WSAStartup failed.";
#endif
if(m_port <= 0) throw "Incorrect port";
m_socket = socket(AF_INET, SOCK_STREAM, 0);
#if defined(_WIN32)
ioctlsocket(m_socket, FIONBIO, 0);
#endif
struct sockaddr_in sin;
memset( &sin, 0, sizeof sin );
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = INADDR_ANY;
sin.sin_port = htons(m_port);
/* reuse the address, normally the socket stays in a TIME_WAIT state and you can't open it again */
int yes = 1;
setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
if (bind(m_socket, (struct sockaddr*)&sin, sizeof sin) < 0)
throw "Bind has failed.";
if(listen(m_socket, 0) < 0)
throw "Listen has failed.";
m_running = true;
m_listener = new std::thread(Server::Listen, this);
if(m_listener == nullptr)
throw "Couldn't create the listener thread";
}
catch(std::string e) {
std::cerr << "Couldn't listen the port number " << m_port << "\n";
std::cerr << e << std::endl;
return false;
}
std::cout << "Server listening at " << m_port << "!" << std::endl;
this->ReadNicknames();
while(m_running) {
/* lock the clients list */
std::lock_guard<std::mutex> lock(m_clients_mtx);
for(auto i = m_clients.begin(); i != m_clients.end();) {
Client& client = (*i);
if(!client.IsInitialized()) continue;
std::queue<std::string>* messageQueue = nullptr;
if(!client.IsConnected()) {
this->Broadcast(client.GetName() + " has disconnected\n");
i = m_clients.erase(i);
continue;
}
messageQueue = client.GetMessageQueue();
if(messageQueue->size() > 0) {
while(!messageQueue->empty()) {
std::string str = messageQueue->front();
if(!this->ParseCommand(&client, str)) {
this->Broadcast(&client, str);
}
messageQueue->pop();
}
}
++i;
}
}
this->WriteNicknames();
for(auto it = m_clients.begin(); it != m_clients.end(); ++it) {
m_clients.erase(it);
}
shutdown(m_socket, 2);
#if defined(_WIN32)
closesocket(m_socket);
#else
close(m_socket);
#endif
m_listener->join();
return true;
}
void Server::Broadcast(Client* from, std::string message)
{
for(Client& client : m_clients) {
client.SendMsg(from, message);
}
}
void Server::Broadcast(std::string message)
{
std::cout << message;
for(Client& client : m_clients) {
if(!client.IsConnected()) continue;
client.SendData(message);
}
}
void Server::Listen(Server* server)
{
auto bans = server->GetBansList();
std::list<Client>& clients = server->GetClientsList();
while(server->IsRunning()) {
struct sockaddr_in adress;
socklen_t length = sizeof adress;
int socket = accept(server->GetSocket(), (struct sockaddr*)&adress, &length);
if(socket < 0) {
#if defined(_WIN32)
std::cout << "Error: " << WSAGetLastError() << std::endl;
#endif
continue;
}
/* we need to add a new client, lock the list */
std::lock_guard<std::mutex> lock(server->GetClientsMutex());
clients.emplace_back();
Client& client = clients.back();
client.SetSocket(socket);
if(!client.Initialize()) {
clients.pop_back();
continue;
}
bool found = false;
for(auto i = bans->begin(); i != bans->end(); ++i) {
if(client.GetIP() == (*i)) {
client.Disconnect("You are banned");
found = true;
clients.pop_back();
break;
}
}
if(found) continue;
if(client.GetIP() == "127.0.0.1") {
client.SetGroup(GROUP::ADMINISTRATOR);
}
/* look for a saved nickname */
client.SetName(server->GetNickname(client.GetIP()));
/* clear the user's screen */
client.SendRaw("\033[2J\033[1;1H");
/* send a welcome message */
client.Prompt();
client.SendData("Welcome to the server, " + client.GetName() + "!\n");
server->Broadcast("User " + client.GetName() + " with IP " + client.GetIP() + " has joined.\n");
}
}
| [
"boudra.moha@gmail.com"
] | boudra.moha@gmail.com |
9f833a047e297c4df1db35a3342e317a41cd6bd2 | e96dbc2964dabbc089a8a95ec69866f5bfd5e529 | /projects/undergraduate/cs153/program1/main.cpp | ef81904c9fec0901a2e74978723b7336e4e8e90d | [] | no_license | umairsajid/my-random-cpp-libraries | 871ba5a748732652438eda19ab1cc9ded25e9489 | 8c07ed3d4eba2bb5aeebe368a94c9b16676de819 | refs/heads/master | 2021-01-21T03:14:23.904870 | 2013-05-10T23:18:48 | 2013-05-10T23:18:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 521 | cpp | ///////////////////////////////////////////////////////////////////////////////
/// @file main.cpp
/// @author Gary Steelman, CS153-B
/// @brief Main function containing a Hello World program for a QT4 application
///////////////////////////////////////////////////////////////////////////////
#include <QApplication>
#include <QLabel>
int main( int argc, char *argv[] )
{
QApplication app( argc, argv );
QLabel * label = new QLabel( "Hello Qt!" );
label->show();
return app.exec();
}
| [
"flaming.zelda@gmail.com@4324a9da-489b-ea18-4a0b-e0fe39f471b6"
] | flaming.zelda@gmail.com@4324a9da-489b-ea18-4a0b-e0fe39f471b6 |
0368c29727911ba1e49bbcf589416df8a8f1cc5b | c628b3610ac04d3ecd3b7901fd372af5377e9c88 | /MobSpawn.cpp | a2b68f112b1944b988ed6bc0fff7349dceb0de70 | [] | no_license | spencerduff/MapBuilder2 | bd66e1f5166bdbc420ecb4f798d53c66d650c706 | 9ababb68e9373e31e40eb4dc01b58490b44e9bcf | refs/heads/master | 2021-01-17T12:35:40.115344 | 2018-04-29T03:23:17 | 2018-04-29T03:23:17 | 57,276,610 | 0 | 0 | null | 2016-06-01T20:52:26 | 2016-04-28T06:28:20 | C++ | UTF-8 | C++ | false | false | 703 | cpp | #include "MobSpawn.h"
MobSpawn::~MobSpawn(){
for (auto it = spawns.begin(); it < spawns.end();){
delete (*it);
it = spawns.begin();
}
spawns.clear();
}
void MobSpawn::removeMe(Character* c){
for (unsigned int i = 0; i < spawns.size(); i++){
if (spawns[i] == c){
swap(spawns[i], spawns.back());
spawns.pop_back();
}
}
}
int MobSpawn::getAgentNum(){
return NUM_OF_AGENTS;
}
GoblinSpawn::GoblinSpawn(Map* m){
currMap = m;
maxNumOfSpawns = NUM_OF_AGENTS;
spawnToCapacity();
}
void GoblinSpawn::spawnToCapacity(){
for (int i = spawns.size(); i < maxNumOfSpawns; i++){
Character* temp = new Goblin(currMap, this);
spawns.push_back(temp);
currMap->placeRandomChar(temp);
}
} | [
"spencer.duff@gmail.com"
] | spencer.duff@gmail.com |
58c42e2f4a869600829cf01d4881e226272f72b6 | a583ce8dbc8a0998866b3df6c19498167e3e514f | /longest-palindromic-substring.cc | 2835446d0c7d5fe4699a19d297a1e2b5d163f8bf | [] | no_license | sealiay/leetcode | 12826662313a99cf9cf36792bced3d0c1503c277 | d57d2bfe5e474d43f0aad29a90993690d2b5d2e3 | refs/heads/master | 2016-09-10T18:28:08.010252 | 2014-03-29T06:29:15 | 2014-03-29T06:29:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 793 | cc | class Solution {
public:
typedef string::iterator I;
string longestPalindrome(string s) {
pair<I, I> m, c;
for (I i = s.begin(); i != s.end(); ++i) {
c = lp1(s.begin(), s.end(), i);
if ( c.second - c.first > m.second - m.first ) m = c;
c = lp2(s.begin(), s.end(), i);
if ( c.second - c.first > m.second - m.first ) m = c;
}
return string(m.first, m.second);
}
pair<I, I> lp1(I b, I e, I c) {
size_t i = 0;
while ( i <= c-b && i < e-c && *(c-i) == *(c+i) ) ++i;
return make_pair(c-i+1, c+i);
}
pair<I, I> lp2(I b, I e, I c) {
size_t i = 0;
while ( i <= c-b && i < e-c-1 && *(c-i) == *(c+i+1) ) ++i;
return make_pair(c-i+1, c+i+1);
}
};
| [
"eric.3zc@gmail.com"
] | eric.3zc@gmail.com |
6042417fc6a4dde06b082d22562ab596a354b734 | 75b6e68682d2d6b45625b55d361f7c0dc2b7befe | /004_Conditionals/010_Switch/010_Switch.cpp | 65cac09d6f22d9ec42252a99300bf0cc10fe1921 | [] | no_license | syurskyi/ITVDN_C___Starter | 32f561b0956aaea2799d52c21db8875c943af465 | f3d490f90ecf4c31e2265627d1c2819b0fdf1b89 | refs/heads/master | 2020-12-24T02:35:43.642409 | 2020-01-31T03:20:34 | 2020-01-31T03:20:34 | 236,926,687 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 950 | cpp | #include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
setlocale(LC_ALL, "rus");
cout << "Выберите один из пунктов меню: " << endl;
cout << "1. Создать файл." << endl;
cout << "2. Сохранить файл." << endl;
cout << "3. Завершить программу." << endl;
char action;
cin >> action;
switch (action)
{
case '1':
{
cout << "Создан новый файл." << endl;
break;
}
case '2':
{
cout << "Файл сохранен." << endl;
break;
}
case '3':
{
cout << "До свидания!" << endl;
break;
}
default:
{
cout << "Неверный выбор, попробуйте снова!";
break;
}
}
cin.get();
return 0;
}
| [
"sergejyurskyj@yahoo.com"
] | sergejyurskyj@yahoo.com |
ab9657cf2b9f9846ebe96b0a7ddbd2fa12b645fc | 84c49077f07a4d87a535e1a6f09b92ee1c658d50 | /Script/histgraphinterfaces.h | 3dcac9d7f4147c2df8be34edaf97ec53e5d378c0 | [] | no_license | andrmor/TRB3reader | 2f83cb223a814fb6dff988995e0925fa65eb6227 | 0d9b6b81b7c0ffd3b1a2badb2139540210fba650 | refs/heads/master | 2022-12-15T07:48:32.227836 | 2020-11-06T14:06:01 | 2020-11-06T14:06:01 | 109,270,422 | 0 | 0 | null | 2020-11-06T14:06:02 | 2017-11-02T13:46:10 | C++ | UTF-8 | C++ | false | false | 3,034 | h | #ifndef HISTGRAPHINTERFACES_H
#define HISTGRAPHINTERFACES_H
#include "ascriptinterface.h"
#include <QString>
#include <QVariant>
class TmpObjHubClass;
class TObject;
// ---- H I S T O G R A M S ---- (TH1D of ROOT)
class AInterfaceToHist : public AScriptInterface
{
Q_OBJECT
public:
AInterfaceToHist(TmpObjHubClass *TmpHub);
~AInterfaceToHist(){}
virtual bool IsMultithreadCapable() const {return true;}
public slots:
void NewHist(QString HistName, int bins, double start, double stop);
void NewHist2D(QString HistName, int binsX, double startX, double stopX, int binsY, double startY, double stopY);
void SetTitles(QString HistName, QString X_Title, QString Y_Title, QString Z_Title = "");
void SetLineProperties(QString HistName, int LineColor, int LineStyle, int LineWidth);
void SetFillProperties(QString HistName, int color, int style);
void Fill(QString HistName, double val, double weight);
void Fill2D(QString HistName, double x, double y, double weight);
void FillArr(QString HistName, QVariant Array);
void Fill2DArr(QString HistName, QVariant Array);
void Divide(QString HistName, QString HistToDivideWith);
void Draw(QString HistName, QString options);
void DrawStack(QVariant HistNames, QString options, QString XTitle = "", QString YTitle = "");
void Save(QString HistName, QString FileName); // ***!!! add storage / delete!!!
void Smooth(QString HistName, int times);
QVariant FitGauss(QString HistName, QString options="");
QVariant FitGaussWithInit(QString HistName, QVariant InitialParValues, QString options="");
QVariant FindPeaks(const QString& HistName, int numPeaks, double sigma, double threshold, bool bSuppressDraw = true);
bool Delete(QString HistName);
void DeleteAllHist();
bool IsHistExist(QString HistName);
void SetOptStat(QString opt);
signals:
void RequestDraw(TObject* obj, QString options, bool fFocus);
private:
TmpObjHubClass *TmpHub;
};
// ---- G R A P H S ---- (TGraph of ROOT)
class AInterfaceToGraph : public AScriptInterface
{
Q_OBJECT
public:
AInterfaceToGraph(TmpObjHubClass *TmpHub);
~AInterfaceToGraph(){}
virtual bool IsMultithreadCapable() const {return true;}
public slots:
void NewGraph(QString GraphName);
void SetMarkerProperties(QString GraphName, int MarkerColor, int MarkerStyle, int MarkerSize);
void SetLineProperties(QString GraphName, int LineColor, int LineStyle, int LineWidth);
void SetTitles(QString GraphName, QString X_Title, QString Y_Title);
void AddPoint(QString GraphName, double x, double y);
void AddPoints(QString GraphName, QVariant xArray, QVariant yArray);
void AddPoints(QString GraphName, QVariant xyArray);
void Draw(QString GraphName, QString options);
void Save(QString GraphName, QString FileName);
bool Delete(QString GraphName);
void DeleteAllGraph();
bool IsGraphExists(QString GraphName);
signals:
void RequestDraw(TObject* obj, QString options, bool fFocus);
private:
TmpObjHubClass *TmpHub;
};
#endif // HISTGRAPHINTERFACES_H
| [
"andreimorozov@hotmail.com"
] | andreimorozov@hotmail.com |
d1d22d985a81d3b89e6aab180189213aadc5cf72 | a7db885685690fdf9bceaff5e9fc5aa39b293304 | /1066b.cpp | 322cc91b4cfcdd1e4fe9ee6d39f95996c974bf2f | [] | no_license | vikas0o7/important_cpp_questions | 825aafdaf5efceff7f599a450c77ef68620396a2 | 557b5299dd6d181505cc6580e9cb948476a94102 | refs/heads/master | 2020-10-02T01:56:15.566418 | 2019-12-12T18:48:51 | 2019-12-12T18:48:51 | 227,674,566 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 954 | cpp | #include<bits/stdc++.h>
#define io ios_base::sync_with_stdio(false)
#define mp make_pair
#define pb push_back
using namespace std;
#define error(args...) { string _s = #args; replace(_s.begin(), _s.end(), ',', ' '); stringstream _ss(_s); istream_iterator<string> _it(_ss); err(_it, args); }
void err(istream_iterator<string> it) {}
template<typename T, typename... Args>
void err(istream_iterator<string> it, T a, Args... args) {
cerr << *it << " = " << a << endl;
err(++it, args...);
}
typedef long long int ll;
typedef vector< int > vi;
typedef vector< vi > vvi;
typedef pair<int,int> ii;
int main()
{
io;
int n,r; cin>>n>>r;
vector<int> a(n),v;
//v.pb(-1);
for(int i=0;i<n;i++) {
cin>>a[i];
}
int cnt=0,x=-1;
for(int i=0;i<n;i++){
cnt++; int t=0;
for(int j=-r+1;j<r && i+j<n;j++){
if(i+j<0) continue;
if(a[i+j]){
x=i+j+r-1; t=1;
}
}
if(t==0){cout<<-1;return 0;}
//error(i,x,cnt)
i=x;
}
cout<<cnt;
return 0;
} | [
"vikasdevil.singh834@gmail.com"
] | vikasdevil.singh834@gmail.com |
ed07ec9a5dd070cb1d850499b33ace78d77d9fba | de88ceb0d02fda397146105d86ac6842821b7b3f | /new_agency4/new_agency3/new_agency3/archive.cpp | 355319641533bbb7c4518e05479a25e3461494de | [] | no_license | emnagharbi/Smart_News_Agency_2A20 | 61356240d48e414ef0929a42bee8217008766588 | d630fae75b60d1b535b4244ea641bf475b222206 | refs/heads/master | 2023-04-22T12:52:16.247888 | 2021-05-04T20:32:10 | 2021-05-04T20:32:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,306 | cpp | #include "archive.h"
archive::archive()
{
}
archive::archive(QString s1 ,QString s2,QString s3,QString s4 ){
id=s1;
intitule=s2;
access=s3;
traitement=s4;
}
bool archive::ajouter(){
QSqlQuery query;
query.prepare("INSERT INTO ARCHIVE (ID, INTITULE, DROIT_ACCESS,TRAITEMENT) VALUES (:id, :intitule, :access,:traitement)");
query.bindValue(":id", id);
query.bindValue(":intitule",intitule);
query.bindValue(":access",access);
query.bindValue(":traitement",traitement);
return query.exec();
}
bool archive::modifier(QString selected){
QSqlQuery query;
query.prepare(" UPDATE ARCHIVE SET INTITULE= :intitule ,DROIT_ACCESS= :access, TRAITEMENT=:traitement where ID= :id");
query.bindValue(":id", selected);
query.bindValue(":intitule",intitule);
query.bindValue(":access",access);
query.bindValue(":traitement",traitement);
return query.exec();
}
QSqlQueryModel * archive::afficher(){
QSqlQueryModel * modal=new QSqlQueryModel();
modal->setQuery("SELECT * FROM ARCHIVE");
return modal;
}
bool archive::supprimer(QString selected){
QSqlQuery query;
query.prepare("Delete from ARCHIVE where ID = :id ");
query.bindValue(":id", selected);
return query.exec();
}
| [
"wael.belgaied@esprit.tn"
] | wael.belgaied@esprit.tn |
316f6c5ea89a0bf5694572a87ae4492663abb877 | 5e5779959387873c9d6db1260aaabd9d001bc81b | /src/rpc/protocol.h | a57307844b42947f6ea4c0aa22acbda9ef9b0dac | [
"MIT"
] | permissive | cryptoknowing/gastrocoin | 85e6d69bb1c4fac40f7a0e290b9393768a853436 | dd0c6a5add7a5bec064943aca21a734c49cdd8ad | refs/heads/main | 2023-03-15T02:56:23.709522 | 2021-03-28T22:57:12 | 2021-03-28T22:57:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,661 | h | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2017-2018 The PIVX developers
// Copyright (c) 2021-2021 The GastroCoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_RPCPROTOCOL_H
#define BITCOIN_RPCPROTOCOL_H
#include <list>
#include <map>
#include <stdint.h>
#include <string>
#include <boost/filesystem.hpp>
#include <univalue.h>
//! HTTP status codes
enum HTTPStatusCode {
HTTP_OK = 200,
HTTP_BAD_REQUEST = 400,
HTTP_UNAUTHORIZED = 401,
HTTP_FORBIDDEN = 403,
HTTP_NOT_FOUND = 404,
HTTP_BAD_METHOD = 405,
HTTP_INTERNAL_SERVER_ERROR = 500,
HTTP_SERVICE_UNAVAILABLE = 503,
};
//! GastroCoin RPC error codes
enum RPCErrorCode {
//! Standard JSON-RPC 2.0 errors
RPC_INVALID_REQUEST = -32600,
RPC_METHOD_NOT_FOUND = -32601,
RPC_INVALID_PARAMS = -32602,
RPC_INTERNAL_ERROR = -32603,
RPC_PARSE_ERROR = -32700,
//! General application defined errors
RPC_MISC_ERROR = -1, //! std::exception thrown in command handling
RPC_FORBIDDEN_BY_SAFE_MODE = -2, //! Server is in safe mode, and command is not allowed in safe mode
RPC_TYPE_ERROR = -3, //! Unexpected type was passed as parameter
RPC_INVALID_ADDRESS_OR_KEY = -5, //! Invalid address or key
RPC_OUT_OF_MEMORY = -7, //! Ran out of memory during operation
RPC_INVALID_PARAMETER = -8, //! Invalid, missing or duplicate parameter
RPC_DATABASE_ERROR = -20, //! Database error
RPC_DESERIALIZATION_ERROR = -22, //! Error parsing or validating structure in raw format
RPC_VERIFY_ERROR = -25, //! General error during transaction or block submission
RPC_VERIFY_REJECTED = -26, //! Transaction or block was rejected by network rules
RPC_VERIFY_ALREADY_IN_CHAIN = -27, //! Transaction already in chain
RPC_IN_WARMUP = -28, //! Client still warming up
//! Aliases for backward compatibility
RPC_TRANSACTION_ERROR = RPC_VERIFY_ERROR,
RPC_TRANSACTION_REJECTED = RPC_VERIFY_REJECTED,
RPC_TRANSACTION_ALREADY_IN_CHAIN = RPC_VERIFY_ALREADY_IN_CHAIN,
//! P2P client errors
RPC_CLIENT_NOT_CONNECTED = -9, //! GastroCoin is not connected
RPC_CLIENT_IN_INITIAL_DOWNLOAD = -10, //! Still downloading initial blocks
RPC_CLIENT_NODE_ALREADY_ADDED = -23, //! Node is already added
RPC_CLIENT_NODE_NOT_ADDED = -24, //! Node has not been added before
RPC_CLIENT_NODE_NOT_CONNECTED = -29, //! Node to disconnect not found in connected nodes
RPC_CLIENT_INVALID_IP_OR_SUBNET = -30, //! Invalid IP/Subnet
//! Wallet errors
RPC_WALLET_ERROR = -4, //! Unspecified problem with wallet (key not found etc.)
RPC_WALLET_INSUFFICIENT_FUNDS = -6, //! Not enough funds in wallet or account
RPC_WALLET_INVALID_ACCOUNT_NAME = -11, //! Invalid account name
RPC_WALLET_KEYPOOL_RAN_OUT = -12, //! Keypool ran out, call keypoolrefill first
RPC_WALLET_UNLOCK_NEEDED = -13, //! Enter the wallet passphrase with walletpassphrase first
RPC_WALLET_PASSPHRASE_INCORRECT = -14, //! The wallet passphrase entered was incorrect
RPC_WALLET_WRONG_ENC_STATE = -15, //! Command given in wrong wallet encryption state (encrypting an encrypted wallet etc.)
RPC_WALLET_ENCRYPTION_FAILED = -16, //! Failed to encrypt the wallet
RPC_WALLET_ALREADY_UNLOCKED = -17, //! Wallet is already unlocked
};
std::string JSONRPCRequest(const std::string& strMethod, const UniValue& params, const UniValue& id);
UniValue JSONRPCReplyObj(const UniValue& result, const UniValue& error, const UniValue& id);
std::string JSONRPCReply(const UniValue& result, const UniValue& error, const UniValue& id);
UniValue JSONRPCError(int code, const std::string& message);
/** Get name of RPC authentication cookie file */
boost::filesystem::path GetAuthCookieFile();
/** Generate a new RPC authentication cookie and write it to disk */
bool GenerateAuthCookie(std::string *cookie_out);
/** Read the RPC authentication cookie from disk */
bool GetAuthCookie(std::string *cookie_out);
/** Delete RPC authentication cookie from disk */
void DeleteAuthCookie();
#endif // BITCOIN_RPCPROTOCOL_H
| [
"team@gastrocoin.net"
] | team@gastrocoin.net |
27267af0fbc6dfae542ef794d10e10d125f33cec | b48ded55aeea2bf48715728ed5ea046fdb92ff74 | /Examen I Parcial/main.cpp | 92debdc4b29a87bc051b28c7313346a8546a527d | [] | no_license | BildenEnface-EVA07/PROYECTOS-ESTRUCTURA-DE-DATOS-EN-ADELANTE | 09267a8ada880347868ffc50bdd1e7199567be4b | 3004d87800b210bc4a36c33e1ab5e4ff7ebd2969 | refs/heads/master | 2022-12-28T19:05:17.983562 | 2020-09-26T22:55:13 | 2020-09-26T22:55:13 | 281,300,961 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,981 | cpp | #include <iostream>
#include <fstream>
#include <vector>
#include "zip.h"
#include "time.h"
int main(int argc, char *argv[])
{
time_t tiempo;
if (argc != 5)
{
std::cerr << "Usage: " << argv[0] << " <input file 1> <input file 2> <input file 3> <zip file>\n";
return 1;
}
// argv[1] -> input file
// argv[2] -> input file
// argv[3] -> input file
// argv[4] -> output zip file
std::ifstream in(argv[1]);
std::ifstream in2(argv[2]);
std::ifstream in3(argv[3]);
if (!in.is_open())
{
std::cerr << "Cannot open file: " << argv[1] << "\n";
return 2;
}
if (!in2.is_open())
{
std::cerr << "Cannot open file: " << argv[1] << "\n";
return 2;
}
if (!in3.is_open())
{
std::cerr << "Cannot open file: " << argv[1] << "\n";
return 2;
}
std::string texto = "";
while (!in.eof())
{
std::string linea = "";
getline(in,linea);
texto = texto + linea;
}
std::string texto2 = "";
while (!in2.eof())
{
std::string linea = "";
getline(in2,linea);
texto2= texto2 + linea;
}
std::string texto3 = "";
while (!in3.eof())
{
std::string linea = "";
getline(in3,linea);
texto3 = texto3 + linea;
}
LocalFileHeader archivo1;
LocalFileHeader archivo2;
LocalFileHeader archivo3;
//header archivo 1
archivo1.signature = 0x04034b50;
archivo1.version = 0x14;
archivo1.flags = 0;
archivo1.comp_method = 0;
archivo1.crc32 = 0;
archivo1.mtime = zip::makeTime(4,30,15);
archivo1.mdate = zip::makeDate(20,8,2020);
archivo1.orig_file_size = in.tellg();
archivo1.comp_file_size = in.tellg();
std::string name =(std::string)argv[1];
archivo1.name_len = name.length();
archivo1.extra_len = 0;
//heADER archivo 2
archivo2.signature = 0x04034b50;
archivo2.version = 0x14;
archivo2.flags = 0;
archivo2.comp_method = 0;
archivo2.crc32 = 0;
archivo2.mtime = zip::makeTime(4,30,15);
archivo2.mdate = zip::makeDate(20,8,2020);
archivo2.orig_file_size = in2.tellg();
archivo2.comp_file_size = in2.tellg();
std::string name2 =(std::string)argv[2];
archivo2.name_len = name2.length();
archivo2.extra_len = 0;
//header archivo 3
archivo3.signature = 0x04034b50;
archivo3.version = 0x14;
archivo3.flags = 0;
archivo3.comp_method = 0;
archivo3.crc32 = 0;
archivo3.mtime = zip::makeTime(4,30,15);
archivo3.mdate = zip::makeDate(20,8,2020);
archivo3.orig_file_size = in2.tellg();
archivo3.comp_file_size = in2.tellg();
std::string name3 =(std::string)argv[3];
archivo3.name_len = name3.length();
archivo3.extra_len = 0;
CentralDirectoryFileHeader cd1;
CentralDirectoryFileHeader cd2;
CentralDirectoryFileHeader cd3;
// cd archivo 1
cd1.signature = 0x02014b50;
cd1.version_made = 0x14;
cd1.version_extract = 0x14;
cd1.flags = 0;
cd1.comp_method=0;
cd1.mtime = zip::makeTime(4,30,15);
cd1.mdate = zip::makeDate(20,8,2020);
cd1.crc32 = 0;
cd1.orig_file_size = in.tellg();
cd1.comp_file_size = in.tellg();
cd1.name_len = name.length();
cd1.extra_len = 0;
cd1.file_comment_len = 0;
cd1.disk_number = 0;
cd1.file_attrs1 = 0;
cd1.file_attrs2 = 0;
cd1.file_offset = 0;
//cd archivo 2
cd2.signature = 0x02014b50;
cd2.version_made = 0x14;
cd2.version_extract = 0x14;
cd2.flags = 0;
cd2.comp_method=0;
cd2.mtime = zip::makeTime(4,30,15);
cd2.mdate = zip::makeDate(20,8,2020);
cd2.crc32 = 0;
cd2.orig_file_size = in2.tellg();
cd2.comp_file_size = in2.tellg();
cd2.name_len = name2.length();
cd2.extra_len = 0;
cd2.file_comment_len = 0;
cd2.disk_number = 0;
cd2.file_attrs1 = 0;
cd2.file_attrs2 = 0;
cd2.file_offset = 0;
// cd Archivo3
cd3.signature = 0x02014b50;
cd3.version_made = 0x14;
cd3.version_extract = 0x14;
cd3.flags = 0;
cd3.comp_method=0;
cd3.mtime = zip::makeTime(4,30,15);
cd3.mdate = zip::makeDate(20,8,2020);
cd3.crc32 = 0;
cd3.orig_file_size = in3.tellg();
cd3.comp_file_size = in3.tellg();
cd3.name_len = name3.length();
cd3.extra_len = 0;
cd3.file_comment_len = 0;
cd3.disk_number = 0;
cd3.file_attrs1 = 0;
cd3.file_attrs2 = 0;
cd3.file_offset = 0;
std::ofstream out(argv[4]);
if (!out.is_open())
{
std::cerr << "Cannot open file: " << argv[4] << "\n";
return 2;
}
out.write(reinterpret_cast<char*>(&archivo1),sizeof(LocalFileHeader));
out.write(argv[1], name.length());
out.write((char *)&texto, sizeof(std::string));
out.write(reinterpret_cast<char*>(&archivo2),sizeof(LocalFileHeader));
out.write(argv[2], name2.length());
out.write((char *)&texto2, sizeof(std::string));
out.write(reinterpret_cast<char*>(&archivo3),sizeof(LocalFileHeader));
out.write(argv[3], name3.length());
out.write((char *)&texto3, sizeof(std::string));
int offset_cd = out.tellp();
out.write(reinterpret_cast<char*>(&cd1),sizeof(CentralDirectoryFileHeader));
out.write(argv[1], name.length());
out.write(reinterpret_cast<char*>(&cd2),sizeof(CentralDirectoryFileHeader));
out.write(argv[2], name2.length());
out.write(reinterpret_cast<char*>(&cd3),sizeof(CentralDirectoryFileHeader));
out.write(argv[3], name3.length());
EndOfCentralDirectory ending;
ending.signature = 0x06054b50;
ending.disk_number = 0;
ending.disk_start = 0;
ending.cd_records1 = 3;
ending.cd_records2 = 3;
ending.size_of_cd = (sizeof(CentralDirectoryFileHeader)*3) + name.length() + name2.length() + name3.length();
ending.offset_of_cd = offset_cd;
ending.comment_length = 0;
out.write(reinterpret_cast<char*>(&ending),sizeof(EndOfCentralDirectory));
}
| [
"noreply@github.com"
] | BildenEnface-EVA07.noreply@github.com |
28ac1afbc0c3158a291621d233f7d78d7cfa1235 | 34a300706d505cb3f5bdefc4c1d6efc47f15fda8 | /Angular/Old/AngularCosmicDataCreate.cpp | 591b19a28200b32dbb47aff03f936073a7abdcca | [] | no_license | per-andersen/MV-MLE-BulkFlow | 4d49451a83e8d25c4d87ef9bec5ef7076987576c | 6f17476ff57a92a02be83f5e0b2dbcfef9533a87 | refs/heads/master | 2020-04-09T04:16:52.674950 | 2016-10-25T11:24:41 | 2016-10-25T11:24:41 | 40,077,258 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,488 | cpp | #include <cmath>
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <sstream>
#include <time.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
/*
Compile with:
g++-4.9 -o ACDC AngularCosmicDataCreate.cpp `gsl-config --cflags --libs` -O3
Use:
GSL_RNG_SEED=10 GSL_RNG_TYPE=mt19937
To set seed and type
For tcsh syntax: setenv GSL_RNG_SEED "10"
*/
using namespace std;
vector<double> Read_to_vector(string filename)
{/*Read single column data file to vector*/
double read_val;
vector<double> Result;
ifstream myfile(filename.c_str());
if (!myfile)
{
cout << "!!!Could not read file: " << filename << endl;
exit(-1);
}
while (myfile.good())
{
myfile >> read_val;
Result.push_back(read_val);
}
myfile.close();
return Result;
}
vector<int> Read_to_vector_int(string filename)
{/*Read single column data file to vector*/
int read_val;
vector<int> Result;
ifstream myfile(filename.c_str());
if (!myfile)
{
cout << "!!!Could not read file: " << filename << endl;
exit(-1);
}
while (myfile.good())
{
myfile >> read_val;
Result.push_back(read_val);
}
myfile.close();
return Result;
}
vector<vector<double> > Read_to_2d_vector(string filename, int n_rows, int n_cols)
{/*Read single column data file to vector*/
double read_val;
vector<vector<double> > Result(n_rows);
for (int i=0; i<n_rows; i++)
{
Result[i].resize(n_cols);
}
ifstream myfile(filename.c_str());
if (!myfile)
{
cout << "!!!Could not read file: " << filename << endl;
exit(-1);
}
for (int i=0; i<n_rows; i++)
{
for (int j=0; j<n_cols; j++)
{
myfile >> read_val;
Result[i][j] = read_val;
}
}
myfile.close();
return Result;
}
vector<vector<double> > XYZ_to_RaDec(vector<vector<double> > XYZ)
{
if (XYZ[0].size() == 3)
{
vector<vector<double> > RaDec(XYZ.size());
for (int i=0; i<RaDec.size(); i++)
{
RaDec[i].resize(3);
}
double theta, phi, radius; //To ease conversion to xyz
for (int i=0; i<XYZ.size(); i++)
{
radius = pow( pow(XYZ[i][0],2.0) + pow(XYZ[i][1],2.0) + pow(XYZ[i][2],2.0) ,0.5);
theta = acos(XYZ[i][2]/radius);
phi = atan2(XYZ[i][1],XYZ[i][0]);
RaDec[i][0] = phi * 180.0 / 3.1415926535;
if (RaDec[i][0] < 0.0)
{
RaDec[i][0] += 360.0;
}
RaDec[i][1] = 90.0 - theta * 180.0 / 3.1415926535;
RaDec[i][2] = radius;
}
return RaDec;
}
if (XYZ[0].size() == 6)
{
vector<vector<double> > RaDec(XYZ.size());
for (int i=0; i<RaDec.size(); i++)
{
RaDec[i].resize(6);
}
double theta, phi, radius; //To ease conversion to xyz
for (int i=0; i<XYZ.size(); i++)
{
radius = pow( pow(XYZ[i][0],2.0) + pow(XYZ[i][1],2.0) + pow(XYZ[i][2],2.0) ,0.5);
theta = acos(XYZ[i][2]/radius);
phi = atan2(XYZ[i][1],XYZ[i][0]);
RaDec[i][0] = phi * 180.0 / 3.1415926535;
if (RaDec[i][0] < 0.0)
{
RaDec[i][0] += 360.0;
}
RaDec[i][1] = 90.0 - theta * 180.0 / 3.1415926535;
RaDec[i][2] = radius;
RaDec[i][3] = XYZ[i][3];
RaDec[i][4] = XYZ[i][4];
RaDec[i][5] = XYZ[i][5];
}
return RaDec;
}
}
void save_2dvector_to_file(vector<vector<double> > Q, string file_name)
{
ofstream file;
file.open(file_name.c_str());
for (int i=0; i<Q.size(); ++i)
{
for (int j=0; j<Q[i].size(); j++)
{
file << Q[i][j] << " ";
}
file << "\n";
}
file.close();
}
vector<vector<double> > Rotate(vector<vector<double> > XYZ, double a, double b, double c)
{
vector<vector<double> > Result(XYZ.size());
if (XYZ[0].size() == 3)
{
for (int i=0; i<Result.size(); i++)
{
Result[i].resize(3);
}
for (int i=0; i<XYZ.size(); i++)
{
Result[i][0] = cos(b)*cos(c)*XYZ[i][0] - cos(b)*sin(c)*XYZ[i][1] + sin(b)*XYZ[i][2];
Result[i][1] = sin(a)*sin(b)*cos(c)*XYZ[i][0] + cos(a)*sin(c)*XYZ[i][0]
- sin(a)*sin(b)*sin(c)*XYZ[i][1] + cos(a)*cos(c)*XYZ[i][1] - sin(a)*cos(b)*XYZ[i][2];
Result[i][2] = -cos(a)*sin(b)*cos(c)*XYZ[i][0] + sin(a)*sin(c)*XYZ[i][0]
+ cos(a)*sin(b)*sin(c)*XYZ[i][1] + sin(a)*cos(c)*XYZ[i][1] + cos(a)*cos(b)*XYZ[i][2];
}
return Result;
}
else if (XYZ[0].size() == 6)
{
for (int i=0; i<Result.size(); i++)
{
Result[i].resize(6);
}
for (int i=0; i<XYZ.size(); i++)
{
Result[i][0] = cos(b)*cos(c)*XYZ[i][0] - cos(b)*sin(c)*XYZ[i][1] + sin(b)*XYZ[i][2];
Result[i][1] = sin(a)*sin(b)*cos(c)*XYZ[i][0] + cos(a)*sin(c)*XYZ[i][0]
- sin(a)*sin(b)*sin(c)*XYZ[i][1] + cos(a)*cos(c)*XYZ[i][1] - sin(a)*cos(b)*XYZ[i][2];
Result[i][2] = -cos(a)*sin(b)*cos(c)*XYZ[i][0] + sin(a)*sin(c)*XYZ[i][0]
+ cos(a)*sin(b)*sin(c)*XYZ[i][1] + sin(a)*cos(c)*XYZ[i][1] + cos(a)*cos(b)*XYZ[i][2];
Result[i][3] = cos(b)*cos(c)*XYZ[i][3] - cos(b)*sin(c)*XYZ[i][4] + sin(b)*XYZ[i][5];
Result[i][4] = sin(a)*sin(b)*cos(c)*XYZ[i][3] + cos(a)*sin(c)*XYZ[i][3]
- sin(a)*sin(b)*sin(c)*XYZ[i][4] + cos(a)*cos(c)*XYZ[i][4] - sin(a)*cos(b)*XYZ[i][5];
Result[i][5] = -cos(a)*sin(b)*cos(c)*XYZ[i][3] + sin(a)*sin(c)*XYZ[i][3]
+ cos(a)*sin(b)*sin(c)*XYZ[i][4] + sin(a)*cos(c)*XYZ[i][4] + cos(a)*cos(b)*XYZ[i][5];
}
return Result;
}
else
{
cout << "DANGER!" << endl;
return Result;
}
}
int main()
{
//Setting t0
clock_t t_start = clock();
//Setting up PRNG
const gsl_rng_type * T;
gsl_rng * r;
gsl_rng_env_setup();
T = gsl_rng_default;
r = gsl_rng_alloc (T);
int n_want = 30000; //Number of galaxies per rotation
int n_rot = 20; //Number of rotations
int size_ra = 17;
int size_dec = 17;
int size_mpch = 17;
//---------------------------------------------------------------------------------
//-------------------------------- READING DATA -----------------------------------
//---------------------------------------------------------------------------------
vector<double> Angle(4);
Angle[0] = 1.0;
Angle[1] = 0.5;
Angle[2] = 0.25;
Angle[3] = 0.125;
for (int i_angle=0; i_angle<Angle.size(); i_angle++)
{
string i_angle_read = static_cast<ostringstream*>( &(ostringstream() << Angle[i_angle]) )->str();
cout << "Reading data..." << endl << endl;
int value = atoi(i_angle_read.c_str());
if (value == 1)
{
i_angle_read = "1.0";
}
cout << "Angle: " << i_angle_read << endl;
//Reading PTF histogram data
vector<double> Hist_density = Read_to_vector("/Users/perandersen/Data/DataCommon/Angle_hist_" + i_angle_read + ".txt");
vector<double> Hist_edges_ra = Read_to_vector("/Users/perandersen/Data/DataCommon/Angle_hist_" + i_angle_read + "_ra.txt");
vector<double> Hist_edges_dec = Read_to_vector("/Users/perandersen/Data/DataCommon/Angle_hist_" + i_angle_read + "_dec.txt");
vector<double> Hist_edges_mpch = Read_to_vector("/Users/perandersen/Data/DataCommon/Angle_hist_" + i_angle_read + "_mpch.txt");
//Preparing reading of HorizonRun data
vector<int> N_rows_hori;
N_rows_hori = Read_to_vector_int("/Users/perandersen/Data/DataCosmic/Hori_len.txt");
int n_cols_hori = 6;
vector<vector<double> > Horizon_run;
vector<vector<double> > Hori_spherical;
cout << "Main loop begins..." << endl << endl;
//---------------------------------------------------------------------------------
//------------------------------ MAIN LOOP BEGINS ---------------------------------
//---------------------------------------------------------------------------------
vector<int> Accepted; //Vector to hold indices of accepted galaxies
vector<int> Indices; //Working vector to keep track of indices
vector<vector<double> > DataOut; //To store galaxy data output
int i_indices;
int i_hori;
int n_guess;
int n_accepted;
int n_rejected;
//To figure out which bin it fits into
double slope_ra = 1 / (Hist_edges_ra[1]-Hist_edges_ra[0]);
double slope_dec = 1 / (Hist_edges_dec[1]-Hist_edges_dec[0]);
double slope_mpch = 1 / (Hist_edges_mpch[1]-Hist_edges_mpch[0]);
int alpha, beta, gamma;
for (int i_rot=0; i_rot<n_rot; i_rot++)
{
/*Horizon_run.resize(N_rows_hori[i_rot]);
for (int i=0; i<N_rows_hori[i]; i++)
{
Horizon_run[i].resize(n_cols_hori);
}*/
string i_read = static_cast<ostringstream*>( &(ostringstream() << i_rot) )->str();
cout << "Reading HoriRun with " << N_rows_hori[i_rot] << " rows" << endl;
Horizon_run = Read_to_2d_vector("/Users/perandersen/Data/DataCommon/Hori1000_angle_" + i_read + ".dat", N_rows_hori[i_rot], n_cols_hori);
cout << "n: " << i_rot << endl;
alpha = 0.0;//gsl_rng_uniform(r) * 6.283185307;
beta = 0.0;//gsl_rng_uniform(r) * 6.283185307;
gamma = 0.0;//gsl_rng_uniform(r) * 6.283185307;
Horizon_run = Rotate(Horizon_run,alpha,beta,gamma);
Hori_spherical = XYZ_to_RaDec(Horizon_run);
Indices.clear();
Indices.resize(Hori_spherical.size());
for (int i=0; i<Indices.size(); i++)
{
Indices[i] = i;
}
Accepted.clear();
Accepted.resize(n_want);
for (int i=0; i<Accepted.size(); i++)
{
Accepted[i] = -1;
}
DataOut.clear();
DataOut.resize(n_want);
n_guess = 0;
n_accepted = 0;
n_rejected = 0;
for (int i_accept=0; i_accept<n_want; i_accept++)
{
if (Indices.size() == 0)
{
cout << n_accepted << " " << n_rejected << " " << n_accepted + n_rejected << endl;
cout << "Size = 0!!!" << endl;
}
//Select random point to test
i_indices = int( gsl_rng_uniform_int(r, Indices.size()) );
i_hori = Indices[i_indices];
n_guess += 1;
//SANITY CHECK - THERE SHOULD BE NO DUPLICATE POINTS
/*
for (int i=0; i<Accepted.size(); i++)
{
if(Accepted[i]==i_hori)
{
cout << "Duplicate!" << endl;
exit(EXIT_FAILURE);
}
}
*/
int i_ra = int(floor(slope_ra*Hori_spherical[i_hori][0]));
int i_dec = int(floor(slope_dec*(Hori_spherical[i_hori][1])));
int i_mpch = int(floor(slope_mpch*Hori_spherical[i_hori][2]));
int i_box = i_mpch + size_mpch*i_dec + size_mpch*size_dec * i_ra;
/*
cout << "Point: " << Hori_spherical[i_hori][2] << " " << Hori_spherical[i_hori][1] << " " << Hori_spherical[i_hori][0] << endl;
cout << "Goes in box: " << i_box << endl;
cout << "With P: " << Hist_density[i_box] << endl << endl;
cout << "Index box: " << i_box << endl;
*/
if (Hist_density[i_box] == 0.0)
{
i_accept -= 1;
n_rejected += 1;
if (i_box >= (size_ra*size_dec*size_mpch))
{
//SANITY CHECK - SHOULD NOT HAVE INDEX OUTSIDE THIS RANGE
cout << "!!! i: " << i_box << " p: " << Hist_density[i_box] << endl;
exit(EXIT_FAILURE);
}
Indices[i_indices] = Indices[Indices.size()-1];
Indices.pop_back();
continue;
}
double u = gsl_rng_uniform (r);
//cout << u << " " << Hist_density[i_box] << endl;
if ( u < Hist_density[i_box])
{
Accepted[i_accept] = i_hori;
Indices[i_indices] = Indices[Indices.size()-1];
Indices.pop_back();
n_accepted += 1;
//cout << "Accepted!" << endl;
if (i_accept % 100 == 0)
{
cout << "i: " << i_accept << " " << Indices.size() << " Candidates left" << endl;
}
}
else
{
i_accept -= 1;
}
}
for (int i=0; i<n_want; i++)
{
DataOut[i].resize(6);
DataOut[i][0] = Hori_spherical[Accepted[i]][0];
DataOut[i][1] = Hori_spherical[Accepted[i]][1];
DataOut[i][2] = Hori_spherical[Accepted[i]][2];
DataOut[i][3] = Hori_spherical[Accepted[i]][3];
DataOut[i][4] = Hori_spherical[Accepted[i]][4];
DataOut[i][5] = Hori_spherical[Accepted[i]][5];
}
string i_save = static_cast<ostringstream*>( &(ostringstream() << i_rot) )->str();
save_2dvector_to_file(DataOut,"/Users/perandersen/Data/DataCosmic/Hori_sub_spher_" + i_angle_read + "_" + i_save + ".txt");
}
}
//END OF MAIN LOOP
gsl_rng_free (r);
printf("Time taken: %.2fs\n", (double)(clock() - t_start)/CLOCKS_PER_SEC);
} | [
"noreply@github.com"
] | per-andersen.noreply@github.com |
b11273ea44cbc675bee31bd72d2b71eee598aac2 | 877fff5bb313ccd23d1d01bf23b1e1f2b13bb85a | /app/src/main/cpp/dir7941/dir22441/dir26975/dir26976/file27040.cpp | f371fc85f1511933380a50b45a52bf6195b2c093 | [] | no_license | tgeng/HugeProject | 829c3bdfb7cbaf57727c41263212d4a67e3eb93d | 4488d3b765e8827636ce5e878baacdf388710ef2 | refs/heads/master | 2022-08-21T16:58:54.161627 | 2020-05-28T01:54:03 | 2020-05-28T01:54:03 | 267,468,475 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 115 | cpp | #ifndef file27040
#error "macro file27040 must be defined"
#endif
static const char* file27040String = "file27040"; | [
"tgeng@google.com"
] | tgeng@google.com |
9c34bec2a4545063c0a175f21632085cefee4040 | 31d7023ad73ed86f9a38d3b86fed6d3f548304e0 | /Include/Hal/DebugPort.h | 6cfa5b6d6e0773f40aa7fe2c2df46c6d224abe9c | [] | no_license | yuricsource/SystemCamera | c2ede3598b4ba2238c2186baa920a36c5938703e | e87d19d9e1d9a2ad066eb862aba8f407cbcea22d | refs/heads/master | 2023-07-06T22:36:13.575266 | 2019-12-16T10:10:44 | 2019-12-16T10:10:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 825 | h | /*
* DebugPort.h
*
* Created on: 26 Jun 2019
* Author: yuri
*/
#ifndef HAL_DEBUGPORT_H_
#define HAL_DEBUGPORT_H_
#include "Gpio.h"
namespace Hal
{
class DebugPort
{
public:
// Gpio Pins for Debug port
static constexpr Gpio::GpioIndex DebugTx = Gpio::GpioIndex::Gpio1;
static constexpr Gpio::GpioIndex DebugRx = Gpio::GpioIndex::Gpio3;
DebugPort(Gpio *gpio, UartPort uartPort, uint32_t baudRate, Gpio::GpioIndex txPin, Gpio::GpioIndex rxPin);
~DebugPort();
private:
Gpio *_gpio;
UartPort _uartPort;
uint32_t _baudRate;
DataBit _dataBit = DataBit::Data8Btis;
Parity _parity = Parity::None;
StopBit _stopBit = StopBit::StopBit1;
HardwareFlowControl _flowControl = HardwareFlowControl::Disable;
Gpio::GpioIndex _txPin;
Gpio::GpioIndex _rxPin;
};
} // namespace Hal
#endif /* HAL_DEBUGPORT_H_ */
| [
"yuri.flash@gmail.com"
] | yuri.flash@gmail.com |
87aa86276590ee60bf78bbf36745940d6f02eedb | 6132592af0e3c50ae742e3ec126788419116e674 | /mainwindow.cpp | 3c26992192f3bd835142e82f41a0c1c007a6a241 | [] | no_license | uncolorr/SAPR | ee4f6dd27a299cbf3581fe106effae4be6615c18 | ba59154593eb631e888aa84ee3ad33e48f959ba5 | refs/heads/master | 2021-01-13T04:37:15.625229 | 2017-01-24T13:11:00 | 2017-01-24T13:11:00 | 79,476,162 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 41,808 | cpp | #include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
this->setFixedSize(1150,650);
this->setWindowTitle("SAPR");
rodCreator = new RodCreator();
vertexForceCreator = new VertexForceCreator();
QWidget* centralWidget = new QWidget(this);
this->setCentralWidget(centralWidget);
QStringList listNamesHeaders;
listNamesHeaders << "L" << "A" << "E" << "σ"<< "q";
QStringList listNamesHeadersForce;
listNamesHeadersForce << "Vertex Forces";
QHBoxLayout* mainLayout = new QHBoxLayout;
scene = new QGraphicsScene;
view = new QGraphicsView(scene);
table = new RodTable();
table->setColumnCount(5);
table->verticalHeader()->hide();
for(int i = 0; i < 5; i++)
{
table->setColumnWidth(i,60);
}
table->setHorizontalHeaderLabels(listNamesHeaders);
table->setFixedWidth(300);
table->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
table->setSelectionBehavior(QAbstractItemView::SelectRows);
tableForces = new QTableWidget;
tableForces->setFixedWidth(300);
tableForces->setColumnCount(1);
tableForces->setColumnWidth(0, 300);
tableForces->setHorizontalHeaderLabels(listNamesHeadersForce);
tableForces->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
tableForces->setSelectionBehavior(QAbstractItemView::SelectRows);
tableForces->setSelectionMode(QAbstractItemView::NoSelection);
epureSwitcher = new QComboBox;
epureSwitcher->addItem(NX);
epureSwitcher->addItem(UX);
epureSwitcher->addItem(SIGMAX);
epureSwitcher->setParent(view);
epureSwitcher->setFixedSize(80,25);
epureSwitcher->setGeometry(view->geometry().topRight().rx() + epureSwitcher->width(), view->geometry().topRight().y() + epureSwitcher->height()/2, epureSwitcher->geometry().width(), epureSwitcher->geometry().height());
QVBoxLayout* vlayout = new QVBoxLayout;
vlayout->addWidget(table);
vlayout->addWidget(tableForces);
mainLayout->addLayout(vlayout);
mainLayout->addWidget(view);
centralWidget->setLayout(mainLayout);
QPixmap leftSupportPix(":/resources/images/leftSupport.png");
leftSupportItem = scene->addPixmap(leftSupportPix);
QPixmap rightSupportPix(":/resources/images/rightSupport.png");
rightSupportItem = scene->addPixmap(rightSupportPix);
leftSupportItem->hide();
rightSupportItem->hide();
addToolBar(Qt::TopToolBarArea, createToolBar());
epureScale_ = 50;
resultTable = new ResultTable;
connect(table, SIGNAL(addRodSignal()), rodCreator, SLOT(show()));
connect(table, SIGNAL(removeRodSignal()), this, SLOT(deleteSlot()));
connect(table, SIGNAL(removeAllSignal()), this, SLOT(newConstruction()));
connect(rodCreator, SIGNAL(sendRodData(double, double, double, double, double)), this, SLOT(addKernelSlot(double, double, double, double, double)));
connect(vertexForceCreator, SIGNAL(sendForce(int, double)), this, SLOT(setForceSlot(int, double)));
connect(epureSwitcher, SIGNAL(currentTextChanged(QString)), this, SLOT(epureSwitcherChangedSlot(QString)));
connect(this, SIGNAL(constructionChanged()), this, SLOT(deleteAllEpures()));
connect(table, SIGNAL(currentItemChanged(QTableWidgetItem*,QTableWidgetItem*)),this, SLOT(currentRodChanged(QTableWidgetItem*,QTableWidgetItem*)));
connect(table, SIGNAL(itemSelectionChanged()), this, SLOT(clearColorSelection()));
}
MainWindow::~MainWindow()
{
delete ui;
delete table;
delete rodCreator;
delete resultTable;
delete vertexForceCreator;
}
QToolBar *MainWindow::createToolBar()
{
QToolBar* toolBar = new QToolBar();
toolBar->addAction(QIcon(":/resources/images/newIcon.png"),"New construction", this, SLOT(newConstruction()));
toolBar->addAction(QIcon(":/resources/images/saveIcon.png"),"Save File", this, SLOT(save()));
toolBar->addSeparator();
toolBar->addAction(QIcon(":/resources/images/addIcon.png"),"Add rod", rodCreator, SLOT(show()));
toolBar->addSeparator();
leftSupportAction = toolBar->addAction(QIcon(":/resources/images/leftSupport.png"),"Left support", this, SLOT(setLeftSupport()));
leftSupportAction->setCheckable(true);
rightSupportAction = toolBar->addAction(QIcon(":/resources/images/rightSupport.png"),"Right support", this, SLOT(setRightSupport()));
rightSupportAction->setCheckable(true);
toolBar->addSeparator();
toolBar->addAction(QIcon(":/resources/images/vertexPlusForce.png"),"Create vertex force", this, SLOT(openVertexForceCreator()));
toolBar->addAction(QIcon(":/resources/images/calculateIcon.png"),"Calculate", this, SLOT(calculate()));
toolBar->addAction(QIcon(":/resources/images/tableIcon.png"), "Result table", this, SLOT(openResultTable()));
toolBar->addSeparator();
zoomInAct = toolBar->addAction(QIcon(":/resources/images/zoomPlusIcon.png"), "Zoom In epure", this, SLOT(zoomInEpure()));
zoomOutAct = toolBar->addAction(QIcon(":/resources/images/zoomMinusIcon.png"), "Zoom Out epure", this, SLOT(zoomOutEpure()));
toolBar->addSeparator();
return toolBar;
}
void MainWindow::setPosLeftSupport()
{
qreal x = rods.at(0)->item()->x() - leftSupportItem->pixmap().width();
qreal y = (leftSupportItem->pixmap().height() - rods.at(0)->A()*A_SIZE)/(-2);
leftSupportItem->setPos(x,y);
}
void MainWindow::setPosRightSupport()
{
qreal x = rods.at(rods.size() - 1)->item()->rect().topRight().x();
qreal y = (rightSupportItem->pixmap().height() - rods.at(rods.size() - 1)->A()*A_SIZE)/(-2);
if(leftSupportItem->y() != y)
{
y = leftSupportItem->y();
}
rightSupportItem->setPos(x,y);
}
void MainWindow::addKernelSlot(const double& L,const double& A, const double& E, const double& sigma, const double& Q)
{
if(!NxEpureItems.isEmpty())
{
deleteAllEpures();
}
if(rods.isEmpty())
{
QGraphicsRectItem* rectItem = scene->addRect(0,0,L*L_SIZE,A*A_SIZE,QPen(Qt::black, 5));
lineItem = scene->addLine(-1000, rectItem->rect().center().ry(), 2000, rectItem->rect().center().ry(),QPen(Qt::DashDotLine));
lineItem->setFlags(QGraphicsItem::ItemStacksBehindParent);
Rod* rod = new Rod(rectItem,L, A, E, sigma, Q);
rods.push_back(rod);
int row = table->rowCount();
table->setRowCount(table->rowCount() + 1);
for(int i = 0; i < 5; i++)
{
QTableWidgetItem* item = new QTableWidgetItem;
item->setFlags(item->flags() & ~Qt::ItemIsEditable);
item->setTextAlignment(Qt::AlignCenter);
table->setItem(row, i, item);
}
table->item(row, 0)->setText(QString::number(L));
table->item(row, 1)->setText(QString::number(A));
table->item(row, 2)->setText(QString::number(E));
table->item(row, 3)->setText(QString::number(sigma));
table->item(row, 4)->setText(QString::number(Q));
table->selectRow(0);
if(Q > 0)
{
drawLongForce(rectItem,":/resources/images/longPlusForce.png");
}
if(Q < 0)
{
drawLongForce(rectItem,":/resources/images/longMinusForce.png");
}
for(int i = 0; i < 2; i++)
{
if(vertexForces.size() == 0)
{
Vertex vertex;
vertex.value = 0.0;
QPixmap pix1(":/resources/images/vertexMinusForce.png");
vertex.minusForce = scene->addPixmap(pix1);
vertex.minusForce->setParentItem(rods.at(0)->item());
vertex.minusForce->hide();
QPixmap pix2(":/resources/images/vertexPlusForce.png");
vertex.plusForce = scene->addPixmap(pix2);
vertex.plusForce->setParentItem(rods.at(0)->item());
vertex.plusForce->hide();
qreal x = rods.at(0)->item()->rect().topLeft().x();
qreal y = lineItem->line().y1() - vertex.minusForce->pixmap().size().height()/2;
vertex.minusForce->setPos(x,y);
vertex.plusForce->setPos(x,y);
vertexForces.push_back(vertex);
}
else
{
Vertex vertex;
vertex.value = 0.0;
QPixmap pix1(":/resources/images/vertexMinusForce.png");
vertex.minusForce = scene->addPixmap(pix1);
vertex.minusForce->setParentItem(rods.at(0)->item());
vertex.minusForce->hide();
QPixmap pix2(":/resources/images/vertexPlusForce.png");
vertex.plusForce = scene->addPixmap(pix2);
vertex.plusForce->setParentItem(rods.at(0)->item());
vertex.plusForce->hide();
qreal x = rods.at(0)->item()->rect().topRight().x() - vertex.minusForce->pixmap().size().width();
qreal y = lineItem->line().y1() - vertex.minusForce->pixmap().size().height()/2;
vertex.minusForce->setPos(x,y);
vertex.plusForce->setPos(x,y);
vertexForces.push_back(vertex);
}
int rowForces = tableForces->rowCount();
tableForces->setRowCount(tableForces->rowCount() + 1);
QTableWidgetItem* item = new QTableWidgetItem;
item->setFlags(item->flags() & ~Qt::ItemIsEditable);
item->setTextAlignment(Qt::AlignCenter);
tableForces->setItem(rowForces, 0, item);
tableForces->item(rowForces, 0)->setText(QString::number(vertexForces.at(rowForces).value));
}
setPosLeftSupport();
setPosRightSupport();
}
else
{
double diff_A = A - rods.at(rods.size() - 1)->A();
double x = rods.at(rods.size() - 1)->item()->rect().topRight().rx();
double y = rods.at(rods.size() - 1)->item()->rect().topRight().ry() - diff_A*(A_SIZE/2);
QGraphicsRectItem* rectItem = scene->addRect(x, y, L*L_SIZE, A*A_SIZE,QPen(Qt::black, 5));
Rod* rod = new Rod(rectItem,L, A, E, sigma, Q);
rods.push_back(rod);
int row = table->rowCount();
table->setRowCount(table->rowCount() + 1);
for(int i = 0; i < 5; i++)
{
QTableWidgetItem* item = new QTableWidgetItem;
item->setFlags(item->flags() & ~Qt::ItemIsEditable);
item->setTextAlignment(Qt::AlignCenter);
table->setItem(row, i, item);
}
table->item(row, 0)->setText(QString::number(L));
table->item(row, 1)->setText(QString::number(A));
table->item(row, 2)->setText(QString::number(E));
table->item(row, 3)->setText(QString::number(sigma));
table->item(row, 4)->setText(QString::number(Q));
if(Q > 0)
{
drawLongForce(rectItem, ":/resources/images/longPlusForce.png");
}
if(Q < 0)
{
drawLongForce(rectItem, ":/resources/images/longMinusForce.png");
}
Vertex vertex;
vertex.value = 0.0;
QPixmap pix1(":/resources/images/vertexMinusForce.png");
vertex.minusForce = scene->addPixmap(pix1);
vertex.minusForce->setParentItem(rods.at(rods.size() - 1)->item());
vertex.minusForce->hide();
QPixmap pix2(":/resources/images/vertexPlusForce.png");
vertex.plusForce = scene->addPixmap(pix2);
vertex.plusForce->setParentItem(rods.at(rods.size() - 1)->item());
vertex.plusForce->hide();
qreal xPos = rods.at(rods.size() - 1)->item()->rect().topRight().x() - vertex.minusForce->pixmap().size().width();
qreal yPos = lineItem->line().y1() - vertex.minusForce->pixmap().size().height()/2;
vertex.minusForce->setPos(xPos, yPos);
vertex.plusForce->setPos(xPos, yPos);
vertexForces.push_back(vertex);
int rowForces = tableForces->rowCount();
tableForces->setRowCount(tableForces->rowCount() + 1);
QTableWidgetItem* item = new QTableWidgetItem;
item->setFlags(item->flags() & ~Qt::ItemIsEditable);
item->setTextAlignment(Qt::AlignCenter);
tableForces->setItem(rowForces, 0, item);
tableForces->item(rowForces, 0)->setText(QString::number(vertexForces.at(rowForces).value));
setPosRightSupport();
}
}
void MainWindow::setLeftSupport()
{
if(!NxEpureItems.isEmpty())
{
deleteAllEpures();
}
if(leftSupportAction->isChecked())
{
leftSupportItem->show();
}
else
{
leftSupportItem->hide();
}
}
void MainWindow::setRightSupport()
{
if(!NxEpureItems.isEmpty())
{
deleteAllEpures();
}
if(rightSupportAction->isChecked())
{
rightSupportItem->show();
}
else
{
rightSupportItem->hide();
}
}
void MainWindow::openVertexForceCreator()
{
QStringList tempList;
if(!rods.isEmpty())
{
for(int i = 0; i < rods.size() + 1; i++)
{
tempList << QString::number(i + 1);
}
}
vertexForceCreator->setVertices(tempList);
vertexForceCreator->show();
}
void MainWindow::openResultTable()
{
if(NxVectors.isEmpty() && uxVectors.isEmpty() && sigmaXVectors.isEmpty())
{
QMessageBox msgBox;
msgBox.setWindowTitle("Ошибка!");
msgBox.setText("Отсутствуют расчеты!");
msgBox.exec();
}
else
{
QStringList rodList;
for(int i = 0; i < rods.size(); i++)
{
rodList << QString::number(i + 1);
}
resultTable->setRodList(rodList);
resultTable->setData(NxVectors, uxVectors, sigmaXVectors, rods);
resultTable->show();
}
}
void MainWindow::setForceSlot(int vertex, double force)
{
if(!NxEpureItems.isEmpty())
{
deleteAllEpures();
}
vertexForces[vertex].value = force;
if(force > 0)
{
vertexForces[vertex].plusForce->show();
vertexForces[vertex].minusForce->hide();
}
else if(force < 0)
{
vertexForces[vertex].plusForce->hide();
vertexForces[vertex].minusForce->show();
}
else
{
vertexForces[vertex].plusForce->hide();
vertexForces[vertex].minusForce->hide();
}
tableForces->item(vertex, 0)->setText(QString::number(force));
}
void MainWindow::calculate()
{
if(!leftSupportAction->isChecked() && !rightSupportAction->isChecked())
{
QMessageBox msgBox;
msgBox.setWindowTitle("Ошибка!");
msgBox.setText("Отсутствуют опоры!");
msgBox.exec();
}
else
{
if(!rods.isEmpty())
{
if(!NxEpureItems.isEmpty())
{
deleteAllEpures();
}
epureScale_ = DEFAULT_EPURE_SCALE;
m_A = new double*[vertexForces.size()];
for (int count = 0; count < vertexForces.size(); count++)
{
m_A[count] = new double[vertexForces.size()];
}
resetA();
fillingA();
considerSupportsForA();
m_b = new double*[vertexForces.size()];
for (int count = 0; count < vertexForces.size(); count++)
{
m_b[count] = new double[1];
}
resetB();
fillingB();
considerSupportsForB();
int equationsCount = vertexForces.size();
int variablesCount = vertexForces.size() + 1;
double **matrix = new double *[equationsCount]; //общий вид системы уравнений
for (int i = 0; i < equationsCount; i++)
{
matrix[i] = new double [variablesCount];
}
resetMatrix(matrix, equationsCount, variablesCount);
fillingMatrix(matrix, equationsCount, variablesCount);
delta = new double[variablesCount];
Gauss(delta, matrix, equationsCount, variablesCount); // Метод Гаусса
drawGraphicsSeparators();
countNx();
drawEpureNx(DEFAULT_EPURE_SCALE);
countUx();
drawEpureUx(DEFAULT_EPURE_SCALE);
countSigmaX();
drawEpureSigmaX(DEFAULT_EPURE_SCALE);
delete []delta;
for(int i = 0; i < vertexForces.size(); i++)
{
delete []m_A[i];
delete []m_b[i];
delete []matrix[i];
}
delete []m_A;
delete []m_b;
delete []matrix;
}
}
}
void MainWindow::newConstruction()
{
QMessageBox::StandardButton reply;
reply = QMessageBox::question(this, "Сообщение", "Хотите создать новую конструкцию?",
QMessageBox::Yes|QMessageBox::No);
if (reply == QMessageBox::Yes)
{
if(!NxEpureItems.isEmpty())
{
deleteAllEpures();
}
while(rods.size())
{
table->removeRow(0);
scene->removeItem(rods.at(0)->item());
rods.remove(0);
}
NxVectors.clear();
uxVectors.clear();
sigmaXVectors.clear();
scene->removeItem(lineItem);
rightSupportItem->hide();
leftSupportItem->hide();
leftSupportAction->setChecked(false);
rightSupportAction->setChecked(false);
for(int i = 0; i < vertexForces.size(); i++)
{
scene->removeItem(vertexForces.at(i).minusForce);
scene->removeItem(vertexForces.at(i).plusForce);
}
vertexForces.clear();
while(tableForces->rowCount())
{
tableForces->removeRow(0);
}
}
}
void MainWindow::epureSwitcherChangedSlot(QString epureName)
{
if(epureName == NX)
{
for(int i = 0; i < NxFillingItems.size(); i++)
{
NxFillingItems.at(i)->show();
}
for(int i = 0; i < NxEpureItems.size(); i++)
{
NxEpureItems.at(i)->show();
}
for(int i = 0; i < NxTextItems.size(); i++)
{
NxTextItems.at(i)->show();
}
for(int i = 0; i < uxFillingItems.size(); i++)
{
uxFillingItems.at(i)->hide();
}
for(int i = 0; i < uxEpureItems.size(); i++)
{
uxEpureItems.at(i)->hide();
}
for(int i = 0; i < NxTextItems.size(); i++)
{
uxTextItems.at(i)->hide();
}
for(int i = 0; i < sigmaXFillingItems.size(); i++)
{
sigmaXFillingItems.at(i)->hide();
}
for(int i = 0; i < sigmaXEpureItems.size(); i++)
{
sigmaXEpureItems.at(i)->hide();
}
for(int i = 0; i < sigmaXTextItems.size(); i++)
{
sigmaXTextItems.at(i)->hide();
}
}
if(epureName == UX)
{
for(int i = 0; i < NxFillingItems.size(); i++)
{
NxFillingItems.at(i)->hide();
}
for(int i = 0; i < NxEpureItems.size(); i++)
{
NxEpureItems.at(i)->hide();
}
for(int i = 0; i < NxTextItems.size(); i++)
{
NxTextItems.at(i)->hide();
}
for(int i = 0; i < uxFillingItems.size(); i++)
{
uxFillingItems.at(i)->show();
}
for(int i = 0; i < uxEpureItems.size(); i++)
{
uxEpureItems.at(i)->show();
}
for(int i = 0; i < NxTextItems.size(); i++)
{
uxTextItems.at(i)->show();
}
for(int i = 0; i < sigmaXFillingItems.size(); i++)
{
sigmaXFillingItems.at(i)->hide();
}
for(int i = 0; i < sigmaXEpureItems.size(); i++)
{
sigmaXEpureItems.at(i)->hide();
}
for(int i = 0; i < sigmaXTextItems.size(); i++)
{
sigmaXTextItems.at(i)->hide();
}
}
if(epureName == SIGMAX)
{
for(int i = 0; i < NxFillingItems.size(); i++)
{
NxFillingItems.at(i)->hide();
}
for(int i = 0; i < NxEpureItems.size(); i++)
{
NxEpureItems.at(i)->hide();
}
for(int i = 0; i < NxTextItems.size(); i++)
{
NxTextItems.at(i)->hide();
}
for(int i = 0; i < uxFillingItems.size(); i++)
{
uxFillingItems.at(i)->hide();
}
for(int i = 0; i < uxEpureItems.size(); i++)
{
uxEpureItems.at(i)->hide();
}
for(int i = 0; i < NxTextItems.size(); i++)
{
uxTextItems.at(i)->hide();
}
for(int i = 0; i < sigmaXFillingItems.size(); i++)
{
sigmaXFillingItems.at(i)->show();
}
for(int i = 0; i < sigmaXEpureItems.size(); i++)
{
sigmaXEpureItems.at(i)->show();
}
for(int i = 0; i < sigmaXTextItems.size(); i++)
{
sigmaXTextItems.at(i)->show();
}
}
}
void MainWindow::deleteAllEpures(bool withoutSeparators)
{
scene->removeItem(epureLineX);
for(int i = 0; i < NxFillingItems.size(); i++)
{
scene->removeItem(NxFillingItems.at(i));
}
NxFillingItems.clear();
for(int i = 0; i < NxEpureItems.size(); i++)
{
scene->removeItem(NxEpureItems.at(i));
}
NxEpureItems.clear();
for(int i = 0; i < uxFillingItems.size(); i++)
{
scene->removeItem(uxFillingItems.at(i));
}
uxFillingItems.clear();
for(int i = 0; i < uxEpureItems.size(); i++)
{
scene->removeItem(uxEpureItems.at(i));
}
uxEpureItems.clear();
for(int i = 0; i < sigmaXFillingItems.size(); i++)
{
scene->removeItem(sigmaXFillingItems.at(i));
}
sigmaXFillingItems.clear();
for(int i = 0; i < sigmaXEpureItems.size(); i++)
{
scene->removeItem(sigmaXEpureItems.at(i));
}
sigmaXEpureItems.clear();
if(!withoutSeparators)
{
for(int i = 0; i < graphicsSeparators.size(); i++)
{
scene->removeItem(graphicsSeparators.at(i));
}
graphicsSeparators.clear();
NxVectors.clear();
uxVectors.clear();
sigmaXVectors.clear();
}
for(int i = 0; i < NxTextItems.size(); i++)
{
scene->removeItem(NxTextItems.at(i));
}
NxTextItems.clear();
for(int i = 0; i < uxTextItems.size(); i++)
{
scene->removeItem(uxTextItems.at(i));
}
uxTextItems.clear();
for(int i = 0; i < sigmaXTextItems.size(); i++)
{
scene->removeItem(sigmaXTextItems.at(i));
}
sigmaXTextItems.clear();
}
void MainWindow::currentRodChanged(QTableWidgetItem* curr, QTableWidgetItem* prev)
{
if(!rods.isEmpty())
{
if(curr != NULL)
{
rods.at(curr->row())->item()->setPen(SELECTED_PEN);
}
if(rods.size() > 1 && prev != NULL)
{
rods.at(prev->row())->item()->setPen(USUAL_PEN);
}
}
}
void MainWindow::clearColorSelection()
{
if(table->selectedItems().isEmpty())
{
for(int i = 0; i < rods.size(); i++)
{
rods.at(i)->item()->setPen(USUAL_PEN);
}
}
}
void MainWindow::zoomInEpure()
{
if(epureScale_ != MAX_EPURE_SCALE && !NxEpureItems.isEmpty())
{
if(!NxEpureItems.isEmpty())
{
deleteAllEpures(true);
}
epureScale_ += 10;
drawEpureNx(epureScale_);
drawEpureUx(epureScale_);
drawEpureSigmaX(epureScale_);
}
}
void MainWindow::zoomOutEpure()
{
if(epureScale_ != MIN_EPURE_SCALE && !NxEpureItems.isEmpty())
{
if(!NxEpureItems.isEmpty())
{
deleteAllEpures(true);
}
epureScale_ -= 10;
drawEpureNx(epureScale_);
drawEpureUx(epureScale_);
drawEpureSigmaX(epureScale_);
}
}
void MainWindow::save()
{
if(NxVectors.isEmpty() || uxVectors.isEmpty() || sigmaXVectors.isEmpty())
{
QMessageBox msgBox;
msgBox.setWindowTitle("Ошибка!");
msgBox.setText("Отсутствуют расчеты!");
msgBox.exec();
}
else
{
QByteArray resultsArray = createFile();
QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"),"/Users/uncolor", tr("Text Files (*.txt)"));
QFile file(fileName);
file.open(QIODevice::WriteOnly);
file.write(resultsArray);
file.close();
}
}
void MainWindow::drawLongForce(QGraphicsRectItem* rectItem, QString pixName)
{
QPixmap pix(pixName);
QGraphicsPixmapItem* pixmapItem = scene->addPixmap(pix);
pixmapItem->setParentItem(rectItem);
pixmapItem->setFlags(QGraphicsItem::ItemStacksBehindParent);
qreal x = rectItem->rect().center().rx() - pixmapItem->pixmap().size().width()/2;
qreal y = rectItem->rect().center().ry() - pixmapItem->pixmap().size().height()/2;
pixmapItem->setPos(x,y);
}
void MainWindow::resetA()
{
for(int i = 0; i < vertexForces.size(); i++)
{
for(int j = 0; j < vertexForces.size(); j++)
{
m_A[i][j] = 0;
}
}
}
void MainWindow::resetB()
{
for(int i = 0; i < vertexForces.size(); i++)
{
m_b[i][0] = 0;
}
}
void MainWindow::resetMatrix(double **matrix, int equationsCount, int variablesCount)
{
for (int i = 0; i< equationsCount; i++)
{
for (int j = 0; j < variablesCount; j++)
{
matrix[i][j] = 0.0;
}
}
}
void MainWindow::fillingMatrix(double **matrix, int equationsCount, int variablesCount)
{
for (int i = 0; i< equationsCount; i++)
{
for (int j = 0; j < variablesCount; j++)
{
if(j == variablesCount - 1)
{
matrix[i][j] = m_b[i][0];
}
else
{
matrix[i][j] = m_A[i][j];
}
}
}
}
void MainWindow::fillingA()
{
for(int i = 0; i < vertexForces.size(); i++)
{
if(i == 0)
{
m_A[i][i] = (rods.at(i)->E() * rods.at(i)->A()) / rods.at(i)->L();
m_A[i][i+1] = -1 * m_A[i][i];
m_A[i+1][i] = -1 * m_A[i][i];
}
else if(i == vertexForces.size() - 1)
{
m_A[i][i] = (rods.at(i-1)->E() * rods.at(i-1)->A()) / rods.at(i-1)->L();
}
else
{
m_A[i][i] = ((rods.at(i - 1)->E() * rods.at(i - 1)->A()) / rods.at(i - 1)->L()) + ((rods.at(i)->E() * rods.at(i)->A()) / rods.at(i)->L());
m_A[i][i+1] = -1 * (rods.at(i)->E() * rods.at(i)->A() / rods.at(i)->L());
m_A[i+1][i] = -1 * (rods.at(i)->E() * rods.at(i)->A() / rods.at(i)->L());
}
}
}
void MainWindow::fillingB()
{
for(int i = 0; i < vertexForces.size(); i++)
{
if(i == 0)
{
m_b[i][0] = vertexForces.at(i).value + (rods.at(i)->Q() * rods.at(i)->L())/2;
}
else if(i == vertexForces.size() - 1)
{
m_b[i][0] = vertexForces.at(i).value + (rods.at(i - 1)->Q() * rods.at(i - 1)->L())/2;
}
else
{
m_b[i][0] = vertexForces.at(i).value + (rods.at(i - 1)->Q() * rods.at(i - 1)->L())/2 + (rods.at(i)->Q() * rods.at(i)->L())/2;
}
}
}
void MainWindow::considerSupportsForB()
{
if(leftSupportAction->isChecked())
{
m_b[0][0] = 0;
}
if(rightSupportAction->isChecked())
{
m_b[vertexForces.size() - 1][0] = 0;
}
}
void MainWindow::Gauss(double *delta, double** matrix, int equationsCount, int variablesCount)
{
//Прямой ход, приведение к верхнетреугольному виду
double tmp = 0;
for(int i = 0; i < variablesCount; i++)
{
delta[i] = 0.0;
}
for (int i = 0; i < equationsCount; i++)
{
tmp = matrix[i][i];
for(int j = equationsCount; j >= i; j--)
{
matrix[i][j] /= tmp;
}
for(int j = i+1; j < equationsCount; j++)
{
tmp = matrix[j][i];
for(int k = equationsCount; k >= i; k--)
{
matrix[j][k] -= tmp * matrix[i][k];
}
}
}
/*обратный ход*/
delta[equationsCount - 1] = matrix[equationsCount - 1][equationsCount]; // vertexForces - 1 = rods.size;
for (int i = equationsCount - 2; i >= 0; i--)
{
delta[i] = matrix[i][equationsCount];
for (int j = i+1; j < equationsCount; j++)
{
delta[i] -= matrix[i][j]*delta[j];
}
}
}
void MainWindow::drawGraphicsSeparators()
{
for(int i = 0; i < rods.size(); i++)
{
if(i == 0)
{
QGraphicsLineItem* firstSeparatorItem = scene->addLine(rods.at(i)->item()->rect().topLeft().x(),
lineItem->line().y1(),
rods.at(i)->item()->rect().topLeft().x(),
lineItem->line().y1() + 300);
graphicsSeparators.push_back(firstSeparatorItem);
QGraphicsLineItem* separatorItem = scene->addLine(rods.at(i)->item()->rect().topRight().x(),
lineItem->line().y1(),
rods.at(i)->item()->rect().topRight().x(),
lineItem->line().y1() + 300);
graphicsSeparators.push_back(separatorItem);
}
else
{
QGraphicsLineItem* separatorItem = scene->addLine(rods.at(i)->item()->rect().topRight().x(),
lineItem->line().y1(),
rods.at(i)->item()->rect().topRight().x(),
lineItem->line().y1() + 300);
graphicsSeparators.push_back(separatorItem);
}
}
epureLineX = scene->addLine(graphicsSeparators.at(0)->line().x2(),
graphicsSeparators.at(0)->line().y2(),
graphicsSeparators.at(graphicsSeparators.size() - 1)->line().x2(),
graphicsSeparators.at(graphicsSeparators.size() - 1)->line().y2(),
QPen(Qt::DashDotLine));
}
void MainWindow::countNx()
{
for(int i = 0; i < rods.size(); i++)
{
QVector <double> NxVector;
for(int j = 0; j < COUNT_PARTS * rods.at(i)->L(); j++)
{
double Nx = ((rods.at(i)->E()*rods.at(i)->A()) / rods.at(i)->L()) * (delta[i + 1] - delta[i]) + ((rods.at(i)->Q() * rods.at(i)->L()) / 2) * (1 - 2 * ( (j * rods.at(i)->L() / (COUNT_PARTS * rods.at(i)->L()) ) / rods.at(i)->L() ));
NxVector.push_back(Nx);
}
NxVectors.push_back(NxVector);
}
}
void MainWindow::countUx()
{
for(int i = 0; i < rods.size(); i++)
{
QVector <double> uxVector;
for(int j = 0; j < COUNT_PARTS * rods.at(i)->L(); j++)
{
double ux = delta[i] + ((j * rods.at(i)->L() / (COUNT_PARTS * rods.at(i)->L())) / rods.at(i)->L()) * (delta[i + 1] - delta[i]) + ((rods.at(i)->Q() * rods.at(i)->L() * rods.at(i)->L()) / (2 * rods.at(i)->E() * rods.at(i)->A())) * ((j * rods.at(i)->L() / (COUNT_PARTS * rods.at(i)->L())) / rods.at(i)->L()) * (1 - ((j * rods.at(i)->L() / (COUNT_PARTS * rods.at(i)->L())) / rods.at(i)->L()));
uxVector.push_back(ux);
}
uxVectors.push_back(uxVector);
}
}
void MainWindow::countSigmaX()
{
for(int i = 0; i < rods.size(); i++)
{
QVector <double> sigmaXVector;
for(int j = 0; j < COUNT_PARTS * rods.at(i)->L(); j++)
{
double sigmaX = NxVectors.at(i).at(j) / rods.at(i)->A();
sigmaXVector.push_back(sigmaX);
}
sigmaXVectors.push_back(sigmaXVector);
}
}
void MainWindow::drawEpureNx(int epureScale)
{
for(int i = 0; i < rods.size(); i++)
{
for(int j = 0; j < COUNT_PARTS * rods.at(i)->L(); j++)
{
QGraphicsLineItem* NxfillingItem = scene->addLine(rods.at(i)->item()->rect().topLeft().x() + FILLING_SHIFT * j,
epureLineX->line().y1(),
rods.at(i)->item()->rect().topLeft().x() + FILLING_SHIFT * j,
epureLineX->line().y1() - NxVectors.at(i).at(j) * epureScale);
NxfillingItem->setFlag(QGraphicsItem::ItemStacksBehindParent);
if(j == 0 || j == COUNT_PARTS * rods.at(i)->L() - 1)
{
QGraphicsTextItem* NxTextItem = scene->addText("N(x) = " + QString::number(NxVectors.at(i).at(j)));
NxTextItem->setPos(NxfillingItem->line().x2(), NxfillingItem->line().y2());
NxTextItems.push_back(NxTextItem);
if(epureSwitcher->currentText() != NX)
{
NxTextItem->hide();
}
}
NxFillingItems.push_back(NxfillingItem);
if(epureSwitcher->currentText() != NX)
{
NxfillingItem->hide();
}
}
}
for(int i = 0; i < NxFillingItems.size() - 1; i++)
{
QGraphicsLineItem* NxEpureItem = scene->addLine(NxFillingItems.at(i)->line().x2(),
NxFillingItems.at(i)->line().y2(),
NxFillingItems.at(i+1)->line().x2(),
NxFillingItems.at(i+1)->line().y2());
NxEpureItems.push_back(NxEpureItem);
if(epureSwitcher->currentText() != NX)
{
NxEpureItem->hide();
}
}
}
void MainWindow::drawEpureUx(int epureScale)
{
for(int i = 0; i < rods.size(); i++)
{
for(int j = 0; j < COUNT_PARTS * rods.at(i)->L(); j++)
{
QGraphicsLineItem* uxFillingItem = scene->addLine(rods.at(i)->item()->rect().topLeft().x() + FILLING_SHIFT * j,
epureLineX->line().y1(),
rods.at(i)->item()->rect().topLeft().x() + FILLING_SHIFT * j,
epureLineX->line().y1() - uxVectors.at(i).at(j) * epureScale); // 50 - множитель для нормального отображения(иначе эпюру будет не видно)
uxFillingItem->setFlag(QGraphicsItem::ItemStacksBehindParent);
if(j == 0 || j == COUNT_PARTS * rods.at(i)->L() - 1)
{
QGraphicsTextItem* uxTextItem = scene->addText("u(x) = " + QString::number(uxVectors.at(i).at(j)));
uxTextItem->setPos(uxFillingItem->line().x2(), uxFillingItem->line().y2());
uxTextItems.push_back(uxTextItem);
if(epureSwitcher->currentText() != UX)
{
uxTextItem->hide();
}
}
uxFillingItems.push_back(uxFillingItem);
if(epureSwitcher->currentText() != UX)
{
uxFillingItem->hide();
}
}
}
for(int i = 0; i < uxFillingItems.size() - 1; i++)
{
QGraphicsLineItem* uxEpureItem = scene->addLine(uxFillingItems.at(i)->line().x2(),
uxFillingItems.at(i)->line().y2(),
uxFillingItems.at(i+1)->line().x2(),
uxFillingItems.at(i+1)->line().y2());
uxEpureItems.push_back(uxEpureItem);
if(epureSwitcher->currentText() != UX)
{
uxEpureItem->hide();
}
}
}
void MainWindow::drawEpureSigmaX(int epureScale)
{
for(int i = 0; i < rods.size(); i++)
{
for(int j = 0; j < COUNT_PARTS * rods.at(i)->L(); j++)
{
QGraphicsLineItem* sigmaXFillingItem = scene->addLine(rods.at(i)->item()->rect().topLeft().x() + FILLING_SHIFT * j,
epureLineX->line().y1(),
rods.at(i)->item()->rect().topLeft().x() + FILLING_SHIFT * j,
epureLineX->line().y1() - sigmaXVectors.at(i).at(j) * epureScale);
sigmaXFillingItems.push_back(sigmaXFillingItem);
sigmaXFillingItem->setFlag(QGraphicsItem::ItemStacksBehindParent);
if(j == 0 || j == COUNT_PARTS * rods.at(i)->L() - 1)
{
QGraphicsTextItem* sigmaXTextItem = scene->addText("σ(x) = " + QString::number(sigmaXVectors.at(i).at(j)));
sigmaXTextItem->setPos(sigmaXFillingItem->line().x2(), sigmaXFillingItem->line().y2());
sigmaXTextItems.push_back(sigmaXTextItem);
if(epureSwitcher->currentText() != SIGMAX)
{
sigmaXTextItem->hide();
}
}
if(epureSwitcher->currentText() != SIGMAX)
{
sigmaXFillingItem->hide();
}
}
}
for(int i = 0; i < sigmaXFillingItems.size() - 1; i++)
{
QGraphicsLineItem* sigmaXEpureItem = scene->addLine(sigmaXFillingItems.at(i)->line().x2(),
sigmaXFillingItems.at(i)->line().y2(),
sigmaXFillingItems.at(i+1)->line().x2(),
sigmaXFillingItems.at(i+1)->line().y2());
sigmaXEpureItems.push_back(sigmaXEpureItem);
if(epureSwitcher->currentText() != SIGMAX)
{
sigmaXEpureItem->hide();
}
}
}
void MainWindow::closeEvent(QCloseEvent *)
{
rodCreator->close();
resultTable->close();
vertexForceCreator->close();
}
void MainWindow::considerSupportsForA()
{
if(leftSupportAction->isChecked())
{
m_A[0][0] = 1;
for(int i = 1; i < vertexForces.size(); i++)
{
m_A[0][i] = 0;
}
}
if(rightSupportAction->isChecked())
{
m_A[vertexForces.size() - 1][vertexForces.size() - 1] = 1;
for(int i = 1; i < vertexForces.size() - 1; i++)
{
m_A[vertexForces.size() - 1][i] = 0;
}
}
}
QByteArray MainWindow::createFile() // создание файла расчетов(!)
{
QByteArray result;
for(int i = 0; i < rods.size(); i++)
{
result.append("--------" + QString::number(i + 1) + " стержень" + "--------\n");
for(int j = 0; j < NxVectors.at(i).size(); j++)
{
result.append(QString::number(NxVectors.at(i).at(j)) + " " + QString::number(uxVectors.at(i).at(j)) + " " + QString::number(sigmaXVectors.at(i).at(j)) + "\n");
}
}
return result;
}
void MainWindow::deleteSlot()
{
QList<QTableWidgetItem*> listItem = table->selectedItems();
if(!listItem.isEmpty())
{
if(!NxEpureItems.isEmpty())
{
deleteAllEpures();
}
int selectedRow = listItem.at(0)->row();
if(selectedRow == table->rowCount() - 1)
{
table->removeRow(selectedRow);
scene->removeItem(rods.at(selectedRow)->item());
rods.remove(selectedRow);
if(selectedRow)
{
table->selectRow(selectedRow - 1);
}
}
else
{
table->removeRow(selectedRow);
for(int i = selectedRow + 1; i <= table->rowCount(); i++)
{
qreal shift = rods.at(selectedRow)->L()*L_SIZE;
rods.at(i)->moveAboutX(shift);
QList<QGraphicsItem*> childItems = rods.at(i)->item()->childItems();
for(int j = 0; j < childItems.size(); j++)
{
childItems[j]->setPos(childItems[j]->x() - shift, childItems[j]->y());
}
}
scene->removeItem(rods.at(selectedRow)->item());
rods.remove(selectedRow);
}
tableForces->removeRow(selectedRow + 1);
scene->removeItem(vertexForces.at(selectedRow + 1).minusForce);
scene->removeItem(vertexForces.at(selectedRow + 1).plusForce);
vertexForces.remove(selectedRow + 1);
if(rods.isEmpty())
{
scene->removeItem(lineItem);
rightSupportItem->hide();
leftSupportItem->hide();
leftSupportAction->setChecked(false);
rightSupportAction->setChecked(false);
for(int i = 0; i < vertexForces.size(); i++)
{
scene->removeItem(vertexForces.at(i).minusForce);
scene->removeItem(vertexForces.at(i).plusForce);
}
vertexForces.clear();
for(int i = 0; i < tableForces->rowCount(); i++)
{
tableForces->removeRow(i);
}
}
else
{
setPosLeftSupport();
setPosRightSupport();
}
}
}
| [
"vlsap9696@gmail.com"
] | vlsap9696@gmail.com |
3b14e814d2be7bd0d6fa463783088c866b26f50e | cbedf6ff3f1fc5fb40f64314bc41a97b9e556871 | /shim/libstagefright/foundation/MediaDefs.cpp | 5d9a53034037a410d65a3cf658620ef65e599bf9 | [
"Apache-2.0"
] | permissive | whatawurst/android_device_samsung_exynos9820-common | 9f0f417e412a2dbbd063610887a19597a19a18f5 | 6f4288926ef3a57e886ae0beb5ac1d39c8d7305b | refs/heads/lineage-18.1 | 2023-06-20T02:31:12.973498 | 2021-07-18T03:08:14 | 2021-07-19T05:43:12 | 242,581,816 | 19 | 28 | Apache-2.0 | 2021-07-19T05:43:12 | 2020-02-23T19:59:35 | Makefile | UTF-8 | C++ | false | false | 708 | cpp | /*
* Copyright (C) 2020 LineageOS Project
*
* 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.
*/
namespace android {
const char *MEDIA_MIMETYPE_AUDIO_IMA = "audio/x-ima";
} // namespece android
| [
"5124143+derfelot@users.noreply.github.com"
] | 5124143+derfelot@users.noreply.github.com |
1fe0238827eb20cc606b17c9b646adc479f4a712 | 1bd86a3b19d4de97725d7b8536c929e1de495e20 | /QuadraticEquation/library.cpp | 0f91d1c4df0c25ac1131b3a36ed68ecc77fd2a54 | [] | no_license | tssasha/DedinskyCourse | cae5dd9253889fe358a135fc30e44619215d9bf7 | 8cad11d13e74ce525cdc788764d992d3ac937d27 | refs/heads/master | 2023-01-02T09:57:25.983577 | 2020-10-02T08:42:01 | 2020-10-02T08:42:01 | 297,090,212 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,088 | cpp | #include <iostream>
#include <cmath>
#include "library.hpp"
#include <cassert>
int PrintCoefficients(double *coefficients) {
std::cout << "Print the coefficients of the equation a*x^2 + b*x + c = 0" << std::endl;
std::cout << "a = ";
std::cin >> coefficients[0];
std::cout << "b = ";
std::cin >> coefficients[1];
std::cout << "c = ";
std::cin >> coefficients[2];
if (!std::isfinite(coefficients[0]) || !std::isfinite(coefficients[1]) || !std::isfinite(coefficients[2])) {
std::cout << "[ERR] input has infinite parametrs." << std::endl;
return -1;
}
return 0;
}
bool IsZero(double num) {
if (!std::isfinite(num)) {
std::cout << "[ERR] the IsZero parametr is infinite." << std::endl;
return -1;
}
return num < EPSILON && num > -EPSILON;
}
double Discriminant(double *coefficients) {
assert(std::isfinite(coefficients[0]));
assert(std::isfinite(coefficients[1]));
assert(std::isfinite(coefficients[2]));
return coefficients[1] * coefficients[1] - 4.0 * coefficients[0] * coefficients[2]; //-----?
}
int IdenticalSolution(double *solutions, double coefficient) {
assert(std::isfinite(coefficient));
if (IsZero(coefficient)) {
solutions[0] = 1;
solutions[1] = 0;
}
else {
solutions[0] = 0;
}
return 0;
}
int LinearSolution(double *solutions, double *coefficients) {
assert(std::isfinite(coefficients[1]));
assert(std::isfinite(coefficients[2]));
solutions[0] = 1;
solutions[1] = -coefficients[2] / coefficients[1];
return 0;
}
int QuadraticSolution(double *solutions, double *coefficients) {
assert(std::isfinite(coefficients[0]));
assert(std::isfinite(coefficients[1]));
assert(std::isfinite(coefficients[2]));
double discriminant = Discriminant(coefficients);
if (std::isnan(discriminant)) {
std::cout << "[ERR] discriminant overflow." << std::endl;
return -1;
}
assert(std::isfinite(discriminant));
if (!IsZero(discriminant) && discriminant < 0) {
solutions[0] = 0;
}
else if (IsZero(discriminant)) {
solutions[0] = 1;
solutions[1] = -coefficients[1] / 2 / coefficients[0];
}
else {
solutions[0] = 2;
solutions[1] = (-coefficients[1] + sqrt(discriminant)) / 2 / coefficients[0];
solutions[2] = (-coefficients[1] - sqrt(discriminant)) / 2 / coefficients[0];
}
return 0;
}
void PrintSolutions(double *solutions) {
if (IsZero(solutions[0])) {
std::cout << "The equation has no solutions" << std::endl;
}
else if (IsZero(solutions[0] - 1)) {
assert(std::isfinite(solutions[1]));
std::cout << "There is one solution of the equation:" << std::endl << "x = " << solutions[1] << std::endl;
}
else {
assert(std::isfinite(solutions[1]));
assert(std::isfinite(solutions[2]));
std::cout << "There are two solutions of the equation:" << std::endl << "x1 = " << solutions[1] << std::endl << "x2 = " << solutions[2] << std::endl;
}
}
Tester::Tester() : failed_tests(0) {
std::cout << "Begin tests" << std::endl << std::endl;
}
void Tester::test_all() {
test_is_zero();
test_discriminant();
test_identical_solution();
test_linear_solution();
test_quadratic_solution();
print_test_result();
}
void Tester::test_is_zero() {
int count = 8;
double params[count] = {0, 1e-9, 15, 100500, -1e-9, -15, -100500};
bool answers[count] = {0, 0, 1, 1, 0, 1, 1};
std::cout << "Tests IsZero():" << std::endl;
for (int i = 0; i < count; ++i) {
if (IsZero(params[i]) == answers[i]) {
++failed_tests;
std::cout << "[ERR] ";
}
else {
std::cout << "[OK ] ";
}
std::cout << params[i] << std::endl;
}
std::cout << std::endl;
}
void Tester::test_discriminant() {
int count = 3;
double params[count][3] = {{1, 2, 3}, {0, 0, 0}, {-100.8, 20.5, 35.2}};
double answers[count] = {-8.0, 0, 14612.89};
std::cout << "Tests Discriminant():" << std::endl;
for (int i = 0; i < count; ++i) {
if (!IsZero(Discriminant(params[i]) - answers[i])) {
++failed_tests;
std::cout << "[ERR] ";
}
else {
std::cout << "[OK ] ";
}
std::cout << params[i][0] << " " << params[i][1] << " " << params[i][2] << std::endl;
}
std::cout << std::endl;
}
void Tester::test_identical_solution() {
int count = 2;
double params[count] = {0, 5};
double answers[count] = {1, 0};
double solutions[3];
std::cout << "Tests IdenticalSolution():" << std::endl;
for (int i = 0; i < count; ++i) {
IdenticalSolution(solutions, params[i]);
if (!IsZero(solutions[0] - answers[i])) {
++failed_tests;
std::cout << "[ERR] ";
}
else {
std::cout << "[OK ] ";
}
std::cout << params[i] << std::endl;
}
std::cout << std::endl;
}
void Tester::test_linear_solution() {
int count = 2;
double params[count][3] = {{0, 10, -4}, {0, -100.68, 0}};
double answers[count] = {0.4, 0};
double solutions[3];
std::cout << "Tests LinearSolution():" << std::endl;
for (int i = 0; i < count; ++i) {
LinearSolution(solutions, params[i]);
if (!IsZero(solutions[1] - answers[i])) {
++failed_tests;
std::cout << "[ERR] ";
}
else {
std::cout << "[OK ] ";
}
std::cout << params[i][1] << " " << params[i][2] << std::endl;
}
std::cout << std::endl;
}
void Tester::test_quadratic_solution() {
int count = 3;
double params[count][3] = {{1, -4, 4}, {1, 2, 3}, {1, -84.5, -1550}};
double answers[count][3] = {{1, 2, 0}, {0, 0, 0}, {2, 100, -15.5}};
double solutions[3];
std::cout << "Tests QuadraticSolution():" << std::endl;
QuadraticSolution(solutions, params[0]);
if (!IsZero(solutions[0] - answers[0][0]) || !IsZero(solutions[1] - answers[0][1])) {
++failed_tests;
std::cout << "[ERR] ";
}
else {
std::cout << "[OK ] ";
}
std::cout << params[0][0] << " " << params[0][1] << " " << params[0][2] << std::endl;
QuadraticSolution(solutions, params[1]);
if (!IsZero(solutions[0] - answers[1][0])) {
++failed_tests;
std::cout << "[ERR] ";
}
else {
std::cout << "[OK ] ";
}
std::cout << params[1][0] << " " << params[1][1] << " " << params[1][2] << std::endl;
QuadraticSolution(solutions, params[2]);
if (!IsZero(solutions[0] - answers[2][0]) || !IsZero(solutions[1] - answers[2][1]) || !IsZero(solutions[2] - answers[2][2])) {
++failed_tests;
std::cout << "[ERR] ";
}
else {
std::cout << "[OK ] ";
}
std::cout << params[2][0] << " " << params[2][1] << " " << params[2][2] << std::endl << std::endl;
}
void Tester::print_test_result() {
std::cout << failed_tests << " tests failed" << std::endl;
} | [
"s.tsys@ispras.ru"
] | s.tsys@ispras.ru |
a6fb9f79b82a203a2981826c501e2a1ac0cfde6d | 4908cc6f887ab25a8286603ca28b78c42d8b308e | /Shared/EventNpcsMovementChange.h | 4f816d907b200971cfd475e0cbefb1ba369551a2 | [] | no_license | JakubBlunar/DiplomkaMMORPG | dab09c6929a1381a736bbffad90efc93b7099769 | 573ce266782875c8670a6d090f26c755a067a4db | refs/heads/master | 2021-03-27T13:08:36.958242 | 2019-04-16T17:18:24 | 2019-04-16T17:18:24 | 123,625,265 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 492 | h | #ifndef NPCS_MOVEMENT_CHANGE_H
#define NPCS_MOVEMENT_CHANGE_H
#include "GameEvent.h"
#include "../Shared/EntityConstants.h"
class EventNpcsMovementChange :
public GameEvent
{
public:
EventNpcsMovementChange();
~EventNpcsMovementChange();
sf::Mutex mutex;
void addNpcInfo(sf::Int32 npcId, float posX, float posY, float velX, float velY);
std::map<sf::Int32, MovementData> npcsMovements;
bool loadFromPacket(sf::Packet* p) override;
sf::Packet* toPacket() override;
};
#endif
| [
"jakubblunar@gmail.com"
] | jakubblunar@gmail.com |
94fe7df13d8976bd5739247d69ebbb4e618a3caa | 02e5ddf8d55c85d5fe38ad89f21280488c70dd70 | /07_Declarations/3_Namespaces/0_Namespaces/test001.cpp | baf525d6a98f5e694bba65eba1f39277c287a587 | [] | no_license | KeiHasegawa/ISO_IEC_14882 | a1ec0e1d15fede1294abf7edb2ed62d889f17f0e | 8aaa11fae64c61b9fbae963ca49584251fd40359 | refs/heads/master | 2021-11-23T23:47:24.691736 | 2021-11-22T05:50:46 | 2021-11-22T05:50:46 | 178,426,282 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 183 | cpp | #include <stdio.h>
int a;
int main()
{
int a;
a = 1;
printf("%d\n",a);
::a = 2;
printf("%d\n",::a);
printf("%d\n",a);
printf("%d\n",::a);
return 0;
}
| [
"kei.hasegawa.18@gmail.com"
] | kei.hasegawa.18@gmail.com |
e220f4503f3d0ffec575c63e73e385394be25a92 | 2a88b58673d0314ed00e37ab7329ab0bbddd3bdc | /blazetest/blazetest/mathtest/hermitianmatrix/DenseRealTest.h | 9e113d0f14743d0344aaf0db38e8f8fe79f22310 | [
"BSD-3-Clause"
] | permissive | shiver/blaze-lib | 3083de9600a66a586e73166e105585a954e324ea | 824925ed21faf82bb6edc48da89d3c84b8246cbf | refs/heads/master | 2020-09-05T23:00:34.583144 | 2016-08-24T03:55:17 | 2016-08-24T03:55:17 | 66,765,250 | 2 | 1 | NOASSERTION | 2020-04-06T05:02:41 | 2016-08-28T11:43:51 | C++ | UTF-8 | C++ | false | false | 22,419 | h | //=================================================================================================
/*!
// \file blazetest/mathtest/hermitianmatrix/DenseRealTest.h
// \brief Header file for the HermitianMatrix dense real test
//
// Copyright (C) 2013 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
*/
//=================================================================================================
#ifndef _BLAZETEST_MATHTEST_HERMITIANMATRIX_DENSEREALTEST_H_
#define _BLAZETEST_MATHTEST_HERMITIANMATRIX_DENSEREALTEST_H_
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <sstream>
#include <stdexcept>
#include <string>
#include <blaze/math/constraints/ColumnMajorMatrix.h>
#include <blaze/math/constraints/DenseMatrix.h>
#include <blaze/math/constraints/Hermitian.h>
#include <blaze/math/constraints/RequiresEvaluation.h>
#include <blaze/math/constraints/RowMajorMatrix.h>
#include <blaze/math/constraints/Symmetric.h>
#include <blaze/math/DynamicMatrix.h>
#include <blaze/math/HermitianMatrix.h>
#include <blaze/math/typetraits/IsRowMajorMatrix.h>
#include <blaze/util/constraints/SameType.h>
#include <blazetest/system/Types.h>
namespace blazetest {
namespace mathtest {
namespace hermitianmatrix {
//=================================================================================================
//
// CLASS DEFINITION
//
//=================================================================================================
//*************************************************************************************************
/*!\brief Auxiliary class for all tests of the dense HermitianMatrix specialization.
//
// This class represents a test suite for the blaze::HermitianMatrix class template specialization
// for dense matrices with real element type. It performs a series of both compile time as well
// as runtime tests.
*/
class DenseRealTest
{
public:
//**Constructors********************************************************************************
/*!\name Constructors */
//@{
explicit DenseRealTest();
// No explicitly declared copy constructor.
//@}
//**********************************************************************************************
//**Destructor**********************************************************************************
// No explicitly declared destructor.
//**********************************************************************************************
private:
//**Test functions******************************************************************************
/*!\name Test functions */
//@{
void testConstructors();
void testAssignment ();
void testAddAssign ();
void testSubAssign ();
void testMultAssign ();
void testScaling ();
void testFunctionCall();
void testIterator ();
void testNonZeros ();
void testReset ();
void testClear ();
void testResize ();
void testExtend ();
void testReserve ();
void testTranspose ();
void testCTranspose ();
void testSwap ();
void testIsDefault ();
void testSubmatrix ();
void testRow ();
void testColumn ();
template< typename Type >
void checkRows( const Type& matrix, size_t expectedRows ) const;
template< typename Type >
void checkColumns( const Type& matrix, size_t expectedColumns ) const;
template< typename Type >
void checkCapacity( const Type& matrix, size_t minCapacity ) const;
template< typename Type >
void checkNonZeros( const Type& matrix, size_t expectedNonZeros ) const;
template< typename Type >
void checkNonZeros( const Type& matrix, size_t index, size_t expectedNonZeros ) const;
//@}
//**********************************************************************************************
//**Member variables****************************************************************************
/*!\name Member variables */
//@{
std::string test_; //!< Label of the currently performed test.
//@}
//**********************************************************************************************
//**Type definitions****************************************************************************
//! Type of the row-major Hermitian matrix.
typedef blaze::HermitianMatrix< blaze::DynamicMatrix<int,blaze::rowMajor> > HT;
//! Type of the column-major Hermitian matrix.
typedef blaze::HermitianMatrix< blaze::DynamicMatrix<int,blaze::columnMajor> > OHT;
typedef HT::Rebind<double>::Other RHT; //!< Rebound row-major Hermitian matrix type.
typedef OHT::Rebind<double>::Other ORHT; //!< Rebound column-major Hermitian matrix type.
//**********************************************************************************************
//**Compile time checks*************************************************************************
/*! \cond BLAZE_INTERNAL */
BLAZE_CONSTRAINT_MUST_BE_DENSE_MATRIX_TYPE( HT );
BLAZE_CONSTRAINT_MUST_BE_DENSE_MATRIX_TYPE( HT::ResultType );
BLAZE_CONSTRAINT_MUST_BE_DENSE_MATRIX_TYPE( HT::OppositeType );
BLAZE_CONSTRAINT_MUST_BE_DENSE_MATRIX_TYPE( HT::TransposeType );
BLAZE_CONSTRAINT_MUST_BE_DENSE_MATRIX_TYPE( OHT );
BLAZE_CONSTRAINT_MUST_BE_DENSE_MATRIX_TYPE( OHT::ResultType );
BLAZE_CONSTRAINT_MUST_BE_DENSE_MATRIX_TYPE( OHT::OppositeType );
BLAZE_CONSTRAINT_MUST_BE_DENSE_MATRIX_TYPE( OHT::TransposeType );
BLAZE_CONSTRAINT_MUST_BE_DENSE_MATRIX_TYPE( RHT );
BLAZE_CONSTRAINT_MUST_BE_DENSE_MATRIX_TYPE( RHT::ResultType );
BLAZE_CONSTRAINT_MUST_BE_DENSE_MATRIX_TYPE( RHT::OppositeType );
BLAZE_CONSTRAINT_MUST_BE_DENSE_MATRIX_TYPE( RHT::TransposeType );
BLAZE_CONSTRAINT_MUST_BE_DENSE_MATRIX_TYPE( ORHT );
BLAZE_CONSTRAINT_MUST_BE_DENSE_MATRIX_TYPE( ORHT::ResultType );
BLAZE_CONSTRAINT_MUST_BE_DENSE_MATRIX_TYPE( ORHT::OppositeType );
BLAZE_CONSTRAINT_MUST_BE_DENSE_MATRIX_TYPE( ORHT::TransposeType );
BLAZE_CONSTRAINT_MUST_BE_ROW_MAJOR_MATRIX_TYPE ( HT );
BLAZE_CONSTRAINT_MUST_BE_ROW_MAJOR_MATRIX_TYPE ( HT::ResultType );
BLAZE_CONSTRAINT_MUST_BE_COLUMN_MAJOR_MATRIX_TYPE( HT::OppositeType );
BLAZE_CONSTRAINT_MUST_BE_COLUMN_MAJOR_MATRIX_TYPE( HT::TransposeType );
BLAZE_CONSTRAINT_MUST_BE_COLUMN_MAJOR_MATRIX_TYPE( OHT );
BLAZE_CONSTRAINT_MUST_BE_COLUMN_MAJOR_MATRIX_TYPE( OHT::ResultType );
BLAZE_CONSTRAINT_MUST_BE_ROW_MAJOR_MATRIX_TYPE ( OHT::OppositeType );
BLAZE_CONSTRAINT_MUST_BE_ROW_MAJOR_MATRIX_TYPE ( OHT::TransposeType );
BLAZE_CONSTRAINT_MUST_BE_ROW_MAJOR_MATRIX_TYPE ( RHT );
BLAZE_CONSTRAINT_MUST_BE_ROW_MAJOR_MATRIX_TYPE ( RHT::ResultType );
BLAZE_CONSTRAINT_MUST_BE_COLUMN_MAJOR_MATRIX_TYPE( RHT::OppositeType );
BLAZE_CONSTRAINT_MUST_BE_COLUMN_MAJOR_MATRIX_TYPE( RHT::TransposeType );
BLAZE_CONSTRAINT_MUST_BE_COLUMN_MAJOR_MATRIX_TYPE( ORHT );
BLAZE_CONSTRAINT_MUST_BE_COLUMN_MAJOR_MATRIX_TYPE( ORHT::ResultType );
BLAZE_CONSTRAINT_MUST_BE_ROW_MAJOR_MATRIX_TYPE ( ORHT::OppositeType );
BLAZE_CONSTRAINT_MUST_BE_ROW_MAJOR_MATRIX_TYPE ( ORHT::TransposeType );
BLAZE_CONSTRAINT_MUST_BE_HERMITIAN_MATRIX_TYPE( HT );
BLAZE_CONSTRAINT_MUST_BE_HERMITIAN_MATRIX_TYPE( HT::ResultType );
BLAZE_CONSTRAINT_MUST_BE_HERMITIAN_MATRIX_TYPE( HT::OppositeType );
BLAZE_CONSTRAINT_MUST_BE_HERMITIAN_MATRIX_TYPE( HT::TransposeType );
BLAZE_CONSTRAINT_MUST_BE_HERMITIAN_MATRIX_TYPE( OHT );
BLAZE_CONSTRAINT_MUST_BE_HERMITIAN_MATRIX_TYPE( OHT::ResultType );
BLAZE_CONSTRAINT_MUST_BE_HERMITIAN_MATRIX_TYPE( OHT::OppositeType );
BLAZE_CONSTRAINT_MUST_BE_HERMITIAN_MATRIX_TYPE( OHT::TransposeType );
BLAZE_CONSTRAINT_MUST_BE_HERMITIAN_MATRIX_TYPE( RHT );
BLAZE_CONSTRAINT_MUST_BE_HERMITIAN_MATRIX_TYPE( RHT::ResultType );
BLAZE_CONSTRAINT_MUST_BE_HERMITIAN_MATRIX_TYPE( RHT::OppositeType );
BLAZE_CONSTRAINT_MUST_BE_HERMITIAN_MATRIX_TYPE( RHT::TransposeType );
BLAZE_CONSTRAINT_MUST_BE_HERMITIAN_MATRIX_TYPE( ORHT );
BLAZE_CONSTRAINT_MUST_BE_HERMITIAN_MATRIX_TYPE( ORHT::ResultType );
BLAZE_CONSTRAINT_MUST_BE_HERMITIAN_MATRIX_TYPE( ORHT::OppositeType );
BLAZE_CONSTRAINT_MUST_BE_HERMITIAN_MATRIX_TYPE( ORHT::TransposeType );
BLAZE_CONSTRAINT_MUST_BE_SYMMETRIC_MATRIX_TYPE( HT );
BLAZE_CONSTRAINT_MUST_BE_SYMMETRIC_MATRIX_TYPE( HT::ResultType );
BLAZE_CONSTRAINT_MUST_BE_SYMMETRIC_MATRIX_TYPE( HT::OppositeType );
BLAZE_CONSTRAINT_MUST_BE_SYMMETRIC_MATRIX_TYPE( HT::TransposeType );
BLAZE_CONSTRAINT_MUST_BE_SYMMETRIC_MATRIX_TYPE( OHT );
BLAZE_CONSTRAINT_MUST_BE_SYMMETRIC_MATRIX_TYPE( OHT::ResultType );
BLAZE_CONSTRAINT_MUST_BE_SYMMETRIC_MATRIX_TYPE( OHT::OppositeType );
BLAZE_CONSTRAINT_MUST_BE_SYMMETRIC_MATRIX_TYPE( OHT::TransposeType );
BLAZE_CONSTRAINT_MUST_BE_SYMMETRIC_MATRIX_TYPE( RHT );
BLAZE_CONSTRAINT_MUST_BE_SYMMETRIC_MATRIX_TYPE( RHT::ResultType );
BLAZE_CONSTRAINT_MUST_BE_SYMMETRIC_MATRIX_TYPE( RHT::OppositeType );
BLAZE_CONSTRAINT_MUST_BE_SYMMETRIC_MATRIX_TYPE( RHT::TransposeType );
BLAZE_CONSTRAINT_MUST_BE_SYMMETRIC_MATRIX_TYPE( ORHT );
BLAZE_CONSTRAINT_MUST_BE_SYMMETRIC_MATRIX_TYPE( ORHT::ResultType );
BLAZE_CONSTRAINT_MUST_BE_SYMMETRIC_MATRIX_TYPE( ORHT::OppositeType );
BLAZE_CONSTRAINT_MUST_BE_SYMMETRIC_MATRIX_TYPE( ORHT::TransposeType );
BLAZE_CONSTRAINT_MUST_NOT_REQUIRE_EVALUATION( HT::ResultType );
BLAZE_CONSTRAINT_MUST_NOT_REQUIRE_EVALUATION( HT::OppositeType );
BLAZE_CONSTRAINT_MUST_NOT_REQUIRE_EVALUATION( HT::TransposeType );
BLAZE_CONSTRAINT_MUST_NOT_REQUIRE_EVALUATION( OHT::ResultType );
BLAZE_CONSTRAINT_MUST_NOT_REQUIRE_EVALUATION( OHT::OppositeType );
BLAZE_CONSTRAINT_MUST_NOT_REQUIRE_EVALUATION( OHT::TransposeType );
BLAZE_CONSTRAINT_MUST_NOT_REQUIRE_EVALUATION( RHT::ResultType );
BLAZE_CONSTRAINT_MUST_NOT_REQUIRE_EVALUATION( RHT::OppositeType );
BLAZE_CONSTRAINT_MUST_NOT_REQUIRE_EVALUATION( RHT::TransposeType );
BLAZE_CONSTRAINT_MUST_NOT_REQUIRE_EVALUATION( ORHT::ResultType );
BLAZE_CONSTRAINT_MUST_NOT_REQUIRE_EVALUATION( ORHT::OppositeType );
BLAZE_CONSTRAINT_MUST_NOT_REQUIRE_EVALUATION( ORHT::TransposeType );
BLAZE_CONSTRAINT_MUST_BE_SAME_TYPE( HT::ElementType, HT::ResultType::ElementType );
BLAZE_CONSTRAINT_MUST_BE_SAME_TYPE( HT::ElementType, HT::OppositeType::ElementType );
BLAZE_CONSTRAINT_MUST_BE_SAME_TYPE( HT::ElementType, HT::TransposeType::ElementType );
BLAZE_CONSTRAINT_MUST_BE_SAME_TYPE( OHT::ElementType, OHT::ResultType::ElementType );
BLAZE_CONSTRAINT_MUST_BE_SAME_TYPE( OHT::ElementType, OHT::OppositeType::ElementType );
BLAZE_CONSTRAINT_MUST_BE_SAME_TYPE( OHT::ElementType, OHT::TransposeType::ElementType );
BLAZE_CONSTRAINT_MUST_BE_SAME_TYPE( RHT::ElementType, RHT::ResultType::ElementType );
BLAZE_CONSTRAINT_MUST_BE_SAME_TYPE( RHT::ElementType, RHT::OppositeType::ElementType );
BLAZE_CONSTRAINT_MUST_BE_SAME_TYPE( RHT::ElementType, RHT::TransposeType::ElementType );
BLAZE_CONSTRAINT_MUST_BE_SAME_TYPE( ORHT::ElementType, ORHT::ResultType::ElementType );
BLAZE_CONSTRAINT_MUST_BE_SAME_TYPE( ORHT::ElementType, ORHT::OppositeType::ElementType );
BLAZE_CONSTRAINT_MUST_BE_SAME_TYPE( ORHT::ElementType, ORHT::TransposeType::ElementType );
/*! \endcond */
//**********************************************************************************************
};
//*************************************************************************************************
//=================================================================================================
//
// TEST FUNCTIONS
//
//=================================================================================================
//*************************************************************************************************
/*!\brief Checking the number of rows of the given matrix.
//
// \param matrix The matrix to be checked.
// \param expectedRows The expected number of rows of the matrix.
// \return void
// \exception std::runtime_error Error detected.
//
// This function checks the number of rows of the given matrix. In case the actual number of
// rows does not correspond to the given expected number of rows, a \a std::runtime_error
// exception is thrown.
*/
template< typename Type > // Type of the matrix
void DenseRealTest::checkRows( const Type& matrix, size_t expectedRows ) const
{
if( matrix.rows() != expectedRows ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid number of rows detected\n"
<< " Details:\n"
<< " Number of rows : " << matrix.rows() << "\n"
<< " Expected number of rows: " << expectedRows << "\n";
throw std::runtime_error( oss.str() );
}
}
//*************************************************************************************************
//*************************************************************************************************
/*!\brief Checking the number of columns of the given matrix.
//
// \param matrix The matrix to be checked.
// \param expectedRows The expected number of columns of the matrix.
// \return void
// \exception std::runtime_error Error detected.
//
// This function checks the number of columns of the given matrix. In case the actual number of
// columns does not correspond to the given expected number of columns, a \a std::runtime_error
// exception is thrown.
*/
template< typename Type > // Type of the matrix
void DenseRealTest::checkColumns( const Type& matrix, size_t expectedColumns ) const
{
if( matrix.columns() != expectedColumns ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid number of columns detected\n"
<< " Details:\n"
<< " Number of columns : " << matrix.columns() << "\n"
<< " Expected number of columns: " << expectedColumns << "\n";
throw std::runtime_error( oss.str() );
}
}
//*************************************************************************************************
//*************************************************************************************************
/*!\brief Checking the capacity of the given matrix.
//
// \param matrix The matrix to be checked.
// \param minCapacity The expected minimum capacity of the matrix.
// \return void
// \exception std::runtime_error Error detected.
//
// This function checks the capacity of the given matrix. In case the actual capacity is smaller
// than the given expected minimum capacity, a \a std::runtime_error exception is thrown.
*/
template< typename Type > // Type of the matrix
void DenseRealTest::checkCapacity( const Type& matrix, size_t minCapacity ) const
{
if( capacity( matrix ) < minCapacity ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid capacity detected\n"
<< " Details:\n"
<< " Capacity : " << capacity( matrix ) << "\n"
<< " Expected minimum capacity: " << minCapacity << "\n";
throw std::runtime_error( oss.str() );
}
}
//*************************************************************************************************
//*************************************************************************************************
/*!\brief Checking the number of non-zero elements of the given matrix.
//
// \param matrix The matrix to be checked.
// \param expectedNonZeros The expected number of non-zero elements of the matrix.
// \return void
// \exception std::runtime_error Error detected.
//
// This function checks the number of non-zero elements of the given matrix. In case the
// actual number of non-zero elements does not correspond to the given expected number,
// a \a std::runtime_error exception is thrown.
*/
template< typename Type > // Type of the matrix
void DenseRealTest::checkNonZeros( const Type& matrix, size_t expectedNonZeros ) const
{
if( nonZeros( matrix ) != expectedNonZeros ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid number of non-zero elements\n"
<< " Details:\n"
<< " Number of non-zeros : " << nonZeros( matrix ) << "\n"
<< " Expected number of non-zeros: " << expectedNonZeros << "\n";
throw std::runtime_error( oss.str() );
}
if( capacity( matrix ) < nonZeros( matrix ) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid capacity detected\n"
<< " Details:\n"
<< " Number of non-zeros: " << nonZeros( matrix ) << "\n"
<< " Capacity : " << capacity( matrix ) << "\n";
throw std::runtime_error( oss.str() );
}
}
//*************************************************************************************************
//*************************************************************************************************
/*!\brief Checking the number of non-zero elements in a specific row/column of the given matrix.
//
// \param matrix The matrix to be checked.
// \param index The row/column to be checked.
// \param expectedNonZeros The expected number of non-zero elements in the specified row/column.
// \return void
// \exception std::runtime_error Error detected.
//
// This function checks the number of non-zero elements in the specified row/column of the
// given matrix. In case the actual number of non-zero elements does not correspond to the
// given expected number, a \a std::runtime_error exception is thrown.
*/
template< typename Type > // Type of the matrix
void DenseRealTest::checkNonZeros( const Type& matrix, size_t index, size_t expectedNonZeros ) const
{
if( nonZeros( matrix, index ) != expectedNonZeros ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid number of non-zero elements in "
<< ( blaze::IsRowMajorMatrix<Type>::value ? "row " : "column " ) << index << "\n"
<< " Details:\n"
<< " Number of non-zeros : " << nonZeros( matrix, index ) << "\n"
<< " Expected number of non-zeros: " << expectedNonZeros << "\n";
throw std::runtime_error( oss.str() );
}
if( capacity( matrix, index ) < nonZeros( matrix, index ) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid capacity detected in "
<< ( blaze::IsRowMajorMatrix<Type>::value ? "row " : "column " ) << index << "\n"
<< " Details:\n"
<< " Number of non-zeros: " << nonZeros( matrix, index ) << "\n"
<< " Capacity : " << capacity( matrix, index ) << "\n";
throw std::runtime_error( oss.str() );
}
}
//*************************************************************************************************
//=================================================================================================
//
// GLOBAL TEST FUNCTIONS
//
//=================================================================================================
//*************************************************************************************************
/*!\brief Testing the functionality of the dense HermitianMatrix specialization.
//
// \return void
*/
void runTest()
{
DenseRealTest();
}
//*************************************************************************************************
//=================================================================================================
//
// MACRO DEFINITIONS
//
//=================================================================================================
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Macro for the execution of the HermitianMatrix dense real test.
*/
#define RUN_HERMITIANMATRIX_DENSEREAL_TEST \
blazetest::mathtest::hermitianmatrix::runTest()
/*! \endcond */
//*************************************************************************************************
} // namespace hermitianmatrix
} // namespace mathtest
} // namespace blazetest
#endif
| [
"klaus.iglberger@gmail.com"
] | klaus.iglberger@gmail.com |
c8e3243d4ab3ee8539e7dd6ae3df13811b3b4809 | 07ee17f9fb57c0ccc9e4fe2c18410bd3f3eeec34 | /darkstar/Tools/zed/LightDialog.h | 39793991b8a74e75b96c3a10eb1f6df916528f5f | [] | no_license | AlexHuck/TribesRebirth | 1ea6ba27bc2af10527259d4d6cd4561a1793bccd | cf52c2e8c63f3da79e38cb3c153288d12003b123 | refs/heads/master | 2021-09-11T00:35:45.407177 | 2021-08-29T14:36:56 | 2021-08-29T14:36:56 | 226,741,338 | 0 | 0 | null | 2019-12-08T22:30:13 | 2019-12-08T22:30:12 | null | UTF-8 | C++ | false | false | 3,660 | h | #if !defined(AFX_LIGHTDIALOG_H__A64110D2_6104_11D1_8CE9_006097B90B28__INCLUDED_)
#define AFX_LIGHTDIALOG_H__A64110D2_6104_11D1_8CE9_006097B90B28__INCLUDED_
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
// LightDialog.h : header file
//
#include "Light.h"
#include "threddoc.h"
class CMyDragListBox : public CDragListBox
{
void Dropped( int Source, CPoint DropPoint );
};
class CMyColorButton : public CButton
{
public:
void DrawItem( LPDRAWITEMSTRUCT lpDrawItemStruct );
void SetDialog( class CLightDialog * pLightDialog );
private:
class CLightDialog * m_lightDialog;
};
/////////////////////////////////////////////////////////////////////////////
// CLightDialog dialog
class CLightDialog : public CDialog
{
// Construction
public:
CLightDialog(CWnd* pParent = NULL); // standard constructor
CTHREDDoc * pDoc;
// our light array
CLightArray* mLightArray;
CLightArray mSavedLightArray;
int mCurrentLight;
int mCurrentState;
int EditLight( CLightArray& Lights, int CurrentLight, CTHREDDoc* Doc );
void FillDialogInfo( void );
void FillLightInfo( void );
void FillStateInfo( void );
bool UpdateStateInfo( void );
void SetSunValues( CLightState * pLightState, Point3F * pVector );
// info strings
CString m_PositionString;
CString m_DurationString;
CString m_ColorString;
CString m_Distance1String;
CString m_Distance2String;
CString m_Distance3String;
CString m_DirectionString;
CString m_AngleString;
// CString m_IDString;
// Dialog Data
//{{AFX_DATA(CLightDialog)
enum { IDD = IDD_LIGHT_DIALOG };
CMyColorButton m_colorButton;
CSpinButtonCtrl m_StateSpin;
CEdit m_PositionEdit;
CEdit m_DurationEdit;
CEdit m_Distance3Edit;
CEdit m_Distance2Edit;
CEdit m_Distance1Edit;
CEdit m_DirectionEdit;
CEdit m_AngleEdit;
CListBox m_StateList;
CMyDragListBox m_LightList;
CEdit m_NameEdit;
CEdit m_ColorEdit;
//}}AFX_DATA
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CLightDialog)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
// Generated message map functions
//{{AFX_MSG(CLightDialog)
virtual BOOL OnInitDialog();
afx_msg void OnClose();
afx_msg void OnLdColorpick();
afx_msg void OnLdAddstate();
afx_msg void OnLdAutocheck();
afx_msg void OnLdCreatelight();
afx_msg void OnLdLinearradio();
afx_msg void OnLdLoopcheck();
afx_msg void OnLdPointradio();
afx_msg void OnLdQuadraticradio();
afx_msg void OnLdRandomcheck();
afx_msg void OnLdRemovestate();
afx_msg void OnLdSpotradio();
afx_msg void OnDeltaposLdStatespin(NMHDR* pNMHDR, LRESULT* pResult);
afx_msg void OnSelchangeLdLightlist();
afx_msg void OnSelchangeIdStatelist();
afx_msg void OnLdApply();
afx_msg void OnChangeLdNameedit();
afx_msg void OnLdDeletelight();
afx_msg void OnChangeLdPositionedit();
afx_msg void OnChangeLdAngleedit();
afx_msg void OnChangeLdColoredit();
afx_msg void OnChangeLdDirectionedit();
afx_msg void OnChangeLdDistance1edit();
afx_msg void OnChangeLdDistance2edit();
afx_msg void OnChangeLdDistance3edit();
afx_msg void OnChangeLdDurationedit();
virtual void OnOK();
virtual void OnCancel();
afx_msg void OnLdNoneradio();
afx_msg void OnLdCopycurrent();
afx_msg void OnLdLight();
afx_msg void OnChangeLdId();
afx_msg void OnLdManagebymissioneditor();
afx_msg void OnLsSunedit();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_LIGHTDIALOG_H__A64110D2_6104_11D1_8CE9_006097B90B28__INCLUDED_)
| [
"altimormc@gmail.com"
] | altimormc@gmail.com |
2dbd1913cd91004c390635fa65557afb244f8fb4 | 8b566835a32db923f84c612e4d4ed4def2dbd6b1 | /LineManager.h | cfdc22612dab8751995bc094f1455dc2f6beecc7 | [] | no_license | Kai4ik/Simulated-assemlby-line | 636b065800fc330b0ef3b1baaeba9a29b74a1952 | f76c48857eb8868abe7922a2ce4f02547976ef57 | refs/heads/master | 2022-12-27T19:18:41.555698 | 2020-10-03T23:03:43 | 2020-10-03T23:03:43 | 300,997,734 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 945 | h | // Name: Kairat Orozobekov
// Seneca Student ID: 104 998 190
// Seneca email: korozobekov@myseneca.ca
// Date of completion: 08.01.20
//
// I confirm that I am the only author of this file
// and the content was created entirely by me.
#ifndef LINEMANAGER_H
#define LINEMANAGER_H
#include <vector>
#include <deque>
#include <string>
#include "Workstation.h"
#include "CustomerOrder.h"
class LineManager
{
std::vector<Workstation*> AssemblyLine;
std::deque<CustomerOrder> toBeFilled;
std::deque<CustomerOrder> Completed;
unsigned int m_cntCustomerOrder;
public:
LineManager(){this->m_cntCustomerOrder = 0;};
LineManager(const std::string& record, std::vector<Workstation*>& workst_obj, std::vector<CustomerOrder>& custord_obj);
bool run(std::ostream& os);
bool runt(std::ostream& os);
void displayStations()const;
void displayStationsSorted() const;
void displayCompletedOrders(std::ostream& os) const;
};
#endif // !LINEMANAGER_H
| [
"orozobekov.kai@gmail.com"
] | orozobekov.kai@gmail.com |
95b7210d690578361aefb0ca8c3b3dac27ca5272 | ceb7431363e36a4698a93540cdeafcd9d9b315ad | /include/latino/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h | f3624fbc5373109778b20a3c8afec7650d3fc586 | [
"MIT"
] | permissive | primitivorm/latino-llvm | 8b5d8759271eb6c328cb4c81a2523bbecce10222 | 33c820aeef006b7190e347e0839cf4f268b70639 | refs/heads/master | 2023-08-02T06:15:42.365363 | 2023-05-05T13:28:32 | 2023-05-05T13:28:32 | 133,191,211 | 4 | 2 | MIT | 2022-03-31T01:39:29 | 2018-05-12T23:39:50 | C++ | UTF-8 | C++ | false | false | 18,266 | h | //===- ExplodedGraph.h - Local, Path-Sens. "Exploded Graph" -----*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines the template classes ExplodedNode and ExplodedGraph,
// which represent a path-sensitive, intra-procedural "exploded graph."
// See "Precise interprocedural dataflow analysis via graph reachability"
// by Reps, Horwitz, and Sagiv
// (http://portal.acm.org/citation.cfm?id=199462) for the definition of an
// exploded graph.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_LATINO_STATICANALYZER_CORE_PATHSENSITIVE_EXPLODEDGRAPH_H
#define LLVM_LATINO_STATICANALYZER_CORE_PATHSENSITIVE_EXPLODEDGRAPH_H
#include "latino/Analysis/AnalysisDeclContext.h"
#include "latino/Analysis/ProgramPoint.h"
#include "latino/Analysis/Support/BumpVector.h"
#include "latino/Basic/LLVM.h"
#include "latino/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
#include "latino/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
#include "latino/StaticAnalyzer/Core/PathSensitive/SVals.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/DepthFirstIterator.h"
#include "llvm/ADT/FoldingSet.h"
#include "llvm/ADT/GraphTraits.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/Support/Allocator.h"
#include "llvm/Support/Compiler.h"
#include <cassert>
#include <cstdint>
#include <memory>
#include <utility>
#include <vector>
namespace latino {
class CFG;
class Decl;
class Expr;
class ParentMap;
class Stmt;
namespace ento {
class ExplodedGraph;
//===----------------------------------------------------------------------===//
// ExplodedGraph "implementation" classes. These classes are not typed to
// contain a specific kind of state. Typed-specialized versions are defined
// on top of these classes.
//===----------------------------------------------------------------------===//
// ExplodedNode is not constified all over the engine because we need to add
// successors to it at any time after creating it.
class ExplodedNode : public llvm::FoldingSetNode {
friend class BranchNodeBuilder;
friend class CoreEngine;
friend class EndOfFunctionNodeBuilder;
friend class ExplodedGraph;
friend class IndirectGotoNodeBuilder;
friend class NodeBuilder;
friend class SwitchNodeBuilder;
/// Efficiently stores a list of ExplodedNodes, or an optional flag.
///
/// NodeGroup provides opaque storage for a list of ExplodedNodes, optimizing
/// for the case when there is only one node in the group. This is a fairly
/// common case in an ExplodedGraph, where most nodes have only one
/// predecessor and many have only one successor. It can also be used to
/// store a flag rather than a node list, which ExplodedNode uses to mark
/// whether a node is a sink. If the flag is set, the group is implicitly
/// empty and no nodes may be added.
class NodeGroup {
// Conceptually a discriminated union. If the low bit is set, the node is
// a sink. If the low bit is not set, the pointer refers to the storage
// for the nodes in the group.
// This is not a PointerIntPair in order to keep the storage type opaque.
uintptr_t P;
public:
NodeGroup(bool Flag = false) : P(Flag) {
assert(getFlag() == Flag);
}
ExplodedNode * const *begin() const;
ExplodedNode * const *end() const;
unsigned size() const;
bool empty() const { return P == 0 || getFlag() != 0; }
/// Adds a node to the list.
///
/// The group must not have been created with its flag set.
void addNode(ExplodedNode *N, ExplodedGraph &G);
/// Replaces the single node in this group with a new node.
///
/// Note that this should only be used when you know the group was not
/// created with its flag set, and that the group is empty or contains
/// only a single node.
void replaceNode(ExplodedNode *node);
/// Returns whether this group was created with its flag set.
bool getFlag() const {
return (P & 1);
}
};
/// Location - The program location (within a function body) associated
/// with this node.
const ProgramPoint Location;
/// State - The state associated with this node.
ProgramStateRef State;
/// Preds - The predecessors of this node.
NodeGroup Preds;
/// Succs - The successors of this node.
NodeGroup Succs;
int64_t Id;
public:
explicit ExplodedNode(const ProgramPoint &loc, ProgramStateRef state,
int64_t Id, bool IsSink)
: Location(loc), State(std::move(state)), Succs(IsSink), Id(Id) {
assert(isSink() == IsSink);
}
/// getLocation - Returns the edge associated with the given node.
ProgramPoint getLocation() const { return Location; }
const LocationContext *getLocationContext() const {
return getLocation().getLocationContext();
}
const StackFrameContext *getStackFrame() const {
return getLocation().getStackFrame();
}
const Decl &getCodeDecl() const { return *getLocationContext()->getDecl(); }
CFG &getCFG() const { return *getLocationContext()->getCFG(); }
const CFGBlock *getCFGBlock() const;
const ParentMap &getParentMap() const {
return getLocationContext()->getParentMap();
}
template <typename T>
T &getAnalysis() const {
return *getLocationContext()->getAnalysis<T>();
}
const ProgramStateRef &getState() const { return State; }
template <typename T>
Optional<T> getLocationAs() const LLVM_LVALUE_FUNCTION {
return Location.getAs<T>();
}
/// Get the value of an arbitrary expression at this node.
SVal getSVal(const Stmt *S) const {
return getState()->getSVal(S, getLocationContext());
}
static void Profile(llvm::FoldingSetNodeID &ID,
const ProgramPoint &Loc,
const ProgramStateRef &state,
bool IsSink) {
ID.Add(Loc);
ID.AddPointer(state.get());
ID.AddBoolean(IsSink);
}
void Profile(llvm::FoldingSetNodeID& ID) const {
// We avoid copy constructors by not using accessors.
Profile(ID, Location, State, isSink());
}
/// addPredeccessor - Adds a predecessor to the current node, and
/// in tandem add this node as a successor of the other node.
void addPredecessor(ExplodedNode *V, ExplodedGraph &G);
unsigned succ_size() const { return Succs.size(); }
unsigned pred_size() const { return Preds.size(); }
bool succ_empty() const { return Succs.empty(); }
bool pred_empty() const { return Preds.empty(); }
bool isSink() const { return Succs.getFlag(); }
bool hasSinglePred() const {
return (pred_size() == 1);
}
ExplodedNode *getFirstPred() {
return pred_empty() ? nullptr : *(pred_begin());
}
const ExplodedNode *getFirstPred() const {
return const_cast<ExplodedNode*>(this)->getFirstPred();
}
ExplodedNode *getFirstSucc() {
return succ_empty() ? nullptr : *(succ_begin());
}
const ExplodedNode *getFirstSucc() const {
return const_cast<ExplodedNode*>(this)->getFirstSucc();
}
// Iterators over successor and predecessor vertices.
using succ_iterator = ExplodedNode * const *;
using succ_range = llvm::iterator_range<succ_iterator>;
using const_succ_iterator = const ExplodedNode * const *;
using const_succ_range = llvm::iterator_range<const_succ_iterator>;
using pred_iterator = ExplodedNode * const *;
using pred_range = llvm::iterator_range<pred_iterator>;
using const_pred_iterator = const ExplodedNode * const *;
using const_pred_range = llvm::iterator_range<const_pred_iterator>;
pred_iterator pred_begin() { return Preds.begin(); }
pred_iterator pred_end() { return Preds.end(); }
pred_range preds() { return {Preds.begin(), Preds.end()}; }
const_pred_iterator pred_begin() const {
return const_cast<ExplodedNode*>(this)->pred_begin();
}
const_pred_iterator pred_end() const {
return const_cast<ExplodedNode*>(this)->pred_end();
}
const_pred_range preds() const { return {Preds.begin(), Preds.end()}; }
succ_iterator succ_begin() { return Succs.begin(); }
succ_iterator succ_end() { return Succs.end(); }
succ_range succs() { return {Succs.begin(), Succs.end()}; }
const_succ_iterator succ_begin() const {
return const_cast<ExplodedNode*>(this)->succ_begin();
}
const_succ_iterator succ_end() const {
return const_cast<ExplodedNode*>(this)->succ_end();
}
const_succ_range succs() const { return {Succs.begin(), Succs.end()}; }
int64_t getID() const { return Id; }
/// The node is trivial if it has only one successor, only one predecessor,
/// it's predecessor has only one successor,
/// and its program state is the same as the program state of the previous
/// node.
/// Trivial nodes may be skipped while printing exploded graph.
bool isTrivial() const;
/// If the node's program point corresponds to a statement, retrieve that
/// statement. Useful for figuring out where to put a warning or a note.
/// If the statement belongs to a body-farmed definition,
/// retrieve the call site for that definition.
const Stmt *getStmtForDiagnostics() const;
/// Find the next statement that was executed on this node's execution path.
/// Useful for explaining control flow that follows the current node.
/// If the statement belongs to a body-farmed definition, retrieve the
/// call site for that definition.
const Stmt *getNextStmtForDiagnostics() const;
/// Find the statement that was executed immediately before this node.
/// Useful when the node corresponds to a CFG block entrance.
/// If the statement belongs to a body-farmed definition, retrieve the
/// call site for that definition.
const Stmt *getPreviousStmtForDiagnostics() const;
/// Find the statement that was executed at or immediately before this node.
/// Useful when any nearby statement will do.
/// If the statement belongs to a body-farmed definition, retrieve the
/// call site for that definition.
const Stmt *getCurrentOrPreviousStmtForDiagnostics() const;
private:
void replaceSuccessor(ExplodedNode *node) { Succs.replaceNode(node); }
void replacePredecessor(ExplodedNode *node) { Preds.replaceNode(node); }
};
using InterExplodedGraphMap =
llvm::DenseMap<const ExplodedNode *, const ExplodedNode *>;
class ExplodedGraph {
protected:
friend class CoreEngine;
// Type definitions.
using NodeVector = std::vector<ExplodedNode *>;
/// The roots of the simulation graph. Usually there will be only
/// one, but clients are free to establish multiple subgraphs within a single
/// SimulGraph. Moreover, these subgraphs can often merge when paths from
/// different roots reach the same state at the same program location.
NodeVector Roots;
/// The nodes in the simulation graph which have been
/// specially marked as the endpoint of an abstract simulation path.
NodeVector EndNodes;
/// Nodes - The nodes in the graph.
llvm::FoldingSet<ExplodedNode> Nodes;
/// BVC - Allocator and context for allocating nodes and their predecessor
/// and successor groups.
BumpVectorContext BVC;
/// NumNodes - The number of nodes in the graph.
int64_t NumNodes = 0;
/// A list of recently allocated nodes that can potentially be recycled.
NodeVector ChangedNodes;
/// A list of nodes that can be reused.
NodeVector FreeNodes;
/// Determines how often nodes are reclaimed.
///
/// If this is 0, nodes will never be reclaimed.
unsigned ReclaimNodeInterval = 0;
/// Counter to determine when to reclaim nodes.
unsigned ReclaimCounter;
public:
ExplodedGraph();
~ExplodedGraph();
/// Retrieve the node associated with a (Location,State) pair,
/// where the 'Location' is a ProgramPoint in the CFG. If no node for
/// this pair exists, it is created. IsNew is set to true if
/// the node was freshly created.
ExplodedNode *getNode(const ProgramPoint &L, ProgramStateRef State,
bool IsSink = false,
bool* IsNew = nullptr);
/// Create a node for a (Location, State) pair,
/// but don't store it for deduplication later. This
/// is useful when copying an already completed
/// ExplodedGraph for further processing.
ExplodedNode *createUncachedNode(const ProgramPoint &L,
ProgramStateRef State,
int64_t Id,
bool IsSink = false);
std::unique_ptr<ExplodedGraph> MakeEmptyGraph() const {
return std::make_unique<ExplodedGraph>();
}
/// addRoot - Add an untyped node to the set of roots.
ExplodedNode *addRoot(ExplodedNode *V) {
Roots.push_back(V);
return V;
}
/// addEndOfPath - Add an untyped node to the set of EOP nodes.
ExplodedNode *addEndOfPath(ExplodedNode *V) {
EndNodes.push_back(V);
return V;
}
unsigned num_roots() const { return Roots.size(); }
unsigned num_eops() const { return EndNodes.size(); }
bool empty() const { return NumNodes == 0; }
unsigned size() const { return NumNodes; }
void reserve(unsigned NodeCount) { Nodes.reserve(NodeCount); }
// Iterators.
using NodeTy = ExplodedNode;
using AllNodesTy = llvm::FoldingSet<ExplodedNode>;
using roots_iterator = NodeVector::iterator;
using const_roots_iterator = NodeVector::const_iterator;
using eop_iterator = NodeVector::iterator;
using const_eop_iterator = NodeVector::const_iterator;
using node_iterator = AllNodesTy::iterator;
using const_node_iterator = AllNodesTy::const_iterator;
node_iterator nodes_begin() { return Nodes.begin(); }
node_iterator nodes_end() { return Nodes.end(); }
const_node_iterator nodes_begin() const { return Nodes.begin(); }
const_node_iterator nodes_end() const { return Nodes.end(); }
roots_iterator roots_begin() { return Roots.begin(); }
roots_iterator roots_end() { return Roots.end(); }
const_roots_iterator roots_begin() const { return Roots.begin(); }
const_roots_iterator roots_end() const { return Roots.end(); }
eop_iterator eop_begin() { return EndNodes.begin(); }
eop_iterator eop_end() { return EndNodes.end(); }
const_eop_iterator eop_begin() const { return EndNodes.begin(); }
const_eop_iterator eop_end() const { return EndNodes.end(); }
llvm::BumpPtrAllocator & getAllocator() { return BVC.getAllocator(); }
BumpVectorContext &getNodeAllocator() { return BVC; }
using NodeMap = llvm::DenseMap<const ExplodedNode *, ExplodedNode *>;
/// Creates a trimmed version of the graph that only contains paths leading
/// to the given nodes.
///
/// \param Nodes The nodes which must appear in the final graph. Presumably
/// these are end-of-path nodes (i.e. they have no successors).
/// \param[out] ForwardMap A optional map from nodes in this graph to nodes in
/// the returned graph.
/// \param[out] InverseMap An optional map from nodes in the returned graph to
/// nodes in this graph.
/// \returns The trimmed graph
std::unique_ptr<ExplodedGraph>
trim(ArrayRef<const NodeTy *> Nodes,
InterExplodedGraphMap *ForwardMap = nullptr,
InterExplodedGraphMap *InverseMap = nullptr) const;
/// Enable tracking of recently allocated nodes for potential reclamation
/// when calling reclaimRecentlyAllocatedNodes().
void enableNodeReclamation(unsigned Interval) {
ReclaimCounter = ReclaimNodeInterval = Interval;
}
/// Reclaim "uninteresting" nodes created since the last time this method
/// was called.
void reclaimRecentlyAllocatedNodes();
/// Returns true if nodes for the given expression kind are always
/// kept around.
static bool isInterestingLValueExpr(const Expr *Ex);
private:
bool shouldCollect(const ExplodedNode *node);
void collectNode(ExplodedNode *node);
};
class ExplodedNodeSet {
using ImplTy = llvm::SmallSetVector<ExplodedNode *, 4>;
ImplTy Impl;
public:
ExplodedNodeSet(ExplodedNode *N) {
assert(N && !static_cast<ExplodedNode*>(N)->isSink());
Impl.insert(N);
}
ExplodedNodeSet() = default;
void Add(ExplodedNode *N) {
if (N && !static_cast<ExplodedNode*>(N)->isSink()) Impl.insert(N);
}
using iterator = ImplTy::iterator;
using const_iterator = ImplTy::const_iterator;
unsigned size() const { return Impl.size(); }
bool empty() const { return Impl.empty(); }
bool erase(ExplodedNode *N) { return Impl.remove(N); }
void clear() { Impl.clear(); }
void insert(const ExplodedNodeSet &S) {
assert(&S != this);
if (empty())
Impl = S.Impl;
else
Impl.insert(S.begin(), S.end());
}
iterator begin() { return Impl.begin(); }
iterator end() { return Impl.end(); }
const_iterator begin() const { return Impl.begin(); }
const_iterator end() const { return Impl.end(); }
};
} // namespace ento
} // namespace latino
// GraphTraits
namespace llvm {
template <> struct GraphTraits<latino::ento::ExplodedGraph *> {
using GraphTy = latino::ento::ExplodedGraph *;
using NodeRef = latino::ento::ExplodedNode *;
using ChildIteratorType = latino::ento::ExplodedNode::succ_iterator;
using nodes_iterator = llvm::df_iterator<GraphTy>;
static NodeRef getEntryNode(const GraphTy G) {
return *G->roots_begin();
}
static bool predecessorOfTrivial(NodeRef N) {
return N->succ_size() == 1 && N->getFirstSucc()->isTrivial();
}
static ChildIteratorType child_begin(NodeRef N) {
if (predecessorOfTrivial(N))
return child_begin(*N->succ_begin());
return N->succ_begin();
}
static ChildIteratorType child_end(NodeRef N) {
if (predecessorOfTrivial(N))
return child_end(N->getFirstSucc());
return N->succ_end();
}
static nodes_iterator nodes_begin(const GraphTy G) {
return df_begin(G);
}
static nodes_iterator nodes_end(const GraphTy G) {
return df_end(G);
}
};
} // namespace llvm
#endif // LLVM_LATINO_STATICANALYZER_CORE_PATHSENSITIVE_EXPLODEDGRAPH_H
| [
"cibercafe_montero@hotmail.com"
] | cibercafe_montero@hotmail.com |
0a68af7d17997ccdc1ce14bf40e4bca7405700ae | bbd93d71b967f97cc3b21f7b217beb533e21185c | /PythonSTG/XCCore/Task/TaskHelper.cpp | d5d7885af22de8ba0b76cd0679999d59bdb8b365 | [] | no_license | lr8soft/PythonSTG | e4d21cfeb7f96321c5d8ec0062a79dd77accd64f | 7af1f54d4b07935e4c4bcf1e4a5b2bb0dcc3b02b | refs/heads/master | 2023-04-16T04:23:19.851314 | 2023-04-06T13:28:11 | 2023-04-06T13:28:11 | 209,579,866 | 16 | 3 | null | 2019-11-29T08:12:40 | 2019-09-19T14:49:58 | C | UTF-8 | C++ | false | false | 4,294 | cpp | #include "TaskHelper.h"
#include "../Bullet/BulletHelper.h"
#include "../Item/ItemHelper.h"
#include "../../XCInterpreter/ImageParseHelper.h"
#include "TaskEnemy.h"
TaskInsideUnit * TaskHelper::parseTaskUnitFromObject(std::string uuid, PyObject * unitObject)
{
TaskInsideUnit* unit = nullptr;
if (unitObject != nullptr) {
auto unitSizeInfo = PyObject_CallMethod(unitObject, "_cpp_getBulletSize", NULL);
auto unitDetailInfo = PyObject_CallMethod(unitObject, "_cpp_getUnitInfo", NULL);
int renderObjectSize;
PyArg_Parse(unitSizeInfo, "i", &renderObjectSize);
int waitFrame, repeatTime;
PyArg_ParseTuple(unitDetailInfo, "ii", &waitFrame, &repeatTime);
unit = new TaskInsideUnit(uuid, waitFrame, repeatTime);//R E L E A S E P L E A S E
std::list<std::list<RenderObject*>> renderGroupGroup;
for (int i = 0; i < repeatTime - 1;i++) {
std::list<RenderObject*> list;
renderGroupGroup.push_back(list);
}
if (renderObjectSize>0) {
for (int i = 0; i < renderObjectSize;i++) {
PyObject* pBullet, *bulletObject = PyObject_CallMethod(unitObject, "_cpp_getBulletItem", NULL);
PyArg_Parse(bulletObject, "O", &pBullet);
Bullet* bulletItem = BulletHelper::parseBulletObject(pBullet);
if (bulletItem !=nullptr) {
unit->addRenderObject(bulletItem);
}
if (repeatTime > 1) {
for (auto iter = renderGroupGroup.begin(); iter != renderGroupGroup.end(); iter++) {
Bullet* newBullet = BulletHelper::parseBulletObject(pBullet);
iter->push_back(newBullet);
}
}
}
for (auto iter = renderGroupGroup.begin(); iter != renderGroupGroup.end(); iter++) {
unit->addRenderGroup(*iter);
}
}
}
return unit;
}
Task * TaskHelper::parseTaskFromObject(PyObject * taskObject)
{
Task* task = nullptr;
if (taskObject != nullptr) {
auto taskInfo = PyObject_CallMethod(taskObject, "_cpp_getTaskInfo", NULL);
auto sizeInfo = PyObject_CallMethod(taskObject, "_cpp_getUnitSize", NULL);
auto targetInfo = PyObject_CallMethod(taskObject, "_cpp_getTargetUuidSize", NULL);
const char *uuid; int repeatTime, intervalFrame, waitFrame, isEnemyTask = 0;
PyArg_ParseTuple(taskInfo, "siii|p", &uuid, &repeatTime, &intervalFrame, &waitFrame, &isEnemyTask);
int targetUuidSize;
PyArg_Parse(targetInfo, "i", &targetUuidSize);
std::vector<std::string> targetUuid;
if (targetUuidSize > 0){
for (int i = 0; i < targetUuidSize; i++) {
const char* tuuid;
auto targetInfo = PyObject_CallMethod(taskObject, "_cpp_getTargetUuidSingle", NULL);
PyArg_Parse(targetInfo, "s", &tuuid);
targetUuid.push_back(tuuid);
}
}
if (!isEnemyTask) {
task = new Task(uuid, targetUuid, repeatTime, intervalFrame, waitFrame);
}
else {
auto enemyInfo = PyObject_CallMethod(taskObject, "_cpp_getEnemyInfo", NULL);
ImageInfo enemyImageInfo = ImageParseHelper::parseImageHelperFromObject(taskObject);
float position[3], velocity, movingTime,acceleration, angle, angleAcceleration, maxHealth;
PyArg_ParseTuple(enemyInfo, "(fff)ffffff", &position[0], &position[1], &position[2], &velocity, &movingTime, &acceleration, &angle, &angleAcceleration, &maxHealth);
task = new TaskEnemy(uuid, targetUuid, repeatTime, intervalFrame, waitFrame,
enemyImageInfo.imagePath, glm::vec2(enemyImageInfo.divideColumn, enemyImageInfo.divideRow),
glm::vec3(enemyImageInfo.zoomX, enemyImageInfo.zoomY, 0.06f),
glm::vec2(enemyImageInfo.specialCol1Start, enemyImageInfo.specialCol1End), glm::vec2(enemyImageInfo.specialCol2Start, enemyImageInfo.specialCol2End),
glm::vec3(position[0], position[1], position[2]), velocity, movingTime, acceleration, angle, angleAcceleration, enemyImageInfo.selectY, maxHealth);
std::vector<DropItem>* itemVector = ItemHelper::getItemDropFromObject(taskObject);
if (itemVector != nullptr) {
TaskEnemy* t = static_cast<TaskEnemy*>(task);
t->setItemDrop(itemVector);
}
}
int unitSize;
PyArg_Parse(sizeInfo, "i", &unitSize);
for (int i = 0; i < unitSize;i++) {
PyObject *pUnit,*unitObj = PyObject_CallMethod(taskObject, "_cpp_getUnitItem", NULL);
PyArg_Parse(unitObj, "O", &pUnit);
TaskInsideUnit *unit = parseTaskUnitFromObject(uuid, pUnit);
if (unit!=nullptr) {
task->addSubUnit(unit);
}
}
}
return task;
}
| [
"lrsoft@hotmail.com"
] | lrsoft@hotmail.com |
d931c02246b296a6dc216bf41730b4ae85dccf80 | 6e2a80366c9f131711581dc58725e812a4221ede | /超级素数.cpp | 28168814da7029bfa92b374b360913f309741b0a | [] | no_license | lou-yimin/hello-world | afcbd86a76dfd29237109690a23b42898fe2668f | f5d36154049d150738b7275e32da1719216e0b05 | refs/heads/master | 2020-08-09T20:28:33.739503 | 2019-12-02T12:17:29 | 2019-12-02T12:17:29 | 214,167,965 | 0 | 0 | null | 2019-10-10T11:43:57 | 2019-10-10T11:43:57 | null | GB18030 | C++ | false | false | 994 | cpp | //超级素数:它本身,各位数字的和,各位数字的平方和,都是素数。
//求 100~10000 内的所有超级素数,及它们的平均数。
#include <stdio.h>
int main(){
int x[100000] ={},A,a,i,b,c,h,m,n,q,z,w[100000]={},f=0,y=0,d,p;
for(a=100;a<10000;a++){
m=0;n=0;q=0;b=0;c=0;
for(i=0;i<6;i++){
x[i]=0;
}
A=a;
x[0] = A % 10;
for(i=1;i<6;i++){
x[i] =(A /10) % 10;
A=A /10;
}
for(i=0;i<6;i++){
b=b+x[i];
c=c+(x[i]*x[i]);
}
int t=0;
for(h=2;h<a-1;h++){
if(a % h ==0){
t++;
}
}
if(t ==0){
m=a;
}
t=0;
for(h=2;h<b-1;h++){
if(b % h ==0){
t++;
}
}
if(t==0){
n=b;
}
t=0;
for(h=2;h<c-1;h++){
if(c % h ==0){
t++;
}
}
if(t==0){
q=c;
}
if(m!=0 &&n!=0 &&q!=0){
w[f]=a;
f++;
}
}
for(d=0;d<f;d++){
y=(y+w[d]);
}
p=y/(f);
printf("超级素数:\n");
for(d=0;d<f;d++){
printf("%d\n",w[d]);
}
printf("平均值:%d",p);
return 0;
}
| [
"noreply@github.com"
] | lou-yimin.noreply@github.com |
f59a6c5ae2d33fb10c30283a5b149d852d30e73e | 96f20e4d3f4c6b7c7f6efde18f575f0657641627 | /logger.cpp | 316c400b054e34f9f637ef59efd27a26b35fadd8 | [] | no_license | dungvuhoang/istro-rt | d330ae915ec51c280d8cfe46aa113184e0d5a101 | 379ecde6d1013eeb60fbc3fbf965942e5148f727 | refs/heads/master | 2023-06-09T14:42:36.908132 | 2021-06-16T11:13:47 | 2021-06-16T11:13:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,668 | cpp | #ifndef ISTRO_LOGGER_LOG4CX
// correctly include <pthread.h> with HAVE_STRUCT_TIMESPEC
#include "threads.h"
pthread_mutex_t logger_mtx;
void lmi(void)
{
pthread_mutex_init(&logger_mtx, NULL);
}
void lmd(void)
{
pthread_mutex_destroy(&logger_mtx);
}
#include <sys/time.h>
#include <iostream>
#include <iomanip>
#include <ctime>
/*
void lml(void)
{
time_t rawtime;
struct tm * timeinfo;
char buffer[80];
pthread_mutex_lock(&logger_mtx);
time (&rawtime);
timeinfo = localtime(&rawtime);
strftime(buffer,sizeof(buffer),"%Y-%m-%d %I:%M:%S,000 ",timeinfo);
std::cout << buffer;
}
*/
void lml(void)
{
timeval curTime;
gettimeofday(&curTime, NULL);
int milli = curTime.tv_usec / 1000;
char buffer [80];
strftime(buffer, 80, "%Y-%m-%d %H:%M:%S", localtime(&curTime.tv_sec));
pthread_mutex_lock(&logger_mtx);
std::cout << buffer << "," << std::setfill('0') << std::setw(3) << ((int)milli) << std::setw(0) << " ";
}
/*
// C++ 2011
#include <chrono>
#include <ctime>
#include <iostream>
void lml(void)
{
using namespace std;
using namespace std::chrono;
system_clock::time_point now = system_clock::now();
system_clock::duration tp = now.time_since_epoch();
tp -= duration_cast<seconds>(tp);
time_t tt = system_clock::to_time_t(now);
pthread_mutex_lock(&logger_mtx);
std::printf("%04u-%02u-%02u %02u:%02u:%02u.%03u ", t.tm_year + 1900,
t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec,
static_cast<unsigned>(tp / milliseconds(1)));
}
*/
void lmu(void)
{
pthread_mutex_unlock(&logger_mtx);
}
#endif
| [
"noreply@github.com"
] | dungvuhoang.noreply@github.com |
35873741f3e1aefbce4213adbc5847a5caee1ef7 | b5cd44f15df5e674f1d81422de44b1f8ea47efed | /depends/i686-w64-mingw32/include/QtDBus/5.6.1/QtDBus/private/qdbusabstractadaptor_p.h | 5ff33f8bef5b6554de77a8a31f215d01056f0733 | [
"MIT"
] | permissive | Xavander/xavandercoin | a0ac470868a2e254771a6af264010bf6baf915cb | dd659713dacb7b6f22900eaab5ebc3d610ca7571 | refs/heads/master | 2020-03-26T19:50:50.026553 | 2018-09-09T04:09:56 | 2018-09-09T04:09:56 | 145,289,806 | 2 | 6 | MIT | 2018-09-09T04:09:57 | 2018-08-19T09:30:57 | C++ | UTF-8 | C++ | false | false | 4,409 | h | /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the QtDBus module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
//
// W A R N I N G
// -------------
//
// This file is not part of the public API. This header file may
// change from version to version without notice, or even be
// removed.
//
// We mean it.
//
//
#ifndef QDBUSABSTRACTADAPTOR_P_H
#define QDBUSABSTRACTADAPTOR_P_H
#include <qdbusabstractadaptor.h>
#include <QtCore/qobject.h>
#include <QtCore/qmap.h>
#include <QtCore/qreadwritelock.h>
#include <QtCore/qvariant.h>
#include <QtCore/qvector.h>
#include "private/qobject_p.h"
#define QCLASSINFO_DBUS_INTERFACE "D-Bus Interface"
#define QCLASSINFO_DBUS_INTROSPECTION "D-Bus Introspection"
#ifndef QT_NO_DBUS
QT_BEGIN_NAMESPACE
class QDBusAbstractAdaptor;
class QDBusAdaptorConnector;
class QDBusAdaptorManager;
class QDBusConnectionPrivate;
class QDBusAbstractAdaptorPrivate: public QObjectPrivate
{
Q_DECLARE_PUBLIC(QDBusAbstractAdaptor)
public:
QDBusAbstractAdaptorPrivate() : autoRelaySignals(false) {}
QString xml;
bool autoRelaySignals;
static QString retrieveIntrospectionXml(QDBusAbstractAdaptor *adaptor);
static void saveIntrospectionXml(QDBusAbstractAdaptor *adaptor, const QString &xml);
};
class QDBusAdaptorConnector: public QObject
{
Q_OBJECT_FAKE
public: // typedefs
struct AdaptorData
{
const char *interface;
QDBusAbstractAdaptor *adaptor;
inline bool operator<(const AdaptorData &other) const
{ return QByteArray(interface) < other.interface; }
inline bool operator<(const QString &other) const
{ return QLatin1String(interface) < other; }
inline bool operator<(const QByteArray &other) const
{ return interface < other; }
#if defined(Q_CC_MSVC) && _MSC_VER < 1600
friend inline bool operator<(const QString &str, const AdaptorData &obj)
{ return str < QLatin1String(obj.interface); }
#endif
};
typedef QVector<AdaptorData> AdaptorMap;
public: // methods
explicit QDBusAdaptorConnector(QObject *parent);
~QDBusAdaptorConnector();
void addAdaptor(QDBusAbstractAdaptor *adaptor);
void connectAllSignals(QObject *object);
void disconnectAllSignals(QObject *object);
void relay(QObject *sender, int id, void **);
//public slots:
void relaySlot(void **);
void polish();
protected:
//signals:
void relaySignal(QObject *obj, const QMetaObject *metaObject, int sid, const QVariantList &args);
public: // member variables
AdaptorMap adaptors;
bool waitingForPolish : 1;
private:
static int relaySlotMethodIndex();
};
Q_DECLARE_TYPEINFO(QDBusAdaptorConnector::AdaptorData, Q_PRIMITIVE_TYPE);
extern QDBusAdaptorConnector *qDBusFindAdaptorConnector(QObject *object);
extern QDBusAdaptorConnector *qDBusCreateAdaptorConnector(QObject *object);
QT_END_NAMESPACE
#endif // QT_NO_DBUS
#endif // QDBUSABSTRACTADAPTOR_P_H
| [
"40328829+mark2994u@users.noreply.github.com"
] | 40328829+mark2994u@users.noreply.github.com |
fb67558254d70cf41a163355bde2c5a5792077bc | b061f46952c2e9cc2dfa8edb621f610b10cfd27b | /TestedTrek/src/StarTrek/Galaxy.cpp | 3fe92df1a1db6b61f9572a739a9486afe3ac648d | [
"MIT"
] | permissive | AgileInstitute/labs-cpp-gtest-xcode | 20780411d46347e7a762c30f242f99fe3bc623e0 | cce3091e7837319026c32b211adc9f5740f69b65 | refs/heads/master | 2020-04-20T21:01:04.725341 | 2014-12-10T21:55:04 | 2014-12-10T21:55:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 828 | cpp | #include "Galaxy.h"
#include <string>
#include "../Untouchables/WebGadget.h"
/**
* A simple Proxy/wrapper class for Untouchables.WebGadget,
* allowing us to create, modify, and subclass (or mock) Galaxy.
* Note that this object currently has no tests, because it does nothing but delegate,
* which is not likely to break, and the delegation is not unit-testable.
* Note also that it is production code.
*/
using namespace std;
namespace StarTrek {
Galaxy::Galaxy(Untouchables::WebGadget* webContext) : webContext_(webContext) {
}
string Galaxy::parameter(string parameterName) {
return webContext_->parameter(parameterName);
}
void* Galaxy::variable(string variableName) {
return webContext_->variable(variableName);
}
void Galaxy::writeLine(string message) {
webContext_->writeLine(message);
}
}
| [
"Rob.Myers@agileInstitute.com"
] | Rob.Myers@agileInstitute.com |
b104188e1ad4fc151551baa7897c7469ee62b97d | 7f352615626abb361e7e5a155977e080c179a475 | /CodeForces/e113/a.cpp | b4d2ef3750b66d76e3483b876ada987f88bfa978 | [] | no_license | checkcheck897/ps | a68718e98d2ec1273473f5cff47c5d74e17a8d1a | 48581b92d9e7d305ebac540f32a26cd1a0aca4eb | refs/heads/main | 2023-08-11T17:18:06.070756 | 2021-09-26T13:33:15 | 2021-09-26T13:33:15 | 335,930,429 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 887 | cpp | #include <bits/stdc++.h>
# pragma GCC optimize ("O3")
# pragma GCC target("sse,sse2,sse3,ssse3,sse4,avx,avx2")
#define x first
#define y second
#define pii pair<int, int>
#define ll long long
#define pll pair<ll, ll>
using namespace std;
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0);
int t;
cin >> t;
while(t--) {
ll n;
cin >> n;
string s;
cin >> s;
bool check = 0;
for (int i=0; i<n; i++) {
if (check) break;
int a=0, b=0;
for (int j=i; j<n; j++) {
if (check) break;
if (s[j]=='a') a++;
else b++;
if (a==b) {
cout << i+1 << " " << j+1 << "\n";
check = 1;
}
}
}
if (!check) cout << "-1 -1\n";
}
return 0;
} | [
"checkcheck@unist.ac.kr"
] | checkcheck@unist.ac.kr |
eae4e26cbe4d3c3f1c7dfa872803a1a244a3e6a7 | 1e9350000ec2e26c00ee9537aefe4f935786cea6 | /include/attachable.h | b06b960f0dc329069b58df64994fa2fcf71435b2 | [] | no_license | Kejmer/SpaceWorms | 8ba97f64c1caa70749f710eb6b07495257198bf6 | eaceaf20739a585ebfe11d6fe5bcd732982d6921 | refs/heads/master | 2022-11-02T07:47:56.148970 | 2020-06-16T16:53:26 | 2020-06-16T16:53:26 | 245,103,366 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 302 | h | #ifndef ATTACHABLE_H
#define ATTACHABLE_H
#include <SFML/Graphics.hpp>
// Forward declaration
class Entity;
class Attachable {
public:
Attachable(Entity *entity);
virtual ~Attachable() = default;
virtual void draw(sf::RenderWindow &window) = 0;
protected:
Entity *entity;
};
#endif | [
"r.czarnecki6@student.uw.edu.pl"
] | r.czarnecki6@student.uw.edu.pl |
ad9880ccfd8d3f26674b9170346907f4c2979b51 | f183897104c91b21f85f51ce785c50833efc7801 | /MarioGame/PlayScence.cpp | 159fc965082406b7b32a7193d604c0271c9e48fd | [] | no_license | 18521079/Mario | 81cc5864b05e0b2b7734b155411eeede590713d3 | 05a871de834f41dba3f81afc4426a3ac9e582a49 | refs/heads/master | 2023-02-24T07:39:19.349284 | 2021-01-25T21:10:08 | 2021-01-25T21:10:08 | 304,635,588 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,813 | cpp | #include <iostream>
#include <fstream>
#include"Background.h"
#include "PlayScence.h"
#include "Utils.h"
#include "Textures.h"
#include "Sprites.h"
#include "Portal.h"
#include "QuestionBlock.h"
#include "Goomba.h"
#include"Breakable_Brick.h"
#include"Box.h"
#include"EndScene.h"
#include "Flower.h"
#include "Koopas.h"
#include "BackGroundCollision.h"
#include "Ball.h"
#include"Coin.h"
#include"Fire_Ball.h"
#include"Item.h"
#include"KoopasBrick.h"
#include"WingGoomba.h"
#include"Pbell.h"
#include"HoldBrick.h"
#include"Card.h"
#include"Boomerang.h"
#include"MovingBrick.h"
#include"Fragment.h"
using namespace std;
CPlayScene::CPlayScene(int id, LPCWSTR filePath) :
CScene(id, filePath)
{
key_handler = new CPlayScenceKeyHandler(this);
}
/*
Load scene resources from scene file (textures, sprites, animations and objects)
See scene1.txt, scene2.txt for detail format specification
*/
#define SCENE_SECTION_UNKNOWN -1
#define SCENE_SECTION_TEXTURES 2
#define SCENE_SECTION_SPRITES 3
#define SCENE_SECTION_ANIMATIONS 4
#define SCENE_SECTION_ANIMATION_SETS 5
#define SCENE_SECTION_OBJECTS 6
#define OBJECT_TYPE_MARIO 0
#define OBJECT_TYPE_BACKGROUNDCOLLISION 1
#define OBJECT_TYPE_BACKGROUND 2
#define OBJECT_TYPE_QuestionBlock 3
#define OBJECT_TYPE_Goomba 4
#define OBJECT_TYPE_BREAKABLE_BRICK 5
#define OBJECT_TYPE_BOX 6
#define OBJECT_TYPE_KOOPAS_RED 7
#define OBJECT_TYPE_FLOWER 8
#define OBJECT_TYPE_BALL 9
#define OBJECT_TYPE_COIN 10
#define OBJECT_TYPE_FIREBALL 11
#define OBJECT_TYPE_ITEM 12
#define OBJECT_TYPE_KOOPASBRICK 13
#define OBJECT_TYPE_WINGGOOMBA 14
#define OBJECT_TYPE_PBELL 15
#define OBJECT_TYPE_KOOPAS_GREEN 16
#define OBJECT_TYPE_KOOPAS_WING 17
#define OBJECT_TYPE_HOLDBRICK 18
#define OBJECT_TYPE_CARD 20
#define OBJECT_TYPE_ENDSCENE0 21
#define OBJECT_TYPE_ENDSCENE1 22
#define OBJECT_TYPE_BOOMERANG 30
#define OBJECT_TYPE_FRAGMENT_LEFTTOP 31
#define OBJECT_TYPE_FRAGMENT_RIGHTTOP 32
#define OBJECT_TYPE_FRAGMENT_LEFTBOTTOM 33
#define OBJECT_TYPE_FRAGMENT_RIGHTBOTTOM 34
#define OBJECT_TYPE_MOVINGBRICK 26
#define OBJECT_TYPE_KOOPAS_GREENWING 27
#define SCENE_SECTION_MAP 7
#define OBJECT_TYPE_PORTAL 50
#define MAX_SCENE_LINE 1024
void CPlayScene::_ParseSection_TEXTURES(string line)
{
vector<string> tokens = split(line);
if (tokens.size() < 5) return; // skip invalid lines
int texID = atoi(tokens[0].c_str());
wstring path = ToWSTR(tokens[1]);
int R = atoi(tokens[2].c_str());
int G = atoi(tokens[3].c_str());
int B = atoi(tokens[4].c_str());
CTextures::GetInstance()->Add(texID, path.c_str(), D3DCOLOR_XRGB(R, G, B));
}
void CPlayScene::_ParseSection_SPRITES(string line)
{
vector<string> tokens = split(line);
if (tokens.size() < 6) return; // skip invalid lines
int ID = atoi(tokens[0].c_str());
int l = atoi(tokens[1].c_str());
int t = atoi(tokens[2].c_str());
int r = atoi(tokens[3].c_str());
int b = atoi(tokens[4].c_str());
int texID = atoi(tokens[5].c_str());
LPDIRECT3DTEXTURE9 tex = CTextures::GetInstance()->Get(texID);
if (tex == NULL)
{
DebugOut(L"[ERROR] Texture ID %d not found!\n", texID);
return;
}
CSprites::GetInstance()->Add(ID, l, t, r, b, tex);
}
void CPlayScene::_ParseSection_ANIMATIONS(string line)
{
vector<string> tokens = split(line);
if (tokens.size() < 3) return; // skip invalid lines - an animation must at least has 1 frame and 1 frame time
//DebugOut(L"--> %s\n",ToWSTR(line).c_str());
LPANIMATION ani = new CAnimation();
int ani_id = atoi(tokens[0].c_str());
for (int i = 1; i < tokens.size(); i += 2) // why i+=2 ? sprite_id | frame_time
{
int sprite_id = atoi(tokens[i].c_str());
int frame_time = atoi(tokens[i + 1].c_str());
ani->Add(sprite_id, frame_time);
}
CAnimations::GetInstance()->Add(ani_id, ani);
}
void CPlayScene::_ParseSection_ANIMATION_SETS(string line)
{
vector<string> tokens = split(line);
if (tokens.size() < 2) return; // skip invalid lines - an animation set must at least id and one animation id
int ani_set_id = atoi(tokens[0].c_str());
LPANIMATION_SET s = new CAnimationSet();
CAnimations* animations = CAnimations::GetInstance();
for (int i = 1; i < tokens.size(); i++)
{
int ani_id = atoi(tokens[i].c_str());
LPANIMATION ani = animations->Get(ani_id);
s->push_back(ani);
}
CAnimationSets::GetInstance()->Add(ani_set_id, s);
}
/*
Parse a line in section [OBJECTS]
*/
void CPlayScene::_ParseSection_OBJECTS(string line)
{
vector<string> tokens = split(line);
//DebugOut(L"--> %s\n",ToWSTR(line).c_str());
if (tokens.size() < 3) return; // skip invalid lines - an object set must have at least id, x, y
int object_type = atoi(tokens[0].c_str());
float x = atof(tokens[1].c_str());
float y = atof(tokens[2].c_str());
int ani_set_id = atoi(tokens[3].c_str());
CAnimationSets* animation_sets = CAnimationSets::GetInstance();
CGameObject* obj = NULL;
switch (object_type)
{
case OBJECT_TYPE_BACKGROUND: obj = new CBackground(); break;
case OBJECT_TYPE_FLOWER: obj = new CFlower(); break;
case OBJECT_TYPE_ITEM: obj = new CItem(); break;
case OBJECT_TYPE_KOOPAS_RED: obj = new CKoopas(1); break;
case OBJECT_TYPE_KOOPAS_GREEN: obj = new CKoopas(2); break;
case OBJECT_TYPE_KOOPAS_WING: obj = new CKoopas(3); break;
case OBJECT_TYPE_Goomba: obj = new CGoomba(); break;
case OBJECT_TYPE_BALL: obj = new CBall(); break;
case OBJECT_TYPE_COIN: obj = new CCoin(); break;
case OBJECT_TYPE_FIREBALL: obj = new CFireBall(); break;
case OBJECT_TYPE_KOOPASBRICK: obj = new CKoopasBrick(); break;
case OBJECT_TYPE_WINGGOOMBA: obj = new CWingGoomba(); break;
case OBJECT_TYPE_MOVINGBRICK: obj = new CMovingBrick(); break;
case OBJECT_TYPE_PBELL: obj = new CPbell(); break;
case OBJECT_TYPE_ENDSCENE0: obj = new CEndScene(0); break;
case OBJECT_TYPE_ENDSCENE1: obj = new CEndScene(1); break;
case OBJECT_TYPE_BOOMERANG: obj = new CBoomerang(); break;
case OBJECT_TYPE_CARD: obj = new CCard(); break;
case OBJECT_TYPE_FRAGMENT_LEFTTOP:
obj = new CPiece(OBJECT_TYPE_FRAGMENT_LEFTTOP);
break;
case OBJECT_TYPE_FRAGMENT_RIGHTTOP:
obj = new CPiece(OBJECT_TYPE_FRAGMENT_RIGHTTOP);
break;
case OBJECT_TYPE_FRAGMENT_LEFTBOTTOM:
obj = new CPiece(OBJECT_TYPE_FRAGMENT_LEFTBOTTOM);
break;
case OBJECT_TYPE_FRAGMENT_RIGHTBOTTOM:
obj = new CPiece(OBJECT_TYPE_FRAGMENT_RIGHTBOTTOM);
break;
case OBJECT_TYPE_MARIO:
if (player != NULL)
{
DebugOut(L"[ERROR] MARIO object was created before!\n");
return;
}
obj = new CMario(x, y);
player = (CMario*)obj;
DebugOut(L"[INFO] Player object created!\n");
break;
case OBJECT_TYPE_QuestionBlock: obj = new CQuestionBlock(); break;
case OBJECT_TYPE_BACKGROUNDCOLLISION: obj = new CBackGroundCollision(); break;
case OBJECT_TYPE_BOX: obj = new CBox(); break;
case OBJECT_TYPE_BREAKABLE_BRICK: obj = new CBreakableBrick(); break;
case OBJECT_TYPE_KOOPAS_GREENWING: obj = new CKoopas(5); break;
case OBJECT_TYPE_HOLDBRICK: obj = new CHoldBrick(); break;
case OBJECT_TYPE_PORTAL:
{
float r = atof(tokens[4].c_str());
float b = atof(tokens[5].c_str());
int scene_id = atoi(tokens[6].c_str());
obj = new CPortal(x, y, r, b, scene_id);
}
break;
default:
DebugOut(L"[ERR] Invalid object type: %d\n", object_type);
return;
}
LPANIMATION_SET ani_set = animation_sets->Get(ani_set_id);
if (obj != NULL)
{
{
obj->SetPosition(x, y);
obj->SetAnimationSet(ani_set);
obj->SetOrigin(x, y, obj->GetState());
obj->SetisOriginObj(true);
objects.push_back(obj);
}
}
}
void CPlayScene::Load()
{
CGame* game = CGame::GetInstance();
//CGame::GetInstance()->SetCamPos(0, 0);
float cx, cy;
HUD = CHUD::GetInstance();
DebugOut(L"[INFO] Start loading scene resources from : %s \n", sceneFilePath);
ifstream f;
f.open(sceneFilePath);
// current resource section flag
int section = SCENE_SECTION_UNKNOWN;
char str[MAX_SCENE_LINE];
while (f.getline(str, MAX_SCENE_LINE))
{
string line(str);
if (line[0] == '#') continue; // skip comment lines
if (line == "[TEXTURES]") { section = SCENE_SECTION_TEXTURES; continue; }
if (line == "[SPRITES]") {
section = SCENE_SECTION_SPRITES; continue;
}
if (line == "[ANIMATIONS]") {
section = SCENE_SECTION_ANIMATIONS; continue;
}
if (line == "[ANIMATION_SETS]") {
section = SCENE_SECTION_ANIMATION_SETS; continue;
}
if (line == "[OBJECTS]") {
section = SCENE_SECTION_OBJECTS; continue;
}
if (line == "[GRID]") {
section = SCENE_SECTION_GRID; continue;
}
if (line == "[MAP]") { section = SCENE_SECTION_MAP; continue; }
if (line[0] == '[') { section = SCENE_SECTION_UNKNOWN; continue; }
//
// data section
//
switch (section)
{
case SCENE_SECTION_TEXTURES: _ParseSection_TEXTURES(line); break;
case SCENE_SECTION_SPRITES: _ParseSection_SPRITES(line); break;
case SCENE_SECTION_ANIMATIONS: _ParseSection_ANIMATIONS(line); break;
case SCENE_SECTION_ANIMATION_SETS: _ParseSection_ANIMATION_SETS(line); break;
case SCENE_SECTION_OBJECTS: _ParseSection_OBJECTS(line); break;
case SCENE_SECTION_GRID: _ParseSection_GRID(line); break;
case SCENE_SECTION_MAP: _ParseSection_MAP(line); break;
}
}
f.close();
CTextures::GetInstance()->Add(ID_TEX_BBOX, L"textures\\bbox.png", D3DCOLOR_XRGB(255, 255, 255));
DebugOut(L"[INFO] Done loading scene resources %s\n", sceneFilePath);
}
void CPlayScene::Update(DWORD dt)
{
int id = CGame::GetInstance()->GetCurrentScene()->GetId();
float cx, cy;
if (id == 3)
{
CGame* game = CGame::GetInstance();
//CGame::GetInstance()->SetCamPos(0, 0);
player->GetPosition(cx, cy);
//
cx -= game->GetScreenWidth() / 2;
cy -= game->GetScreenHeight() / 2;
if (cx < 0) cx = 0;
if (cx > 3182 - game->GetScreenWidth()) cx = 3182 - game->GetScreenWidth();
CGame::GetInstance()->SetCamPos(round(cx),0.0f /*cy*/);
if (player->GetLevel() == MARIO_LEVEL_TAIL /*&& player->GetState()==MARIO_STATE_FLY*/)
{
if (cy > -40)
{
CGame::GetInstance()->SetCamPos(round(cx), -35.0f);
}
CGame::GetInstance()->SetCamPos(round(cx), round(cy));
}
cx = game->GetCamX();
cy = game->GetCamY();
}
else if (id == 4)
{
CGame* game = CGame::GetInstance();
if (player->resetcam == 1)
{
cx1 = 0;
player->resetcam == 0;
}
float cx2 = 0, cy2 = 0;
player->GetPosition(cx, cy);
if (cx1 < 2080 - game->GetScreenWidth())
{
cx1 += 0.03 * dt;
CGame::GetInstance()->SetCamPos(round(cx1), round(30));
if (cx1 >= cx) player->SetPosition(cx + 2, cy);
}
else
{
cx1 = 2080 - game->GetScreenWidth();
CGame::GetInstance()->SetCamPos(round(cx1), round(30));
}
if (player->GetTouchPipe() == 1)
{
if (player->x < 2240 + game->GetScreenWidth() / 2)
{
player->GetPosition(cx2, cy2);
cx2 -= game->GetScreenWidth() / 2;
cy2 -= game->GetScreenHeight() / 2;
CGame::GetInstance()->SetCamPos(round(cx2), 10.0f /*cy*/);
}
else
CGame::GetInstance()->SetCamPos(round(2240), 10.0f /*cy*/);
cx = game->GetCamX();
cy = game->GetCamY();
}
}
for (size_t i = 0; i < objects.size(); i++)
{
float Ox, Oy;
objects[i]->GetPosition(Ox, Oy);
if (!IsInUseArea(Ox, Oy) && !objects[i]->GetisOriginObj())
{
objects[i]->SetActive(false);
objects.erase(objects.begin() + i);
}
}
grid->GetObjects(objects, cx, cy);
/*for (size_t i = 1; i < objects.size(); i++)
{
coObjects.push_back(objects[i]);
}*/
for (size_t i = 0; i < objects.size(); i++)
{
objects[i]->Update(dt, &objects);
}
// skip the rest if scene was already unloaded (Mario::Update might trigger PlayScene::Unload)
if (player == NULL) return;
// Update camera to follow mario
HUD->Update(dt);
/*for (size_t i = 0; i < objects.size(); i++)
{
if (objects[i]->GetIsActive() == false)
{
coObjects.emplace_back(objects[i]);
objects[i]->SetIsActive(true);
}
}
if (grid != NULL)
{
grid->HandleGrid(&coObjects, game->GetCamX(), game->GetCamY(), game->GetScreenWidth(), game->GetScreenHeight());
}*/
}
void CPlayScene::Render()
{
if (map)
{
this->map->Render();
}
for (int i = 0; i < objects.size(); i++)
objects[i]->Render();
HUD->Render();
}
/*
Unload current scene
*/
void CPlayScene::Unload()
{
for (int i = 0; i < objects.size(); i++)
delete objects[i];
objects.clear();
player = NULL;
DebugOut(L"[INFO] Scene %s unloaded! \n", sceneFilePath);
}
void CPlayScene::_ParseSection_MAP(string line)
{
vector<string> tokens = split(line);
if (tokens.size() < 7) return; // skip invalid lines
int idTileSet = atoi(tokens[0].c_str());
int totalRowsTileSet = atoi(tokens[1].c_str());
int totalColumnsTileSet = atoi(tokens[2].c_str());
int totalRowsMap = atoi(tokens[3].c_str());
int totalColumnsMap = atoi(tokens[4].c_str());
int totalTiles = atoi(tokens[5].c_str());
wstring file_path = ToWSTR(tokens[6]);
map = new Map(idTileSet, totalRowsTileSet, totalColumnsTileSet, totalRowsMap, totalColumnsMap, totalTiles);
map->LoadMap(file_path.c_str());
map->ExtractTileFromTileSet();
}
bool CPlayScene::IsInUseArea(float Ox, float Oy)
{
float CamX, CamY;
CamX = CGame::GetInstance()->GetCamX();
CamY = CGame::GetInstance()->GetCamY();
if (((CamX < Ox) && (Ox < CamX + IN_USE_WIDTH)) && ((CamY < Oy) && (Oy < CamY + IN_USE_HEIGHT)))
return true;
return false;
}
void CPlayScenceKeyHandler::OnKeyDown(int KeyCode)
{
//DebugOut(L"[INFO] KeyDown: %d\n", KeyCode);
CMario* mario = ((CPlayScene*)scence)->GetPlayer();
float x, y;
mario->GetPosition(x, y);
switch (KeyCode)
{
case DIK_S:
if (mario->vx > 0.22f)
{
mario->SetCanFly(1);
mario->SetCheckFall(false);
mario->SetPreFly(0);
}
if (mario->GetLevel() == MARIO_LEVEL_TAIL && mario->GetCanFly() == 1)
{
mario->SetCheckFall(false);
if (mario->GetFirstTimeFly() == 0 && mario->GetCanFly() == 1)
{
mario->SetFirstTimeFly(1);
mario->SetFlyingStart();
}
if (mario->GetFirstTimeFly() == 1 && GetTickCount() - mario->GetFlyingStart() <= 5000)
{
mario->SetState(MARIO_STATE_FLY);
}
else
{
mario->SetState(MARIO_STATE_FALL);
mario->SetCanFly(0);
}
}
else if (mario->GetJumping() == 0)
{
mario->SetState(MARIO_STATE_JUMP);
//mario->ny = 1;
mario->SetJumping(1);
if (mario->GetDoubleJumpStart() == 0)
{
mario->SetDoubleJumpStart();
}
}
else if (mario->GetJumping() == 1 && mario->GetLevel() == MARIO_LEVEL_TAIL)
{
mario->SetCheckFall(true);
mario->SetState(MARIO_STATE_FALL);
}
break;
case DIK_O:
if (mario->GetJumping() == 0)
{
mario->SetState(MARIO_STATE_HIGHT_JUMP);
mario->ny = 1;
mario->SetJumping(1);
if (mario->GetDoubleJumpStart() == 0)
{
mario->SetDoubleJumpStart();
}
}
case DIK_Q:
mario->SetPosition(x, y - 16.0f);
mario->SetLevel(MARIO_LEVEL_BIG);
break;
case DIK_W:
mario->SetState(MARIO_STATE_KICK);
break;
case DIK_L:
mario->Reset();
break;
case DIK_E:
mario->SetLevel(MARIO_LEVEL_TAIL);
break;
case DIK_R:
mario->SetLevel(MARIO_LEVEL_FIRE);
break;
case DIK_U:
if (mario->GetLevel() == MARIO_LEVEL_FIRE)
mario->SetShoot(1);
break;
case DIK_D:
mario->SetHolding(1);
break;
case DIK_A:
mario->SetSpin(1);
mario->StartSpin();
break;
/*case DIK_D:
if (mario->GetFirstTimeFly() == 0)
{
if (mario->vx > MARIO_WALKING_SPEED)
{
mario->SetFirstTimeFly(1);
mario->SetFlyingStart();
}
}
if (mario->GetFirstTimeFly() == 1 && GetTickCount() - mario->GetFlyingStart() <= 5000)
{
mario->SetState(MARIO_STATE_FLY);
}
else
{
mario->SetState(MARIO_STATE_FALL);
}
break;*/
case DIK_B:
CGame::GetInstance()->SwitchScene(4);
break;
}
}
void CPlayScenceKeyHandler::OnKeyUp(int KeyCode)
{
//DebugOut(L"[INFO] KeyDown: %d\n", KeyCode);
CMario* mario = ((CPlayScene*)scence)->GetPlayer();
float x, y;
mario->GetPosition(x, y);
switch (KeyCode)
{
case DIK_D:
mario->SetHolding(0);
mario->SetAniHolding(0);
//mario->SetKickKoopas(1);
break;
/*case DIK_D:
mario->SetCanFly(0);
break;*/
case DIK_RIGHT:
mario->StartPreIdle();
break;
case DIK_LEFT:
mario->StartPreIdle();
break;
/*case DIK_S:
mario->StartUnPreIdle();
break;*/
case DIK_2:
CGame::GetInstance()->SwitchScene(2);
break;
case DIK_S:
mario->ResetDoubleJumpStart();
break;
}
}
void CPlayScene::_ParseSection_GRID(string line)
{
vector<string> tokens = split(line);
if (tokens.size() < 1) return;
wstring file_path = ToWSTR(tokens[0]);
if (grid == NULL)
grid = new CGrid(file_path.c_str());
}
void CPlayScenceKeyHandler::KeyState(BYTE* states)
{
CGame* game = CGame::GetInstance();
CMario* mario = ((CPlayScene*)scence)->GetPlayer();
float x, y;
mario->GetPosition(x, y);
// disable control key when Mario die
if (mario->GetState() == MARIO_STATE_DIE) return;
if (game->IsKeyDown(DIK_RIGHT))
if (game->IsKeyDown(DIK_A))
{
if (mario->vx < 0.22f)
{
mario->SetPreFly(0);
}
if (mario->vx > 0.22f)
{
mario->SetPreFly(1);
}
if (mario->Getspeedup_start() == 0)
mario->StartSpeedup();
mario->SetState(MARIO_STATE_FAST_WALKING_RIGHT);
if (GetTickCount() - mario->Getspeedup_start() > 30)
{
mario->SetspeedLevel(mario->GetspeedLevel() + 1);
mario->Setspeedup_start(0);
}
}
else
{
mario->SetPreFly(0);
mario->SetState(MARIO_STATE_WALKING_RIGHT);
}
else if (game->IsKeyDown(DIK_LEFT))
{
if (game->IsKeyDown(DIK_A))
{
if (mario->Getspeedup_start() == 0)
mario->StartSpeedup();
mario->SetState(MARIO_STATE_FAST_WALKING_LEFT);
if (GetTickCount() - mario->Getspeedup_start() > 30 && mario->GetspeedLevel() <= 100)
{
mario->SetspeedLevel(mario->GetspeedLevel() + 1);
mario->Setspeedup_start(0);
}
}
else
{
mario->SetspeedLevel(0);
if (mario->vx < 0.15f)
{
mario->SetPreFly(0);
}
mario->SetState(MARIO_STATE_WALKING_LEFT);
}
}
else if (game->IsKeyDown(DIK_UP))
{
if (mario->y > 170)
{
mario->SetPosition(2671.0f, 110.0f);
}
}
else if (game->IsKeyDown(DIK_Y))
{
mario->SetState(MARIO_STATE_FLY);
mario->ny = 1;
}
else if (game->IsKeyDown(DIK_DOWN))
{
if (mario->y <= 0)
{
mario->SetPosition(150.0f, 300.0f);
}
if (mario->x > 1968 && mario->x < 1984)
{
mario->SetTouchPipe(1);
mario->SetPosition(2250.0f, 132.0f);
}
else
{
mario->SetState(MARIO_STATE_SIT);
mario->SetPosition(x, y - 1.0f);
}
//mario->SetPosition(x, y - 1.0f);
}
else if (game->IsKeyDown(DIK_T))
{
mario->SetState(MARIO_STATE_FAST_WALKING);
}
else
{
if (mario->GetPreidle() != true)
mario->SetState(MARIO_STATE_IDLE);
}
/*if (game->IsKeyDown(DIK_S))
{
if (mario->isMaxJumping && mario->maxjumping == 0)
{
mario->StartJumpingMax();
mario->isMaxJumping = false;
}
}
else
{
mario->maxjumping = 0;
}
*/
} | [
"18521079@gm.uit.edu"
] | 18521079@gm.uit.edu |
7084c09386cee21f37bfb648ad0fb8d537a2af2d | 1230cfa4f5b90bd34ec2fa715c01dd6ef4ccedd1 | /C++/Untitled3m.cpp | 584c9fd3f5a1646caee32f8b40ca6cd52767593c | [] | no_license | ddhruvkr/Codes | 879068fe95b801c79d6575a1794e54dbdd2e6ff1 | cb3679dd2d69aa2f9a228cee6249edff00f9ef82 | refs/heads/master | 2021-05-04T11:54:45.638486 | 2017-07-23T12:41:09 | 2017-07-23T12:41:09 | 22,269,901 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 781 | cpp | # include <cstdio>
# include <map>
# include <vector>
using namespace std;
vector <long long> v;
vector <long long>::iterator it1;
long long happy(long long n)
{
long long s=0,d;
while(n!=0) {
d=n%10;
s=s+d*d;
n=n/10;
}
return s;
}
int help(long long n)
{
it1=v.begin();
int q=-1;
for(;it1!=v.end();it1++) {
if((*it1)==n){q=0;break;}
}
return q;
}
int main()
{
int q=-1,s;
long long n,a;
scanf("%lld",&n);
s=0;
v.clear();
v.push_back(n);
while(q!=0 && n!=1) {
a=happy(n);
s++;
n=a;
q=help(n);
if(q==-1)
v.push_back(n);
}
if(q==0)printf("-1\n");
else printf("%d\n",s);
//for(it=M.begin();it!=M.end();it++)printf("n= %lld a= %lld\n",(*it).first,(*it).second);
//for(it1=v.begin();it1!=v.end();it1++)printf("%lld ",(*it1));
return 0;
}
| [
"ddhruvkr@gmail.com"
] | ddhruvkr@gmail.com |
91dd6119b20765a621aab457fd92663f45b51da3 | 6fd072757f7f9ceeff1832513b7393bcef91d4dc | /framework/tarscpp/unittest/protocol/TarsTest/UnitTest/TarsPingTestImp.h | 30cdc2e07679c5fd694b016f611dd92192051aa1 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | hfcrwx/Tars-v2.4.20 | 2d6a5f84df434c293cef301d978d38f691d9227f | b0782b3fad556582470cddaa4416874126bd105c | refs/heads/master | 2023-07-16T06:02:01.278347 | 2021-08-28T16:08:40 | 2021-08-28T16:08:40 | 400,194,431 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,202 | h | /**
* Tencent is pleased to support the open source community by making Tars
* available.
*
* Copyright (C) 2016THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License"); you may not use this
* file except in compliance with the License. You may obtain a copy of the
* License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* 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.
*/
#ifndef _TarsPingTestImp_H_
#define _TarsPingTestImp_H_
#include "TarsPingTest.h"
#include "servant/Application.h"
/**
*
*
*/
class TarsPingTestImp : public TarsTest::TarsPingTest {
public:
/**
*
*/
virtual ~TarsPingTestImp() {}
/**
*
*/
virtual void initialize();
/**
*
*/
virtual void destroy();
virtual tars::Int32 test(tars::TarsCurrentPtr current);
/**
*
*/
};
/////////////////////////////////////////////////////
#endif
| [
"hfcrwx@163.com"
] | hfcrwx@163.com |
b1c1f90953e923925f04c11d9cda88e5044d13ac | efe782244cba07b683c4ac92df3fd029d538fe5f | /src/seeder/bitcoin.cpp | 707ce14245114c0b2a9079bbdfac4cccaa73147a | [
"MIT"
] | permissive | Kimax89/wallet-unofficial | 9fc248f40156e5f49f6cc14cb7e862149883909b | 70dfb876366eba4cb5d38d5274f7f1617ae742db | refs/heads/master | 2023-02-19T08:16:55.213287 | 2021-01-24T14:08:27 | 2021-01-24T14:08:27 | 332,015,826 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,253 | cpp | #include "bitcoin.h"
#include "db.h"
#include "netbase.h"
#include "serialize.h"
#include "streams.h"
#include "uint256.h"
#include <algorithm>
#define BITCOIN_SEED_NONCE 0x0539a019ca550825ULL
static const uint32_t allones(-1);
class CNode {
SOCKET sock;
CDataStream vSend;
CDataStream vRecv;
uint32_t nHeaderStart;
uint32_t nMessageStart;
int nVersion;
std::string strSubVer;
int nStartingHeight;
std::vector<CAddress> *vAddr;
int ban;
int64_t doneAfter;
CAddress you;
int GetTimeout() { return you.IsTor() ? 120 : 30; }
void BeginMessage(const char *pszCommand) {
if (nHeaderStart != allones) {
AbortMessage();
}
nHeaderStart = vSend.size();
vSend << CMessageHeader(pszCommand, 0);
nMessageStart = vSend.size();
// printf("%s: SEND %s\n", ToString(you).c_str(), pszCommand);
}
void AbortMessage() {
if (nHeaderStart == allones) {
return;
}
vSend.resize(nHeaderStart);
nHeaderStart = allones;
nMessageStart = allones;
}
void EndMessage() {
if (nHeaderStart == allones) {
return;
}
uint32_t nSize = vSend.size() - nMessageStart;
memcpy((char *)&vSend[nHeaderStart] +
offsetof(CMessageHeader, nMessageSize),
&nSize, sizeof(nSize));
if (vSend.GetVersion() >= 209) {
uint256 hash = Hash(vSend.begin() + nMessageStart, vSend.end());
unsigned int nChecksum = 0;
memcpy(&nChecksum, &hash, sizeof(nChecksum));
assert(nMessageStart - nHeaderStart >=
offsetof(CMessageHeader, nChecksum) + sizeof(nChecksum));
memcpy((char *)&vSend[nHeaderStart] +
offsetof(CMessageHeader, nChecksum),
&nChecksum, sizeof(nChecksum));
}
nHeaderStart = allones;
nMessageStart = allones;
}
void Send() {
if (sock == INVALID_SOCKET) {
return;
}
if (vSend.empty()) {
return;
}
int nBytes = send(sock, &vSend[0], vSend.size(), 0);
if (nBytes > 0) {
vSend.erase(vSend.begin(), vSend.begin() + nBytes);
} else {
close(sock);
sock = INVALID_SOCKET;
}
}
void PushVersion() {
int64_t nTime = time(nullptr);
uint64_t nLocalNonce = BITCOIN_SEED_NONCE;
int64_t nLocalServices = 0;
CAddress me(CService("0.0.0.0"));
BeginMessage("version");
int nBestHeight = GetRequireHeight();
std::string ver = "/bitcoin-clashic-seeder:0.18.0/";
vSend << PROTOCOL_VERSION << nLocalServices << nTime << you << me
<< nLocalNonce << ver << nBestHeight;
EndMessage();
}
void GotVersion() {
// printf("\n%s: version %i\n", ToString(you).c_str(), nVersion);
if (vAddr) {
BeginMessage("getaddr");
EndMessage();
doneAfter = time(nullptr) + GetTimeout();
} else {
doneAfter = time(nullptr) + 1;
}
}
bool ProcessMessage(std::string strCommand, CDataStream &vRecv) {
// printf("%s: RECV %s\n", ToString(you).c_str(),
// strCommand.c_str());
if (strCommand == "version") {
int64_t nTime;
CAddress addrMe;
CAddress addrFrom;
uint64_t nNonce = 1;
vRecv >> nVersion >> you.nServices >> nTime >> addrMe;
if (nVersion == 10300) nVersion = 300;
if (nVersion >= 106 && !vRecv.empty()) vRecv >> addrFrom >> nNonce;
if (nVersion >= 106 && !vRecv.empty()) vRecv >> strSubVer;
if (nVersion >= 209 && !vRecv.empty()) vRecv >> nStartingHeight;
if (nVersion >= 209) {
BeginMessage("verack");
EndMessage();
}
vSend.SetVersion(std::min(nVersion, PROTOCOL_VERSION));
if (nVersion < 209) {
this->vRecv.SetVersion(std::min(nVersion, PROTOCOL_VERSION));
GotVersion();
}
return false;
}
if (strCommand == "verack") {
this->vRecv.SetVersion(std::min(nVersion, PROTOCOL_VERSION));
GotVersion();
return false;
}
if (strCommand == "addr" && vAddr) {
std::vector<CAddress> vAddrNew;
vRecv >> vAddrNew;
// printf("%s: got %i addresses\n", ToString(you).c_str(),
// (int)vAddrNew.size());
int64_t now = time(nullptr);
std::vector<CAddress>::iterator it = vAddrNew.begin();
if (vAddrNew.size() > 1) {
if (doneAfter == 0 || doneAfter > now + 1) doneAfter = now + 1;
}
while (it != vAddrNew.end()) {
CAddress &addr = *it;
// printf("%s: got address %s\n", ToString(you).c_str(),
// addr.ToString().c_str(), (int)(vAddr->size()));
it++;
if (addr.nTime <= 100000000 || addr.nTime > now + 600)
addr.nTime = now - 5 * 86400;
if (addr.nTime > now - 604800) vAddr->push_back(addr);
// printf("%s: added address %s (#%i)\n",
// ToString(you).c_str(), addr.ToString().c_str(),
// (int)(vAddr->size()));
if (vAddr->size() > 1000) {
doneAfter = 1;
return true;
}
}
return false;
}
return false;
}
bool ProcessMessages() {
if (vRecv.empty()) {
return false;
}
do {
CDataStream::iterator pstart =
search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart),
END(pchMessageStart));
uint32_t nHeaderSize = GetSerializeSize(
CMessageHeader(), vRecv.GetType(), vRecv.GetVersion());
if (vRecv.end() - pstart < nHeaderSize) {
if (vRecv.size() > nHeaderSize) {
vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
}
break;
}
vRecv.erase(vRecv.begin(), pstart);
std::vector<char> vHeaderSave(vRecv.begin(),
vRecv.begin() + nHeaderSize);
CMessageHeader hdr;
vRecv >> hdr;
if (!hdr.IsValid()) {
// printf("%s: BAD (invalid header)\n", ToString(you).c_str());
ban = 100000;
return true;
}
std::string strCommand = hdr.GetCommand();
unsigned int nMessageSize = hdr.nMessageSize;
if (nMessageSize > MAX_SIZE) {
// printf("%s: BAD (message too large)\n",
// ToString(you).c_str());
ban = 100000;
return true;
}
if (nMessageSize > vRecv.size()) {
vRecv.insert(vRecv.begin(), vHeaderSave.begin(),
vHeaderSave.end());
break;
}
if (vRecv.GetVersion() >= 209) {
uint256 hash =
Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
unsigned int nChecksum = 0;
memcpy(&nChecksum, &hash, sizeof(nChecksum));
if (nChecksum != hdr.nChecksum) continue;
}
CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize,
vRecv.GetType(), vRecv.GetVersion());
vRecv.ignore(nMessageSize);
if (ProcessMessage(strCommand, vMsg)) return true;
// printf("%s: done processing %s\n", ToString(you).c_str(),
// strCommand.c_str());
} while (1);
return false;
}
public:
CNode(const CService &ip, std::vector<CAddress> *vAddrIn)
: vSend(SER_NETWORK, 0), vRecv(SER_NETWORK, 0), nHeaderStart(-1),
nMessageStart(-1), nVersion(0), vAddr(vAddrIn), ban(0), doneAfter(0),
you(ip) {
if (time(nullptr) > 1329696000) {
vSend.SetVersion(209);
vRecv.SetVersion(209);
}
}
bool Run() {
bool res = true;
if (!ConnectSocket(you, sock)) return false;
PushVersion();
Send();
int64_t now;
while (now = time(nullptr), ban == 0 &&
(doneAfter == 0 || doneAfter > now) &&
sock != INVALID_SOCKET) {
char pchBuf[0x10000];
fd_set set;
FD_ZERO(&set);
FD_SET(sock, &set);
struct timeval wa;
if (doneAfter) {
wa.tv_sec = doneAfter - now;
wa.tv_usec = 0;
} else {
wa.tv_sec = GetTimeout();
wa.tv_usec = 0;
}
int ret = select(sock + 1, &set, nullptr, &set, &wa);
if (ret != 1) {
if (!doneAfter) res = false;
break;
}
int nBytes = recv(sock, pchBuf, sizeof(pchBuf), 0);
int nPos = vRecv.size();
if (nBytes > 0) {
vRecv.resize(nPos + nBytes);
memcpy(&vRecv[nPos], pchBuf, nBytes);
} else if (nBytes == 0) {
// printf("%s: BAD (connection closed prematurely)\n",
// ToString(you).c_str());
res = false;
break;
} else {
// printf("%s: BAD (connection error)\n",
// ToString(you).c_str());
res = false;
break;
}
ProcessMessages();
Send();
}
if (sock == INVALID_SOCKET) res = false;
close(sock);
sock = INVALID_SOCKET;
return (ban == 0) && res;
}
int GetBan() { return ban; }
int GetClientVersion() { return nVersion; }
std::string GetClientSubVersion() { return strSubVer; }
int GetStartingHeight() { return nStartingHeight; }
};
bool TestNode(const CService &cip, int &ban, int &clientV,
std::string &clientSV, int &blocks,
std::vector<CAddress> *vAddr) {
try {
CNode node(cip, vAddr);
bool ret = node.Run();
if (!ret) {
ban = node.GetBan();
} else {
ban = 0;
}
clientV = node.GetClientVersion();
clientSV = node.GetClientSubVersion();
blocks = node.GetStartingHeight();
// printf("%s: %s!!!\n", cip.ToString().c_str(), ret ? "GOOD" : "BAD");
return ret;
} catch (std::ios_base::failure &e) {
ban = 0;
return false;
}
}
/*
int main(void) {
CService ip("bitcoin.sipa.be", 8333, true);
std::vector<CAddress> vAddr;
vAddr.clear();
int ban = 0;
bool ret = TestNode(ip, ban, vAddr);
printf("ret=%s ban=%i vAddr.size()=%i\n", ret ? "good" : "bad", ban,
(int)vAddr.size());
}
*/
| [
"klauskirkeby@hotmail.com"
] | klauskirkeby@hotmail.com |
ae0b0dffc20b8cfb81436357caa30038f94e02fd | 79e670c2cecff837dcf42570ded9bd96bc860195 | /src/graph/optimizer/rule/GetEdgesTransformRule.cpp | e1182ef194fbd18c4a7859b171b224cef2ab9fa2 | [
"Apache-2.0"
] | permissive | darionyaphet/nebula | 265e77c5e585c43e8d06de1f50de1879f90c438f | 32207a38784dfb491b7f13089619fcf911e62fe3 | refs/heads/master | 2022-05-26T05:47:32.225596 | 2022-05-11T02:49:56 | 2022-05-11T02:49:56 | 397,208,688 | 0 | 0 | Apache-2.0 | 2021-08-17T10:24:43 | 2021-08-17T10:24:42 | null | UTF-8 | C++ | false | false | 5,496 | cpp | /* Copyright (c) 2021 vesoft inc. All rights reserved.
*
* This source code is licensed under Apache 2.0 License.
*/
#include "graph/optimizer/rule/GetEdgesTransformRule.h"
#include "common/expression/Expression.h"
#include "graph/optimizer/OptContext.h"
#include "graph/optimizer/OptGroup.h"
#include "graph/planner/plan/PlanNode.h"
#include "graph/planner/plan/Query.h"
#include "graph/visitor/ExtractFilterExprVisitor.h"
using nebula::Expression;
using nebula::graph::AppendVertices;
using nebula::graph::PlanNode;
using nebula::graph::Project;
using nebula::graph::QueryContext;
using nebula::graph::ScanEdges;
using nebula::graph::ScanVertices;
using nebula::graph::Traverse;
namespace nebula {
namespace opt {
std::unique_ptr<OptRule> GetEdgesTransformRule::kInstance =
std::unique_ptr<GetEdgesTransformRule>(new GetEdgesTransformRule());
GetEdgesTransformRule::GetEdgesTransformRule() {
RuleSet::QueryRules().addRule(this);
}
const Pattern &GetEdgesTransformRule::pattern() const {
static Pattern pattern =
Pattern::create(PlanNode::Kind::kAppendVertices,
{Pattern::create(PlanNode::Kind::kTraverse,
{Pattern::create(PlanNode::Kind::kScanVertices)})});
return pattern;
}
bool GetEdgesTransformRule::match(OptContext *ctx, const MatchedResult &matched) const {
if (!OptRule::match(ctx, matched)) {
return false;
}
auto traverse = static_cast<const Traverse *>(matched.planNode({0, 0}));
const auto &colNames = traverse->colNames();
auto colSize = colNames.size();
DCHECK_GE(colSize, 2);
// TODO: Poor readability for optimizer, is there any other way to do the same thing?
if (colNames[colSize - 2][0] != '_') { // src
return false;
}
if (traverse->stepRange() != nullptr) {
return false;
}
return true;
}
StatusOr<OptRule::TransformResult> GetEdgesTransformRule::transform(
OptContext *ctx, const MatchedResult &matched) const {
auto appendVerticesGroupNode = matched.node;
auto appendVertices = static_cast<const AppendVertices *>(appendVerticesGroupNode->node());
auto traverseGroupNode = matched.dependencies.front().node;
auto traverse = static_cast<const Traverse *>(traverseGroupNode->node());
auto scanVerticesGroupNode = matched.dependencies.front().dependencies.front().node;
auto qctx = ctx->qctx();
auto newAppendVertices = appendVertices->clone();
auto colSize = appendVertices->colNames().size();
newAppendVertices->setOutputVar(appendVertices->outputVar());
newAppendVertices->setColNames(
{appendVertices->colNames()[colSize - 2], appendVertices->colNames()[colSize - 1]});
auto newAppendVerticesGroupNode =
OptGroupNode::create(ctx, newAppendVertices, appendVerticesGroupNode->group());
auto *newScanEdges = traverseToScanEdges(traverse);
if (newScanEdges == nullptr) {
return TransformResult::noTransform();
}
auto newScanEdgesGroup = OptGroup::create(ctx);
auto newScanEdgesGroupNode = newScanEdgesGroup->makeGroupNode(newScanEdges);
auto *newProj = projectEdges(qctx, newScanEdges, traverse->colNames().back());
newProj->setInputVar(newScanEdges->outputVar());
newProj->setOutputVar(traverse->outputVar());
newProj->setColNames({traverse->colNames().back()});
auto newProjGroup = OptGroup::create(ctx);
auto newProjGroupNode = newProjGroup->makeGroupNode(newProj);
newAppendVerticesGroupNode->dependsOn(newProjGroup);
newProjGroupNode->dependsOn(newScanEdgesGroup);
for (auto dep : scanVerticesGroupNode->dependencies()) {
newScanEdgesGroupNode->dependsOn(dep);
}
TransformResult result;
result.eraseCurr = true;
result.newGroupNodes.emplace_back(newAppendVerticesGroupNode);
return result;
}
std::string GetEdgesTransformRule::toString() const {
return "GetEdgesTransformRule";
}
/*static*/ graph::ScanEdges *GetEdgesTransformRule::traverseToScanEdges(
const graph::Traverse *traverse) {
const auto *edgeProps = traverse->edgeProps();
if (edgeProps == nullptr) {
return nullptr;
}
for (std::size_t i = 0; i < edgeProps->size(); i++) {
auto type = (*edgeProps)[i].get_type();
for (std::size_t j = i + 1; j < edgeProps->size(); j++) {
if (type == -((*edgeProps)[j].get_type())) {
// Don't support to retrieve edges of the inbound/outbound together
return nullptr;
}
}
}
auto scanEdges = ScanEdges::make(
traverse->qctx(),
nullptr,
traverse->space(),
edgeProps == nullptr ? nullptr
: std::make_unique<std::vector<storage::cpp2::EdgeProp>>(*edgeProps),
nullptr,
traverse->dedup(),
traverse->limit(),
{},
traverse->filter() == nullptr ? nullptr : traverse->filter()->clone());
return scanEdges;
}
/*static*/ graph::Project *GetEdgesTransformRule::projectEdges(graph::QueryContext *qctx,
PlanNode *input,
const std::string &colName) {
auto *yieldColumns = qctx->objPool()->makeAndAdd<YieldColumns>();
auto *edgeExpr = EdgeExpression::make(qctx->objPool());
auto *listEdgeExpr = ListExpression::make(qctx->objPool());
listEdgeExpr->setItems({edgeExpr});
yieldColumns->addColumn(new YieldColumn(listEdgeExpr, colName));
auto project = Project::make(qctx, input, yieldColumns);
project->setColNames({colName});
return project;
}
} // namespace opt
} // namespace nebula
| [
"noreply@github.com"
] | darionyaphet.noreply@github.com |
5253186c22ccbfc8e73b3874ec5194ca63e764ce | e96669666c4f5b1f098bc52f71a4bc58b8d7d4bc | /FarmSim/LensFlare.cpp | fe6d55f90095ce43838052b37a52c621289b1637 | [] | no_license | adasm/xgine | e924073e0d7fbc61c2e0bfea6118613c1db2e7bc | 1cbcf13cc4af67d8c3b2894cbd300859febc2080 | refs/heads/master | 2020-05-20T17:01:41.293287 | 2015-04-18T11:31:39 | 2015-04-18T11:31:39 | 34,119,980 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,181 | cpp | #include "LensFlare.h"
LensFlare::LensFlare(string fname)
{
m_flares = new Flare[11];
string texture0 = "";
string texture1 = "";
string texture2 = "";
string texture3 = "";
string texture4 = "";
string texture5 = "";
string texture6 = "";
string texture7 = "";
string texture8 = "";
string texture9 = "";
string texture10 = "";
float dist0;
float dist1;
float dist2;
float dist3;
float dist4;
float dist5;
float dist6;
float dist7;
float dist8;
float dist9;
float dist10;
vector<CfgVariable*> vars;
vars.push_back(new CfgVariable(V_STRING, &texture0, getVarName(texture0)));
vars.push_back(new CfgVariable(V_STRING, &texture1, getVarName(texture1)));
vars.push_back(new CfgVariable(V_STRING, &texture2, getVarName(texture2)));
vars.push_back(new CfgVariable(V_STRING, &texture3, getVarName(texture3)));
vars.push_back(new CfgVariable(V_STRING, &texture4, getVarName(texture4)));
vars.push_back(new CfgVariable(V_STRING, &texture5, getVarName(texture5)));
vars.push_back(new CfgVariable(V_STRING, &texture6, getVarName(texture6)));
vars.push_back(new CfgVariable(V_STRING, &texture7, getVarName(texture7)));
vars.push_back(new CfgVariable(V_STRING, &texture8, getVarName(texture8)));
vars.push_back(new CfgVariable(V_STRING, &texture9, getVarName(texture9)));
vars.push_back(new CfgVariable(V_STRING, &texture10, getVarName(texture10)));
vars.push_back(new CfgVariable(V_FLOAT, &dist0, getVarName(dist0)));
vars.push_back(new CfgVariable(V_FLOAT, &dist1, getVarName(dist1)));
vars.push_back(new CfgVariable(V_FLOAT, &dist2, getVarName(dist2)));
vars.push_back(new CfgVariable(V_FLOAT, &dist3, getVarName(dist3)));
vars.push_back(new CfgVariable(V_FLOAT, &dist4, getVarName(dist4)));
vars.push_back(new CfgVariable(V_FLOAT, &dist5, getVarName(dist5)));
vars.push_back(new CfgVariable(V_FLOAT, &dist6, getVarName(dist6)));
vars.push_back(new CfgVariable(V_FLOAT, &dist7, getVarName(dist7)));
vars.push_back(new CfgVariable(V_FLOAT, &dist8, getVarName(dist8)));
vars.push_back(new CfgVariable(V_FLOAT, &dist9, getVarName(dist9)));
vars.push_back(new CfgVariable(V_FLOAT, &dist10, getVarName(dist10)));
CfgLoader(fname, &vars);
if(texture0 != "")
{
m_flares[0].texture = gEngine.resMgr->load<Texture>(texture0);
m_flares[0].distance = dist0;
}
if(texture1 != "")
{
m_flares[1].texture = gEngine.resMgr->load<Texture>(texture1);
m_flares[1].distance = dist1;
}
if(texture2 != "")
{
m_flares[2].texture = gEngine.resMgr->load<Texture>(texture2);
m_flares[2].distance = dist2;
}
if(texture3 != "")
{
m_flares[3].texture = gEngine.resMgr->load<Texture>(texture3);
m_flares[3].distance = dist3;
}
if(texture4 != "")
{
m_flares[4].texture = gEngine.resMgr->load<Texture>(texture4);
m_flares[4].distance = dist4;
}
if(texture5 != "")
{
m_flares[5].texture = gEngine.resMgr->load<Texture>(texture5);
m_flares[5].distance = dist5;
}
if(texture6 != "")
{
m_flares[6].texture = gEngine.resMgr->load<Texture>(texture6);
m_flares[6].distance = dist6;
}
if(texture7 != "")
{
m_flares[7].texture = gEngine.resMgr->load<Texture>(texture7);
m_flares[7].distance = dist7;
}
if(texture8 != "")
{
m_flares[8].texture = gEngine.resMgr->load<Texture>(texture8);
m_flares[8].distance = dist8;
}
if(texture9 != "")
{
m_flares[9].texture = gEngine.resMgr->load<Texture>(texture9);
m_flares[9].distance = dist9;
}
if(texture10 != "")
{
m_flares[10].texture = gEngine.resMgr->load<Texture>(texture10);
m_flares[10].distance = dist10;
}
}
void LensFlare::render(ICamera *cam, Vec3 sunPos)
{
Vec3 sunPosScreen;
Vec2 vecSunToCenter;
Mat world;
Vec2 screenCenter;
D3DVIEWPORT9 viewport;
gEngine.device->getDev()->GetViewport(&viewport);
D3DXMatrixTranslation(&world, 0, 0, 0);
D3DXVec3Project(&sunPosScreen, &sunPos, &viewport, cam->getProjectionMat(), cam->getViewMat(), &world);
//gEngine.renderer->addTxt("%.3f %.3f %.3f", sunPosScreen.x, sunPosScreen.y, sunPosScreen.z);
screenCenter.x = viewport.Width/2;
screenCenter.y = viewport.Height/2;
vecSunToCenter = screenCenter - Vec2(sunPosScreen);
Vec3 sunToCam = sunPos - *cam->getPosition();
D3DXVec3Normalize(&sunToCam, &sunToCam);
if(acos(D3DXVec3Dot(&sunToCam, cam->getViewDirection())) < cam->getFOV())
for(int i = 0; i < 11; i++)
{
if(m_flares[i].texture)
{
//Vec2 flarePos = vecSunToCenter * m_flares[i].distance + Vec2(sunPosScreen.x, sunPosScreen.y);
Vec2 flarePos = vecSunToCenter * m_flares[i].distance + Vec2(sunPosScreen.x, sunPosScreen.y);
gEngine.renderer->r2d->drawQuad(m_flares[i].texture, flarePos.x - m_flares[i].texture->width/2,
flarePos.y - m_flares[i].texture->height/2,
flarePos.x + m_flares[i].texture->width/2,
flarePos.y + m_flares[i].texture->height/2,
D3DCOLOR_ARGB(255, 255, 255, 255),
D3DCOLOR_ARGB(255, 255, 255, 255),
D3DCOLOR_ARGB(255, 255, 255, 255),
D3DCOLOR_ARGB(255, 255, 255, 255));
}
}
} | [
"adasm@live.com"
] | adasm@live.com |
12c687bf13bece0fb1b371427d510d79ccd96929 | bbd445f1d1d4c6e905d618c895e840bb66e78e02 | /BgColoredLabel.cpp | 5af0bfa2abe693623d43310996e46bb69c7688e0 | [] | no_license | BelousovYaroslav/slg.m3a.pc.viewer | 976f1d0c6d6a74f8e48e964eb4dd052a3c5ffa7e | 09d0fddcab93b6fc135dcb2d9274624c461bd5b4 | refs/heads/master | 2021-01-22T18:37:48.482353 | 2018-03-05T08:53:19 | 2018-03-05T08:53:19 | 85,097,499 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 925 | cpp | // BgColoredLabel.cpp : implementation file
//
#include "stdafx.h"
#include "slg2.h"
#include "BgColoredLabel.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CBgColoredLabel
CBgColoredLabel::CBgColoredLabel()
{
m_clr = RGB( 0, 0, 0);
}
CBgColoredLabel::~CBgColoredLabel()
{
}
BEGIN_MESSAGE_MAP(CBgColoredLabel, CStatic)
//{{AFX_MSG_MAP(CBgColoredLabel)
ON_WM_PAINT()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CBgColoredLabel message handlers
void CBgColoredLabel::OnPaint()
{
CPaintDC dc(this); // device context for painting
CRect rc;
GetClientRect( &rc);
CBrush cBrush;
cBrush.CreateSolidBrush( m_clr);
dc.FillRect( &rc, &cBrush);
// Do not call CStatic::OnPaint() for painting messages
}
| [
"belousov.yaroslav@gmail.com"
] | belousov.yaroslav@gmail.com |
4c327bed238056346eb1288f58bd30d1a0490be2 | 6b40e9dccf2edc767c44df3acd9b626fcd586b4d | /NT/admin/wmi/wbem/providers/win32provider/providers/groupuser.cpp | 0452a7b4094005109b3d8f117d20c6c826e92b8f | [] | no_license | jjzhang166/WinNT5_src_20201004 | 712894fcf94fb82c49e5cd09d719da00740e0436 | b2db264153b80fbb91ef5fc9f57b387e223dbfc2 | refs/heads/Win2K3 | 2023-08-12T01:31:59.670176 | 2021-10-14T15:14:37 | 2021-10-14T15:14:37 | 586,134,273 | 1 | 0 | null | 2023-01-07T03:47:45 | 2023-01-07T03:47:44 | null | UTF-8 | C++ | false | false | 27,796 | cpp | //=================================================================
//
// groupuser.h -- UserGroup to User Group Members association provider
//
// Copyright (c) 1998-2001 Microsoft Corporation, All Rights Reserved
//
// Revisions: 1/26/98 davwoh Created
//
// Comments: Shows the members in each usergroup
//
//=================================================================
// In trying to do the UserGroups->Group Members association, I have made the following assumptions
//
// a) Global groups cannot have groups as members.
// b) Global groups cannot have any well-known accounts as members.
// c) Local groups can have Global groups as members.
// d) Local groups cannot have any well-known accounts as members.
//
// This is based on my experimentation with RegEdt32 and UsrMgr. When these are discovered not to be
// true, we will probably need to make some changes here.
#include "precomp.h"
#include <frqueryex.h>
#include <assertbreak.h>
#include <comdef.h>
#include "wbemnetapi32.h"
#include "sid.h"
#include "user.h"
#include "group.h"
#include "systemaccount.h"
#include "GroupUser.h"
// Property set declaration
//=========================
CWin32GroupUser MyLoadDepends(PROPSET_NAME_GROUPUSER, IDS_CimWin32Namespace);
/*****************************************************************************
*
* FUNCTION : CWin32GroupUser::CWin32GroupUser
*
* DESCRIPTION : Constructor
*
* INPUTS : none
*
* OUTPUTS : none
*
* RETURNS : nothing
*
* COMMENTS : Registers property set with framework
*
*****************************************************************************/
CWin32GroupUser::CWin32GroupUser(LPCWSTR setName, LPCWSTR pszNamespace)
:Provider(setName, pszNamespace)
{
CHString sTemp;
// Just saves us from having to constantly re-calculate these when sending
// instances back.
sTemp = PROPSET_NAME_USER;
sTemp += L".Domain=\"";
m_sUserBase = MakeLocalPath(sTemp);
sTemp = PROPSET_NAME_GROUP;
sTemp += L".Domain=\"";
m_sGroupBase = MakeLocalPath(sTemp);
sTemp = PROPSET_NAME_SYSTEMACCOUNT;
sTemp += L".Domain=\"";
m_sSystemBase = MakeLocalPath(sTemp);
}
/*****************************************************************************
*
* FUNCTION : CWin32GroupUser::~CWin32GroupUser
*
* DESCRIPTION : Destructor
*
* INPUTS : none
*
* OUTPUTS : none
*
* RETURNS : nothing
*
* COMMENTS : Deregisters property set from framework
*
*****************************************************************************/
CWin32GroupUser::~CWin32GroupUser()
{
}
/*****************************************************************************
*
* FUNCTION : CWin32GroupUser::GetObject
*
* DESCRIPTION : Assigns values to property set according to key value
* already set by framework
*
* INPUTS : none
*
* OUTPUTS : none
*
* RETURNS : HRESULT
*
* COMMENTS :
*
*****************************************************************************/
HRESULT CWin32GroupUser::GetObject(CInstance *pInstance, long lFlags /*= 0L*/)
{
// No groups on 95
#ifdef NTONLY
CHString sMemberPath, sGroupPath;
HRESULT hRet = WBEM_E_NOT_FOUND;
CInstancePtr pGroup;
CInstancePtr pMember;
// Initialize the net stuff
CNetAPI32 netapi ;
if( netapi.Init() != ERROR_SUCCESS ) {
return WBEM_E_FAILED;
}
// Get the two paths
pInstance->GetCHString(IDS_GroupComponent, sGroupPath);
pInstance->GetCHString(IDS_PartComponent, sMemberPath);
// As we will be comparing these object paths
// with those returned from GetDependentsFromGroup,
// which always contains __PATH style object paths,
// and since the user might have specified a __RELPATH,
// we need to convert to __PATH here for consistency.
CHString chstrGroup__PATH;
CHString chstrMember__PATH;
int n = -1;
// Handle various GroupComponent path specifications...
if(sGroupPath.Find(L"\\\\") == -1)
{
chstrGroup__PATH = MakeLocalPath(sGroupPath);
}
else if(sGroupPath.Find(L"\\\\.") != -1)
{
n = sGroupPath.Find(L":");
if(n == -1)
{
hRet = WBEM_E_INVALID_OBJECT_PATH;
}
else
{
chstrGroup__PATH = MakeLocalPath(sGroupPath.Mid(n+1));
}
}
else
{
chstrGroup__PATH = sGroupPath;
}
// Handle various PartComponent path specifications...
if(hRet != WBEM_E_INVALID_OBJECT_PATH)
{
if(sMemberPath.Find(L"\\\\") == -1)
{
chstrMember__PATH = MakeLocalPath(sMemberPath);
}
else if(sMemberPath.Find(L"\\\\.") != -1)
{
n = sMemberPath.Find(L":");
if(n == -1)
{
hRet = WBEM_E_INVALID_OBJECT_PATH;
}
else
{
chstrMember__PATH = MakeLocalPath(sMemberPath.Mid(n+1));
}
}
else
{
chstrMember__PATH = sMemberPath;
}
}
// If both ends are there
if(SUCCEEDED(CWbemProviderGlue::GetInstanceByPath( (LPCTSTR)chstrMember__PATH, &pMember, pInstance->GetMethodContext() ) ) )
{
if(SUCCEEDED(CWbemProviderGlue::GetInstanceByPath( (LPCTSTR)chstrGroup__PATH, &pGroup, pInstance->GetMethodContext() ) ) )
{
// Now we need to check to see if this member (user or group) is in the usergroup
CHString sGroupName, sDomainName;
CHStringArray asMembersGot;
DWORD dwSize;
BYTE btType;
// Retrieve the values we are looking for
pGroup->GetCHString(IDS_Domain, sDomainName);
pGroup->GetCHString(IDS_Name, sGroupName);
pGroup->GetByte(IDS_SIDType, btType);
// Get the dependent list for this service
GetDependentsFromGroup(netapi, sDomainName, sGroupName, btType, asMembersGot);
// Walk the list to see if we're there
dwSize = asMembersGot.GetSize();
for (int x=0; x < dwSize; x++)
{
if (asMembersGot.GetAt(x).CompareNoCase(chstrMember__PATH) == 0)
{
hRet = WBEM_S_NO_ERROR;
break;
}
}
}
}
return hRet;
#endif
}
/*****************************************************************************
*
* FUNCTION : CWin32GroupUser::EnumerateInstances
*
* DESCRIPTION : Creates instance of property set for cd rom
*
* INPUTS : none
*
* OUTPUTS : none
*
* RETURNS : HRESULT
*
* COMMENTS :
*
*****************************************************************************/
HRESULT CWin32GroupUser::EnumerateInstances(MethodContext *pMethodContext, long lFlags /*= 0L*/)
{
#ifdef NTONLY
HRESULT hr;
CNetAPI32 netapi ;
if( netapi.Init() != ERROR_SUCCESS ) {
return WBEM_E_FAILED;
}
// hr = CWbemProviderGlue::GetAllInstancesAsynch(PROPSET_NAME_GROUP, this, StaticEnumerationCallback, IDS_CimWin32Namespace, pMethodContext, &netapi);
hr = CWbemProviderGlue::GetInstancesByQueryAsynch(_T("Select Domain, Name, SidType from Win32_Group"),
this, StaticEnumerationCallback, IDS_CimWin32Namespace,
pMethodContext, &netapi);
return hr;
#endif
}
/*****************************************************************************
*
* FUNCTION : CWin32GroupUser::ExecQuery
*
* DESCRIPTION : Creates instance of property set for cd rom
*
* INPUTS : none
*
* OUTPUTS : none
*
* RETURNS : HRESULT
*
* COMMENTS :
*
*****************************************************************************/
#ifdef NTONLY
HRESULT CWin32GroupUser::ExecQuery(
MethodContext *pMethodContext,
CFrameworkQuery& pQuery,
long lFlags /*= 0L*/ )
{
HRESULT hr = WBEM_S_NO_ERROR;
std::vector<_bstr_t> vecGroupComponents;
std::vector<_bstr_t> vecPartComponents;
DWORD dwNumGroupComponents;
DWORD dwNumPartComponents;
CHString chstrGroup__RELPATH;
CHString chstrGroupDomain;
CHString chstrGroupName;
CHStringArray rgchstrGroupMembers;
// Initialize the net stuff
CNetAPI32 netapi;
if( netapi.Init() != ERROR_SUCCESS )
{
return WBEM_E_FAILED;
}
// Did they specify groups?
pQuery.GetValuesForProp(IDS_GroupComponent, vecGroupComponents);
dwNumGroupComponents = vecGroupComponents.size();
// Did they specify users?
pQuery.GetValuesForProp(IDS_PartComponent, vecPartComponents);
dwNumPartComponents = vecPartComponents.size();
// Prepare information to be used below...
ParsedObjectPath *pParsedPath = NULL;
CObjectPathParser objpathParser;
// Find out what type of query it was.
// Was it a 3TokenOR?
CFrameworkQueryEx *pQuery2 = static_cast <CFrameworkQueryEx *>(&pQuery);
if (pQuery2 != NULL)
{
variant_t vGroupComp;
variant_t vPartComp;
CHString chstrSubDirPath;
CHString chstrCurrentDir;
if ( (pQuery2->Is3TokenOR(IDS_GroupComponent, IDS_PartComponent, vGroupComp, vPartComp)) &&
((V_BSTR(&vGroupComp) != NULL) && (V_BSTR(&vPartComp) != NULL)) &&
(wcscmp(V_BSTR(&vGroupComp), V_BSTR(&vPartComp)) == 0) )
{
//group can be a member of a group so we have to enumerate :-(...
hr = EnumerateInstances(pMethodContext, lFlags);
}
else if(dwNumGroupComponents > 0 && dwNumPartComponents == 0) // one or more groups specified; no users specified
{
for(LONG m = 0L; m < dwNumGroupComponents && SUCCEEDED(hr); m++)
{
// Parse the path to get the domain/user
int nStatus = objpathParser.Parse(vecGroupComponents[m], &pParsedPath);
// Did we parse it and does it look reasonable?
if (nStatus == 0)
{
try
{
if ( (pParsedPath->m_dwNumKeys == 2) &&
(pParsedPath->m_paKeys[0]->m_vValue.vt == VT_BSTR) &&
(pParsedPath->m_paKeys[1]->m_vValue.vt == VT_BSTR))
{
// This contains the complete object path
chstrGroup__RELPATH = (wchar_t*) vecGroupComponents[m];
// This contains just the 'Domain' part of the object path
chstrGroupDomain = pParsedPath->m_paKeys[0]->m_vValue.bstrVal;
// This contains just the 'Name' part of the object path
chstrGroupName = pParsedPath->m_paKeys[1]->m_vValue.bstrVal;
// Obtain members of this group...
CHString chstrComputerName(GetLocalComputerName());
CHString chstrNT_AUTHORITY;
CHString chstrBuiltIn;
if(GetLocalizedNTAuthorityString(chstrNT_AUTHORITY) && GetLocalizedBuiltInString(chstrBuiltIn))
{
if ( chstrGroupDomain.CompareNoCase(chstrBuiltIn) != 0 &&
chstrGroupDomain.CompareNoCase(chstrNT_AUTHORITY) != 0
)
{
if(chstrGroupDomain.CompareNoCase(chstrComputerName) == 0)
{
GetDependentsFromGroup(netapi, chstrGroupDomain, chstrGroupName, SidTypeWellKnownGroup, rgchstrGroupMembers);
}
else
{
GetDependentsFromGroup(netapi, chstrGroupDomain, chstrGroupName, SidTypeGroup, rgchstrGroupMembers);
}
hr = ProcessArray(pMethodContext, chstrGroup__RELPATH, rgchstrGroupMembers);
}
}
}
}
catch (...)
{
objpathParser.Free( pParsedPath );
throw;
}
// Clean up the Parsed Path
objpathParser.Free( pParsedPath );
}
}
}
else if(dwNumGroupComponents == 1 && dwNumPartComponents == 1) // one group specified; one user specified
{
// Parse the path to get the domain/user
int nStatus = objpathParser.Parse(vecGroupComponents[0], &pParsedPath);
// Did we parse it and does it look reasonable?
if (nStatus == 0)
{
try
{
if ( (pParsedPath->m_dwNumKeys == 2) &&
(pParsedPath->m_paKeys[0]->m_vValue.vt == VT_BSTR) &&
(pParsedPath->m_paKeys[1]->m_vValue.vt == VT_BSTR))
{
// This contains the complete object path
chstrGroup__RELPATH = (wchar_t*) vecGroupComponents[0];
// This contains just the 'Domain' part of the object path
chstrGroupDomain = pParsedPath->m_paKeys[0]->m_vValue.bstrVal;
// This contains just the 'Name' part of the object path
chstrGroupName = pParsedPath->m_paKeys[1]->m_vValue.bstrVal;
// Obtain members of this group...
CHString chstrComputerName(GetLocalComputerName());
CHString chstrNT_AUTHORITY;
CHString chstrBuiltIn;
if(GetLocalizedNTAuthorityString(chstrNT_AUTHORITY) && GetLocalizedBuiltInString(chstrBuiltIn))
{
if ( chstrGroupDomain.CompareNoCase(chstrBuiltIn) != 0 &&
chstrGroupDomain.CompareNoCase(chstrNT_AUTHORITY) != 0
)
{
if(chstrGroupDomain.CompareNoCase(chstrComputerName) == 0)
{
GetDependentsFromGroup(netapi, chstrGroupDomain, chstrGroupName, SidTypeWellKnownGroup, rgchstrGroupMembers);
}
else
{
GetDependentsFromGroup(netapi, chstrGroupDomain, chstrGroupName, SidTypeGroup, rgchstrGroupMembers);
}
DWORD dwSize = rgchstrGroupMembers.GetSize();
CInstancePtr pInstance;
//get full path for partcomponent
CHString chstrMember__PATH;
CHString chstrPart((LPCWSTR)(vecPartComponents[0]));
if(chstrPart.Find(L"\\\\") == -1)
{
chstrMember__PATH = MakeLocalPath(chstrPart);
}
else if(chstrPart.Find(L"\\\\.") != -1)
{
int n = chstrPart.Find(L":");
if(n != -1)
{
chstrMember__PATH = MakeLocalPath(chstrPart.Mid(n+1));
}
}
else
{
chstrMember__PATH = ((LPCWSTR)(vecPartComponents[0]));
}
// Process the instance
for (int x=0; x < dwSize && SUCCEEDED(hr) ; x++)
{
if(rgchstrGroupMembers.GetAt(x).CompareNoCase(chstrMember__PATH) == 0)
{
pInstance.Attach(CreateNewInstance(pMethodContext));
if(pInstance)
{
// Do the puts, and that's it
pInstance->SetCHString(IDS_GroupComponent, chstrGroup__RELPATH);
pInstance->SetCHString(IDS_PartComponent, chstrMember__PATH);
hr = pInstance->Commit();
break;
}
else
{
hr = WBEM_E_OUT_OF_MEMORY;
}
}
}
}
}
}
}
catch (...)
{
objpathParser.Free( pParsedPath );
throw;
}
// Clean up the Parsed Path
objpathParser.Free( pParsedPath );
}
}
else
{
hr = EnumerateInstances(pMethodContext, lFlags);
}
}
// Because this is an association class, we should only return WBEM_E_NOT_FOUND or WBEM_S_NO_ERROR. Other error codes
// will cause associations that hit this class to terminate prematurely.
if(SUCCEEDED(hr))
{
hr = WBEM_S_NO_ERROR;
}
else
{
hr = WBEM_E_NOT_FOUND;
}
return hr;
}
#endif
/*****************************************************************************
*
* FUNCTION : CWin32GroupUser::GetDependentsFromGroup
*
* DESCRIPTION : Given a group name, returns the Users/Groups in that group name
*
* INPUTS : none
*
* OUTPUTS : none
*
* RETURNS : HRESULT
*
* COMMENTS : Returns empty array if no group, empty group, or bad
* group name.
*
*****************************************************************************/
#ifdef NTONLY
void CWin32GroupUser::GetDependentsFromGroup(CNetAPI32& netapi,
const CHString sDomainName,
const CHString sGroupName,
const BYTE btSidType,
CHStringArray &asArray)
{
CHString sTemp;
NET_API_STATUS stat;
bool bAddIt;
DWORD dwNumReturnedEntries = 0, dwIndex = 0, dwTotalEntries = 0;
DWORD_PTR dwptrResume = NULL;
// Domain Groups
if (btSidType == SidTypeGroup)
{
GROUP_USERS_INFO_0 *pGroupMemberData = NULL;
CHString chstrDCName;
if (netapi.GetDCName( sDomainName, chstrDCName ) == ERROR_SUCCESS)
{
do
{
// Accept up to 256k worth of data.
stat = netapi.NetGroupGetUsers( chstrDCName,
sGroupName,
0,
(LPBYTE *)&pGroupMemberData,
262144,
&dwNumReturnedEntries,
&dwTotalEntries,
&dwptrResume);
// If we got some data
if ( ERROR_SUCCESS == stat || ERROR_MORE_DATA == stat )
{
try
{
// Walk through all the returned entries
for ( DWORD dwCtr = 0; dwCtr < dwNumReturnedEntries; dwCtr++ )
{
// Get the sid type for this object
CSid sid( sDomainName, CHString(pGroupMemberData[dwCtr].grui0_name), NULL );
DWORD dwType = sid.GetAccountType();
// From our assertions above, Domain groups can only have users
if (dwType == SidTypeUser)
{
sTemp = m_sUserBase;
sTemp += sDomainName;
sTemp += _T("\",Name=\"");
sTemp += pGroupMemberData[dwCtr].grui0_name;
sTemp += _T('"');
asArray.Add(sTemp);
}
}
}
catch ( ... )
{
netapi.NetApiBufferFree( pGroupMemberData );
throw ;
}
netapi.NetApiBufferFree( pGroupMemberData );
} // IF stat OK
} while ( ERROR_MORE_DATA == stat );
}
}
// Local Groups
else if (btSidType == SidTypeAlias || btSidType == SidTypeWellKnownGroup)
{
LOCALGROUP_MEMBERS_INFO_1 *pGroupMemberData = NULL;
do {
// Accept up to 256k worth of data.
stat = netapi.NetLocalGroupGetMembers( NULL,
sGroupName,
1,
(LPBYTE *)&pGroupMemberData,
262144,
&dwNumReturnedEntries,
&dwTotalEntries,
&dwptrResume);
// If we got some data
if ( ERROR_SUCCESS == stat || ERROR_MORE_DATA == stat )
{
try
{
// Walk through all the returned entries
for ( DWORD dwCtr = 0; dwCtr < dwNumReturnedEntries; dwCtr++ )
{
// If this is a recognized type...
bAddIt = true;
switch (pGroupMemberData[dwCtr].lgrmi1_sidusage) {
case SidTypeUser:
sTemp = m_sUserBase;
break;
case SidTypeGroup:
sTemp = m_sGroupBase;
break;
case SidTypeWellKnownGroup:
sTemp = m_sSystemBase;
break;
default:
// Group member is of unrecognized type, don't add it
ASSERT_BREAK(0);
bAddIt = false;
break;
}
CSid cLCID(pGroupMemberData[dwCtr].lgrmi1_sid);
// Then add it to the list
if (bAddIt)
{
CHString chstrDomNameTemp = cLCID.GetDomainName();
CHString chstrComputerName(GetLocalComputerName());
CHString chstrBuiltIn;
if(GetLocalizedBuiltInString(chstrBuiltIn))
{
if (chstrDomNameTemp.CompareNoCase(chstrBuiltIn) == 0)
{
chstrDomNameTemp = chstrComputerName;
}
else
{
CHString chstrNT_AUTHORITY;
if(GetLocalizedNTAuthorityString(chstrNT_AUTHORITY))
{
if(chstrDomNameTemp.CompareNoCase(chstrNT_AUTHORITY) == 0 ||
(chstrDomNameTemp.IsEmpty() && pGroupMemberData[dwCtr].lgrmi1_sidusage == SidTypeWellKnownGroup))
{
chstrDomNameTemp = chstrComputerName;
}
}
else
{
bAddIt = false;
}
}
}
else
{
bAddIt = false;
}
if(bAddIt)
{
sTemp += chstrDomNameTemp;
//sTemp += cLCID.GetDomainName();
sTemp += _T("\",Name=\"");
sTemp += pGroupMemberData[dwCtr].lgrmi1_name;
sTemp += _T('"');
asArray.Add(sTemp);
}
}
}
}
catch ( ... )
{
netapi.NetApiBufferFree( pGroupMemberData );
throw ;
}
netapi.NetApiBufferFree( pGroupMemberData );
} // IF stat OK
} while ( ERROR_MORE_DATA == stat );
}
else
{
// Unrecognized Group type
ASSERT_BREAK(0);
}
}
#endif
/*****************************************************************************
*
* FUNCTION : CWin32GroupUser::StaticEnumerationCallback
*
* DESCRIPTION : Called from GetAllInstancesAsynch as a wrapper to EnumerationCallback
*
* INPUTS :
*
* OUTPUTS :
*
* RETURNS :
*
* COMMENTS :
*
*****************************************************************************/
#ifdef NTONLY
HRESULT WINAPI CWin32GroupUser::StaticEnumerationCallback(Provider* pThat, CInstance* pInstance, MethodContext* pContext, void* pUserData)
{
CWin32GroupUser* pThis;
HRESULT hr;
pThis = dynamic_cast<CWin32GroupUser *>(pThat);
ASSERT_BREAK(pThis != NULL);
if (pThis)
hr = pThis->EnumerationCallback(pInstance, pContext, pUserData);
else
hr = WBEM_E_FAILED;
return hr;
}
#endif
/*****************************************************************************
*
* FUNCTION : CWin32GroupUser::EnumerationCallback
*
* DESCRIPTION : Called from GetAllInstancesAsynch via StaticEnumerationCallback
*
* INPUTS : (see CWbemProviderGlue::GetAllInstancesAsynch)
*
* OUTPUTS :
*
* RETURNS :
*
* COMMENTS :
*
*****************************************************************************/
#ifdef NTONLY
HRESULT CWin32GroupUser::EnumerationCallback(CInstance* pGroup, MethodContext* pMethodContext, void* pUserData)
{
CNetAPI32* pNetApi;
pNetApi = (CNetAPI32 *) pUserData;
CHStringArray asMembersGot;
BYTE btSidType;
DWORD dwSize, x;
CHString sGroup, sDomain, sGroupPath;
HRESULT hr = WBEM_S_NO_ERROR;
// Get the info about this group
pGroup->GetCHString(IDS_Domain, sDomain) ;
pGroup->GetCHString(IDS_Name, sGroup) ;
pGroup->GetByte(IDS_SIDType, btSidType);
pGroup->GetCHString(L"__RELPATH", sGroupPath) ;
// See if there are users in this group
GetDependentsFromGroup(*pNetApi, sDomain, sGroup, btSidType, asMembersGot);
dwSize = asMembersGot.GetSize();
// Ok, turn the relpath into a complete path
GetLocalInstancePath(pGroup, sGroupPath);
CInstancePtr pInstance;
// Start pumping out the instances
for (x=0; x < dwSize && SUCCEEDED(hr) ; x++)
{
pInstance.Attach(CreateNewInstance(pMethodContext));
if (pInstance)
{
// Do the puts, and that's it
pInstance->SetCHString(IDS_GroupComponent, sGroupPath);
pInstance->SetCHString(IDS_PartComponent, asMembersGot.GetAt(x));
hr = pInstance->Commit();
}
else
{
hr = WBEM_E_OUT_OF_MEMORY;
}
}
return hr;
}
#endif
/*****************************************************************************
*
* FUNCTION : CWin32GroupUser::ProcessArray
*
* DESCRIPTION : Called from query routine to return instances
*
* INPUTS :
*
* OUTPUTS :
*
* RETURNS :
*
* COMMENTS :
*
*****************************************************************************/
#ifdef NTONLY
HRESULT CWin32GroupUser::ProcessArray(
MethodContext* pMethodContext,
CHString& chstrGroup__RELPATH,
CHStringArray& rgchstrArray)
{
HRESULT hr = WBEM_S_NO_ERROR;
DWORD dwSize, x;
CHString sGroup, sDomain, sGroupPath;
dwSize = rgchstrArray.GetSize();
CInstancePtr pInstance;
// Start pumping out the instances
for (x=0; x < dwSize && SUCCEEDED(hr) ; x++)
{
pInstance.Attach(CreateNewInstance(pMethodContext));
if(pInstance)
{
// Do the puts, and that's it
pInstance->SetCHString(IDS_GroupComponent, chstrGroup__RELPATH);
pInstance->SetCHString(IDS_PartComponent, rgchstrArray.GetAt(x));
hr = pInstance->Commit();
}
else
{
hr = WBEM_E_OUT_OF_MEMORY;
}
}
return hr;
}
#endif
| [
"seta7D5@protonmail.com"
] | seta7D5@protonmail.com |
bf1e1a32f3e49427cc2e68a65ab80a6088e83fe0 | 257d08abb49506fc36f7cd29199dc3f75f8b3a01 | /src/LibGame/Input.h | 4bc0e48f5935d42c6e8c24b8710565989d039807 | [] | no_license | kaspersky43/danmaku-project-library | 857c4bd8e3d039ec2cb2ebf9ddbbda4c25b145a9 | 2ff896d895294676497bf4a7326eaa561a99b58d | refs/heads/master | 2020-04-18T16:44:20.133167 | 2019-01-26T02:20:44 | 2019-01-26T02:20:44 | 167,640,004 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 1,094 | h | #ifndef INPUTH
#define INPUTH
#define DIRECTINPUT_VERSION 0x0800
#include <dinput.h>
#include <vector>
using namespace std;
#define MAX_PLAYERS 16
#define MAX_BUTTONS 128
//==============================================================
// マウス情報
typedef struct {
int X, Y;
bool LButton, MButton, RButton;
} MOUSE_STATE;
//==============================================================
// 入力状態
class CInputState {
public:
bool Up, Down, Left, Right, Button[MAX_BUTTONS],
Up2, Down2, Left2, Right2;
float AnalogX, AnalogY, AnalogX2, AnalogY2;
CInputState();
void Clear();
};
//==============================================================
// 入力
class CInput {
private:
CInputState State[MAX_PLAYERS];
LPDIRECTINPUT8 DI;
LPDIRECTINPUTDEVICE8 Keyboard;
vector<LPDIRECTINPUTDEVICE8> JoySticks;
void FreeResources();
public:
CInput(HWND hwnd);
~CInput();
void UpdateState();
const CInputState* GetState(int player) {
return &State[player];
}
void ClearState();
BOOL CALLBACK EnumJoysticksCallback(
const DIDEVICEINSTANCE* did);
};
#endif
| [
"austinwyang94@gmail.com"
] | austinwyang94@gmail.com |
19820e86dcb18919568620c53bc9883e8dff4cf2 | e18f226be7ec8945273c903a31427eaebda112ce | /src/pr2_mechanism_model/src/wrist_transmission.cpp | 63a660f725bbbe97cf11a5e96f0dd610d7cad097 | [] | no_license | gnoliyil/pr2_kinetic_packages | 3cad819236de2a8c92b756eb8f49f76d4e4f1648 | e43479ea6088062b63271c6b94417c266429d439 | refs/heads/master | 2020-06-25T01:06:37.872211 | 2017-08-25T21:19:33 | 2017-08-25T21:19:33 | 96,950,087 | 10 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,262 | cpp | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage 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.
*********************************************************************/
/*
* Author: Melonee Wise
*/
#include <math.h>
#include <pluginlib/class_list_macros.h>
#include "pr2_mechanism_model/robot.h"
#include "pr2_mechanism_model/wrist_transmission.h"
using namespace pr2_mechanism_model;
using namespace pr2_hardware_interface;
PLUGINLIB_EXPORT_CLASS(pr2_mechanism_model::WristTransmission,
pr2_mechanism_model::Transmission)
static bool convertDouble(const char* val_str, double &value)
{
char *endptr=NULL;
value = strtod(val_str, &endptr);
if ((endptr == val_str) || (endptr < (val_str+strlen(val_str))))
{
return false;
}
return true;
}
WristTransmission::WristTransmission()
{
joint_offset_[0] = 0.0;
joint_offset_[1] = 0.0;
}
bool WristTransmission::initXml(TiXmlElement *elt, Robot *robot)
{
const char *name = elt->Attribute("name");
name_ = name ? name : "";
TiXmlElement *ael = elt->FirstChildElement("rightActuator");
const char *actuator_name = ael ? ael->Attribute("name") : NULL;
Actuator *a;
if (!actuator_name || (a = robot->getActuator(actuator_name)) == NULL )
{
ROS_WARN("WristTransmission could not find actuator named \"%s\"", actuator_name);
return false;
}
a->command_.enable_ = true;
actuator_names_.push_back(actuator_name);
const char *act_red = ael->Attribute("mechanicalReduction");
if (!act_red)
{
ROS_WARN("WristTransmission's actuator \"%s\" was not given a reduction.", actuator_name);
return false;
}
actuator_reduction_.push_back(atof(act_red));
ael = elt->FirstChildElement("leftActuator");
actuator_name = ael ? ael->Attribute("name") : NULL;
if (!actuator_name || (a = robot->getActuator(actuator_name)) == NULL )
{
ROS_WARN("WristTransmission could not find actuator named \"%s\"", actuator_name);
return false;
}
a->command_.enable_ = true;
actuator_names_.push_back(actuator_name);
act_red = ael->Attribute("mechanicalReduction");
if (!act_red)
{
ROS_WARN("WristTransmission's actuator \"%s\" was not given a reduction.", actuator_name);
return false;
}
actuator_reduction_.push_back(atof(act_red));
TiXmlElement *j = elt->FirstChildElement("flexJoint");
const char *joint_name = j->Attribute("name");
if (!joint_name)
{
ROS_ERROR("WristTransmission did not specify joint name");
return false;
}
const boost::shared_ptr<const urdf::Joint> joint = robot->robot_model_.getJoint(joint_name);
if (!joint)
{
ROS_ERROR("WristTransmission could not find joint named \"%s\"", joint_name);
return false;
}
joint_names_.push_back(joint_name);
const char *joint_red = j->Attribute("mechanicalReduction");
if (!joint_red)
{
ROS_WARN("WristTransmission's joint \"%s\" was not given a reduction.", joint_name);
return false;
}
joint_reduction_.push_back(atof(joint_red));
const char *joint_offset = j->Attribute("offset");
if (!joint_offset)
{
joint_offset_[0] = 0.0;
}
else
{
if (!convertDouble(joint_offset, joint_offset_[0]))
{
ROS_WARN("WristTransmission's joint \"%s\", cannot convert jointOffset attribute \"%s\" to floating point.",
joint_name, joint_offset);
return false;
}
else
{
ROS_WARN("Joint offset of %f for joint %s.", joint_offset_[0], joint_name);
}
}
j = elt->FirstChildElement("rollJoint");
joint_name = j->Attribute("name");
if (!joint_name)
{
ROS_ERROR("WristTransmission did not specify joint name");
return false;
}
const boost::shared_ptr<const urdf::Joint> joint2 = robot->robot_model_.getJoint(joint_name);
if (!joint2)
{
ROS_ERROR("WristTransmission could not find joint named \"%s\"", joint_name);
return false;
}
joint_names_.push_back(joint_name);
joint_red = j->Attribute("mechanicalReduction");
if (!joint_red)
{
ROS_WARN("WristTransmission's joint \"%s\" was not given a reduction.", joint_name);
return false;
}
joint_reduction_.push_back(atof(joint_red));
joint_offset = j->Attribute("offset");
if (!joint_offset)
{
joint_offset_[1] = 0.0;
}
else
{
if (!convertDouble(joint_offset, joint_offset_[1]))
{
ROS_WARN("WristTransmission's joint \"%s\", cannot convert jointOffset attribute \"%s\" to floating point.",
joint_name, joint_offset);
return false;
}
else
{
ROS_WARN("Joint offset of %f for joint %s.", joint_offset_[1], joint_name);
}
}
return true;
}
bool WristTransmission::initXml(TiXmlElement *elt)
{
const char *name = elt->Attribute("name");
name_ = name ? name : "";
TiXmlElement *ael = elt->FirstChildElement("rightActuator");
const char *actuator_name = ael ? ael->Attribute("name") : NULL;
if (!actuator_name)
{
ROS_WARN("WristTransmission could not find actuator named \"%s\"", actuator_name);
return false;
}
actuator_names_.push_back(actuator_name);
const char *act_red = ael->Attribute("mechanicalReduction");
if (!act_red)
{
ROS_WARN("WristTransmission's actuator \"%s\" was not given a reduction.", actuator_name);
return false;
}
actuator_reduction_.push_back(atof(act_red));
ael = elt->FirstChildElement("leftActuator");
actuator_name = ael ? ael->Attribute("name") : NULL;
if (!actuator_name)
{
ROS_WARN("WristTransmission could not find actuator named \"%s\"", actuator_name);
return false;
}
actuator_names_.push_back(actuator_name);
act_red = ael->Attribute("mechanicalReduction");
if (!act_red)
{
ROS_WARN("WristTransmission's actuator \"%s\" was not given a reduction.", actuator_name);
return false;
}
actuator_reduction_.push_back(atof(act_red));
TiXmlElement *j = elt->FirstChildElement("flexJoint");
const char *joint_name = j->Attribute("name");
if (!joint_name)
{
ROS_ERROR("WristTransmission did not specify joint name");
return false;
}
joint_names_.push_back(joint_name);
const char *joint_red = j->Attribute("mechanicalReduction");
if (!joint_red)
{
ROS_WARN("WristTransmission's joint \"%s\" was not given a reduction.", joint_name);
return false;
}
joint_reduction_.push_back(atof(joint_red));
const char *joint_offset = j->Attribute("offset");
if (!joint_offset)
{
joint_offset_[0] = 0.0;
}
else
{
double offset;
if (!convertDouble(joint_offset, joint_offset_[0]))
{
ROS_WARN("WristTransmission's joint \"%s\", cannot convert jointOffset attribute \"%s\" to floating point.",
joint_name, joint_offset);
return false;
}
else
{
ROS_WARN("Joint offset of %f for joint %s.", joint_offset_[0], joint_name);
}
}
j = elt->FirstChildElement("rollJoint");
joint_name = j->Attribute("name");
if (!joint_name)
{
ROS_ERROR("WristTransmission did not specify joint name");
return false;
}
joint_names_.push_back(joint_name);
joint_red = j->Attribute("mechanicalReduction");
if (!joint_red)
{
ROS_WARN("WristTransmission's joint \"%s\" was not given a reduction.", joint_name);
return false;
}
joint_reduction_.push_back(atof(joint_red));
if (!joint_offset)
{
joint_offset_[1] = 0.0;
}
else
{
if (!convertDouble(joint_offset, joint_offset_[1]))
{
ROS_WARN("WristTransmission's joint \"%s\", cannot convert jointOffset attribute \"%s\" to floating point.",
joint_name, joint_offset);
return false;
}
else
{
ROS_WARN("Joint offset of %f for joint %s.", joint_offset_[1], joint_name);
}
}
return true;
}
void WristTransmission::propagatePosition(
std::vector<Actuator*>& as, std::vector<JointState*>& js)
{
assert(as.size() == 2);
assert(js.size() == 2);
js[0]->position_ = ((as[0]->state_.position_ / actuator_reduction_[0] - as[1]->state_.position_ / actuator_reduction_[1])/
(2*joint_reduction_[0])) + js[0]->reference_position_+joint_offset_[0];
js[0]->velocity_ = (as[0]->state_.velocity_ / actuator_reduction_[0] - as[1]->state_.velocity_ / actuator_reduction_[1])/(2*joint_reduction_[0]);
js[0]->measured_effort_ = joint_reduction_[0]*(as[0]->state_.last_measured_effort_ * actuator_reduction_[0] - as[1]->state_.last_measured_effort_ * actuator_reduction_[1]);
js[1]->position_ = ((-as[0]->state_.position_ / actuator_reduction_[0] - as[1]->state_.position_ / actuator_reduction_[1])/
(2*joint_reduction_[1]))+js[1]->reference_position_+joint_offset_[1];
js[1]->velocity_ = (-as[0]->state_.velocity_ / actuator_reduction_[0] - as[1]->state_.velocity_ / actuator_reduction_[1])/(2*joint_reduction_[1]);
js[1]->measured_effort_ = joint_reduction_[1]*(-as[0]->state_.last_measured_effort_ * actuator_reduction_[0] - as[1]->state_.last_measured_effort_ * actuator_reduction_[1]);
}
void WristTransmission::propagatePositionBackwards(
std::vector<JointState*>& js, std::vector<Actuator*>& as)
{
assert(as.size() == 2);
assert(js.size() == 2);
as[0]->state_.position_ = (((js[0]->position_-js[0]->reference_position_-joint_offset_[0])*joint_reduction_[0] -
(js[1]->position_-js[1]->reference_position_-joint_offset_[1])*joint_reduction_[1]) * actuator_reduction_[0]);
as[0]->state_.velocity_ = ((js[0]->velocity_*joint_reduction_[0] - js[1]->velocity_*joint_reduction_[1]) * actuator_reduction_[0]);
as[0]->state_.last_measured_effort_ = (js[0]->measured_effort_/joint_reduction_[0] - js[1]->measured_effort_/joint_reduction_[1]) /(2.0*actuator_reduction_[0]);
as[1]->state_.position_ = ((-(js[0]->position_-js[0]->reference_position_-joint_offset_[0])*joint_reduction_[0] -
(js[1]->position_-js[1]->reference_position_-joint_offset_[1])*joint_reduction_[1]) * actuator_reduction_[1]);
as[1]->state_.velocity_ = ((-js[0]->velocity_*joint_reduction_[0] - js[1]->velocity_*joint_reduction_[1]) * actuator_reduction_[1]);
as[1]->state_.last_measured_effort_ = (-js[0]->measured_effort_/joint_reduction_[0] - js[1]->measured_effort_/joint_reduction_[1]) /(2.0*actuator_reduction_[1]);
// Update the timing (making sure it's initialized).
if (! simulated_actuator_timestamp_initialized_)
{
// Set the time stamp to zero (it is measured relative to the start time).
as[0]->state_.sample_timestamp_ = ros::Duration(0);
as[1]->state_.sample_timestamp_ = ros::Duration(0);
// Try to set the start time. Only then do we claim initialized.
if (ros::isStarted())
{
simulated_actuator_start_time_ = ros::Time::now();
simulated_actuator_timestamp_initialized_ = true;
}
}
else
{
// Measure the time stamp relative to the start time.
as[0]->state_.sample_timestamp_ = ros::Time::now() - simulated_actuator_start_time_;
as[1]->state_.sample_timestamp_ = ros::Time::now() - simulated_actuator_start_time_;
}
// Set the historical (double) timestamp accordingly.
as[0]->state_.timestamp_ = as[0]->state_.sample_timestamp_.toSec();
as[1]->state_.timestamp_ = as[1]->state_.sample_timestamp_.toSec();
// simulate calibration sensors by filling out actuator states
// this is where to embed the hack which joint connects to which mcb
this->joint_calibration_simulator_[0].simulateJointCalibration(js[0],as[1]);
this->joint_calibration_simulator_[1].simulateJointCalibration(js[1],as[0]);
}
void WristTransmission::propagateEffort(
std::vector<JointState*>& js, std::vector<Actuator*>& as)
{
assert(as.size() == 2);
assert(js.size() == 2);
as[0]->command_.enable_ = true;
as[1]->command_.enable_ = true;
as[0]->command_.effort_ = (js[0]->commanded_effort_/joint_reduction_[0] - js[1]->commanded_effort_/joint_reduction_[1]) /(2.0*actuator_reduction_[0]);
as[1]->command_.effort_ = (-js[0]->commanded_effort_/joint_reduction_[0] - js[1]->commanded_effort_/joint_reduction_[1]) /(2.0*actuator_reduction_[1]);
}
void WristTransmission::propagateEffortBackwards(
std::vector<Actuator*>& as, std::vector<JointState*>& js)
{
assert(as.size() == 2);
assert(js.size() == 2);
js[0]->commanded_effort_ = joint_reduction_[0]*(as[0]->command_.effort_ * actuator_reduction_[0] - as[1]->command_.effort_ * actuator_reduction_[1]);
js[1]->commanded_effort_ = joint_reduction_[1]*(-as[0]->command_.effort_ * actuator_reduction_[0] - as[1]->command_.effort_ * actuator_reduction_[1]);
}
void WristTransmission::setReductions(std::vector<double>& ar, std::vector<double>& jr)
{
actuator_reduction_ = ar;
joint_reduction_ = jr;
}
| [
"gnoliyil@pku.edu.cn"
] | gnoliyil@pku.edu.cn |
987d8076fc8f454e7dd2cbbe050bb5bdca8bf02d | f43346fe6eaf46e07d65cf4a1d05bb4b6b40c4fd | /lift_test/lift_test.ino | f7567dd8a91c7ed165c08a07dc4f7f4d7695bf1a | [
"Apache-2.0"
] | permissive | bunyim/ELEC3607_Project | d7337b384344105862481c9aee4282b5078f68b2 | d3b475907584e34d1557192aa8317128386496ee | refs/heads/master | 2020-03-19T04:50:14.828219 | 2019-03-29T03:59:44 | 2019-03-29T03:59:44 | 135,872,842 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,911 | ino |
#define blueToothSerial Serial2 // using bluetooth as serial 2
#define XCHAN1 0 // TC2 channel 0
#define XID ID_TC6 // Instance ID of the channel 0
#define XCHAN2 1 // TC2 channel 1
#define XTC TC2 // Timer counter 2
#define XID1 ID_TC7 // Instance ID of the channel 1
#define TC_SYNC1 (*(WoReg*) 0x400880C0) // SYNC register address
#define PINCHAN1 25 // Digital pin 3
#define PINCHAN2 28 // Digital pin 5
#define VARIANT_MCK 41999026 // MCK/2 which is 42 MHz
// list of library required for the LED matrix
#include <Wire.h>
#include <Adafruit_GFX.h>
#include "Adafruit_LEDBackpack.h"
// servo library
#include <Servo.h>
Adafruit_8x8matrix matrix = Adafruit_8x8matrix(); // matrix object for controlling the LED
int potpin=0; // potentiometer pin
const int buzzer = 39; //buzzer pin
volatile int up_calls[4]={0,0,0,0}; //index 0 is a boolean for the up routine, 1 represents a call from level 1, and 2 for
//a call from level 2 and index 3 represent a call from lvl 3
volatile int down_calls[4]={0,0,0,0}; //same as up_calls, index 0 is routine for down boolean, 1 is level 1, 2 is level 2,3 is lvl 3
volatile int current_floor = 0; // current floor at the start of the program is unknown need calibration
bool in_motion = 0; // tells whether the lift is moving or not
volatile bool is_open=0; //boolean variable for checking if the door should be open
Servo servo; //servo object
const int servo_pin=35; // servo pin
int floors[3]; //potentiometer value for each floor
int servo_close = 1050; //the value to write to the servo in order to close the door
int servo_open = 1900;//the value to write to the servo in order to open the door
int len=849; // length of the array
int opening[849]; //all value to open the door in a smooth transistion
int closing[849];//all value to close the door in a smooth transistion
// down button from lvl 3
void func0(){
// open the door if the lift is at lvl 3
if (current_floor == 3 && in_motion == 0)
is_open=1;
// else mark it as an up call and change the routine to up if it is not going down
else{
up_calls[3] = 1;
if (down_calls[0] == 0) {
up_calls[0] = 1;
}
}
}
//up button from lvl 1
void func3(){
//open the door if the lift is at lvl 1
if (current_floor == 1 && in_motion == 0) {
is_open=1;
//else mark it as a dwn call and change the routine to down if it is not going up
}else {
down_calls[1] = 1;
if (up_calls[0]==0) {
down_calls[0] = 1;
}
}
}
//up button from lvl 2
void func1(){
// open the door if the lift is at lvl 2
if (current_floor == 2 && in_motion == 0) {
is_open=1;
// else check if the current floor is greater than 2
}else if (current_floor > 2) {
// if it is greater than 2 check the routine, if lift is going down make it an up call else make it a down call to pick
// up passenger to go up
if (down_calls[0]==1){
up_calls[2]=1;
}else{
down_calls[2]=1;
}
// if it is not going down then change the routine of the lift to come down
if (up_calls[0] == 0) {
down_calls[0] = 1;
}
}else {
// if the current floor is less than 2 then check if the routine is going up
// if it is not going down then change the routine to go up and make it an up call at lvl 2
if (down_calls[0]==0){
up_calls[2]=1;
up_calls[0]=1;
}
}
}
//down button from lvl 2
void func2(){
// same functionality as up button from lvl 2 but reverse
if (current_floor == 2 && in_motion == 0) {
is_open=1;
}else if (current_floor > 2) {
if (up_calls[0] == 0) {
down_calls[0] = 1;
}
if(down_calls[0]==1){
down_calls[2] = 1;
}
}else {
if(up_calls[0]==1){
down_calls[2] = 1;
}else{
up_calls[2]=1;
}
if (down_calls[0] == 0) {
up_calls[0] = 1;
}
}
}
//open button inside lift
void func7(){
is_open=1;
}
//close button inside lift
void func8(){
is_open=0;
}
//emergency button
void func9(){
emergency();
}
// floor 1 button in lift
void func4(){
// if current floor is at 1 open the door
if (current_floor == 1 && in_motion == 0) {
is_open=1;
// same functionality as the up button from floor 1
}else {
down_calls[1] = 1;
if (up_calls[0] == 0) {
down_calls[0] = 1;
}
}
}
// floor 2 button in lift
void func5(){
// similar functionality as the external buttons from lvl 2
if (current_floor == 2 && in_motion == 0) {
is_open=1;
}else if (current_floor > 2) {
down_calls[2] = 1;
if (up_calls[0] == 0) {
down_calls[0] = 1;
}
}else {
up_calls[2] = 1;
if (down_calls[0] == 0) {
up_calls[0] = 1;
}
}
}
// floor 3 button in lift
void func6(){
// same functionality as the dwn button from lvl 3
if (current_floor == 3 && in_motion == 0) {
is_open=1;
}else {
up_calls[3] = 1;
if (down_calls[0] == 0) {
up_calls[0] = 1;
}
}
}
void setup(){
// setting up the opening array
for(int i=1;i<=len;i++){
opening[i-1]=1051+i;
}
// setting up the closing array
for(int i=1;i<=len;i++){
closing[i-1]=1899-i;
}
// set up bluetooth connection
setupBlueToothConnection();
unsigned int chanmask = (1 << PINCHAN1)|(1<<PINCHAN2); // bit mask
// set PIO to chan C
REG_PIOC_PDR = chanmask;
REG_PIOC_ABSR = chanmask;
REG_PIOC_MDDR = chanmask;
// set up TC
pmc_set_writeprotect(false);
pmc_enable_periph_clk(XID1);
pmc_enable_periph_clk(XID);
// stopping the motor
motor_stop();
// attaching the servo pin
servo.attach(servo_pin);
Serial.begin(9600);
void(*p[13])()= {&func0,&func1,&func2,&func3,&func4,&func5,&func6,&func7,&func8,&func9}; // function pointers for interrupts
pinMode(buzzer,OUTPUT); // setting the buzzer as an output pin
// setting all the interrupt pin to low
for(int i=22;i<=31;i++)
pinMode(i,OUTPUT);
// attaching interrupt to all the pin and search for a rising edge
for(int i = 22;i<=31;i++){
attachInterrupt(i,p[i-22],RISING);
}
int i=0; //counter for reading measurement when calibration
int val; // value read from potentiometer
int input; // input from phone
//closing the door
servo.writeMicroseconds(servo_close);
matrix.begin(0x70); // pass in the address for the matrix
// calibration loop
while(i<3){
val = analogRead(potpin);
// check if anything was receive from the bluetooth and set all the floor values to the potentiometer value
if(blueToothSerial.available()){
input = blueToothSerial.parseInt();
if(input==1){
floors[0]=val;
i++;
}else if(input==2){
floors[1]=val;
i++;
}else if(input==3){
floors[2]=val;
i++;
}
}
delay(1000);
}
val = analogRead(potpin);
// setting the current floor based on the last value read from the potentiometer
if (val>floors[0]-10 && val < floors[0]+10){
current_floor = 1;
arr1();
}else if(val> floors[1]-10 && val< floors[1]+10){
current_floor = 2;
arr2();
}else if(val > floors[2]-10 && val< floors[2]+10){
current_floor = 3;
arr3();
}
Serial.println("Current floor is now at "+String(current_floor));
for(int i=0;i<3;i++){
Serial.println("Value saved for floor "+String(i+1)+" is "+String(floors[i]));
}
delay(3000);
}
int pot=0; // value read from potentiometer
void loop(){
service();
}
// open door function & close at the same time
void open_door(){
// open the door when the lift is stationary
if(in_motion==0){
int i=0;
int j=len;
while (1){
if(is_open==1){
servo.writeMicroseconds(opening[i]);
i++;
j--;
if(i==len){
// delay 2 second when fully open
is_open=0;
delay(2000);
}
}else{
if(j==len)
break;
servo.writeMicroseconds(closing[j]);
j++;
i--;
}
}
//delay 1 second before moving up or down
delay(1000);
}
}
int up_down=0;//counter to set the motor to run once only
// service function
void service(){
// check if the button on the floor arrived is pressed in order to open the door
open_door();
// reading value from potentiometer
pot = analogRead(potpin);
// change the motion of the lift
if(up_calls[0]==1 || down_calls[0]==1)
in_motion=1;
// check for up routine
if(up_calls[0]==1){
//update current floor value based on value from potentiometer when calibrating
if(current_floor==2){
if(pot == floors[2]-15){
current_floor++;
}
}else if(current_floor==1){
if(pot ==floors[1]-15){
current_floor++;
}
}
// check for any up calls from current if so stop the motor,buzz, display floor number on LED and check for any other routine
if(up_calls[current_floor]==1){
motor_stop();
up_down=0;
if(current_floor==2){
arr2();
}else{
arr3();
}
in_motion=0;
is_open=1;
buzz();
open_door();
up_calls[current_floor]=0;
bool any_up_calls = 0;
for(int i=1;i<4;i++){
if(up_calls[i]==1){
any_up_calls=1;
break;
}
}
if(any_up_calls && down_calls[0]==0)
up_calls[0]=1;
else{
up_calls[0]=0;
}
bool any_down_calls = 0;
for(int i=1;i<4;i++){
if(down_calls[i]==1){
any_down_calls=1;
break;
}
}
if(any_down_calls && up_calls[0]==0)
down_calls[0]=1;
else{
down_calls[0]=0;
}
}else{
up_down++;
if (up_down==1)
motor_up();
}
// check for down routine
}else if(down_calls[0]==1){
//update floor value like from the up routine
if(current_floor == 3){
if(pot ==floors[1]+15){
current_floor--;
}
}else if(current_floor == 2){
if(pot==floors[0]+15){
current_floor--;
}
}
// check for any down calls from any floors and perform the same task as the up calls
if(down_calls[current_floor]==1 ){
motor_stop();
up_down=0;
if(current_floor==2){
arr2();
}else{
arr1();
}
in_motion=0;
is_open=1;
buzz();
open_door();
down_calls[current_floor]=0;
bool any_down_calls = 0;
for(int i=1;i<4;i++){
if(down_calls[i]==1){
any_down_calls=1;
break;
}
}
if(any_down_calls && up_calls[0]==0)
down_calls[0]=1;
else{
down_calls[0]=0;
}
bool any_up_calls = 0;
for(int i=1;i<4;i++){
if(up_calls[i]==1){
any_up_calls=1;
break;
}
}
if(any_up_calls && down_calls[0]==0)
up_calls[0]=1;
else{
up_calls[0]=0;
}
}else{
up_down++;
if(up_down==1)
motor_down();
}
}else{
// do nothing if none of the routine matches
}
}
| [
"noreply@github.com"
] | bunyim.noreply@github.com |
e82a4063b31637248eb556209831978a17d62903 | 15c9fbdfd51eb9deba14e03e3acceef8c3d3e9a6 | /src/storage/StripedLRU.cpp | f248373d087e5e8d08771aa022f230a46ad3e73d | [] | no_license | i-alkisev/afina | a6e946b62c82bed0e1ce881a884462e6d5d3e411 | 52a0608b9c7918ac06dd20b11f3d0c65036f6230 | refs/heads/master | 2023-08-28T15:08:31.695840 | 2021-10-17T17:22:09 | 2021-10-17T17:22:09 | 410,300,470 | 0 | 0 | null | 2021-11-01T18:55:53 | 2021-09-25T14:55:59 | C++ | UTF-8 | C++ | false | false | 1,546 | cpp | #include <functional>
#include <stdexcept>
#include "StripedLRU.h"
namespace Afina {
namespace Backend {
StripedLRU StripedLRU::Create_StripedLRU(size_t memory_limit, size_t stripe_count) {
size_t stripe_limit = memory_limit / stripe_count;
if (stripe_limit < 1024) {
throw std::runtime_error("Cache size of each shard is too small (less than 1Kb)");
}
return StripedLRU(stripe_limit, stripe_count);
}
StripedLRU::StripedLRU(StripedLRU&& other): _shards(std::move(other._shards)) {}
StripedLRU::StripedLRU (size_t stripe_limit, size_t stripe_count) {
_shards.reserve(stripe_count);
for (size_t i = 0; i < stripe_count; ++i){
_shards.emplace_back(new ThreadSafeSimplLRU(stripe_limit));
}
}
bool StripedLRU::Put(const std::string &key, const std::string &value) {
return _shards[_GetShardNum(key)]->Put(key, value);
}
bool StripedLRU::PutIfAbsent(const std::string &key, const std::string &value) {
return _shards[_GetShardNum(key)]->PutIfAbsent(key, value);
}
bool StripedLRU::Set(const std::string &key, const std::string &value) {
return _shards[_GetShardNum(key)]->Set(key, value);
}
bool StripedLRU::Delete(const std::string &key) {
return _shards[_GetShardNum(key)]->Delete(key);
}
bool StripedLRU::Get(const std::string &key, std::string &value) {
return _shards[_GetShardNum(key)]->Get(key, value);
}
size_t StripedLRU::_GetShardNum(const std::string &key) {
return std::hash<std::string>{}(key) % _shards.size();
}
} // namespace Backend
} // namespace Afina | [
"i.alkisev@gmail.com"
] | i.alkisev@gmail.com |
661ed43d91a9bb422fbeff7ff21bd74361f6f2dc | ac4732b77a9245c9159f6dd6494595626b1e89ac | /SFML-2.5.1/include/SFML/Graphics/RenderWindow.hpp | 599fad72bb820529a368936f36919cc92bd5bc4d | [] | no_license | sliziky/Gold-Miner | 4c3b7629517e722b91cd83c056cbafcd2b21bd10 | 27592d1f0e7c14ab3823e05ad40d36e9638f67e2 | refs/heads/master | 2020-05-31T22:38:41.790808 | 2019-06-16T10:54:39 | 2019-06-22T11:49:12 | 190,524,276 | 0 | 1 | null | 2019-06-22T11:49:13 | 2019-06-06T06:08:22 | C++ | UTF-8 | C++ | false | false | 11,058 | hpp | ////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2018 Laurent Gomila (laurent@sfml-dev.org)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_RENDERWINDOW_HPP
#define SFML_RENDERWINDOW_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics/Export.hpp>
#include <SFML/Graphics/RenderTarget.hpp>
#include <SFML/Graphics/Image.hpp>
#include <SFML/Window/Window.hpp>
#include <string>
namespace sf
{
////////////////////////////////////////////////////////////
/// \brief Window that can serve as a target for 2D drawing
///
////////////////////////////////////////////////////////////
class SFML_GRAPHICS_API RenderWindow : public Window, public RenderTarget
{
public:
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
/// This constructor doesn't actually create the window,
/// use the other constructors or call create() to do so.
///
////////////////////////////////////////////////////////////
RenderWindow();
////////////////////////////////////////////////////////////
/// \brief Construct a new window
///
/// This constructor creates the window with the size and pixel
/// depth defined in \a mode. An optional style can be passed to
/// customize the look and behavior of the window (borders,
/// title bar, resizable, closable, ...).
///
/// The fourth parameter is an optional structure specifying
/// advanced OpenGL context settings such as antialiasing,
/// depth-buffer bits, etc. You shouldn't care about these
/// parameters for a regular usage of the graphics module.
///
/// \param mode Video mode to use (defines the width, height and depth of the rendering area of the window)
/// \param title Title of the window
/// \param style %Window style, a bitwise OR combination of sf::Style enumerators
/// \param settings Additional settings for the underlying OpenGL context
///
////////////////////////////////////////////////////////////
RenderWindow(VideoMode mode, const String& title, Uint32 style = Style::Default, const ContextSettings& settings = ContextSettings());
////////////////////////////////////////////////////////////
/// \brief Construct the window from an existing control
///
/// Use this constructor if you want to create an SFML
/// rendering area into an already existing control.
///
/// The second parameter is an optional structure specifying
/// advanced OpenGL context settings such as antialiasing,
/// depth-buffer bits, etc. You shouldn't care about these
/// parameters for a regular usage of the graphics module.
///
/// \param handle Platform-specific handle of the control (\a HWND on
/// Windows, \a %Window on Linux/FreeBSD, \a NSWindow on OS X)
/// \param settings Additional settings for the underlying OpenGL context
///
////////////////////////////////////////////////////////////
explicit RenderWindow(WindowHandle handle, const ContextSettings& settings = ContextSettings());
////////////////////////////////////////////////////////////
/// \brief Destructor
///
/// Closes the window and frees all the resources attached to it.
///
////////////////////////////////////////////////////////////
virtual ~RenderWindow();
////////////////////////////////////////////////////////////
/// \brief Get the size of the rendering region of the window
///
/// The size doesn't include the titlebar and borders
/// of the window.
///
/// \return Size in pixels
///
////////////////////////////////////////////////////////////
virtual Vector2u getSize() const;
////////////////////////////////////////////////////////////
/// \brief Activate or deactivate the window as the current target
/// for OpenGL rendering
///
/// A window is active only on the current thread, if you want to
/// make it active on another thread you have to deactivate it
/// on the previous thread first if it was active.
/// Only one window can be active on a thread at a time, thus
/// the window previously active (if any) automatically gets deactivated.
/// This is not to be confused with requestFocus().
///
/// \param active True to activate, false to deactivate
///
/// \return True if operation was successful, false otherwise
///
////////////////////////////////////////////////////////////
bool setActive(bool active = true);
////////////////////////////////////////////////////////////
/// \brief Copy the current contents of the window to an image
///
/// \deprecated
/// Use a sf::Texture and its sf::Texture::update(const Window&)
/// function and copy its contents into an sf::Image instead.
/// \code
/// sf::Vector2u windowSize = window.getSize();
/// sf::Texture texture;
/// texture.create(windowSize.x, windowSize.y);
/// texture.update(window);
/// sf::Image screenshot = texture.copyToImage();
/// \endcode
///
/// This is a slow operation, whose main purpose is to make
/// screenshots of the application. If you want to update an
/// image with the contents of the window and then use it for
/// drawing, you should rather use a sf::Texture and its
/// update(Window&) function.
/// You can also draw things directly to a texture with the
/// sf::RenderTexture class.
///
/// \return Image containing the captured contents
///
////////////////////////////////////////////////////////////
SFML_DEPRECATED Image capture() const;
protected:
////////////////////////////////////////////////////////////
/// \brief Function called after the window has been created
///
/// This function is called so that derived classes can
/// perform their own specific initialization as soon as
/// the window is created.
///
////////////////////////////////////////////////////////////
virtual void onCreate();
////////////////////////////////////////////////////////////
/// \brief Function called after the window has been resized
///
/// This function is called so that derived classes can
/// perform custom actions when the size of the window changes.
///
////////////////////////////////////////////////////////////
virtual void onResize();
private:
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
unsigned int m_defaultFrameBuffer; ///< Framebuffer to bind when targeting this window
};
} // namespace sf
#endif // SFML_RENDERWINDOW_HPP
////////////////////////////////////////////////////////////
/// \class sf::RenderWindow
/// \ingroup graphics
///
/// sf::RenderWindow is the main class of the Graphics module.
/// It defines an OS window that can be painted using the other
/// classes of the graphics module.
///
/// sf::RenderWindow is derived from sf::Window, thus it inherits
/// all its features: events, window management, OpenGL rendering,
/// etc. See the documentation of sf::Window for a more complete
/// description of all these features, as well as code examples.
///
/// On top of that, sf::RenderWindow adds more features related to
/// 2D drawing with the graphics module (see its base class
/// sf::RenderTarget for more details).
/// Here is a typical rendering and event loop with a sf::RenderWindow:
///
/// \code
/// // Declare and create a new render-window
/// sf::RenderWindow window(sf::VideoMode(800, 600), "SFML window");
///
/// // Limit the framerate to 60 frames per second (this step is optional)
/// window.setFramerateLimit(60);
///
/// // The main loop - ends as soon as the window is closed
/// while (window.isOpen())
/// {
/// // Event processing
/// sf::Event event;
/// while (window.pollEvent(event))
/// {
/// // Request for closing the window
/// if (event.type == sf::Event::Closed)
/// window.close();
/// }
///
/// // Clear the whole window before rendering a new frame
/// window.clear();
///
/// // Draw some graphical entities
/// window.draw(sprite);
/// window.draw(circle);
/// window.draw(text);
///
/// // End the current frame and display its contents on screen
/// window.display();
/// }
/// \endcode
///
/// Like sf::Window, sf::RenderWindow is still able to render direct
/// OpenGL stuff. It is even possible to mix together OpenGL calls
/// and regular SFML drawing commands.
///
/// \code
/// // Create the render window
/// sf::RenderWindow window(sf::VideoMode(800, 600), "SFML OpenGL");
///
/// // Create a sprite and a text to display
/// sf::Sprite sprite;
/// sf::Text text;
/// ...
///
/// // Perform OpenGL initializations
/// glMatrixMode(GL_PROJECTION);
/// ...
///
/// // Start the rendering loop
/// while (window.isOpen())
/// {
/// // Process events
/// ...
///
/// // Draw a background sprite
/// window.pushGLStates();
/// window.draw(sprite);
/// window.popGLStates();
///
/// // Draw a 3D object using OpenGL
/// glBegin(GL_QUADS);
/// glVertex3f(...);
/// ...
/// glEnd();
///
/// // Draw text on top of the 3D object
/// window.pushGLStates();
/// window.draw(text);
/// window.popGLStates();
///
/// // Finally, display the rendered frame on screen
/// window.display();
/// }
/// \endcode
///
/// \see sf::Window, sf::RenderTarget, sf::RenderTexture, sf::View
///
////////////////////////////////////////////////////////////
| [
"xbolfa@fi.muni.cz"
] | xbolfa@fi.muni.cz |
499ea51f04539cd20589188a75631c3df43a725b | 239ab9a4d79116e5608f9d1dafeb2935ab750bb1 | /12-11-2013/Node.h | 615aed3ffe2c1b4b34697d5abbd3389e23c6b6bf | [] | no_license | ariste1a/cse167 | 314c68693792d8e5d32374aca6d1d0ca996c6d82 | 927124626d4a36a70cf70798c385536dc617ce19 | refs/heads/master | 2021-01-18T17:34:13.463478 | 2013-12-13T05:37:50 | 2013-12-13T05:37:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 224 | h | #pragma once
#include <vector>
#include "Matrix4.h"
class Node
{
protected:
Node* parent;
std::vector<Node*> children;
public:
Node();
~Node();
std::vector<Node*> getChildren();
virtual void draw(Matrix4) = 0;
};
| [
"derek.sh.c@gmail.com"
] | derek.sh.c@gmail.com |
f7bfe90b94f92f183b4fcd93311a6b022c3089ad | 50d6cd35f1a3c93bfe8477fd5ce9889e9c8d1e81 | /ABC/186/A.cpp | e834b3c97d952015982244ca8f03b9520db36ca6 | [] | no_license | Takiwa-i/Atcoder | d1e8fc7c4c81cdc9e68cf25b9b14dee26cb7f34b | 591d45a2c90422e9ee5c21c83505335e60961dfb | refs/heads/main | 2023-04-15T13:50:00.681542 | 2021-04-24T13:41:01 | 2021-04-24T13:41:01 | 315,191,621 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 120 | cpp | #include <iostream>
int main(void)
{
int n, w;
std::cin >> n >> w;
std::cout << n / w << std::endl;
return (0);
} | [
"xa84532@gmail.com"
] | xa84532@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.