hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ad6c2a49df9bc9bcb60ca1a02d36e2837e67b352 | 270 | cpp | C++ | tests/op/testdata/unknown_imports.cpp | PeaStew/contentos-go | dc6029153cda3969d4879f0af5e6c9407d33b031 | [
"MIT"
] | 50 | 2018-10-22T08:12:35.000Z | 2022-01-31T10:28:10.000Z | tests/op/testdata/unknown_imports.cpp | hassoon1986/contentos-go | 5810123c4b353c8733e3b6fd2bb11229bc17bf6b | [
"MIT"
] | 12 | 2019-01-04T03:06:33.000Z | 2022-01-05T09:42:17.000Z | tests/op/testdata/unknown_imports.cpp | hassoon1986/contentos-go | 5810123c4b353c8733e3b6fd2bb11229bc17bf6b | [
"MIT"
] | 19 | 2019-04-28T04:46:28.000Z | 2022-03-21T09:50:51.000Z | #include <cosiolib/contract.hpp>
extern "C" void unknown_func(uint32_t);
class unknown_imports : public cosio::contract {
public:
using cosio::contract::contract;
void hello(uint32_t n) {
unknown_func(n);
}
};
COSIO_ABI(unknown_imports, (hello))
| 18 | 48 | 0.696296 | PeaStew |
ad6c726c957eff3c2181f350da5bbc63fcd9f7de | 5,517 | cc | C++ | src/lib/storage/fs_management/cpp/mount.cc | PlugFox/fuchsia | 39afe5230d41628b3c736a6e384393df954968c8 | [
"BSD-2-Clause"
] | 2 | 2021-12-29T10:11:08.000Z | 2022-01-04T15:37:09.000Z | src/lib/storage/fs_management/cpp/mount.cc | PlugFox/fuchsia | 39afe5230d41628b3c736a6e384393df954968c8 | [
"BSD-2-Clause"
] | null | null | null | src/lib/storage/fs_management/cpp/mount.cc | PlugFox/fuchsia | 39afe5230d41628b3c736a6e384393df954968c8 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 2016 The Fuchsia 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 <errno.h>
#include <fcntl.h>
#include <fidl/fuchsia.hardware.block/cpp/wire.h>
#include <fidl/fuchsia.io.admin/cpp/wire.h>
#include <fidl/fuchsia.io/cpp/wire.h>
#include <lib/fdio/cpp/caller.h>
#include <lib/fdio/directory.h>
#include <lib/fdio/fd.h>
#include <lib/fdio/fdio.h>
#include <lib/fdio/limits.h>
#include <lib/fdio/namespace.h>
#include <lib/fdio/vfs.h>
#include <lib/zx/channel.h>
#include <string.h>
#include <unistd.h>
#include <zircon/compiler.h>
#include <zircon/device/block.h>
#include <zircon/device/vfs.h>
#include <zircon/processargs.h>
#include <zircon/syscalls.h>
#include <iostream>
#include <utility>
#include <fbl/algorithm.h>
#include <fbl/alloc_checker.h>
#include <fbl/unique_fd.h>
#include <fbl/vector.h>
#include <fs-management/mount.h>
#include <pretty/hexdump.h>
#include "src/lib/storage/vfs/cpp/fuchsia_vfs.h"
namespace fs_management {
namespace {
namespace fio = fuchsia_io;
using DirectoryAdmin = fuchsia_io_admin::DirectoryAdmin;
zx::status<std::pair<fidl::ClientEnd<DirectoryAdmin>, fidl::ClientEnd<DirectoryAdmin>>>
StartFilesystem(fbl::unique_fd device_fd, DiskFormat df, const MountOptions& options,
LaunchCallback cb, zx::channel crypt_client) {
// get the device handle from the device_fd
zx_status_t status;
zx::channel device;
status = fdio_get_service_handle(device_fd.release(), device.reset_and_get_address());
if (status != ZX_OK) {
return zx::error(status);
}
// convert mount options to init options
InitOptions init_options = {
.readonly = options.readonly,
.verbose_mount = options.verbose_mount,
.collect_metrics = options.collect_metrics,
.wait_until_ready = options.wait_until_ready,
.write_compression_algorithm = options.write_compression_algorithm,
// TODO(jfsulliv): This is currently only used in tests. Plumb through mount options if
// needed.
.write_compression_level = -1,
.cache_eviction_policy = options.cache_eviction_policy,
.fsck_after_every_transaction = options.fsck_after_every_transaction,
.sandbox_decompression = options.sandbox_decompression,
.callback = cb,
};
// launch the filesystem process
auto export_root_or = FsInit(std::move(device), df, init_options, std::move(crypt_client));
if (export_root_or.is_error()) {
return export_root_or.take_error();
}
// Extract the handle to the root of the filesystem from the export root. The POSIX flags will
// cause the writable and executable rights to be inherited (if present).
uint32_t flags = fio::wire::kOpenRightReadable | fio::wire::kOpenFlagPosixWritable |
fio::wire::kOpenFlagPosixExecutable;
if (options.admin)
flags |= fio::wire::kOpenRightAdmin;
auto root_or = FsRootHandle(fidl::UnownedClientEnd<DirectoryAdmin>(*export_root_or), flags);
if (root_or.is_error())
return root_or.take_error();
return zx::ok(std::make_pair(*std::move(export_root_or), *std::move(root_or)));
}
std::string StripTrailingSlash(const std::string& in) {
if (!in.empty() && in.back() == '/') {
return in.substr(0, in.length() - 1);
} else {
return in;
}
}
} // namespace
MountedFilesystem::~MountedFilesystem() {
if (export_root_.is_valid()) [[maybe_unused]]
auto result = UnmountImpl();
}
zx::status<> MountedFilesystem::UnmountImpl() {
zx_status_t status = ZX_OK;
if (!mount_path_.empty()) {
// Ignore errors unbinding, since we still want to continue and try and shut down the
// filesystem.
fdio_ns_t* ns;
status = fdio_ns_get_installed(&ns);
if (status == ZX_OK)
status = fdio_ns_unbind(ns, StripTrailingSlash(mount_path_).c_str());
}
auto result = Shutdown(export_root_);
return status != ZX_OK ? zx::error(status) : result;
}
__EXPORT
zx::status<> Shutdown(fidl::UnownedClientEnd<DirectoryAdmin> export_root) {
auto admin_or = fidl::CreateEndpoints<fuchsia_fs::Admin>();
if (admin_or.is_error())
return admin_or.take_error();
if (zx_status_t status =
fdio_service_connect_at(export_root.channel()->get(),
fidl::DiscoverableProtocolDefaultPath<fuchsia_fs::Admin> + 1,
admin_or->server.TakeChannel().release());
status != ZX_OK) {
return zx::error(status);
}
auto resp = fidl::WireCall(admin_or->client)->Shutdown();
if (resp.status() != ZX_OK)
return zx::error(resp.status());
return zx::ok();
}
__EXPORT
zx::status<MountedFilesystem> Mount(fbl::unique_fd device_fd, const char* mount_path, DiskFormat df,
const MountOptions& options, LaunchCallback cb) {
zx::channel crypt_client(options.crypt_client);
auto result = StartFilesystem(std::move(device_fd), df, options, cb, std::move(crypt_client));
if (result.is_error())
return result.take_error();
auto [export_root, data_root] = *std::move(result);
if (mount_path) {
fdio_ns_t* ns;
if (zx_status_t status = fdio_ns_get_installed(&ns); status != ZX_OK)
return zx::error(status);
if (zx_status_t status = fdio_ns_bind(ns, mount_path, data_root.TakeChannel().release());
status != ZX_OK)
return zx::error(status);
}
return zx::ok(MountedFilesystem(std::move(export_root), mount_path ? mount_path : ""));
}
} // namespace fs_management
| 33.846626 | 100 | 0.699474 | PlugFox |
ad6cffae77963f86606f1bf89512a8d731965953 | 8,869 | cpp | C++ | openstudiocore/src/model/AirGap.cpp | hellok-coder/OS-Testing | e9e18ad9e99f709a3f992601ed8d2e0662175af4 | [
"blessing"
] | 1 | 2019-11-12T02:07:03.000Z | 2019-11-12T02:07:03.000Z | openstudiocore/src/model/AirGap.cpp | hellok-coder/OS-Testing | e9e18ad9e99f709a3f992601ed8d2e0662175af4 | [
"blessing"
] | 1 | 2019-02-04T23:30:45.000Z | 2019-02-04T23:30:45.000Z | openstudiocore/src/model/AirGap.cpp | hellok-coder/OS-Testing | e9e18ad9e99f709a3f992601ed8d2e0662175af4 | [
"blessing"
] | null | null | null | /***********************************************************************************************************************
* OpenStudio(R), Copyright (c) 2008-2019, Alliance for Sustainable Energy, LLC, and other contributors. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
*
* (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
*
* (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products
* derived from this software without specific prior written permission from the respective party.
*
* (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works
* may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior
* written permission from Alliance for Sustainable Energy, LLC.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY 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(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED
* STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
***********************************************************************************************************************/
#include "AirGap.hpp"
#include "AirGap_Impl.hpp"
#include <utilities/idd/OS_Material_AirGap_FieldEnums.hxx>
#include <utilities/idd/IddEnums.hxx>
#include "../utilities/units/Unit.hpp"
#include "../utilities/core/Assert.hpp"
namespace openstudio {
namespace model {
namespace detail {
AirGap_Impl::AirGap_Impl(const IdfObject& idfObject,
Model_Impl* model,
bool keepHandle)
: OpaqueMaterial_Impl(idfObject,model,keepHandle)
{
OS_ASSERT(idfObject.iddObject().type() == AirGap::iddObjectType());
}
AirGap_Impl::AirGap_Impl(const openstudio::detail::WorkspaceObject_Impl& other,
Model_Impl* model,
bool keepHandle)
: OpaqueMaterial_Impl(other,model,keepHandle)
{
OS_ASSERT(other.iddObject().type() == AirGap::iddObjectType());
}
AirGap_Impl::AirGap_Impl(const AirGap_Impl& other,
Model_Impl* model,
bool keepHandle)
: OpaqueMaterial_Impl(other,model,keepHandle)
{}
double AirGap_Impl::thickness() const {
return 0.0;
}
double AirGap_Impl::thermalConductivity() const {
LOG_AND_THROW("Unable to convert thermal resistance to thermal conductivity for AirGap "
<< briefDescription() << ".");
return 0.0;
}
double AirGap_Impl::thermalConductance() const {
OS_ASSERT(thermalResistance());
return 1.0/thermalResistance();
}
double AirGap_Impl::thermalResistivity() const {
LOG_AND_THROW("Unable to convert thermal resistance to thermal resistivity for AirGap "
<< briefDescription() << ".");
return 0.0;
}
double AirGap_Impl::thermalResistance() const {
OptionalDouble od = getDouble(OS_Material_AirGapFields::ThermalResistance,true);
if (!od) {
LOG_AND_THROW("Thermal resistance is not set for AirGap " << briefDescription() << ".");
}
return *od;
}
double AirGap_Impl::thermalAbsorptance() const {
OptionalDouble od(0.0);
return *od;
}
OptionalDouble AirGap_Impl::thermalReflectance() const {
OptionalDouble od(0.0);
return od;
}
double AirGap_Impl::solarAbsorptance() const {
OptionalDouble od(0.0);
return *od;
}
OptionalDouble AirGap_Impl::solarReflectance() const {
OptionalDouble od(0.0);
return od;
}
double AirGap_Impl::visibleTransmittance() const {
return 1.0;
}
double AirGap_Impl::visibleAbsorptance() const {
OptionalDouble od(0.0);
return *od;
}
OptionalDouble AirGap_Impl::visibleReflectance() const {
OptionalDouble od(0.0);
return od;
}
const std::vector<std::string>& AirGap_Impl::outputVariableNames() const
{
static std::vector<std::string> result;
return result;
}
IddObjectType AirGap_Impl::iddObjectType() const {
return AirGap::iddObjectType();
}
bool AirGap_Impl::setThickness(double value) {
return false;
}
bool AirGap_Impl::setThermalConductivity(double value) {
return false;
}
bool AirGap_Impl::setThermalConductance(double value) {
return setThermalResistance(1.0/value);
}
bool AirGap_Impl::setThermalResistivity(double value) {
return false;
}
bool AirGap_Impl::setThermalResistance(double value) {
return setDouble(OS_Material_AirGapFields::ThermalResistance,value);
}
bool AirGap_Impl::setThermalAbsorptance(double value) {
return false;
}
bool AirGap_Impl::setThermalReflectance(OptionalDouble value) {
return false;
}
bool AirGap_Impl::setSolarAbsorptance(OptionalDouble value) {
return false;
}
bool AirGap_Impl::setSolarReflectance(OptionalDouble value) {
return false;
}
bool AirGap_Impl::setVisibleAbsorptance(OptionalDouble value) {
return false;
}
bool AirGap_Impl::setVisibleReflectance(OptionalDouble value) {
return false;
}
OSOptionalQuantity AirGap_Impl::getThermalResistance(bool returnIP) const {
double value = thermalResistance();
return getQuantityFromDouble(OS_Material_AirGapFields::ThermalResistance, value, returnIP);
}
bool AirGap_Impl::setThermalResistance(boost::optional<double> thermalResistance) {
bool result(false);
if (thermalResistance) {
result = setDouble(OS_Material_AirGapFields::ThermalResistance, thermalResistance.get());
}
else {
resetThermalResistance();
result = true;
}
return result;
}
bool AirGap_Impl::setThermalResistance(const OSOptionalQuantity& thermalResistance) {
bool result(false);
OptionalDouble value;
if (thermalResistance.isSet()) {
value = getDoubleFromQuantity(OS_Material_AirGapFields::ThermalResistance,thermalResistance.get());
if (value) {
result = setThermalResistance(value);
}
}
else {
result = setThermalResistance(value);
}
return result;
}
void AirGap_Impl::resetThermalResistance() {
bool result = setString(OS_Material_AirGapFields::ThermalResistance, "");
OS_ASSERT(result);
}
openstudio::OSOptionalQuantity AirGap_Impl::thermalResistance_SI() const {
return getThermalResistance(false);
}
openstudio::OSOptionalQuantity AirGap_Impl::thermalResistance_IP() const {
return getThermalResistance(true);
}
} // detail
AirGap::AirGap(const Model& model,
double thermalResistance)
: OpaqueMaterial(AirGap::iddObjectType(),model)
{
OS_ASSERT(getImpl<detail::AirGap_Impl>());
// TODO: Appropriately handle the following required object-list fields.
bool ok = true;
// ok = setHandle();
OS_ASSERT(ok);
ok = setThermalResistance(thermalResistance);
OS_ASSERT(ok);
}
IddObjectType AirGap::iddObjectType() {
return IddObjectType(IddObjectType::OS_Material_AirGap);
}
double AirGap::thermalResistance() const {
return getImpl<detail::AirGap_Impl>()->thermalResistance();
}
OSOptionalQuantity AirGap::getThermalResistance(bool returnIP) const {
return getImpl<detail::AirGap_Impl>()->getThermalResistance(returnIP);
}
bool AirGap::setThermalResistance(double thermalResistance) {
return getImpl<detail::AirGap_Impl>()->setThermalResistance(thermalResistance);
}
bool AirGap::setThermalResistance(const Quantity& thermalResistance) {
return getImpl<detail::AirGap_Impl>()->setThermalResistance(thermalResistance);
}
void AirGap::resetThermalResistance() {
getImpl<detail::AirGap_Impl>()->resetThermalResistance();
}
/// @cond
AirGap::AirGap(std::shared_ptr<detail::AirGap_Impl> impl)
: OpaqueMaterial(std::move(impl))
{}
/// @endcond
} // model
} // openstudio
| 31.78853 | 125 | 0.7038 | hellok-coder |
ad6f041656d64c087ad6bb0bfde7db987fc3e0f5 | 2,113 | cpp | C++ | blockchain/chain.cpp | p-shubham/resilientdb | 8e69c28e73ddebdfca8359479be4499c1cb5de41 | [
"MIT"
] | 1 | 2022-03-04T20:34:29.000Z | 2022-03-04T20:34:29.000Z | blockchain/chain.cpp | p-shubham/resilientdb | 8e69c28e73ddebdfca8359479be4499c1cb5de41 | [
"MIT"
] | null | null | null | blockchain/chain.cpp | p-shubham/resilientdb | 8e69c28e73ddebdfca8359479be4499c1cb5de41 | [
"MIT"
] | 1 | 2020-02-12T01:20:26.000Z | 2020-02-12T01:20:26.000Z | #include "chain.h"
/* Set the identifier for the block. */
void BChainStruct::set_txn_id(uint64_t tid)
{
txn_id = tid;
}
/* Get the identifier of this block. */
uint64_t BChainStruct::get_txn_id()
{
return txn_id;
}
/* Store the BatchRequests to this block. */
void BChainStruct::add_batch(BatchRequests *msg) {
char *buf = create_msg_buffer(msg);
Message *deepMsg = deep_copy_msg(buf, msg);
batch_info = (BatchRequests *)deepMsg;
delete_msg_buffer(buf);
}
/* Store the commit messages to this block. */
void BChainStruct::add_commit_proof(Message *msg) {
char *buf = create_msg_buffer(msg);
Message *deepMsg = deep_copy_msg(buf, msg);
commit_proof.push_back(deepMsg);
delete_msg_buffer(buf);
}
/* Release the contents of the block. */
void BChainStruct::release_data() {
Message::release_message(this->batch_info);
PBFTCommitMessage *cmsg;
while(this->commit_proof.size()>0)
{
cmsg = (PBFTCommitMessage *)this->commit_proof[0];
this->commit_proof.erase(this->commit_proof.begin());
Message::release_message(cmsg);
}
}
/****************************************/
/* Add a block to the chain. */
void BChain::add_block(TxnManager *txn) {
BChainStruct *blk = (BChainStruct *)mem_allocator.alloc(sizeof(BChainStruct));
new (blk) BChainStruct();
blk->set_txn_id(txn->get_txn_id());
blk->add_batch(txn->batchreq);
for(uint64_t i=0; i<txn->commit_msgs.size(); i++) {
blk->add_commit_proof(txn->commit_msgs[i]);
}
chainLock.lock();
bchain_map.push_back(blk);
chainLock.unlock();
}
/* Remove a block from the chain bbased on its identifier. */
void BChain::remove_block(uint64_t tid)
{
BChainStruct *blk;
bool found = false;
chainLock.lock();
for (uint64_t i = 0; i < bchain_map.size(); i++)
{
blk = bchain_map[i];
if (blk->get_txn_id() == tid)
{
bchain_map.erase(bchain_map.begin() + i);
found = true;
break;
}
}
chainLock.unlock();
if(found) {
blk->release_data();
mem_allocator.free(blk, sizeof(BChainStruct));
}
}
/*****************************************/
BChain *BlockChain;
std::mutex chainLock;
| 22.72043 | 79 | 0.661619 | p-shubham |
ad70dad8450ff3bdf94943f8227f4ad509e43549 | 311 | cpp | C++ | Scripts/367.cpp | zzz0906/LeetCode | cd0b4a4fd03d0dff585c9ef349984eba1922ece0 | [
"MIT"
] | 17 | 2018-08-23T08:53:56.000Z | 2021-04-17T00:06:13.000Z | Scripts/367.cpp | zzz0906/LeetCode | cd0b4a4fd03d0dff585c9ef349984eba1922ece0 | [
"MIT"
] | null | null | null | Scripts/367.cpp | zzz0906/LeetCode | cd0b4a4fd03d0dff585c9ef349984eba1922ece0 | [
"MIT"
] | null | null | null | class Solution {
public:
bool isPerfectSquare(int num) {
for (int i = 0; i < num; i++){
if ((long long)i*i > (long long)num){
return false;
}
if (i*i == num){
return true;
}
}
return true;
}
}; | 22.214286 | 49 | 0.379421 | zzz0906 |
ad70fb393035ed63f8a45bd219bceb896d6cfb10 | 2,263 | hpp | C++ | contracts/libraries/include/gxclib/token.hpp | Game-X-Coin/gxc-contracts-v1 | cc5cc59cab0422238a44d2c4d909a31200817a35 | [
"MIT"
] | 1 | 2019-07-01T01:41:02.000Z | 2019-07-01T01:41:02.000Z | contracts/libraries/include/gxclib/token.hpp | Game-X-Coin/gxc-contracts-v1 | cc5cc59cab0422238a44d2c4d909a31200817a35 | [
"MIT"
] | null | null | null | contracts/libraries/include/gxclib/token.hpp | Game-X-Coin/gxc-contracts-v1 | cc5cc59cab0422238a44d2c4d909a31200817a35 | [
"MIT"
] | null | null | null | /**
* @file
* @copyright defined in gxc/LICENSE
*/
#pragma once
#include <eosio/name.hpp>
#include <eosio/asset.hpp>
#include <eosio/action.hpp>
#include <eoslib/crypto.hpp>
#include <eoslib/symbol.hpp>
#include <cmath>
namespace gxc {
using namespace eosio;
using namespace eosio::internal_use_do_not_use;
constexpr name token_account = "gxc.token"_n;
inline double get_float_amount(asset quantity) {
return quantity.amount / (double)pow(10, quantity.symbol.precision());
}
asset get_supply(name issuer, symbol_code sym_code) {
asset supply;
db_get_i64(db_find_i64(token_account.value, issuer.value, "stat"_n.value, sym_code.raw()),
reinterpret_cast<void*>(&supply), sizeof(asset));
return supply;
}
asset get_balance(name owner, name issuer, symbol_code sym_code) {
asset balance;
auto esc = extended_symbol_code(sym_code, issuer);
db_get_i64(db_find_i64(token_account.value, issuer.value, "accounts"_n.value,
#ifdef TARGET_TESTNET
fasthash64(reinterpret_cast<const char*>(&esc), sizeof(uint128_t))),
#else
xxh64(reinterpret_cast<const char*>(&esc), sizeof(uint128_t))),
#endif
reinterpret_cast<void*>(&balance), sizeof(asset));
return balance;
}
struct token_contract_mock {
token_contract_mock(name auth) {
auths.emplace_back(permission_level(auth, active_permission));
}
token_contract_mock& with(name auth) {
auths.emplace_back(permission_level(auth, active_permission));
return *this;
}
using key_value = std::pair<std::string, std::vector<int8_t>>;
void mint(extended_asset value, std::vector<key_value> opts) {
action_wrapper<"mint"_n, &token_contract_mock::mint>(std::move(name(token_account)), auths)
.send(value, opts);
}
void transfer(name from, name to, extended_asset value, std::string memo) {
action_wrapper<"transfer"_n, &token_contract_mock::transfer>(std::move(name(token_account)), auths)
.send(from, to, value, memo);
}
void burn(extended_asset value, std::string memo) {
action_wrapper<"burn"_n, &token_contract_mock::burn>(std::move(name(token_account)), auths)
.send(value, memo);
}
std::vector<permission_level> auths;
};
}
| 29.38961 | 105 | 0.699072 | Game-X-Coin |
ad7281476dc7e4bb30b4e2a95ff1a68dcbc9978d | 1,699 | hh | C++ | src/elle/reactor/network/udp-server-socket.hh | infinitio/elle | d9bec976a1217137436db53db39cda99e7024ce4 | [
"Apache-2.0"
] | null | null | null | src/elle/reactor/network/udp-server-socket.hh | infinitio/elle | d9bec976a1217137436db53db39cda99e7024ce4 | [
"Apache-2.0"
] | null | null | null | src/elle/reactor/network/udp-server-socket.hh | infinitio/elle | d9bec976a1217137436db53db39cda99e7024ce4 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <elle/reactor/network/fwd.hh>
#include <elle/reactor/network/socket.hh>
#include <elle/reactor/signal.hh>
namespace elle
{
namespace reactor
{
namespace network
{
/// XXX[doc].
class UDPServerSocket
: public Socket
{
/*---------.
| Typedefs |
`---------*/
public:
using Super = Socket;
using EndPoint = boost::asio::ip::udp::endpoint;
/*-------------.
| Construction |
`-------------*/
public:
UDPServerSocket(Scheduler& sched,
UDPServer* server,
EndPoint const& peer);
virtual
~UDPServerSocket();
/*-----.
| Read |
`-----*/
public:
void
read(Buffer buffer,
DurationOpt timeout = DurationOpt(),
int* bytes_read = nullptr) override;
Size
read_some(Buffer buffer,
DurationOpt timeout = DurationOpt(),
int* bytes_read = nullptr) override;
private:
friend class UDPServer;
UDPServer* _server;
EndPoint _peer;
Byte* _read_buffer;
Size _read_buffer_capacity;
Size _read_buffer_size;
Signal _read_ready;
/*------.
| Write |
`------*/
public:
virtual
void
write(Buffer buffer);
using Super::write;
/*----------------.
| Pretty printing |
`----------------*/
public:
void
print(std::ostream& s) const override;
};
}
}
}
| 22.959459 | 58 | 0.446733 | infinitio |
ad81380094a28e623c896422d6ae66359fc8df78 | 6,836 | cpp | C++ | tests/cxx/isce3/geometry/geometry/geometry.cpp | piyushrpt/isce3 | 1741af321470cb5939693459765d11a19c5c6fc2 | [
"Apache-2.0"
] | null | null | null | tests/cxx/isce3/geometry/geometry/geometry.cpp | piyushrpt/isce3 | 1741af321470cb5939693459765d11a19c5c6fc2 | [
"Apache-2.0"
] | null | null | null | tests/cxx/isce3/geometry/geometry/geometry.cpp | piyushrpt/isce3 | 1741af321470cb5939693459765d11a19c5c6fc2 | [
"Apache-2.0"
] | null | null | null | //-*- C++ -*-
//-*- coding: utf-8 -*-
//
// Author: Bryan Riel
// Copyright 2018
//
#include <iostream>
#include <cstdio>
#include <string>
#include <sstream>
#include <fstream>
#include <gtest/gtest.h>
// isce3::io
#include <isce3/io/IH5.h>
// isce3::core
#include <isce3/core/Constants.h>
#include <isce3/core/DateTime.h>
#include <isce3/core/Ellipsoid.h>
#include <isce3/core/Orbit.h>
#include <isce3/core/Serialization.h>
#include <isce3/core/TimeDelta.h>
// isce3::product
#include <isce3/product/Product.h>
// isce3::geometry
#include <isce3/geometry/DEMInterpolator.h>
#include <isce3/geometry/geometry.h>
// Declaration for utility function to read test data
void loadTestData(std::vector<std::string> & aztimes, std::vector<double> & ranges,
std::vector<double> & heights,
std::vector<double> & ref_data, std::vector<double> & ref_zerodop);
struct GeometryTest : public ::testing::Test {
// isce3::core objects
isce3::core::Ellipsoid ellipsoid;
isce3::core::LUT2d<double> doppler;
isce3::core::Orbit orbit;
// isce3::product objects
isce3::product::ProcessingInformation proc;
isce3::product::Swath swath;
isce3::core::LookSide lookSide;
// Constructor
protected:
GeometryTest() {
// Open the HDF5 product
std::string h5file(TESTDATA_DIR "envisat.h5");
isce3::io::IH5File file(h5file);
// Instantiate a Product
isce3::product::Product product(file);
// Extract core and product objects
orbit = product.metadata().orbit();
proc = product.metadata().procInfo();
swath = product.swath('A');
doppler = proc.dopplerCentroid('A');
lookSide = product.lookSide();
ellipsoid.a(isce3::core::EarthSemiMajorAxis);
ellipsoid.e2(isce3::core::EarthEccentricitySquared);
// For this test, use biquintic interpolation for Doppler LUT
doppler.interpMethod(isce3::core::BIQUINTIC_METHOD);
}
};
TEST_F(GeometryTest, RdrToGeoWithOrbit) {
// Load test data
std::vector<std::string> aztimes;
std::vector<double> ranges, heights, ref_data, ref_zerodop;
loadTestData(aztimes, ranges, heights, ref_data, ref_zerodop);
// Loop over test data
const double degrees = 180.0 / M_PI;
for (size_t i = 0; i < aztimes.size(); ++i) {
// Make azimuth time in seconds
isce3::core::DateTime azDate = aztimes[i];
const double azTime = (azDate - orbit.referenceEpoch()).getTotalSeconds();
// Evaluate Doppler
const double dopval = doppler.eval(azTime, ranges[i]);
// Make constant DEM interpolator set to input height
isce3::geometry::DEMInterpolator dem(heights[i]);
// Initialize guess
isce3::core::cartesian_t targetLLH = {0.0, 0.0, heights[i]};
// Run rdr2geo
int stat = isce3::geometry::rdr2geo(azTime, ranges[i], dopval,
orbit, ellipsoid, dem, targetLLH, swath.processedWavelength(), lookSide,
1.0e-8, 25, 15);
// Check
ASSERT_EQ(stat, 1);
ASSERT_NEAR(degrees * targetLLH[0], ref_data[3*i], 1.0e-8);
ASSERT_NEAR(degrees * targetLLH[1], ref_data[3*i+1], 1.0e-8);
ASSERT_NEAR(targetLLH[2], ref_data[3*i+2], 1.0e-8);
// Run again with zero doppler
stat = isce3::geometry::rdr2geo(azTime, ranges[i], 0.0,
orbit, ellipsoid, dem, targetLLH, swath.processedWavelength(), lookSide,
1.0e-8, 25, 15);
// Check
ASSERT_EQ(stat, 1);
ASSERT_NEAR(degrees * targetLLH[0], ref_zerodop[3*i], 1.0e-8);
ASSERT_NEAR(degrees * targetLLH[1], ref_zerodop[3*i+1], 1.0e-8);
ASSERT_NEAR(targetLLH[2], ref_zerodop[3*i+2], 1.0e-8);
}
}
TEST_F(GeometryTest, GeoToRdr) {
// Make a test LLH
const double radians = M_PI / 180.0;
isce3::core::cartesian_t llh = {
-115.72466801139711 * radians,
34.65846532785868 * radians,
1772.0
};
// Run geo2rdr
double aztime, slantRange;
int stat = isce3::geometry::geo2rdr(llh, ellipsoid, orbit, doppler,
aztime, slantRange, swath.processedWavelength(), lookSide,
1.0e-10, 50, 10.0);
// Convert azimuth time to a date
isce3::core::DateTime azdate = orbit.referenceEpoch() + aztime;
ASSERT_EQ(stat, 1);
ASSERT_EQ(azdate.isoformat(), "2003-02-26T17:55:33.993088889");
ASSERT_NEAR(slantRange, 830450.1859446081, 1.0e-6);
// Run geo2rdr again with zero doppler
isce3::core::LUT2d<double> zeroDoppler;
stat = isce3::geometry::geo2rdr(llh, ellipsoid, orbit, zeroDoppler,
aztime, slantRange, swath.processedWavelength(), lookSide,
1.0e-10, 50, 10.0);
azdate = orbit.referenceEpoch() + aztime;
ASSERT_EQ(stat, 1);
ASSERT_EQ(azdate.isoformat(), "2003-02-26T17:55:34.122893704");
ASSERT_NEAR(slantRange, 830449.6727720434, 1.0e-6);
}
int main(int argc, char * argv[]) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
// Load test data
void loadTestData(std::vector<std::string> & aztimes, std::vector<double> & ranges,
std::vector<double> & heights,
std::vector<double> & ref_data, std::vector<double> & ref_zerodop) {
// Load azimuth times and slant ranges
std::ifstream ifid("input_data.txt");
std::string line;
while (std::getline(ifid, line)) {
std::stringstream stream;
std::string aztime;
double range, h;
stream << line;
stream >> aztime >> range >> h;
aztimes.push_back(aztime);
ranges.push_back(range);
heights.push_back(h);
}
ifid.close();
// Load test data for non-zero doppler
ifid = std::ifstream("output_data.txt");
while (std::getline(ifid, line)) {
std::stringstream stream;
double lat, lon, h;
stream << line;
stream >> lat >> lon >> h;
ref_data.push_back(lon);
ref_data.push_back(lat);
ref_data.push_back(h);
}
ifid.close();
// Load test data for zero doppler
ifid = std::ifstream("output_data_zerodop.txt");
while (std::getline(ifid, line)) {
std::stringstream stream;
double lat, lon, h;
stream << line;
stream >> lat >> lon >> h;
ref_zerodop.push_back(lon);
ref_zerodop.push_back(lat);
ref_zerodop.push_back(h);
}
ifid.close();
// Check sizes
if (aztimes.size() != (ref_data.size() / 3)) {
std::cerr << "Incompatible data sizes" << std::endl;
exit(1);
}
if (aztimes.size() != (ref_zerodop.size() / 3)) {
std::cerr << "Incompatible data sizes" << std::endl;
exit(1);
}
}
// end of file
| 30.654709 | 86 | 0.612785 | piyushrpt |
ad868b84660b86af4fffb6556b419270e2cee7e1 | 1,046 | hpp | C++ | src/frontend/decode/definition/data_processing.hpp | StrikerX3/lunatic | aa2bdd45aab108d4943ec39a923d4256e2eb978e | [
"BSD-3-Clause"
] | 61 | 2020-09-20T16:03:31.000Z | 2022-02-27T18:52:51.000Z | src/frontend/decode/definition/data_processing.hpp | StrikerX3/lunatic | aa2bdd45aab108d4943ec39a923d4256e2eb978e | [
"BSD-3-Clause"
] | 14 | 2021-04-28T21:08:03.000Z | 2022-01-13T09:02:58.000Z | src/frontend/decode/definition/data_processing.hpp | StrikerX3/lunatic | aa2bdd45aab108d4943ec39a923d4256e2eb978e | [
"BSD-3-Clause"
] | 1 | 2021-06-15T02:06:13.000Z | 2021-06-15T02:06:13.000Z | /*
* Copyright (C) 2021 fleroviux. All rights reserved.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#pragma once
#include "common.hpp"
namespace lunatic {
namespace frontend {
struct ARMDataProcessing {
Condition condition;
enum class Opcode {
AND = 0,
EOR = 1,
SUB = 2,
RSB = 3,
ADD = 4,
ADC = 5,
SBC = 6,
RSC = 7,
TST = 8,
TEQ = 9,
CMP = 10,
CMN = 11,
ORR = 12,
MOV = 13,
BIC = 14,
MVN = 15
} opcode;
bool immediate;
bool set_flags;
GPR reg_dst;
GPR reg_op1;
/// Valid if immediate = false
struct {
GPR reg;
struct {
Shift type;
bool immediate;
GPR amount_reg;
uint amount_imm;
} shift;
} op2_reg;
/// Valid if immediate = true
struct {
u32 value;
uint shift;
} op2_imm;
bool thumb_load_address = false;
};
} // namespace lunatic::frontend
} // namespace lunatic
| 16.092308 | 74 | 0.545889 | StrikerX3 |
ad86e89debcbbc0086e927506384307200af081b | 9,378 | cpp | C++ | sourcecode/Runtime/EnsureDynamicMethodInstruction.cpp | fabianmuehlboeck/monnom | 609b307d9fa9e6641443f34dbcc0b035b34d3044 | [
"BSD-3-Clause",
"MIT"
] | 2 | 2021-11-16T20:58:02.000Z | 2021-12-05T18:15:41.000Z | sourcecode/Runtime/EnsureDynamicMethodInstruction.cpp | fabianmuehlboeck/monnom | 609b307d9fa9e6641443f34dbcc0b035b34d3044 | [
"BSD-3-Clause",
"MIT"
] | null | null | null | sourcecode/Runtime/EnsureDynamicMethodInstruction.cpp | fabianmuehlboeck/monnom | 609b307d9fa9e6641443f34dbcc0b035b34d3044 | [
"BSD-3-Clause",
"MIT"
] | null | null | null | #include "EnsureDynamicMethodInstruction.h"
#include <stdio.h>
#include "NomConstants.h"
#include "RefValueHeader.h"
#include "CompileEnv.h"
#include "RTInterface.h"
#include "RTVTable.h"
#include "NomNameRepository.h"
#include "CompileHelpers.h"
#include "RTOutput.h"
#include "CallingConvConf.h"
#include "IntClass.h"
#include "FloatClass.h"
#include "BoolClass.h"
#include "NomMethod.h"
#include "NomMethodTableEntry.h"
#include "llvm/ADT/SmallSet.h"
#include "CastStats.h"
#include "RTLambda.h"
#include "LambdaHeader.h"
#include "IMT.h"
#include "Metadata.h"
using namespace std;
using namespace llvm;
namespace Nom
{
namespace Runtime
{
EnsureDynamicMethodInstruction::EnsureDynamicMethodInstruction(ConstantID methodNameID, RegIndex receiver) : NomInstruction(OpCode::EnsureDynamicMethod), MethodName(methodNameID), Receiver(receiver)
{
}
EnsureDynamicMethodInstruction::~EnsureDynamicMethodInstruction()
{
}
llvm::Value* EnsureDynamicMethodInstruction::GenerateGetBestInvokeDispatcherDyn(NomBuilder& builder, NomValue receiver)
{
BasicBlock* origBlock = builder->GetInsertBlock();
Function* fun = origBlock->getParent();
BasicBlock* refValueBlock = nullptr, * packedIntBlock = nullptr, * packedFloatBlock = nullptr, * primitiveIntBlock = nullptr, * primitiveFloatBlock = nullptr, * primitiveBoolBlock = nullptr;
int mergeBlocks = RefValueHeader::GenerateRefOrPrimitiveValueSwitch(builder, receiver, &refValueBlock, &packedIntBlock, &packedFloatBlock, false, &primitiveIntBlock, nullptr, &primitiveFloatBlock, nullptr, &primitiveBoolBlock, nullptr);
BasicBlock* mergeBlock = BasicBlock::Create(LLVMCONTEXT, "ddLookupMerge", fun);
PHINode* mergePHI = nullptr;
Value* returnVal = nullptr;
if (mergeBlocks == 0)
{
throw new std::exception();
}
if (mergeBlocks > 1)
{
builder->SetInsertPoint(mergeBlock);
mergePHI = builder->CreatePHI(GetDynamicDispatcherLookupResultType(), mergeBlocks);
returnVal = mergePHI;
}
if (refValueBlock != nullptr)
{
builder->SetInsertPoint(refValueBlock);
BasicBlock* packPairBlock = BasicBlock::Create(LLVMCONTEXT, "packRawInvokeDispatcherPair", fun);
BasicBlock* errorBlock = RTOutput_Fail::GenerateFailOutputBlock(builder, "Given value is not invokable!");
auto vtable = RefValueHeader::GenerateReadVTablePointer(builder, receiver);
auto hasRawInvoke = RTVTable::GenerateHasRawInvoke(builder, vtable);
builder->CreateIntrinsic(Intrinsic::expect, { inttype(1) }, { hasRawInvoke, MakeUInt(1,1) });
builder->CreateCondBr(hasRawInvoke, packPairBlock, errorBlock, GetLikelyFirstBranchMetadata());
builder->SetInsertPoint(packPairBlock);
auto rawInvokePtr = builder->CreatePointerCast(RefValueHeader::GenerateReadRawInvoke(builder, receiver), GetIMTFunctionType()->getPointerTo());
auto partialPair = builder->CreateInsertValue(UndefValue::get(GetDynamicDispatcherLookupResultType()), rawInvokePtr, { 0 });
auto returnVal2 = builder->CreateInsertValue(partialPair, builder->CreatePointerCast(receiver, POINTERTYPE), { 1 });
if (mergePHI != nullptr)
{
mergePHI->addIncoming(returnVal2, builder->GetInsertBlock());
}
else
{
returnVal = returnVal2;
}
builder->CreateBr(mergeBlock);
}
if (packedIntBlock != nullptr)
{
RTOutput_Fail::MakeBlockFailOutputBlock(builder, "Cannot invoke integer values!", packedIntBlock);
}
if (packedFloatBlock != nullptr)
{
RTOutput_Fail::MakeBlockFailOutputBlock(builder, "Cannot invoke float values!", packedFloatBlock);
}
if (primitiveIntBlock != nullptr)
{
RTOutput_Fail::MakeBlockFailOutputBlock(builder, "Cannot invoke integer values!", primitiveIntBlock);
}
if (primitiveFloatBlock != nullptr)
{
RTOutput_Fail::MakeBlockFailOutputBlock(builder, "Cannot invoke float values!", primitiveFloatBlock);
}
if (primitiveBoolBlock != nullptr)
{
RTOutput_Fail::MakeBlockFailOutputBlock(builder, "Cannot invoke boolean values!", primitiveBoolBlock);
}
builder->SetInsertPoint(mergeBlock);
return returnVal;
}
void EnsureDynamicMethodInstruction::Compile(NomBuilder& builder, CompileEnv* env, int lineno)
{
NomValue receiver = (*env)[Receiver];
BasicBlock* origBlock = builder->GetInsertBlock();
Function* fun = origBlock->getParent();
auto methodName = NomConstants::GetString(MethodName)->GetText()->ToStdString();
if (methodName.empty())
{
if (NomCastStats)
{
builder->CreateCall(GetIncDynamicInvokes(*builder->GetInsertBlock()->getParent()->getParent()), {});
}
env->PushDispatchPair(GenerateGetBestInvokeDispatcherDyn(builder, receiver));
return;
}
if (NomCastStats)
{
builder->CreateCall(GetIncDynamicMethodCalls(*builder->GetInsertBlock()->getParent()->getParent()), {});
}
BasicBlock* refValueBlock = nullptr, * packedIntBlock = nullptr, * packedFloatBlock = nullptr, * primitiveIntBlock = nullptr, * primitiveFloatBlock = nullptr, * primitiveBoolBlock = nullptr;
Value* primitiveIntVal, * primitiveFloatVal, * primitiveBoolVal;
int mergeBlocks = RefValueHeader::GenerateRefOrPrimitiveValueSwitch(builder, receiver, &refValueBlock, &packedIntBlock, &packedFloatBlock, false, &primitiveIntBlock, &primitiveIntVal, &primitiveFloatBlock, &primitiveFloatVal, &primitiveBoolBlock, &primitiveBoolVal);
BasicBlock* mergeBlock = BasicBlock::Create(LLVMCONTEXT, "ddLookupMerge", fun);
PHINode* mergePHI = nullptr;
Value* returnVal = nullptr;
if (mergeBlocks == 0)
{
throw new std::exception();
}
if (mergeBlocks > 1)
{
builder->SetInsertPoint(mergeBlock);
mergePHI = builder->CreatePHI(GetDynamicDispatcherLookupResultType(), mergeBlocks);
returnVal = mergePHI;
}
if (refValueBlock != nullptr)
{
builder->SetInsertPoint(refValueBlock);
auto vtable = RefValueHeader::GenerateReadVTablePointer(builder, receiver);
auto returnVal2 = RTVTable::GenerateFindDynamicDispatcherPair(builder, receiver, vtable, NomNameRepository::Instance().GetNameID(methodName));
if (mergePHI != nullptr)
{
mergePHI->addIncoming(returnVal2, builder->GetInsertBlock());
}
else
{
returnVal = returnVal2;
}
builder->CreateBr(mergeBlock);
}
if (packedIntBlock != nullptr)
{
builder->SetInsertPoint(packedIntBlock);
auto intDispatcher = RTVTable::GenerateFindDynamicDispatcherPair(builder, receiver, NomIntClass::GetInstance()->GetLLVMElement(*env->Module), NomNameRepository::Instance().GetNameID(methodName));
if (mergePHI != nullptr)
{
mergePHI->addIncoming(intDispatcher, builder->GetInsertBlock());
}
else
{
returnVal = intDispatcher;
}
builder->CreateBr(mergeBlock);
}
if (packedFloatBlock != nullptr)
{
builder->SetInsertPoint(packedFloatBlock);
auto floatDispatcher = RTVTable::GenerateFindDynamicDispatcherPair(builder, receiver, NomFloatClass::GetInstance()->GetLLVMElement(*env->Module), NomNameRepository::Instance().GetNameID(methodName));
if (mergePHI != nullptr)
{
mergePHI->addIncoming(floatDispatcher, builder->GetInsertBlock());
}
else
{
returnVal = floatDispatcher;
}
builder->CreateBr(mergeBlock);
}
if (primitiveIntBlock != nullptr)
{
builder->SetInsertPoint(primitiveIntBlock);
auto packedInt = PackInt(builder, receiver);
auto intDispatcher = RTVTable::GenerateFindDynamicDispatcherPair(builder, packedInt, NomIntClass::GetInstance()->GetLLVMElement(*env->Module), NomNameRepository::Instance().GetNameID(methodName));
if (mergePHI != nullptr)
{
mergePHI->addIncoming(intDispatcher, builder->GetInsertBlock());
}
else
{
returnVal = intDispatcher;
}
builder->CreateBr(mergeBlock);
}
if (primitiveFloatBlock != nullptr)
{
builder->SetInsertPoint(primitiveFloatBlock);
auto packedFloat = PackFloat(builder, receiver);
auto floatDispatcher = RTVTable::GenerateFindDynamicDispatcherPair(builder, packedFloat, NomFloatClass::GetInstance()->GetLLVMElement(*env->Module), NomNameRepository::Instance().GetNameID(methodName));
if (mergePHI != nullptr)
{
mergePHI->addIncoming(floatDispatcher, builder->GetInsertBlock());
}
else
{
returnVal = floatDispatcher;
}
builder->CreateBr(mergeBlock);
}
if (primitiveBoolBlock != nullptr)
{
builder->SetInsertPoint(primitiveBoolBlock);
auto packedBool = PackBool(builder, receiver);
auto boolDispatcher = RTVTable::GenerateFindDynamicDispatcherPair(builder, packedBool, NomBoolClass::GetInstance()->GetLLVMElement(*env->Module), NomNameRepository::Instance().GetNameID(methodName));
if (mergePHI != nullptr)
{
mergePHI->addIncoming(boolDispatcher, builder->GetInsertBlock());
}
else
{
returnVal = boolDispatcher;
}
builder->CreateBr(mergeBlock);
}
builder->SetInsertPoint(mergeBlock);
env->PushDispatchPair(returnVal);
}
void EnsureDynamicMethodInstruction::Print(bool resolve)
{
cout << "EnsureDynamicMethod ";
NomConstants::PrintConstant(MethodName, resolve);
cout << "@" << Receiver;
cout << "\n";
}
void EnsureDynamicMethodInstruction::FillConstantDependencies(NOM_CONSTANT_DEPENCENCY_CONTAINER& result)
{
result.push_back(MethodName);
}
}
} | 35.657795 | 269 | 0.72862 | fabianmuehlboeck |
ad89ce2cde6dff49087c80bc904dada098d8a96c | 3,538 | cpp | C++ | src/acd2d_concavity.cpp | yycho0108/acd2d | 2fe3fb337c49b7b1b635a46253f2a3fba9efb5e9 | [
"MIT"
] | null | null | null | src/acd2d_concavity.cpp | yycho0108/acd2d | 2fe3fb337c49b7b1b635a46253f2a3fba9efb5e9 | [
"MIT"
] | null | null | null | src/acd2d_concavity.cpp | yycho0108/acd2d | 2fe3fb337c49b7b1b635a46253f2a3fba9efb5e9 | [
"MIT"
] | null | null | null | //------------------------------------------------------------------------------
// Copyright 2007-2012 by Jyh-Ming Lien and George Mason University
// See the file "LICENSE" for more information
//------------------------------------------------------------------------------
#include "acd2d_concavity.h"
#include "acd2d_util.h"
#include "acd2d_edge_visibility.h"
#include <iostream>
using namespace std;
namespace acd2d
{
///////////////////////////////////////////////////////////////////////////////
cd_vertex * StraightLineMeasurement::
findMaxNotch(cd_vertex * v1, cd_vertex * v2)
{
cd_vertex * r=NULL;
cd_vertex * ptr=v1->getNext();
Vector2d v=(v2->getPos()-v1->getPos());
Vector2d n(-v[1],v[0]);
double norm=n.norm();
if( norm!=0 ) n=n/norm;
do{
double c;
if( norm!=0) c=findDist(n,v1->getPos(),ptr->getPos());
else c=(v1->getPos()-ptr->getPos()).norm();
ptr->setConcavity(c);
if( r==NULL ) r=ptr;
else if( r->getConcavity()<c ){ r=ptr; }
ptr=ptr->getNext();
}while( ptr!=v2 );
v1->setConcavity(0);
v2->setConcavity(0);
return r;
}
double StraightLineMeasurement::
findDist(const Vector2d& n, const Point2d& p, const Point2d& qp)
{
return (qp-p)*n;
}
///////////////////////////////////////////////////////////////////////////////
cd_vertex * ShortestPathMeasurement::
findMaxNotch(cd_vertex * v1, cd_vertex * v2)
{
shortest_path_to_edge(v1,v2);
cd_vertex * ptr=v1->getNext();
cd_vertex * max_v=NULL;
double max_c=-1e20;
do{
if( max_c < ptr->getConcavity() ){
max_c=ptr->getConcavity();
max_v=ptr;
}
ptr=ptr->getNext();
}while( ptr!=v2 );
return max_v;
}
///////////////////////////////////////////////////////////////////////////////
cd_vertex *
HybridMeasurement1::
findMaxNotch(cd_vertex * v1, cd_vertex * v2)
{
StraightLineMeasurement sl;
if( !NeedSP(v1,v2) )
return sl.findMaxNotch(v1,v2);
ShortestPathMeasurement sp;
return sp.findMaxNotch(v1,v2);
}
//check if
bool HybridMeasurement1::NeedSP(cd_vertex * v1, cd_vertex * v2)
{
Vector2d bn=computeNormal(v2->getPos()-v1->getPos());
cd_vertex * v=v1;
do{
if( v->getNormal()*bn<0 ) return true;
v=v->getNext();
}while(v!=v2);
return false;
}
///////////////////////////////////////////////////////////////////////////////
cd_vertex *
HybridMeasurement2::
findMaxNotch(cd_vertex * v1, cd_vertex * v2)
{
if( tau==-1 ){
cerr<<"HybridMeasurement 2 Error : Tau is not set"<<endl;
return NULL;
}
StraightLineMeasurement sl;
cd_vertex * r=sl.findMaxNotch(v1,v2);
if( r->getConcavity()>tau ) return r;
if( !NeedSP(v1,v2) ) return r;
ShortestPathMeasurement sp;
return sp.findMaxNotch(v1,v2);
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
//
// The measurement factory
//
///////////////////////////////////////////////////////////////////////////////
IConcavityMeasure * ConcavityMeasureFac::createMeasure( const string& name )
{
if( name=="straightline" || name=="sl" || name=="SL" )
return new StraightLineMeasurement();
else if( name=="shortestpath" || name=="sp" || name=="SP" )
return new ShortestPathMeasurement();
else if( name=="hybrid1" )
return new HybridMeasurement1();
else if( name=="hybrid2" )
return new HybridMeasurement2();
else{
cerr<<"unknow concavity measurement name : "<<name<<endl;
return NULL;
}
}
} //namespace acd2d
| 26.80303 | 80 | 0.52035 | yycho0108 |
ad89ce8726d1e335d53394bf745b277e22bc1fa0 | 26,897 | cxx | C++ | MUON/MUONmapping/AliMpTriggerReader.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 52 | 2016-12-11T13:04:01.000Z | 2022-03-11T11:49:35.000Z | MUON/MUONmapping/AliMpTriggerReader.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 1,388 | 2016-11-01T10:27:36.000Z | 2022-03-30T15:26:09.000Z | MUON/MUONmapping/AliMpTriggerReader.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 275 | 2016-06-21T20:24:05.000Z | 2022-03-31T13:06:19.000Z | /**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpeateose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
// $Id$
// $MpId: AliMpTriggerReader.cxx,v 1.4 2006/05/24 13:58:52 ivana Exp $
#include "AliMpTriggerReader.h"
#include "AliLog.h"
#include "AliMpConstants.h"
#include "AliMpDataStreams.h"
#include "AliMpFiles.h"
#include "AliMpHelper.h"
#include "AliMpMotif.h"
#include "AliMpMotifPosition.h"
#include "AliMpMotifReader.h"
#include "AliMpMotifSpecial.h"
#include "AliMpMotifType.h"
#include "AliMpPCB.h"
#include "AliMpSlat.h"
#include "AliMpSlatMotifMap.h"
#include "AliMpSlatMotifMap.h"
#include "AliMpSt345Reader.h"
#include "AliMpTrigger.h"
#include "Riostream.h"
#include "TClass.h"
#include "TList.h"
#include "TObjString.h"
#include "TString.h"
#include <TArrayI.h>
#include <cstdlib>
#include <sstream>
//-----------------------------------------------------------------------------
/// \class AliMpTriggerReader
/// Read trigger slat ASCII files
/// Basically provides two methods:
/// - AliMpTrigger* ReadSlat()
/// - AliMpPCB* ReadPCB()
///
/// \author Laurent Aphecetche
//-----------------------------------------------------------------------------
/// \cond CLASSIMP
ClassImp(AliMpTriggerReader)
/// \endcond
//
// static private methods
//
//_____________________________________________________________________________
const TString& AliMpTriggerReader::GetKeywordLayer()
{
/// Keyword: LAYER
static const TString kKeywordLayer("LAYER");
return kKeywordLayer;
}
//_____________________________________________________________________________
const TString& AliMpTriggerReader::GetKeywordScale()
{
/// Keyword: SCALE
static const TString kKeywordScale("SCALE");
return kKeywordScale;
}
//_____________________________________________________________________________
const TString& AliMpTriggerReader::GetKeywordPcb()
{
/// Keyword : PCB
static const TString kKeywordPcb("PCB");
return kKeywordPcb;
}
//_____________________________________________________________________________
const TString& AliMpTriggerReader::GetKeywordFlipX()
{
/// Keyword : FLIPX
static const TString kKeywordFlipX("FLIP_X");
return kKeywordFlipX;
}
//_____________________________________________________________________________
const TString& AliMpTriggerReader::GetKeywordFlipY()
{
/// Keyword : FLIPY
static const TString kKeywordFlipY("FLIP_Y");
return kKeywordFlipY;
}
//
// ctors, dtor
//
//_____________________________________________________________________________
AliMpTriggerReader::AliMpTriggerReader(AliMpSlatMotifMap* motifMap)
: TObject(),
fMotifMap(motifMap),
fLocalBoardMap()
{
///
/// Default ctor.
///
fLocalBoardMap.SetOwner(kTRUE);
}
//_____________________________________________________________________________
AliMpTriggerReader::~AliMpTriggerReader()
{
///
/// Dtor.
///
fLocalBoardMap.DeleteAll();
}
//_____________________________________________________________________________
AliMpSlat*
AliMpTriggerReader::BuildSlat(const AliMpDataStreams& dataStreams,
const char* slatName,
AliMp::PlaneType planeType,
const TList& lines,
Double_t scale)
{
/// Construct a slat from the list of lines, taking into account
/// the scale factor. The returned pointer must be deleted by the client
AliDebug(1,Form("slat %s %s scale %e",
slatName,PlaneTypeName(planeType).Data(),scale))
;
AliMpSlat* slat = new AliMpSlat(slatName, planeType);
TIter it(&lines);
// StdoutToAliDebug(3,lines.Print(););
TObjString* osline;
while ( ( osline = (TObjString*)it.Next() ) )
{
// note that at this stage lines should not be empty.
TString sline(osline->String());
TObjArray* tokens = sline.Tokenize(' ');
TString& keyword = ((TObjString*)tokens->At(0))->String();
if ( keyword == GetKeywordPcb() )
{
if ( tokens->GetEntriesFast() != 3 )
{
AliErrorClass(Form("Syntax error : expecting PCB type localboard-list"
" in following line:\n%s",sline.Data()));
delete slat;
delete tokens;
return 0;
}
TString pcbName = ((TObjString*)tokens->At(1))->String();
TObjArray* localBoardList = ((TObjString*)tokens->At(2))->String().Tokenize(',');
if ( scale != 1.0 )
{
std::ostringstream s;
s << pcbName.Data() << "x" << scale;
pcbName = s.str().c_str();
}
AliMpPCB* pcbType = ReadPCB(dataStreams, pcbName.Data());
if (!pcbType)
{
AliErrorClass(Form("Cannot read pcbType=%s",pcbName.Data()));
delete slat;
delete tokens;
return 0;
}
TArrayI allLocalBoards;
for ( Int_t ilb = 0; ilb < localBoardList->GetEntriesFast(); ++ilb)
{
TArrayI localBoardNumbers;
TString& localBoards = ((TObjString*)localBoardList->At(ilb))->String();
Ssiz_t pos = localBoards.First('-');
if ( pos < 0 )
{
pos = localBoards.Length();
}
AliMpHelper::DecodeName(localBoards(pos-1,localBoards.Length()-pos+1).Data(),
';',localBoardNumbers);
for ( int i = 0; i < localBoardNumbers.GetSize(); ++i )
{
std::ostringstream name;
name << localBoards(0,pos-1) << localBoardNumbers[i];
AliDebugClass(3,name.str().c_str());
localBoardNumbers[i] = LocalBoardNumber(dataStreams,name.str().c_str());
AliDebugClass(3,Form("LOCALBOARDNUMBER %d\n",localBoardNumbers[i]));
allLocalBoards.Set(allLocalBoards.GetSize()+1);
allLocalBoards[allLocalBoards.GetSize()-1] = localBoardNumbers[i];
if (localBoardNumbers[i] < 0 )
{
AliErrorClass(Form("Got a negative local board number in %s ? Unlikely"
" to be correct... : %s\n",slatName,name.str().c_str()));
}
}
}
AliDebug(3,"Deleting tokens");
delete tokens;
AliDebug(3,"Deleting localBoardList");
delete localBoardList;
AliDebug(3,"Adding pcb to slat");
slat->Add(*pcbType,allLocalBoards);
AliDebug(3,Form("Deleting pcbType=%p %s",pcbType,pcbName.Data()));
delete pcbType;
}
}
if ( slat->DX()== 0 || slat->DY() == 0 )
{
AliFatalClass(Form("Slat %s has invalid null size\n",slat->GetID()));
}
return slat;
}
//_____________________________________________________________________________
TString
AliMpTriggerReader::GetBoardNameFromPCBLine(const TString& s)
{
/// Decode the string to get the board name
TString boardName;
TObjArray* tokens = s.Tokenize(' ');
TString& keyword = ((TObjString*)tokens->At(0))->String();
if ( keyword == GetKeywordPcb() &&
tokens->GetEntriesFast() == 3 )
{
boardName = ((TObjString*)tokens->At(2))->String();
}
delete tokens;
return boardName;
}
//_____________________________________________________________________________
void
AliMpTriggerReader::FlipLines(const AliMpDataStreams& dataStreams,
TList& lines, Bool_t flipX, Bool_t flipY,
Int_t srcLine, Int_t destLine)
{
///
/// Change the local board names contained in lines,
/// to go from right to left, and/or
/// from top to bottom
///
if ( flipX )
{
// Simply swaps R(ight) and L(eft) in the first character of
// local board names
TObjString* oline;
TIter it(&lines);
while ( ( oline = (TObjString*)it.Next() ) )
{
TString& s = oline->String();
if ( s.Contains("RC") )
{
// Change right to left
s.ReplaceAll("RC","LC");
}
else if ( s.Contains("LC") )
{
// Change left to right
s.ReplaceAll("LC","RC");
}
}
}
if ( flipY )
{
// Change line number, according to parameters srcLine and destLine
// Note that because of road opening (for planes 3 and 4 at least),
// we loop for srcLine +-1
//
for ( Int_t line = -1; line <=1; ++line )
{
std::ostringstream src,dest;
src << "L" << srcLine+line;
dest << "L" << destLine-line;
if ( src.str() == dest.str() ) continue;
for ( Int_t i = 0; i < lines.GetSize(); ++i )
{
TObjString* oline = (TObjString*)lines.At(i);
TString& s = oline->String();
if ( !s.Contains(GetKeywordPcb()) )
{
// Only consider PCB lines.
continue;
}
if ( s.Contains(src.str().c_str()) )
{
AliDebugClass(4,Form("Replacing %s by %s in %s\n",
src.str().c_str(),dest.str().c_str(),s.Data()));
s.ReplaceAll(src.str().c_str(),dest.str().c_str());
AliDebugClass(4,s.Data());
TString boardName(GetBoardNameFromPCBLine(s));
if ( line )
{
// We must also change board numbers, with the tricky
// thing that up and down must be swapped...
// Up can only be 1 card so it must be B1
// Down must be the uppper card of the line before, so
// the biggest possible board number for this Line,Column
if (line>0)
{
// force to B1
AliDebugClass(4,Form("Forcing B1 in %s\n",s.Data()));
s.ReplaceAll(boardName(boardName.Length()-2,2),"B1");
AliDebugClass(4,s.Data());
}
else
{
// find the largest valid board number
for ( int b = 4; b>=1; --b )
{
std::ostringstream bs;
bs << boardName(0,boardName.Length()-1) << b;
if ( LocalBoardNumber(dataStreams,bs.str().c_str()) >= 0 )
{
AliDebugClass(4,Form("Replacing %s by %s in %s\n",
boardName(boardName.Length()-2,2).Data(),
Form("B%d",b),
s.Data()));
s.ReplaceAll(boardName(boardName.Length()-2,2),
Form("B%d",b));
AliDebugClass(4,s);
break;
}
}
}
// Check that the replacement we did is ok. If not,
// skip the line.
Int_t lbn = LocalBoardNumber(dataStreams,GetBoardNameFromPCBLine(s));
if ( lbn < 0 )
{
AliDebugClass(4,Form("Removing line %s\n",s.Data()));
lines.Remove(oline);
}
} // if (line)
}
}
}
}
}
//___________________________________________________________________________
Int_t
AliMpTriggerReader::IsLayerLine(const TString& sline) const
{
/// Whether sline contains LAYER keyword
if ( sline.BeginsWith(GetKeywordLayer()) )
{
return 1;
}
else
{
return 0;
}
}
//___________________________________________________________________________
Int_t
AliMpTriggerReader::DecodeFlipLine(const TString& sline,
TString& slatType2,
Bool_t& flipX, Bool_t& flipY)
{
/// Decode a line containing FLIP_X and/or FLIP_Y keywords
Ssiz_t blankPos = sline.First(' ');
if ( blankPos < 0 ) return 0;
TString keyword(sline(0,blankPos));
if ( keyword == GetKeywordFlipX() )
{
flipX = kTRUE;
} else if ( keyword == GetKeywordFlipY() )
{
flipY = kTRUE;
}
else
{
return 0;
}
slatType2 = sline(blankPos+1,sline.Length()-blankPos-1);
return 1;
}
//___________________________________________________________________________
Int_t
AliMpTriggerReader::DecodeScaleLine(const TString& sline,
Double_t& scale, TString& slatType)
{
/// Decode sline containing SCALE keyword
if ( sline(0,GetKeywordScale().Length()) == GetKeywordScale() )
{
TString tmp(sline(GetKeywordScale().Length()+1,
sline.Length()-GetKeywordScale().Length()-1));
Ssiz_t blankPos = tmp.First(' ');
if ( blankPos < 0 )
{
AliErrorClass(Form("Syntax error in slat file, should get a slatType after "
" SCALE keyword : %s\n",tmp.Data()));
return -1;
}
else
{
slatType = tmp(0,blankPos);
scale = TString(tmp(blankPos+1,tmp.Length()-blankPos-1)).Atof();
return 1;
}
}
scale = 1.0;
return 0;
}
//_____________________________________________________________________________
Int_t
AliMpTriggerReader::GetLine(const TString& slatType)
{
///
/// Assuming slatType is a 4 character string of the form XSLN
/// where X=1,2,3 or 4
/// S = R or L
/// N is the line number
/// returns N
if ( isdigit(slatType[0]) &&
( slatType[1] == 'R' || slatType[1] == 'L' ) &&
slatType[2] == 'L' )
{
return atoi(slatType(3,1).Data());
}
return -1;
}
//_____________________________________________________________________________
int
AliMpTriggerReader::LocalBoardNumber(const AliMpDataStreams& dataStreams,
const char* localBoardName)
{
/// From local board name to local board number
if ( !fLocalBoardMap.GetSize() )
{
ReadLocalBoardMapping(dataStreams);
}
TPair* pair = (TPair*)fLocalBoardMap.FindObject(localBoardName);
if (pair)
{
return atoi(((TObjString*)pair->Value())->String().Data());
}
return -1;
}
//_____________________________________________________________________________
void
AliMpTriggerReader::ReadLines(const AliMpDataStreams& dataStreams,
const char* slatType,
AliMp::PlaneType planeType,
TList& lines,
Double_t& scale,
Bool_t& flipX, Bool_t& flipY,
Int_t& srcLine, Int_t& destLine)
{
///
/// Reads in lines from file for a given slat
/// Returns the list of lines (lines), together with some global
/// information as the scale, whether to flip the lines, etc...
///
AliDebugClass(2,Form("SlatType %s Scale %e FlipX %d FlipY %d srcLine %d"
" destLine %d\n",slatType,scale,flipX,flipY,
srcLine,destLine));
istream& in
= dataStreams.
CreateDataStream(AliMpFiles::SlatFilePath(
AliMp::kStationTrigger,slatType, planeType));
char line[80];
while ( in.getline(line,80) )
{
TString sline(AliMpHelper::Normalize(line));
if ( sline.Length() == 0 || sline[0] == '#' ) continue;
Bool_t isKeywordThere =
sline.Contains(GetKeywordPcb()) ||
sline.Contains(GetKeywordLayer()) ||
sline.Contains(GetKeywordScale()) ||
sline.Contains(GetKeywordFlipX()) ||
sline.Contains(GetKeywordFlipY());
if ( !isKeywordThere )
{
AliErrorClass(Form("Got a line with no keyword : %s."
"That's not valid\n",line));
continue;
}
Double_t scale2;
TString slatType2;
Int_t isScaleLine = DecodeScaleLine(sline,scale2,slatType2);
scale *= scale2;
if ( isScaleLine < 0 )
{
AliFatalClass(Form("Syntax error near %s keyword\n",GetKeywordScale().Data()));
}
else if ( isScaleLine > 0 && slatType2 != slatType )
{
ReadLines(dataStreams,
slatType2.Data(),planeType,lines,scale,flipX,flipY,srcLine,destLine);
}
else
{
Bool_t fx(kFALSE);
Bool_t fy(kFALSE);
Int_t isFlipLine = DecodeFlipLine(sline,slatType2,fx,fy);
if ( isFlipLine )
{
if (fy)
{
srcLine = GetLine(slatType2);
destLine = GetLine(slatType);
}
flipX |= fx;
flipY |= fy;
ReadLines(dataStreams,
slatType2.Data(),planeType,lines,scale,flipX,flipY,srcLine,destLine);
}
else
{
lines.Add(new TObjString(sline.Data()));
}
}
}
delete ∈
}
//_____________________________________________________________________________
void
AliMpTriggerReader::ReadLocalBoardMapping(const AliMpDataStreams& dataStreams)
{
/// Reads the file that contains the mapping local board name <-> number
fLocalBoardMap.DeleteAll();
UShort_t mask;
istream& in
= dataStreams.
CreateDataStream(AliMpFiles::LocalTriggerBoardMapping());
char line[80];
Char_t localBoardName[20];
Int_t j,localBoardId;
UInt_t switches;
Int_t nofBoards;
while (!in.eof())
{
for (Int_t i = 0; i < 4; ++i)
if (!in.getline(line,80)) continue; //skip 4 first lines
// read mask
if (!in.getline(line,80)) break;
sscanf(line,"%hx",&mask);
// read # boards
if (!in.getline(line,80)) break;
sscanf(line,"%d",&nofBoards);
for ( Int_t i = 0; i < nofBoards; ++i )
{
if (!in.getline(line,80)) break;
sscanf(line,"%02d %19s %03d %03x", &j, localBoardName, &localBoardId, &switches);
if (localBoardId <= AliMpConstants::NofLocalBoards())
{
fLocalBoardMap.Add(new TObjString(localBoardName), new TObjString(Form("%d",localBoardId)));
AliDebugClass(10,Form("Board %s has number %d\n", localBoardName, localBoardId));
}
// skip 2 following lines
if (!in.getline(line,80)) break;
if (!in.getline(line,80)) break;
}
}
delete ∈
}
//_____________________________________________________________________________
AliMpPCB*
AliMpTriggerReader::ReadPCB(const AliMpDataStreams& dataStreams,
const char* pcbType)
{
///
/// Create a new AliMpPCB object, by reading it from file.
/// Returned pointer must be deleted by client.
AliDebugClass(2,Form("pcbType=%s\n",pcbType));
TString pcbName(pcbType);
Ssiz_t pos = pcbName.First('x');
Double_t scale = 1.0;
if ( pos > 0 )
{
scale = TString(pcbName(pos+1,pcbName.Length()-pos-1)).Atof();
pcbName = pcbName(0,pos);
}
istream& in
= dataStreams.
CreateDataStream(AliMpFiles::SlatPCBFilePath(
AliMp::kStationTrigger,pcbName));
AliMpMotifReader reader(AliMp::kStationTrigger, AliMq::kNotSt12, AliMp::kNonBendingPlane);
// note that the nonbending
// parameter is of no use for trigger, as far as reading motif is
// concerned, as all motifs are supposed to be in the same directory
// (as they are shared by bending/non-bending planes).
char line[80];
const TString kSizeKeyword("SIZES");
const TString kMotifKeyword("MOTIF");
const TString kMotifSpecialKeyword("SPECIAL_MOTIF");
AliMpPCB* pcb(0x0);
while ( in.getline(line,80) )
{
if ( line[0] == '#' ) continue;
TString sline(line);
if ( sline(0,kSizeKeyword.Length()) == kSizeKeyword )
{
std::istringstream sin(sline(kSizeKeyword.Length(),
sline.Length()-kSizeKeyword.Length()-1).Data());
float padSizeX = 0.0;
float padSizeY = 0.0;
float pcbSizeX = 0.0;
float pcbSizeY = 0.0;
sin >> padSizeX >> padSizeY >> pcbSizeX >> pcbSizeY;
if (pcb)
{
AliError("pcb not null as expected");
}
pcb = new AliMpPCB(fMotifMap,pcbType,padSizeX*scale,padSizeY*scale,
pcbSizeX*scale,pcbSizeY*scale);
}
if ( sline(0,kMotifSpecialKeyword.Length()) == kMotifSpecialKeyword )
{
std::istringstream sin(sline(kMotifSpecialKeyword.Length(),
sline.Length()-kMotifSpecialKeyword.Length()).Data());
TString sMotifSpecial;
TString sMotifType;
sin >> sMotifSpecial >> sMotifType;
TString id = reader.MotifSpecialName(sMotifSpecial,scale);
AliMpMotifSpecial* specialMotif =
dynamic_cast<AliMpMotifSpecial*>(fMotifMap->FindMotif(id));
if (!specialMotif)
{
AliDebug(1,Form("Reading motifSpecial %s (%s) from file",
sMotifSpecial.Data(),id.Data()));
AliMpMotifType* motifType = fMotifMap->FindMotifType(sMotifType.Data());
if ( !motifType)
{
AliDebug(1,Form("Reading motifType %s (%s) from file",
sMotifType.Data(),id.Data()));
motifType = reader.BuildMotifType(dataStreams,sMotifType.Data());
fMotifMap->AddMotifType(motifType);
}
else
{
AliDebug(1,Form("Got motifType %s (%s) from motifMap",
sMotifType.Data(),id.Data()));
}
specialMotif = reader.BuildMotifSpecial(dataStreams,sMotifSpecial,motifType,scale);
fMotifMap->AddMotif(specialMotif);
}
else
{
AliDebug(1,Form("Got motifSpecial %s from motifMap",sMotifSpecial.Data()));
}
if (pcb)
{
AliError("pcb not null as expected");
}
pcb = new AliMpPCB(pcbType,specialMotif);
}
if ( sline(0,kMotifKeyword.Length()) == kMotifKeyword )
{
std::istringstream sin(sline(kMotifKeyword.Length(),
sline.Length()-kMotifKeyword.Length()).Data());
TString sMotifType;
int ix;
int iy;
sin >> sMotifType >> ix >> iy;
AliMpMotifType* motifType = fMotifMap->FindMotifType(sMotifType.Data());
if ( !motifType)
{
AliDebug(1,Form("Reading motifType %s from file",sMotifType.Data()));
motifType = reader.BuildMotifType(dataStreams,sMotifType.Data());
fMotifMap->AddMotifType(motifType);
}
else
{
AliDebug(1,Form("Got motifType %s from motifMap",sMotifType.Data()));
}
if (! pcb)
{
AliError("pcb null");
continue;
}
pcb->Add(motifType,ix,iy);
}
}
delete ∈
return pcb;
}
//_____________________________________________________________________________
AliMpTrigger*
AliMpTriggerReader::ReadSlat(const AliMpDataStreams& dataStreams,
const char* slatType, AliMp::PlaneType planeType)
{
///
/// Create a new AliMpTrigger object, by reading it from file.
/// Returned object must be deleted by client.
Double_t scale = 1.0;
Bool_t flipX = kFALSE;
Bool_t flipY = kFALSE;
TList lines;
lines.SetOwner(kTRUE);
Int_t srcLine(-1);
Int_t destLine(-1);
// Read the file and its include (if any) and store the result
// in a TObjArray of TObjStrings.
ReadLines(dataStreams,
slatType,planeType,lines,scale,flipX,flipY,srcLine,destLine);
// Here some more sanity checks could be done.
// For the moment we only insure that the first line contains
// a layer keyword.
TString& firstLine = ((TObjString*)lines.First())->String();
if ( !IsLayerLine(firstLine) )
{
std::ostringstream s;
s << GetKeywordLayer();
lines.AddFirst(new TObjString(s.str().c_str()));
}
AliDebugClass(2,Form("Scale=%g\n",scale));
FlipLines(dataStreams,lines,flipX,flipY,srcLine,destLine);
// Now splits the lines in packets corresponding to different layers
// (if any), and create sub-slats.
TObjArray layers;
layers.SetOwner(kTRUE);
Int_t ilayer(-1);
TIter it(&lines);
TObjString* osline;
while ( ( osline = (TObjString*)it.Next() ) )
{
TString& s = osline->String();
if ( IsLayerLine(s) )
{
TList* list = new TList;
list->SetOwner(kTRUE);
layers.Add(list);
++ilayer;
}
else
{
((TList*)layers.At(ilayer))->Add(new TObjString(s));
}
}
AliDebugClass(2,Form("nlayers=%d\n",layers.GetEntriesFast()));
AliMpTrigger* triggerSlat = new AliMpTrigger(slatType, planeType);
for ( ilayer = 0; ilayer < layers.GetEntriesFast(); ++ilayer )
{
TList& lines1 = *((TList*)layers.At(ilayer));
std::ostringstream slatName;
slatName << slatType << "-LAYER" << ilayer;
AliMpSlat* slat = BuildSlat(dataStreams,
slatName.str().c_str(),planeType,lines1,scale);
if ( slat )
{
Bool_t ok = triggerSlat->AdoptLayer(slat);
if (!ok)
{
StdoutToAliError(cout << "could not add slat=" << endl;
slat->Print();
cout << "to the triggerSlat=" << endl;
triggerSlat->Print();
);
AliError("Slat is=");
for ( Int_t i = 0; i < slat->GetSize(); ++i )
{
AliMpPCB* pcb = slat->GetPCB(i);
AliError(Form("ERR pcb %d size %e,%e (unscaled is %e,%e)",
i,pcb->DX()*2,pcb->DY()*2,
pcb->DX()*2/scale,pcb->DY()*2/scale));
}
AliError("TriggerSlat is=");
for ( Int_t j = 0; j < triggerSlat->GetSize(); ++j )
{
AliMpSlat* slat1 = triggerSlat->GetLayer(j);
AliError(Form("Layer %d",j));
for ( Int_t i = 0; i < slat1->GetSize(); ++i )
{
AliMpPCB* pcb = slat1->GetPCB(i);
AliError(Form("ERR pcb %d size %e,%e (unscaled is %e,%e)",
i,pcb->DX()*2,pcb->DY()*2,
pcb->DX()*2/scale,pcb->DY()*2/scale));
}
}
StdoutToAliError(fMotifMap->Print(););
}
}
else
{
AliErrorClass(Form("Could not read %s\n",slatName.str().c_str()));
delete triggerSlat;
return 0;
}
}
return triggerSlat;
}
| 29.952116 | 93 | 0.57921 | AllaMaevskaya |
ad8b37b509b129f91848ffd1b40db84a5da1764c | 30,946 | cc | C++ | topside/qgc/src/ui/DebugConsole.cc | slicht-uri/Sandshark-Beta-Lab- | 6cff36b227b49b776d13187c307e648d2a52bdae | [
"MIT"
] | null | null | null | topside/qgc/src/ui/DebugConsole.cc | slicht-uri/Sandshark-Beta-Lab- | 6cff36b227b49b776d13187c307e648d2a52bdae | [
"MIT"
] | null | null | null | topside/qgc/src/ui/DebugConsole.cc | slicht-uri/Sandshark-Beta-Lab- | 6cff36b227b49b776d13187c307e648d2a52bdae | [
"MIT"
] | 1 | 2019-10-18T06:25:14.000Z | 2019-10-18T06:25:14.000Z | /*=====================================================================
QGroundControl Open Source Ground Control Station
(c) 2009, 2010 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
This file is part of the QGROUNDCONTROL project
QGROUNDCONTROL 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.
QGROUNDCONTROL 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 QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
/**
* @file
* @brief This file implements the Debug Console, a serial console built-in to QGC.
*
* @author Lorenz Meier <mavteam@student.ethz.ch>
*
*/
#include <QPainter>
#include <QSettings>
#include <QScrollBar>
#include <QDebug>
#include "DebugConsole.h"
#include "ui_DebugConsole.h"
#include "LinkManager.h"
#include "UASManager.h"
#include "protocol.h"
#include "QGC.h"
const float DebugConsole::inDataRateThreshold = 0.4f;
DebugConsole::DebugConsole(QWidget *parent) :
QWidget(parent),
currLink(NULL),
holdOn(false),
convertToAscii(true),
filterMAVLINK(true),
autoHold(true),
bytesToIgnore(0),
lastByte(-1),
escReceived(false),
escIndex(0),
sentBytes(),
holdBuffer(),
lineBuffer(""),
lastLineBuffer(0),
lineBufferTimer(),
snapShotTimer(),
lowpassInDataRate(0.0f),
lowpassOutDataRate(0.0f),
commandIndex(0),
m_ui(new Ui::DebugConsole)
{
// Setup basic user interface
m_ui->setupUi(this);
// Hide sent text field - it is only useful after send has been hit
m_ui->sentText->setVisible(false);
// Hide auto-send checkbox
//m_ui->specialCheckBox->setVisible(false);
// Make text area not editable
m_ui->receiveText->setReadOnly(false);
// Limit to 500 lines
m_ui->receiveText->setMaximumBlockCount(500);
// Allow to wrap everywhere
m_ui->receiveText->setWordWrapMode(QTextOption::WrapAnywhere);
// Load settings for this widget
loadSettings();
// Enable traffic measurements. We only start/stop the timer as our links change, as
// these calculations are dependent on the specific link.
connect(&snapShotTimer, SIGNAL(timeout()), this, SLOT(updateTrafficMeasurements()));
snapShotTimer.setInterval(snapShotInterval);
// First connect management slots, then make sure to add all existing objects
// Connect to link manager to get notified about new links
connect(LinkManager::instance(), SIGNAL(newLink(LinkInterface*)), this, SLOT(addLink(LinkInterface*)));
// Connect to UAS manager to get notified about new UAS
connect(UASManager::instance(), SIGNAL(UASCreated(UASInterface*)), this, SLOT(uasCreated(UASInterface*)));
// Get a list of all existing links
links = QList<LinkInterface*>();
foreach (LinkInterface* link, LinkManager::instance()->getLinks()) {
addLink(link);
}
// Get a list of all existing UAS
foreach (UASInterface* uas, UASManager::instance()->getUASList()) {
uasCreated(uas);
}
// Connect link combo box
connect(m_ui->linkComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(linkSelected(int)));
// Connect send button
connect(m_ui->transmitButton, SIGNAL(clicked()), this, SLOT(sendBytes()));
// Connect HEX conversion and MAVLINK filter checkboxes
connect(m_ui->mavlinkCheckBox, SIGNAL(clicked(bool)), this, SLOT(MAVLINKfilterEnabled(bool)));
connect(m_ui->hexCheckBox, SIGNAL(clicked(bool)), this, SLOT(hexModeEnabled(bool)));
connect(m_ui->holdCheckBox, SIGNAL(clicked(bool)), this, SLOT(setAutoHold(bool)));
// Connect hold button
connect(m_ui->holdButton, SIGNAL(toggled(bool)), this, SLOT(hold(bool)));
// Connect connect button
connect(m_ui->connectButton, SIGNAL(clicked()), this, SLOT(handleConnectButton()));
// Connect the special chars combo box
connect(m_ui->addSymbolButton, SIGNAL(clicked()), this, SLOT(appendSpecialSymbol()));
// Connect Checkbox
connect(m_ui->specialComboBox, SIGNAL(highlighted(QString)), this, SLOT(specialSymbolSelected(QString)));
// Allow to send via return
connect(m_ui->sendText, SIGNAL(returnPressed()), this, SLOT(sendBytes()));
}
void DebugConsole::hideEvent(QHideEvent* event)
{
Q_UNUSED(event);
storeSettings();
}
DebugConsole::~DebugConsole()
{
storeSettings();
delete m_ui;
}
void DebugConsole::loadSettings()
{
// Load defaults from settings
QSettings settings;
settings.beginGroup("QGC_DEBUG_CONSOLE");
m_ui->specialComboBox->setCurrentIndex(settings.value("SPECIAL_SYMBOL", m_ui->specialComboBox->currentIndex()).toInt());
m_ui->specialCheckBox->setChecked(settings.value("SPECIAL_SYMBOL_CHECKBOX_STATE", m_ui->specialCheckBox->isChecked()).toBool());
hexModeEnabled(settings.value("HEX_MODE_ENABLED", m_ui->hexCheckBox->isChecked()).toBool());
MAVLINKfilterEnabled(settings.value("MAVLINK_FILTER_ENABLED", filterMAVLINK).toBool());
setAutoHold(settings.value("AUTO_HOLD_ENABLED", autoHold).toBool());
settings.endGroup();
}
void DebugConsole::storeSettings()
{
// Store settings
QSettings settings;
settings.beginGroup("QGC_DEBUG_CONSOLE");
settings.setValue("SPECIAL_SYMBOL", m_ui->specialComboBox->currentIndex());
settings.setValue("SPECIAL_SYMBOL_CHECKBOX_STATE", m_ui->specialCheckBox->isChecked());
settings.setValue("HEX_MODE_ENABLED", m_ui->hexCheckBox->isChecked());
settings.setValue("MAVLINK_FILTER_ENABLED", filterMAVLINK);
settings.setValue("AUTO_HOLD_ENABLED", autoHold);
settings.endGroup();
}
void DebugConsole::uasCreated(UASInterface* uas)
{
connect(uas, SIGNAL(textMessageReceived(int,int,int,QString)),
this, SLOT(receiveTextMessage(int,int,int,QString)), Qt::UniqueConnection);
}
/**
* Add a link to the debug console output
*/
void DebugConsole::addLink(LinkInterface* link)
{
// Add link to link list
links.insert(link->getId(), link);
m_ui->linkComboBox->insertItem(link->getId(), link->getName());
// Set new item as current
m_ui->linkComboBox->setCurrentIndex(qMax(0, links.size() - 1));
linkSelected(m_ui->linkComboBox->currentIndex());
// Register for name changes
connect(link, SIGNAL(nameChanged(QString)), this, SLOT(updateLinkName(QString)), Qt::UniqueConnection);
connect(LinkManager::instance(), &LinkManager::linkDeleted, this, &DebugConsole::removeLink, Qt::UniqueConnection);
}
void DebugConsole::removeLink(LinkInterface* const linkInterface)
{
// Add link to link list
if (links.contains(linkInterface)) {
int linkIndex = links.indexOf(linkInterface);
links.removeAt(linkIndex);
m_ui->linkComboBox->removeItem(linkIndex);
}
// Now if this was the current link, clean up some stuff.
if (linkInterface == currLink)
{
// Like disable the update time for the UI.
snapShotTimer.stop();
currLink = NULL;
}
}
void DebugConsole::linkStatusUpdate(const QString& name,const QString& text)
{
Q_UNUSED(name);
m_ui->receiveText->appendPlainText(text);
// Ensure text area scrolls correctly
m_ui->receiveText->ensureCursorVisible();
}
void DebugConsole::linkSelected(int linkId)
{
// Disconnect
if (currLink)
{
disconnect(currLink, SIGNAL(bytesReceived(LinkInterface*,QByteArray)), this, SLOT(receiveBytes(LinkInterface*, QByteArray)));
disconnect(currLink, &LinkInterface::connected, this, &DebugConsole::_linkConnected);
disconnect(currLink,SIGNAL(communicationUpdate(QString,QString)),this,SLOT(linkStatusUpdate(QString,QString)));
snapShotTimer.stop();
}
// Clear data
m_ui->receiveText->clear();
// Connect new link
if (linkId != -1) {
currLink = links[linkId];
connect(currLink, SIGNAL(bytesReceived(LinkInterface*,QByteArray)), this, SLOT(receiveBytes(LinkInterface*, QByteArray)));
disconnect(currLink, &LinkInterface::connected, this, &DebugConsole::_linkConnected);
connect(currLink,SIGNAL(communicationUpdate(QString,QString)),this,SLOT(linkStatusUpdate(QString,QString)));
_setConnectionState(currLink->isConnected());
snapShotTimer.start();
}
}
/**
* @param name new name for this link - the link is determined to the sender to this slot by QObject::sender()
*/
void DebugConsole::updateLinkName(QString name)
{
// Set name if signal came from a link
LinkInterface* link = qobject_cast<LinkInterface*>(sender());
if((link != NULL) && (links.contains(link)))
{
const qint16 &linkIndex(links.indexOf(link));
m_ui->linkComboBox->setItemText(linkIndex,name);
}
}
void DebugConsole::setAutoHold(bool hold)
{
// Disable current hold if hold had been enabled
if (autoHold && holdOn && !hold) {
this->hold(false);
m_ui->holdButton->setChecked(false);
}
// Set auto hold checkbox
if (m_ui->holdCheckBox->isChecked() != hold) {
m_ui->holdCheckBox->setChecked(hold);
}
if (!hold)
{
// Warn user about not activated hold
m_ui->receiveText->appendHtml(QString("<font color=\"%1\">%2</font>\n").arg(QColor(Qt::red).name(), tr("WARNING: You have NOT enabled auto-hold (stops updating the console if huge amounts of serial data arrive). Updating the console consumes significant CPU load, so if you receive more than about 5 KB/s of serial data, make sure to enable auto-hold if not using the console.")));
}
else
{
m_ui->receiveText->clear();
}
// Set new state
autoHold = hold;
}
/**
* Prints the message in the UAS color
*/
void DebugConsole::receiveTextMessage(int id, int component, int severity, QString text)
{
Q_UNUSED(severity);
if (isVisible())
{
QString name = UASManager::instance()->getUASForId(id)->getUASName();
QString comp;
// Get a human readable name if possible
switch (component) {
// TODO: To be completed
case MAV_COMP_ID_IMU:
comp = tr("IMU");
break;
case MAV_COMP_ID_MAPPER:
comp = tr("MAPPER");
break;
case MAV_COMP_ID_MISSIONPLANNER:
comp = tr("MISSION");
break;
case MAV_COMP_ID_SYSTEM_CONTROL:
comp = tr("SYS-CONTROL");
break;
default:
comp = QString::number(component);
break;
}
//turn off updates while we're appending content to avoid breaking the autoscroll behavior
m_ui->receiveText->setUpdatesEnabled(false);
QScrollBar *scroller = m_ui->receiveText->verticalScrollBar();
m_ui->receiveText->appendHtml(QString("<font color=\"%1\">(%2:%3) %4</font>\n").arg(UASManager::instance()->getUASForId(id)->getColor().name(), name, comp, text));
// Ensure text area scrolls correctly
scroller->setValue(scroller->maximum());
m_ui->receiveText->setUpdatesEnabled(true);
}
}
/**
* This function updates the speed indicator text in the GUI.
* Additionally, if this speed is too high, the display of incoming characters is disabled.
*/
void DebugConsole::updateTrafficMeasurements()
{
// Calculate the rate of incoming data, converting to
// kilobytes per second from the received bits per second.
qint64 inDataRate = currLink->getCurrentInDataRate() / 1000.0f;
lowpassInDataRate = lowpassInDataRate * 0.9f + (0.1f * inDataRate / 8.0f);
// If the incoming data rate is faster than our threshold, don't display the data.
// We don't use the low-passed data rate as we want the true data rate. The low-passed data
// is just for displaying to the user to remove jitter.
if ((inDataRate > inDataRateThreshold) && autoHold) {
// Enable auto-hold
m_ui->holdButton->setChecked(true);
hold(true);
}
// Update the incoming data rate label.
m_ui->downSpeedLabel->setText(tr("%L1 kB/s").arg(lowpassInDataRate, 4, 'f', 1, '0'));
// Calculate the rate of outgoing data, converting to
// kilobytes per second from the received bits per second.
lowpassOutDataRate = lowpassOutDataRate * 0.9f + (0.1f * currLink->getCurrentOutDataRate() / 8.0f / 1000.0f);
// Update the outoing data rate label.
m_ui->upSpeedLabel->setText(tr("%L1 kB/s").arg(lowpassOutDataRate, 4, 'f', 1, '0'));
}
void DebugConsole::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event);
}
void DebugConsole::receiveBytes(LinkInterface* link, QByteArray bytes)
{
int len = bytes.size();
int lastSpace = 0;
if ((this->bytesToIgnore > 260) || (this->bytesToIgnore < -2)) this->bytesToIgnore = 0;
// Only add data from current link
if (link == currLink && !holdOn)
{
// Parse all bytes
for (int j = 0; j < len; j++)
{
unsigned char byte = bytes.at(j);
// Filter MAVLink (http://qgroundcontrol.org/mavlink/) messages out of the stream.
if (filterMAVLINK)
{
if (this->bytesToIgnore > 0)
{
if ( (j + this->bytesToIgnore) < len )
j += this->bytesToIgnore - 1, this->bytesToIgnore = 1;
else
this->bytesToIgnore -= (len - j - 1), j = len - 1;
} else
if (this->bytesToIgnore == -2)
{ // Payload plus header - but we got STX already
this->bytesToIgnore = static_cast<unsigned int>(byte) + MAVLINK_NUM_NON_PAYLOAD_BYTES - 1;
if ( (j + this->bytesToIgnore) < len )
j += this->bytesToIgnore - 1, this->bytesToIgnore = 1;
else
this->bytesToIgnore -= (len - j - 1), j = len - 1;
} else
// Filtering is done by setting an ignore counter based on the MAVLINK packet length
if (static_cast<unsigned char>(byte) == MAVLINK_STX)
{
this->bytesToIgnore = -1;
} else
this->bytesToIgnore = 0;
} else this->bytesToIgnore = 0;
if ( (this->bytesToIgnore <= 0) && (this->bytesToIgnore != -1) )
{
QString str;
// Convert to ASCII for readability
if (convertToAscii)
{
if (escReceived)
{
if (escIndex < static_cast<int>(sizeof(escBytes)))
{
escBytes[escIndex] = byte;
if (/*escIndex == 1 && */escBytes[escIndex] == 0x48)
{
// Handle sequence
// for this one, clear all text
m_ui->receiveText->clear();
escReceived = false;
}
else if (escBytes[escIndex] == 0x4b)
{
// Handle sequence
// for this one, do nothing
escReceived = false;
}
else if (byte == 0x5b)
{
// Do nothing, this is still a valid escape sequence
}
else
{
escReceived = false;
}
}
else
{
// Obviously something went wrong, reset
escReceived = false;
escIndex = 0;
}
}
else if ((byte <= 32) || (byte > 126))
{
switch (byte)
{
case (unsigned char)'\n': // Accept line feed
if (lastByte != '\r') // Do not break line again for LF+CR
str.append(byte); // only break line for single LF or CR bytes
break;
case (unsigned char)' ': // space of any type means don't add another on hex output
case (unsigned char)'\t': // Accept tab
case (unsigned char)'\r': // Catch and carriage return
if (lastByte != '\n') // Do not break line again for CR+LF
str.append(byte); // only break line for single LF or CR bytes
lastSpace = 1;
break;
/* VT100 emulation (partially */
case 0x1b: // ESC received
escReceived = true;
escIndex = 0;
//qDebug() << "GOT ESC";
break;
case 0x08: // BS (backspace) received
// Do nothing for now
break;
default: // Append replacement character (box) if char is not ASCII
QString str2;
if ( lastSpace == 1)
str2.sprintf("0x%02x ", byte);
else str2.sprintf(" 0x%02x ", byte);
str.append(str2);
lastSpace = 1;
escReceived = false;
break;
}
}
else
{
// Ignore carriage return, because that
// is auto-added with '\n'
if (byte != '\r') str.append(byte); // Append original character
lastSpace = 0;
}
}
else
{
QString str2;
str2.sprintf("%02x ", byte);
str.append(str2);
}
lineBuffer.append(str);
lastByte = byte;
}
else
{
if (filterMAVLINK) this->bytesToIgnore--;
}
}
// Plot every 200 ms if windows is visible
if (lineBuffer.length() > 0 && (QGC::groundTimeMilliseconds() - lastLineBuffer) > 200) {
if (isVisible())
{
m_ui->receiveText->appendPlainText(lineBuffer);
lineBuffer.clear();
lastLineBuffer = QGC::groundTimeMilliseconds();
// Ensure text area scrolls correctly
m_ui->receiveText->ensureCursorVisible();
}
if (lineBuffer.size() > 8192)
{
lineBuffer.remove(0, 4096);
}
}
}
else if (link == currLink && holdOn)
{
holdBuffer.append(bytes);
if (holdBuffer.size() > 8192)
holdBuffer.remove(0, 4096); // drop old stuff
}
}
QByteArray DebugConsole::symbolNameToBytes(const QString& text)
{
QByteArray b;
if (text.contains("CR+LF")) {
b.append(static_cast<char>(0x0D));
b.append(static_cast<char>(0x0A));
} else if (text.contains("LF")) {
b.append(static_cast<char>(0x0A));
} else if (text.contains("FF")) {
b.append(static_cast<char>(0x0C));
} else if (text.contains("CR")) {
b.append(static_cast<char>(0x0D));
} else if (text.contains("TAB")) {
b.append(static_cast<char>(0x09));
} else if (text.contains("NUL")) {
b.append(static_cast<char>(0x00));
} else if (text.contains("ESC")) {
b.append(static_cast<char>(0x1B));
} else if (text.contains("~")) {
b.append(static_cast<char>(0x7E));
} else if (text.contains("<Space>")) {
b.append(static_cast<char>(0x20));
}
return b;
}
QString DebugConsole::bytesToSymbolNames(const QByteArray& b)
{
QString text;
if (b.size() > 1 && b.contains(0x0D) && b.contains(0x0A)) {
text = "<CR+LF>";
} else if (b.contains(0x0A)) {
text = "<LF>";
} else if (b.contains(0x0C)) {
text = "<FF>";
} else if (b.contains(0x0D)) {
text = "<CR>";
} else if (b.contains(0x09)) {
text = "<TAB>";
} else if (b.contains((char)0x00)) {
text = "<NUL>";
} else if (b.contains(0x1B)) {
text = "<ESC>";
} else if (b.contains(0x7E)) {
text = "<~>";
} else if (b.contains(0x20)) {
text = "<Space>";
} else {
text.append(b);
}
return text;
}
void DebugConsole::specialSymbolSelected(const QString& text)
{
Q_UNUSED(text);
}
void DebugConsole::appendSpecialSymbol(const QString& text)
{
QString line = m_ui->sendText->text();
QByteArray symbols = symbolNameToBytes(text);
// The text is appended to the enter field
if (convertToAscii) {
line.append(symbols);
} else {
for (int i = 0; i < symbols.size(); i++) {
QString add(" 0x%1");
line.append(add.arg(static_cast<char>(symbols.at(i)), 2, 16, QChar('0')));
}
}
m_ui->sendText->setText(line);
}
void DebugConsole::appendSpecialSymbol()
{
appendSpecialSymbol(m_ui->specialComboBox->currentText());
}
void DebugConsole::sendBytes()
{
// FIXME This store settings should be removed
// once all threading issues have been resolved
// since its called in the destructor, which
// is absolutely sufficient
storeSettings();
// Store command history
commandHistory.append(m_ui->sendText->text());
// Since text was just sent, we're at position commandHistory.length()
// which is the current text
commandIndex = commandHistory.length();
if (!m_ui->sentText->isVisible()) {
m_ui->sentText->setVisible(true);
}
if (!currLink->isConnected()) {
m_ui->sentText->setText(tr("Nothing sent. The link %1 is unconnected. Please connect first.").arg(currLink->getName()));
return;
}
QString transmitUnconverted = m_ui->sendText->text();
QByteArray specialSymbol;
// Append special symbol if checkbox is checked
if (m_ui->specialCheckBox->isChecked()) {
// Get auto-add special symbols
specialSymbol = symbolNameToBytes(m_ui->specialComboBox->currentText());
// Convert them if needed
if (!convertToAscii) {
QString specialSymbolConverted;
for (int i = 0; i < specialSymbol.length(); i++) {
QString add(" 0x%1");
specialSymbolConverted.append(add.arg(static_cast<char>(specialSymbol.at(i)), 2, 16, QChar('0')));
}
specialSymbol.clear();
specialSymbol.append(specialSymbolConverted);
}
}
QByteArray transmit;
QString feedback;
bool ok = true;
if (convertToAscii) {
// ASCII text is not converted
transmit = transmitUnconverted.toLatin1();
// Auto-add special symbol handling
transmit.append(specialSymbol);
QString translated;
// Replace every occurence of a special symbol with its text name
for (int i = 0; i < transmit.size(); ++i) {
QByteArray specialChar;
specialChar.append(transmit.at(i));
translated.append(bytesToSymbolNames(specialChar));
}
feedback.append(translated);
} else {
// HEX symbols are converted to bytes
QString str = transmitUnconverted.toLatin1();
str.append(specialSymbol);
str.remove(' ');
str.remove("0x");
str = str.simplified();
int bufferIndex = 0;
if ((str.size() % 2) == 0) {
for (int i = 0; i < str.size(); i=i+2) {
bool okByte;
QString strBuf = QString(str.at(i));
strBuf.append(str.at(i+1));
unsigned char hex = strBuf.toInt(&okByte, 16);
ok = (ok && okByte);
transmit[bufferIndex++] = hex;
if (okByte) {
// Feedback
feedback.append(str.at(i).toUpper());
feedback.append(str.at(i+1).toUpper());
feedback.append(" ");
} else {
feedback = tr("HEX format error near \"") + strBuf + "\"";
}
}
} else {
ok = false;
feedback = tr("HEX values have to be in pairs, e.g. AA or AA 05");
}
}
// Transmit ASCII or HEX formatted text, only if more than one symbol
if (ok && m_ui->sendText->text().toLatin1().size() > 0) {
// Transmit only if conversion succeeded
currLink->writeBytes(transmit, transmit.size());
m_ui->sentText->setText(tr("Sent: ") + feedback);
} else if (m_ui->sendText->text().toLatin1().size() > 0) {
// Conversion failed, display error message
m_ui->sentText->setText(tr("Not sent: ") + feedback);
}
// Select text to easy follow-up input from user
m_ui->sendText->selectAll();
m_ui->sendText->setFocus(Qt::OtherFocusReason);
}
/**
* @param mode true to convert all in and output to/from HEX, false to send and receive ASCII values
*/
void DebugConsole::hexModeEnabled(bool mode)
{
if (convertToAscii == mode) {
convertToAscii = !mode;
if (m_ui->hexCheckBox->isChecked() != mode) {
m_ui->hexCheckBox->setChecked(mode);
}
m_ui->receiveText->clear();
m_ui->sendText->clear();
m_ui->sentText->clear();
commandHistory.clear();
}
}
/**
* @param filter true to ignore all MAVLINK raw data in output, false, to display all incoming data
*/
void DebugConsole::MAVLINKfilterEnabled(bool filter)
{
if (filterMAVLINK != filter) {
filterMAVLINK = filter;
this->bytesToIgnore = 0;
if (m_ui->mavlinkCheckBox->isChecked() != filter) {
m_ui->mavlinkCheckBox->setChecked(filter);
}
}
}
/**
* @param hold Freeze the input and thus any scrolling
*/
void DebugConsole::hold(bool hold)
{
if (holdOn != hold) {
// Check if we need to append bytes from the hold buffer
if (this->holdOn && !hold) {
// TODO No conversion is done to the bytes in the hold buffer
m_ui->receiveText->appendPlainText(QString(holdBuffer));
holdBuffer.clear();
lowpassInDataRate = 0.0f;
}
this->holdOn = hold;
// Change text interaction mode
if (hold) {
m_ui->receiveText->setTextInteractionFlags(Qt::TextSelectableByKeyboard | Qt::TextSelectableByMouse | Qt::LinksAccessibleByKeyboard | Qt::LinksAccessibleByMouse);
} else {
m_ui->receiveText->setTextInteractionFlags(Qt::NoTextInteraction);
}
if (m_ui->holdCheckBox->isChecked() != hold) {
m_ui->holdCheckBox->setChecked(hold);
}
}
}
void DebugConsole::_linkConnected(void)
{
_setConnectionState(true);
}
void DebugConsole::_linkDisconnected(void)
{
_setConnectionState(false);
}
/**
* Sets the connection state the widget shows to this state
*/
void DebugConsole::_setConnectionState(bool connected)
{
if(connected) {
m_ui->connectButton->setText(tr("Disconn."));
m_ui->receiveText->appendHtml(QString("<font color=\"%1\">%2</font>\n").arg(QGC::colorGreen.name(), tr("Link %1 is connected.").arg(currLink->getName())));
} else {
m_ui->connectButton->setText(tr("Connect"));
m_ui->receiveText->appendHtml(QString("<font color=\"%1\">%2</font>\n").arg(QGC::colorOrange.name(), tr("Link %1 is unconnected.").arg(currLink->getName())));
}
}
/** @brief Handle the connect button */
void DebugConsole::handleConnectButton()
{
if (currLink) {
if (currLink->isConnected()) {
LinkManager::instance()->disconnect(currLink);
} else {
LinkManager::instance()->connectLink(currLink);
}
}
}
void DebugConsole::keyPressEvent(QKeyEvent * event)
{
if (event->key() == Qt::Key_Up) {
cycleCommandHistory(true);
} else if (event->key() == Qt::Key_Down) {
cycleCommandHistory(false);
} else {
QWidget::keyPressEvent(event);
}
}
void DebugConsole::cycleCommandHistory(bool up)
{
// Only cycle if there is a history
if (commandHistory.length() > 0) {
// Store current command if we're not in history yet
if (commandIndex == commandHistory.length() && up) {
currCommand = m_ui->sendText->text();
}
if (up) {
// UP
commandIndex--;
if (commandIndex >= 0) {
m_ui->sendText->setText(commandHistory.at(commandIndex));
}
// If the index
} else {
// DOWN
commandIndex++;
if (commandIndex < commandHistory.length()) {
m_ui->sendText->setText(commandHistory.at(commandIndex));
}
// If the index is at history length, load the last current command
}
// Restore current command if we went out of history
if (commandIndex == commandHistory.length()) {
m_ui->sendText->setText(currCommand);
}
// If we are too far down or too far up, wrap around to current command
if (commandIndex < 0 || commandIndex > commandHistory.length()) {
commandIndex = commandHistory.length();
m_ui->sendText->setText(currCommand);
}
// Bound the index
if (commandIndex < 0) commandIndex = 0;
if (commandIndex > commandHistory.length()) commandIndex = commandHistory.length();
}
}
void DebugConsole::changeEvent(QEvent *e)
{
QWidget::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
m_ui->retranslateUi(this);
break;
default:
break;
}
}
| 35.734411 | 389 | 0.574452 | slicht-uri |
ad8cbf1bf82bb31a17fea7342ba13dfde40d2411 | 268 | hpp | C++ | src/mbgl/programs/program_parameters.hpp | mapzak/mapbox-gl-native-android-minimod | 83f1350747be9a60eb0275bd1a8dcb8e5f027abe | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | src/mbgl/programs/program_parameters.hpp | mapzak/mapbox-gl-native-android-minimod | 83f1350747be9a60eb0275bd1a8dcb8e5f027abe | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | src/mbgl/programs/program_parameters.hpp | mapzak/mapbox-gl-native-android-minimod | 83f1350747be9a60eb0275bd1a8dcb8e5f027abe | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | #pragma once
namespace mbgl {
class ProgramParameters {
public:
ProgramParameters(float pixelRatio_ = 1.0, bool overdraw_ = false)
: pixelRatio(pixelRatio_),
overdraw(overdraw_) {}
float pixelRatio;
bool overdraw;
};
} // namespace mbgl
| 15.764706 | 70 | 0.679104 | mapzak |
ad8e005cd1583ab706d5ac3e7617042dd1b6b9b5 | 3,743 | cpp | C++ | tests/std/tests/GH_002299_implicit_sfinae_constraints/test.compile.pass.cpp | JMazurkiewicz/STL | 1a20fe1133d711a647bbb135d98743f91b7be323 | [
"Apache-2.0"
] | 1 | 2022-03-01T19:31:40.000Z | 2022-03-01T19:31:40.000Z | tests/std/tests/GH_002299_implicit_sfinae_constraints/test.compile.pass.cpp | JMazurkiewicz/STL | 1a20fe1133d711a647bbb135d98743f91b7be323 | [
"Apache-2.0"
] | null | null | null | tests/std/tests/GH_002299_implicit_sfinae_constraints/test.compile.pass.cpp | JMazurkiewicz/STL | 1a20fe1133d711a647bbb135d98743f91b7be323 | [
"Apache-2.0"
] | null | null | null | // Copyright (c) Microsoft Corporation.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include <memory>
#include <type_traits>
#include <utility>
#if _HAS_CXX17
#include <any>
#include <initializer_list>
#include <optional>
#endif // _HAS_CXX17
#define STATIC_ASSERT(...) static_assert(__VA_ARGS__, #__VA_ARGS__)
using namespace std;
// tests for shared_ptr<T>::operator=
template <class T, class U, class = void>
constexpr bool can_shared_ptr_assign = false;
template <class T, class U>
constexpr bool can_shared_ptr_assign<T, U, void_t<decltype(declval<shared_ptr<T>&>() = declval<U>())>> = true;
STATIC_ASSERT(can_shared_ptr_assign<int, shared_ptr<int>>);
STATIC_ASSERT(!can_shared_ptr_assign<int, shared_ptr<long>>);
STATIC_ASSERT(!can_shared_ptr_assign<int, const shared_ptr<long>&>);
STATIC_ASSERT(!can_shared_ptr_assign<int, unique_ptr<long>>);
#if _HAS_AUTO_PTR_ETC
STATIC_ASSERT(!can_shared_ptr_assign<int, auto_ptr<long>>);
#endif
// tests for shared_ptr<T>::reset
template <class Void, class T, class... Us>
constexpr bool can_shared_ptr_reset_impl = false;
template <class T, class... Us>
constexpr bool
can_shared_ptr_reset_impl<void_t<decltype(declval<shared_ptr<T>&>().reset(declval<Us>()...))>, T, Us...> = true;
template <class T, class... Us>
constexpr bool can_shared_ptr_reset = can_shared_ptr_reset_impl<void, T, Us...>;
STATIC_ASSERT(can_shared_ptr_reset<int, int*>);
STATIC_ASSERT(!can_shared_ptr_reset<int, long*>);
STATIC_ASSERT(!can_shared_ptr_reset<int, long*, default_delete<long>>);
STATIC_ASSERT(!can_shared_ptr_reset<int, long*, default_delete<long>, allocator<long>>);
// tests for weak_ptr<T>::operator=
template <class T, class U, class = void>
constexpr bool can_weak_ptr_assign = false;
template <class T, class U>
constexpr bool can_weak_ptr_assign<T, U, void_t<decltype(declval<weak_ptr<T>&>() = declval<U>())>> = true;
STATIC_ASSERT(can_weak_ptr_assign<int, weak_ptr<int>>);
STATIC_ASSERT(!can_weak_ptr_assign<int, weak_ptr<long>>);
STATIC_ASSERT(!can_weak_ptr_assign<int, const weak_ptr<long>&>);
STATIC_ASSERT(!can_weak_ptr_assign<int, const shared_ptr<long>&>);
#if _HAS_CXX17
// tests for make_optional
template <class T, class = void>
constexpr bool can_make_optional_decay = false;
template <class T>
constexpr bool can_make_optional_decay<T, void_t<decltype(make_optional(declval<T>()))>> = true;
template <class Void, class T, class... Us>
constexpr bool can_make_optional_impl = false;
template <class T, class... Us>
constexpr bool can_make_optional_impl<void_t<decltype(make_optional<T>(declval<Us>()...))>, T, Us...> = true;
template <class T, class... Us>
constexpr bool can_make_optional_usual = can_make_optional_impl<void, T, Us...>;
STATIC_ASSERT(can_make_optional_decay<unique_ptr<int>>);
STATIC_ASSERT(!can_make_optional_decay<const unique_ptr<int>&>); // LWG-3627
STATIC_ASSERT(can_make_optional_usual<int, int>);
STATIC_ASSERT(!can_make_optional_usual<int, int, int>);
STATIC_ASSERT(!can_make_optional_usual<int, initializer_list<int>&>);
// tests for make_any
template <class Void, class T, class... Us>
constexpr bool can_make_any_impl = false;
template <class T, class... Us>
constexpr bool can_make_any_impl<void_t<decltype(make_any<T>(declval<Us>()...))>, T, Us...> = true;
template <class T, class... Us>
constexpr bool can_make_any = can_make_any_impl<void, T, Us...>;
STATIC_ASSERT(can_make_any<int, int>);
STATIC_ASSERT(!can_make_any<unique_ptr<int>, const unique_ptr<int>&>);
STATIC_ASSERT(!can_make_any<int, int, int>);
STATIC_ASSERT(!can_make_any<int, initializer_list<int>&>);
#endif // _HAS_CXX17
int main() {} // COMPILE-ONLY
| 37.059406 | 117 | 0.740582 | JMazurkiewicz |
ad8edf10042df96058e2b21cb955b9ee51cf9501 | 1,710 | cpp | C++ | GRUT Engine/src/Scene/SceneManager.cpp | lggmonclar/GRUT | b7d06fd314141395b54a86122374f4f955f653cf | [
"MIT"
] | 2 | 2019-02-14T03:20:59.000Z | 2019-03-12T01:34:59.000Z | GRUT Engine/src/Scene/SceneManager.cpp | lggmonclar/GRUT | b7d06fd314141395b54a86122374f4f955f653cf | [
"MIT"
] | null | null | null | GRUT Engine/src/Scene/SceneManager.cpp | lggmonclar/GRUT | b7d06fd314141395b54a86122374f4f955f653cf | [
"MIT"
] | null | null | null | #include "grutpch.h"
#include "Scene.h"
#include "Core/Parallelism/FrameParams.h"
#include "Core/Memory/MemoryManager.h"
#include "Core/Memory/ObjectHandle.h"
#include "SceneManager.h"
#include "Core/Jobs/JobManager.h"
#include "Components/Rendering/Camera.h"
namespace GRUT {
void SceneManager::Initialize() {
auto currScene = SceneManager::Instance().m_currentScene = MemoryManager::Instance().AllocOnFreeList<Scene>();
auto obj = SceneManager::Instance().m_currentScene->CreateGameObject();
obj->name = "Main Camera";
obj->AddComponent<Camera>();
currScene->mainCamera = obj;
currScene->m_handle = currScene;
}
void SceneManager::FixedUpdate(float p_deltaTime) {
m_currentScene->FixedUpdate(p_deltaTime);
}
void SceneManager::Update(FrameParams& p_prevFrame, FrameParams& p_currFrame) {
p_currFrame.updateJob = JobManager::Instance().KickJob([&]() {
JobManager::Instance().WaitForJobs({ p_currFrame.physicsJob, p_prevFrame.updateJob });
frameIndex = p_currFrame.index;
auto jobs = m_currentScene->Update(p_prevFrame, p_currFrame);
JobManager::Instance().WaitForJobs(jobs);
//Handle deferred object destructions
Scene::GetCurrent()->DestroyScheduledGameObjects();
});
}
ObjectHandle<GameObject> SceneManager::AllocateGameObject() {
return MemoryManager::Instance().AllocOnFreeList<GameObject>();
}
void SceneManager::FreeGameObject(GameObject* obj) {
MemoryManager::Instance().FreeFromFreeList(obj);
}
SceneManager::~SceneManager() {
}
}
| 36.382979 | 118 | 0.65848 | lggmonclar |
74e8170d79d8f40103d188b39789cda88b0b3f79 | 3,056 | cpp | C++ | plugins/core/qPCL/PclUtils/filters/dialogs/MLSDialog.cpp | ohanlonl/qCMAT | f6ca04fa7c171629f094ee886364c46ff8b27c0b | [
"BSD-Source-Code"
] | null | null | null | plugins/core/qPCL/PclUtils/filters/dialogs/MLSDialog.cpp | ohanlonl/qCMAT | f6ca04fa7c171629f094ee886364c46ff8b27c0b | [
"BSD-Source-Code"
] | null | null | null | plugins/core/qPCL/PclUtils/filters/dialogs/MLSDialog.cpp | ohanlonl/qCMAT | f6ca04fa7c171629f094ee886364c46ff8b27c0b | [
"BSD-Source-Code"
] | 1 | 2019-02-03T12:19:42.000Z | 2019-02-03T12:19:42.000Z | //##########################################################################
//# #
//# CLOUDCOMPARE PLUGIN: qPCL #
//# #
//# 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; version 2 or later of the License. #
//# #
//# 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. #
//# #
//# COPYRIGHT: Luca Penasa #
//# #
//##########################################################################
//
#include "MLSDialog.h"
#include "../MLSSmoothingUpsampling.h"
//PCL
//#include <pcl/surface/mls.h>
//Qt
#include <QVariant>
MLSDialog::MLSDialog(QWidget *parent)
: QDialog(parent)
, Ui::MLSDialog()
{
setupUi(this);
updateCombo();
connect (this->upsampling_method, SIGNAL(currentIndexChanged(QString)), this, SLOT(activateMenu(QString)) );
connect (this->search_radius, SIGNAL(valueChanged(double)), this, SLOT(updateSquaredGaussian(double)) );
deactivateAllMethods();
}
void MLSDialog::updateCombo()
{
this->upsampling_method->clear();
this->upsampling_method->addItem(QString("None"), QVariant(MLSParameters::NONE));
this->upsampling_method->addItem(QString("Sample Local Plane"), QVariant(MLSParameters::SAMPLE_LOCAL_PLANE));
this->upsampling_method->addItem(QString("Random Uniform Density"), QVariant(MLSParameters::RANDOM_UNIFORM_DENSITY));
this->upsampling_method->addItem(QString("Voxel Grid Dilation"), QVariant(MLSParameters::VOXEL_GRID_DILATION));
}
void MLSDialog::activateMenu(QString name)
{
deactivateAllMethods();
if (name == "Sample Local Plane")
{
this->sample_local_plane_method->setEnabled(true);
}
else if (name == "Random Uniform Density")
{
this->random_uniform_density_method->setEnabled(true);
}
else if (name == "Voxel Grid Dilation")
{
this->voxel_grid_dilation_method->setEnabled(true);
}
else
{
deactivateAllMethods();
}
}
void MLSDialog::deactivateAllMethods()
{
this->sample_local_plane_method->setEnabled(false);
this->random_uniform_density_method->setEnabled(false);
this->voxel_grid_dilation_method->setEnabled(false);
}
void MLSDialog::toggleMethods(bool status)
{
if (!status)
deactivateAllMethods();
}
void MLSDialog::updateSquaredGaussian(double radius)
{
this->squared_gaussian_parameter->setValue(radius * radius);
}
| 34.337079 | 118 | 0.578534 | ohanlonl |
74e983c73966096c53b2032c6bc0a7448a9b688b | 1,766 | cpp | C++ | ToneArmEngine/OpenGLMaterial.cpp | GDAP/ToneArmEngine | 85da7b8da30c714891bdadfe824bae1bbdd49f94 | [
"Zlib",
"BSD-2-Clause"
] | null | null | null | ToneArmEngine/OpenGLMaterial.cpp | GDAP/ToneArmEngine | 85da7b8da30c714891bdadfe824bae1bbdd49f94 | [
"Zlib",
"BSD-2-Clause"
] | null | null | null | ToneArmEngine/OpenGLMaterial.cpp | GDAP/ToneArmEngine | 85da7b8da30c714891bdadfe824bae1bbdd49f94 | [
"Zlib",
"BSD-2-Clause"
] | null | null | null | #include "OpenGLMaterial.h"
#include "OpenGLProgram.h"
namespace vgs {
/*
========
OpenGLMaterial::OpenGLMaterial
OpenGLMaterial default constructor
========
*/
OpenGLMaterial::OpenGLMaterial( void ) :
m_requiredFeatures( ProgramFeatures::NONE )
{}
/*
========
OpenGLMaterial::~OpenGLMaterial
OpenGLMaterial destructor
========
*/
OpenGLMaterial::~OpenGLMaterial( void )
{}
/*
========
OpenGLMaterial::OpenGLMaterial
OpenGLMaterial copy constructor
========
*/
OpenGLMaterial::OpenGLMaterial( const OpenGLMaterial& orig ) :
Material( orig )
{
m_requiredFeatures = orig.m_requiredFeatures;
}
/*
========
Material::CreateMaterialWithColor
Creates a material with the passed in diffuse color
========
*/
OpenGLMaterial* OpenGLMaterial::CreateMaterialWithColor( const glm::vec3& diffColor ) {
OpenGLMaterial* matPtr = new OpenGLMaterial();
if ( matPtr ) {
matPtr->m_diffuseColor = diffColor;
return matPtr;
} else {
return NULL;
}
}
void OpenGLMaterial::AddTexture( Texture* texture ) {
Material::AddTexture( texture );
if ( texture->IsDiffuseMap() ) {
m_requiredFeatures = ( ProgramFeatures::Value )( m_requiredFeatures | ProgramFeatures::DIFFUSE_TEXTURE );
} else if ( texture->IsNormalMap() ) {
m_requiredFeatures = ( ProgramFeatures::Value )( m_requiredFeatures | ProgramFeatures::NORMAL_MAP );
} else if ( texture->IsSpecularMap() ) {
m_requiredFeatures = ( ProgramFeatures::Value )( m_requiredFeatures | ProgramFeatures::SPEC_MAP );
}
}
void OpenGLMaterial::BindMaterial( void ) {
Material::BindMaterial();
OpenGLProgram* prog = OpenGLProgramManager::GetInstance()->GetActiveProgram();
prog->SetUniform( "u_DiffuseColor", m_diffuseColor );
}
void OpenGLMaterial::UnbindMaterial( void ) {
Material::UnbindMaterial();
}
} | 23.236842 | 107 | 0.722537 | GDAP |
74e98437f534d06652bcc354c66ceadfd37a9e60 | 1,729 | cpp | C++ | ACM-ICPC/1238.cpp | KimBoWoon/ACM-ICPC | 146c36999488af9234d73f7b4b0c10d78486604f | [
"MIT"
] | null | null | null | ACM-ICPC/1238.cpp | KimBoWoon/ACM-ICPC | 146c36999488af9234d73f7b4b0c10d78486604f | [
"MIT"
] | null | null | null | ACM-ICPC/1238.cpp | KimBoWoon/ACM-ICPC | 146c36999488af9234d73f7b4b0c10d78486604f | [
"MIT"
] | null | null | null | #include <cstdio>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
#pragma warning(disable:4996)
#define INF 987654321
vector<pair<int, int> > v[10001], rv[10001];
// first는 거리, second는 다음 정점.
priority_queue<pair<int, int> > q;
int dist[10001], rdist[10001];
int n, m, x, maxDist;
void dijkstra(vector<pair<int, int> > v[10001], int *dist) {
dist[x] = 0;
q.push(make_pair(0, x));
while (!q.empty()) {
pair<int, int> value = q.top();
q.pop();
int current = value.second;
int cost = -value.first;
// 현재 정점까지의 거리가 더 짧은 경우 무시.
if (dist[current] < cost) {
continue;
}
for (int i = 0; i < v[current].size(); i++) {
int next = v[current][i].second;
int nextCost = v[current][i].first + dist[current];
if (dist[next] > nextCost) {
dist[next] = nextCost;
q.push(make_pair(-nextCost, next));
}
}
}
}
int main(void) {
scanf("%d %d %d", &n, &m, &x);
for (int i = 0; i < m; i++) {
int from, to, cost;
scanf("%d %d %d", &from, &to, &cost);
v[from].push_back(make_pair(cost, to));
rv[to].push_back(make_pair(cost, from));
}
// 시작 정점부터 next 정점까지의 최단거리를 빠르게 참조 및 갱신하기 위한 배열.
for (int i = 0; i < 10001; i++) {
dist[i] = rdist[i] = INF;
}
dijkstra(v, dist);
dijkstra(rv, rdist);
/*for (int i = 1; i <= n; i++) {
if (dist[i] == INF) {
printf("INF\n");
}
else {
printf("%d\n", dist[i]);
}
}
for (int i = 1; i <= n; i++) {
if (rdist[i] == INF) {
printf("INF\n");
}
else {
printf("%d\n", rdist[i]);
}
}*/
for (int i = 1; i <= n; i++) {
maxDist = max(maxDist, dist[i] + rdist[i]);
}
printf("%d\n", maxDist);
return 0;
} | 19.647727 | 61 | 0.526894 | KimBoWoon |
74eaeca76cc7601c84d45ae080420decdfa2201c | 2,494 | cpp | C++ | Src-CAH/OI.cpp | SkyZH/STM32Framework | 6711f53897be1cf6fba0eb33ccf661ef4e99ba0a | [
"MIT"
] | 4 | 2021-01-19T07:29:02.000Z | 2021-12-12T13:45:06.000Z | Src-CAH/OI.cpp | skyzh/Hurricane | 6711f53897be1cf6fba0eb33ccf661ef4e99ba0a | [
"MIT"
] | 1 | 2018-12-30T16:16:16.000Z | 2019-01-08T14:15:53.000Z | Src-CAH/OI.cpp | skyzh/Hurricane | 6711f53897be1cf6fba0eb33ccf661ef4e99ba0a | [
"MIT"
] | 2 | 2020-08-31T12:03:19.000Z | 2020-11-05T08:03:41.000Z | //
// Created by Alex Chi on 2018/11/02.
//
#include <cstdio>
#include "hal.h"
#include "OI.h"
#include "HurricaneDebugSystem.h"
#include "HurricaneCANSystem.h"
#include "HurricaneIMUSystem.h"
#include "HurricaneRemoteSystem.h"
#include "HurricaneArmSystem.h"
#include "HurricaneChassisSystem.h"
#include "HurricaneCollectorSystem.h"
#include "HurricaneClawSystem.h"
#include "MainTask.h"
#include "CAHRR/src/Task.h"
OI *oi;
extern "C" void charr_bootstrap() {
oi = new OI;
oi->boostrap();
}
extern "C" void charr_loop() {
oi->loop();
}
Task *mainTask();
void OI::boostrap() {
// initialize sequence
this->debugSystem = new HurricaneDebugSystem;
this->CANSystem = new HurricaneCANSystem(0);
this->IMUSystem = new HurricaneIMUSystem;
this->remoteSystem = new HurricaneRemoteSystem;
this->chassisSystem = new HurricaneChassisSystem;
this->armSystem = new HurricaneArmSystem;
this->collectorSystem = new HurricaneCollectorSystem();
this->clawSystem = new HurricaneClawSystem();
this->initialized = true;
OK(this->debugSystem->initialize());
OK(this->debugSystem->info("OI", "---- booting sequence ----"));
OK(this->CANSystem->initialize());
OK(this->IMUSystem->initialize());
OK(this->remoteSystem->initialize());
OK(this->debugSystem->info("OI", "---- user application ----"));
OK(this->chassisSystem->initialize());
OK(this->armSystem->initialize());
OK(this->collectorSystem->initialize());
OK(this->clawSystem->initialize());
// OK(this->usSystemChassis->initialize());
OK(this->debugSystem->info("OI", "--- system initialized ---"));
HAL_Delay(10);
this->task = mainTask();
OK(this->task->initialize());
}
void OI::loop() {
// update data source
OK(this->debugSystem->alive());
OK(this->remoteSystem->update());
OK(this->IMUSystem->update());
// OK(this->usSystemChassis->update());
// update tasks
OK(this->task->update());
// update user systems
OK(this->chassisSystem->update());
OK(this->armSystem->update());
OK(this->collectorSystem->update());
OK(this->clawSystem->update());
// update data destination
OK(this->CANSystem->update());
HAL_Delay(10);
}
extern "C" void hurricane_error_handler(char *file, int line) {
oi->debugSystem->error("ERR", std::string(file) + "@" + std::to_string(line));
}
extern "C" void hurricane_debug(const char *info) {
oi->debugSystem->info("DBG", info);
} | 26.252632 | 82 | 0.659984 | SkyZH |
74eb73259fc55722766192f5a0a1c89e6033143c | 4,864 | cpp | C++ | src/fume/vr_field.cpp | ekhidbor/FUMe | de50357efcb6dbfd0114802bc72ad316daca0ce3 | [
"CC0-1.0"
] | null | null | null | src/fume/vr_field.cpp | ekhidbor/FUMe | de50357efcb6dbfd0114802bc72ad316daca0ce3 | [
"CC0-1.0"
] | null | null | null | src/fume/vr_field.cpp | ekhidbor/FUMe | de50357efcb6dbfd0114802bc72ad316daca0ce3 | [
"CC0-1.0"
] | null | null | null | /**
* This file is a part of the FUMe project.
*
* To the extent possible under law, the person who associated CC0 with
* FUMe has waived all copyright and related or neighboring rights
* to FUMe.
*
* You should have received a copy of the CC0 legalcode along with this
* work. If not, see http://creativecommons.org/publicdomain/zero/1.0/.
*/
// std
#include <cstdint>
#include <array>
#include <unordered_map>
#include <algorithm>
#include <iterator>
// boost
#include "boost/bimap.hpp"
// local public
#include "mc3msg.h"
#include "mcstatus.h"
// local private
#include "fume/vr_field.h"
using std::array;
using std::unordered_map;
using std::copy;
using boost::bimap;
namespace std
{
template<>
struct hash<std::array<char, 2u> >
{
typedef size_t result_type;
typedef std::array<char, 2u> argument_type;
result_type operator()( const argument_type& val )
{
const size_t v1 = val[0];
const size_t v2 = val[1];
return (v2 << 8) | v1;
}
};
}
namespace fume
{
typedef unordered_map<int, uint8_t> vr_size_map_t;
typedef bimap<int, vr_value_t> vr_value_map_t;
static const vr_size_map_t::value_type VR_SIZE_VALUES[] =
{
{ AE, 2u },
{ AS, 2u },
{ CS, 2u },
{ DA, 2u },
{ DS, 2u },
{ DT, 2u },
{ IS, 2u },
{ LO, 2u },
{ LT, 2u },
{ PN, 2u },
{ SH, 2u },
{ ST, 2u },
{ TM, 2u },
{ UC, 4u },
{ UR, 4u },
{ UT, 4u },
{ UI, 2u },
{ SS, 2u },
{ US, 2u },
{ AT, 2u },
{ SL, 2u },
{ UL, 2u },
{ FL, 2u },
{ FD, 2u },
{ UNKNOWN_VR, 4u },
{ OB, 4u },
{ OW, 4u },
{ OD, 4u },
{ OF, 4u },
{ SQ, 4u },
{ OL, 4u }
};
// Disable "extra braces" warning message. The extra braces
// are unnecessary
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmissing-braces"
static const vr_value_map_t::value_type VR_VALUES[] =
{
{ AE, { 'A', 'E' } },
{ AS, { 'A', 'S' } },
{ CS, { 'C', 'S' } },
{ DA, { 'D', 'A' } },
{ DS, { 'D', 'S' } },
{ DT, { 'D', 'T' } },
{ IS, { 'I', 'S' } },
{ LO, { 'L', 'O' } },
{ LT, { 'L', 'T' } },
{ PN, { 'P', 'N' } },
{ SH, { 'S', 'H' } },
{ ST, { 'S', 'T' } },
{ TM, { 'T', 'M' } },
{ UC, { 'U', 'C' } },
{ UR, { 'U', 'R' } },
{ UT, { 'U', 'T' } },
{ UI, { 'U', 'I' } },
{ SS, { 'S', 'S' } },
{ US, { 'U', 'S' } },
{ AT, { 'A', 'T' } },
{ SL, { 'S', 'L' } },
{ UL, { 'U', 'L' } },
{ FL, { 'F', 'L' } },
{ FD, { 'F', 'D' } },
{ UNKNOWN_VR, { 'U', 'N' } },
{ OB, { 'O', 'B' } },
{ OW, { 'O', 'W' } },
{ OD, { 'O', 'D' } },
{ OF, { 'O', 'F' } },
{ SQ, { 'S', 'Q' } },
{ OL, { 'O', 'L' } }
};
#pragma GCC diagnostic pop
static const vr_value_map_t& vr_value_map()
{
static const vr_value_map_t ret( begin( VR_VALUES ), end( VR_VALUES ) );
return ret;
}
static const vr_size_map_t& vr_size_map()
{
static const vr_size_map_t ret( begin( VR_SIZE_VALUES ),
end( VR_SIZE_VALUES ) );
return ret;
}
static MC_STATUS get_vr_field_size( MC_VR vr, uint8_t& field_size )
{
MC_STATUS ret = MC_CANNOT_COMPLY;
const vr_size_map_t::const_iterator itr = vr_size_map().find( vr );
if( itr != vr_size_map().cend() )
{
field_size = itr->second;
ret = MC_NORMAL_COMPLETION;
}
else
{
ret = MC_INVALID_VR_CODE;
}
return ret;
}
MC_STATUS get_vr_field_value( MC_VR vr, vr_value_t& value, uint8_t& field_size )
{
MC_STATUS ret = MC_CANNOT_COMPLY;
const vr_value_map_t::left_map::const_iterator itr =
vr_value_map().left.find( vr );
if( itr != vr_value_map().left.end() )
{
copy( itr->second.cbegin(), itr->second.cend(), value.begin() );
ret = get_vr_field_size( vr, field_size );
}
else
{
ret = MC_INVALID_VR_CODE;
}
return ret;
}
MC_STATUS get_vr_code( const vr_value_t& value, MC_VR& vr, uint8_t& field_size )
{
MC_STATUS ret = MC_CANNOT_COMPLY;
const vr_value_map_t::right_map::const_iterator itr =
vr_value_map().right.find( value );
if( itr != vr_value_map().right.end() )
{
vr = static_cast<MC_VR>( itr->second );
ret = get_vr_field_size( vr, field_size );
}
else
{
ret = MC_INVALID_VR_CODE;
}
return ret;
}
}
| 23.384615 | 80 | 0.4706 | ekhidbor |
74ed3a7210c2e422b12177729dea2d73f868b614 | 2,789 | cc | C++ | ios/consumer/base/supports_user_data.cc | nagineni/chromium-crosswalk | 5725642f1c67d0f97e8613ec1c3e8107ab53fdf8 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 231 | 2015-01-08T09:04:44.000Z | 2021-12-30T03:03:10.000Z | ios/consumer/base/supports_user_data.cc | j4ckfrost/android_external_chromium_org | a1a3dad8b08d1fcf6b6b36c267158ed63217c780 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2021-12-13T19:44:12.000Z | 2021-12-13T19:44:12.000Z | ios/consumer/base/supports_user_data.cc | j4ckfrost/android_external_chromium_org | a1a3dad8b08d1fcf6b6b36c267158ed63217c780 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 268 | 2015-01-21T05:53:28.000Z | 2022-03-25T22:09:01.000Z | // Copyright 2013 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 "ios/public/consumer/base/supports_user_data.h"
#include "base/memory/scoped_ptr.h"
#include "base/supports_user_data.h"
namespace ios {
// Class that wraps a ios::SupportsUserData::Data object in a
// base::SupportsUserData::Data object. The wrapper object takes ownership of
// the wrapped object and will delete it on destruction.
class DataAdaptor : public base::SupportsUserData::Data {
public:
DataAdaptor(SupportsUserData::Data* data);
virtual ~DataAdaptor();
SupportsUserData::Data* data() { return data_.get(); }
private:
scoped_ptr<SupportsUserData::Data> data_;
};
DataAdaptor::DataAdaptor(SupportsUserData::Data* data)
: data_(data) {}
DataAdaptor::~DataAdaptor() {}
// Class that subclasses base::SupportsUserData in order to enable it to
// support ios::SupportsUserData::Data objects. It accomplishes this by
// wrapping these objects internally in ios::DataAdaptor objects.
class SupportsUserDataInternal : public base::SupportsUserData {
public:
// Returns the data that is associated with |key|, or NULL if there is no
// such associated data.
ios::SupportsUserData::Data* GetIOSUserData(const void* key);
// Associates |data| with |key|. Takes ownership of |data| and will delete it
// on either a call to |RemoveUserData(key)| or otherwise on destruction.
void SetIOSUserData(const void* key, ios::SupportsUserData::Data* data);
private:
SupportsUserDataInternal() {}
virtual ~SupportsUserDataInternal() {}
friend class ios::SupportsUserData;
};
ios::SupportsUserData::Data* SupportsUserDataInternal::GetIOSUserData(
const void* key) {
DataAdaptor* adaptor = static_cast<DataAdaptor*>(
base::SupportsUserData::GetUserData(key));
if (!adaptor)
return NULL;
return adaptor->data();
}
void SupportsUserDataInternal::SetIOSUserData(
const void* key, ios::SupportsUserData::Data* data) {
base::SupportsUserData::SetUserData(key, new DataAdaptor(data));
}
// ios::SupportsUserData implementation.
SupportsUserData::SupportsUserData()
: internal_helper_(new SupportsUserDataInternal()) {
}
SupportsUserData::~SupportsUserData() {
delete internal_helper_;
}
SupportsUserData::Data* SupportsUserData::GetUserData(const void* key) const {
return internal_helper_->GetIOSUserData(key);
}
void SupportsUserData::SetUserData(const void* key, Data* data) {
internal_helper_->SetIOSUserData(key, data);
}
void SupportsUserData::RemoveUserData(const void* key) {
internal_helper_->RemoveUserData(key);
}
void SupportsUserData::DetachUserDataThread() {
internal_helper_->DetachUserDataThread();
}
} // namespace ios
| 30.648352 | 79 | 0.754392 | nagineni |
74efc4e4a78fc6b3dcbb6d3bcfb4398025191cbe | 1,375 | cpp | C++ | Uebungsaufgaben/ListenStrukturen/stack.cpp | TEL21D/Informatik2 | d0a6b6b5a0fe5dd404dadfd50d25543d5c6d5075 | [
"MIT"
] | null | null | null | Uebungsaufgaben/ListenStrukturen/stack.cpp | TEL21D/Informatik2 | d0a6b6b5a0fe5dd404dadfd50d25543d5c6d5075 | [
"MIT"
] | null | null | null | Uebungsaufgaben/ListenStrukturen/stack.cpp | TEL21D/Informatik2 | d0a6b6b5a0fe5dd404dadfd50d25543d5c6d5075 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
struct element
{
/* data */
int _data;
element *_next;
element(int data = 0, element *next = nullptr)
{
_data = data;
_next = next;
}
bool empty()
{
return _next == nullptr;
}
};
struct s_stack
{
// Member Variablen
int _size = 0;
element *_head = new element();
// Methoden
void push(int data)
{
element *newEl = new element(data, _head);
_head = newEl;
_size++;
}
int pop()
{
/**
* gibt das oberste Elemente zurueck und entfernt es
*
*/
// pruefen ob der Stack Element hat ansonsten `-1`
if (_size > 0)
{
int temp = _head->_data;
element * curr_head = _head;
_head = curr_head->_next;
delete curr_head;
_size--;
return temp;
}
return -1;
}
int top()
{
if (_size > 0)
return _head->_data;
return -1;
}
int size()
{
return _size;
}
void print()
{
element * curr = _head;
while (!curr->empty())
{
std::cout << curr->_data << " ";
curr = curr->_next;
}
std::cout << "\n";
}
};
int main(int argc, char const *argv[])
{
s_stack stack;
std::cout << stack.pop() << "\n";
stack.push(3);
stack.push(2);
stack.push(1);
stack.push(6);
stack.print();
std::cout << stack.pop() << "\n";
stack.print();
return 0;
}
| 14.945652 | 56 | 0.528727 | TEL21D |
74f0c3868289fe5fece793fb2f91691eacd80877 | 3,136 | cc | C++ | dash/src/util/Trace.cc | RuhanDev/dash | c56193149c334e552df6f8439c3fb1510048b7f1 | [
"BSD-3-Clause"
] | 1 | 2019-05-19T20:31:20.000Z | 2019-05-19T20:31:20.000Z | dash/src/util/Trace.cc | RuhanDev/dash | c56193149c334e552df6f8439c3fb1510048b7f1 | [
"BSD-3-Clause"
] | null | null | null | dash/src/util/Trace.cc | RuhanDev/dash | c56193149c334e552df6f8439c3fb1510048b7f1 | [
"BSD-3-Clause"
] | null | null | null | #include <dash/util/Trace.h>
#include <dash/util/Config.h>
#include <dash/Team.h>
#include <map>
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <string>
#include <vector>
#include <unistd.h>
std::map<std::string, dash::util::TraceStore::trace_events_t>
dash::util::TraceStore::_traces
= {{ }};
bool dash::util::TraceStore::_trace_enabled
= false;
bool dash::util::TraceStore::on()
{
_trace_enabled = dash::util::Config::get<bool>("DASH_ENABLE_TRACE");
return _trace_enabled;
}
void dash::util::TraceStore::off()
{
_trace_enabled = false;
}
bool dash::util::TraceStore::enabled()
{
return _trace_enabled == true;
}
void dash::util::TraceStore::clear()
{
_traces.clear();
}
void dash::util::TraceStore::clear(const std::string & context)
{
_traces[context].clear();
}
void dash::util::TraceStore::add_context(const std::string & context)
{
if (_traces.count(context) == 0) {
_traces[context] = trace_events_t();
}
}
dash::util::TraceStore::trace_events_t &
dash::util::TraceStore::context_trace(const std::string & context)
{
return _traces[context];
}
void dash::util::TraceStore::write(std::ostream & out, bool printHeader)
{
if (!dash::util::Config::get<bool>("DASH_ENABLE_TRACE")) {
return;
}
std::ostringstream os;
auto unit = dash::Team::GlobalUnitID();
for (auto context_traces : _traces) {
std::string context = context_traces.first;
trace_events_t & events = context_traces.second;
// Master prints CSV headers:
if (printHeader && unit == 0) {
os << "-- [TRACE] "
<< std::setw(15) << "context" << ","
<< std::setw(5) << "unit" << ","
<< std::setw(15) << "start" << ","
<< std::setw(15) << "end" << ","
<< std::setw(12) << "state"
<< std::endl;
}
for (auto state_timespan : events) {
auto start = state_timespan.start;
auto end = state_timespan.end;
auto state = state_timespan.state;
os << "-- [TRACE] "
<< std::setw(15) << std::fixed << context << ", "
<< std::setw(5) << std::fixed << unit << ", "
<< std::setw(15) << std::fixed << start << ", "
<< std::setw(15) << std::fixed << end << ", "
<< std::setw(12) << std::fixed << state
<< std::endl;
}
}
out << os.str();
}
void dash::util::TraceStore::write(
const std::string & filename,
const std::string & path)
{
if (!dash::util::Config::get<bool>("DASH_ENABLE_TRACE")) {
return;
}
std::string trace_log_dir;
if (dash::util::Config::is_set("DASH_TRACE_LOG_PATH")) {
trace_log_dir = dash::util::Config::get<std::string>(
"DASH_TRACE_LOG_PATH");
if (path.length() > 0) {
trace_log_dir += "/";
}
}
trace_log_dir += path;
auto unit = dash::Team::GlobalUnitID();
std::ostringstream fn;
fn << trace_log_dir << "/"
<< "u" << std::setfill('0') << std::setw(5) << unit
<< "." << filename;
std::string trace_file = fn.str();
std::ofstream out(trace_file);
write(out);
out.close();
}
| 24.310078 | 72 | 0.583227 | RuhanDev |
74f1b617e097b6a333c61d9d66a34f98ac8f71d8 | 1,083 | cpp | C++ | oi/loj/P6433/main.cpp | Riteme/test | b511d6616a25f4ae8c3861e2029789b8ee4dcb8d | [
"BSD-Source-Code"
] | 3 | 2018-08-30T09:43:20.000Z | 2019-12-03T04:53:43.000Z | oi/loj/P6433/main.cpp | Riteme/test | b511d6616a25f4ae8c3861e2029789b8ee4dcb8d | [
"BSD-Source-Code"
] | null | null | null | oi/loj/P6433/main.cpp | Riteme/test | b511d6616a25f4ae8c3861e2029789b8ee4dcb8d | [
"BSD-Source-Code"
] | null | null | null | #include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define NMAX 20
#define SMAX (1 << (NMAX))
#define MOD 998244353
typedef long long i64;
static int n;
static i64 A[NMAX + 10];
static i64 S[SMAX], f[SMAX], g[SMAX], lb[SMAX];
inline void add(i64 &a, i64 b) {
a += b;
if (a >= MOD) a -= MOD;
if (a < 0) a += MOD;
}
int main() {
scanf("%d", &n);
for (int i = 0; i < n; i++) scanf("%lld", A + i);
lb[1] = 0;
S[1] = A[0];
for (int s = 2; s < (1 << n); s++) {
lb[s] = s & 1 ? 0 : lb[s >> 1] + 1;
S[s] = S[s ^ (1 << lb[s])] + A[lb[s]];
}
f[0] = g[0] = 1;
for (int s = 1; s < (1 << n); s++) {
for (int i = lb[s], t = s; t; i = lb[t]) {
t ^= 1 << i;
int a = s ^ (1 << i);
if (S[a] >= 0) add(f[s], f[a]);
if (S[s] < 0) add(g[s], g[a]);
}
}
i64 ans = 0;
int all = (1 << n) - 1;
for (int s = 0; s <= all; s++)
if (S[s]) add(ans, f[s] * S[s] % MOD * g[all ^ s] % MOD);
printf("%lld\n", ans);
return 0;
}
| 22.102041 | 65 | 0.406279 | Riteme |
74f1e7388a837ed992b18edab72ab69646eba10a | 266 | cpp | C++ | Chess_2.1.1/Pieces/Empty.cpp | jeremy-pouzargues/Projet-Tutor- | fa20a5887235f754424087ea776efe608f9ec411 | [
"CC-BY-4.0"
] | null | null | null | Chess_2.1.1/Pieces/Empty.cpp | jeremy-pouzargues/Projet-Tutor- | fa20a5887235f754424087ea776efe608f9ec411 | [
"CC-BY-4.0"
] | null | null | null | Chess_2.1.1/Pieces/Empty.cpp | jeremy-pouzargues/Projet-Tutor- | fa20a5887235f754424087ea776efe608f9ec411 | [
"CC-BY-4.0"
] | null | null | null | #include <iostream>
#include "Pieces/Empty.h"
using namespace std;
Empty::Empty(const pairCoord & coord)
{
myCarac = KEMPTY;
myCoord = coord;
myColor = empty;
myName = "Empty";
myValue = 0;
myInitCoord = coord;
canCastling = false;
}
| 15.647059 | 37 | 0.631579 | jeremy-pouzargues |
74f430d096a1ff97ae947fc9aa2c8e03618ec1cd | 1,825 | cpp | C++ | data/transcoder_evaluation_gfg/cpp/INTEGER_POSITIVE_VALUE_POSITIVE_NEGATIVE_VALUE_ARRAY.cpp | mxl1n/CodeGen | e5101dd5c5e9c3720c70c80f78b18f13e118335a | [
"MIT"
] | 241 | 2021-07-20T08:35:20.000Z | 2022-03-31T02:39:08.000Z | data/transcoder_evaluation_gfg/cpp/INTEGER_POSITIVE_VALUE_POSITIVE_NEGATIVE_VALUE_ARRAY.cpp | mxl1n/CodeGen | e5101dd5c5e9c3720c70c80f78b18f13e118335a | [
"MIT"
] | 49 | 2021-07-22T23:18:42.000Z | 2022-03-24T09:15:26.000Z | data/transcoder_evaluation_gfg/cpp/INTEGER_POSITIVE_VALUE_POSITIVE_NEGATIVE_VALUE_ARRAY.cpp | mxl1n/CodeGen | e5101dd5c5e9c3720c70c80f78b18f13e118335a | [
"MIT"
] | 71 | 2021-07-21T05:17:52.000Z | 2022-03-29T23:49:28.000Z | // Copyright (c) 2019-present, Facebook, Inc.
// All rights reserved.
//
// This source code is licensed under the license found in the
// LICENSE file in the root directory of this source tree.
//
#include <iostream>
#include <cstdlib>
#include <string>
#include <vector>
#include <fstream>
#include <iomanip>
#include <bits/stdc++.h>
using namespace std;
int f_gold ( int arr [ ], int n ) {
unordered_map < int, int > hash;
int maximum = 0;
for ( int i = 0;
i < n;
i ++ ) {
if ( arr [ i ] < 0 ) hash [ abs ( arr [ i ] ) ] -= 1;
else hash [ arr [ i ] ] += 1;
}
for ( int i = 0;
i < n;
i ++ ) if ( hash [ arr [ i ] ] != 0 ) return arr [ i ];
return - 1;
}
//TOFILL
int main() {
int n_success = 0;
vector<vector<int>> param0 {{1,7,10,14,15,24,27,32,33,38,39,40,42,42,47,58,75,76,78,79,83,85,89,96},{-36,14,-76,-70,52,18,64},{0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1},{35,50,36,50,82,54,10,45,13,22,1,41,13,11,4,43,50,27,94,57},{-88,-86,-84,-80,-80,-74,-72,-48,-46,-46,-44,-34,-32,-24,-22,-14,4,4,8,8,10,12,20,20,24,24,24,28,32,34,36,44,46,54,54,60,62,62,62,70,70,80,88,88,90},{0,0},{1,1,3,6,6,8,12,13,17,27,28,31,40,40,42,43,53,55,58,60,60,61,65,66,72,72,75,80,84,89,96,97,99},{52,-38,-82,30,-66,42,54,-96,-46,-30,18,-50,96,90,4,74,-22,8,34,74,-46,8,-32,88,-96,26,-80,50,92,-80,44,36},{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1},{38,20,54,51,11,61,90,28,23,55,65,87,99,70,74,3,68,23,74,53,80,7,57,24,66,8,15,63,18,67,96,31,63,50}};
vector<int> param1 {18,5,17,15,27,1,31,24,16,30};
for(int i = 0; i < param0.size(); ++i)
{
if(f_filled(¶m0[i].front(),param1[i]) == f_gold(¶m0[i].front(),param1[i]))
{
n_success+=1;
}
}
cout << "#Results:" << " " << n_success << ", " << param0.size();
return 0;
} | 38.829787 | 760 | 0.558904 | mxl1n |
74f70f7eebb5748585b252b47529fc89a447600e | 1,558 | cpp | C++ | Hdu/hdu4738.cpp | Tunghohin/Competitive_coding | 879238605d5525cda9fd0cfa1155ba67959179a6 | [
"MIT"
] | 2 | 2021-09-06T08:34:00.000Z | 2021-11-22T14:52:41.000Z | Hdu/hdu4738.cpp | Tunghohin/Competitive_coding | 879238605d5525cda9fd0cfa1155ba67959179a6 | [
"MIT"
] | null | null | null | Hdu/hdu4738.cpp | Tunghohin/Competitive_coding | 879238605d5525cda9fd0cfa1155ba67959179a6 | [
"MIT"
] | null | null | null | #include <cstring>
#include <iostream>
using namespace std;
const int N = 1010, M = 200;
struct edge
{
int to, next, val;
}e[M];
int head[N], tot = 0;
void add_edge(int from, int to, int val)
{
e[++tot].to = to;
e[tot].val = val;
e[tot].next = head[from];
head[from] = tot;
}
int inv_edge(int i)
{
return i - ((i ^ 1) - i);
}
int dfn[N], low[N], timestamp = 0;
bool is_bridge[M];
void tarjan(int u, int from)
{
dfn[u] = low[u] = ++timestamp;
for (int i = head[u]; i; i = e[i].next)
{
int j = e[i].to;
if (!dfn[j])
{
tarjan(j, i);
low[u] = min(low[u], low[j]);
if (dfn[u] < low[j]) is_bridge[i] = is_bridge[inv_edge(i)] = true;
}
else if (i != (inv_edge(from))) low[u] = min(low[u], dfn[j]);
}
}
void init(int n)
{
for (int i = 0; i <= n; i++)
{
dfn[i] = low[i] = 0;
head[i] = 0;
}
timestamp = tot = 0;
memset(is_bridge, false, sizeof(is_bridge));
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr), cout.tie(nullptr);
int n, m;
while (cin >> n >> m, n || m)
{
init(n);
for (int i = 1; i <= m; i++)
{
int a, b, v;
cin >> a >> b >> v;
add_edge(a, b, v), add_edge(b, a, v);
}
int cnt = 0;
for (int i = 1; i <= n; i++)
{
if (!dfn[i]) tarjan(i, -1), cnt++;
}
if (cnt > 1)
{
cout << 0 << '\n';
continue;
}
int res = 0x3f3f3f3f;
for (int i = 1; i <= tot; i += 2)
{
if (is_bridge[i])
{
res = min(res, e[i].val);
}
}
if (res == 0x3f3f3f3f) cout << -1 << '\n';
else if (res == 0) cout << 1 << '\n';
else cout << res << '\n';
}
} | 15.126214 | 69 | 0.497433 | Tunghohin |
74f72855523f3b8a69ece22a604780126cb0d917 | 10,662 | cpp | C++ | src/ui-win/light/LightSpillCust.cpp | steptosky/3DsMax-X-Obj-Exporter | c70f5a60056ee71aba1569f1189c38b9e01d2f0e | [
"BSD-3-Clause"
] | 20 | 2017-07-07T06:07:30.000Z | 2022-03-09T12:00:57.000Z | src/ui-win/light/LightSpillCust.cpp | steptosky/3DsMax-X-Obj-Exporter | c70f5a60056ee71aba1569f1189c38b9e01d2f0e | [
"BSD-3-Clause"
] | 28 | 2017-07-07T06:08:27.000Z | 2022-03-09T12:09:23.000Z | src/ui-win/light/LightSpillCust.cpp | steptosky/3DsMax-X-Obj-Exporter | c70f5a60056ee71aba1569f1189c38b9e01d2f0e | [
"BSD-3-Clause"
] | 7 | 2018-01-24T19:43:22.000Z | 2020-01-06T00:05:40.000Z | /*
** Copyright(C) 2017, StepToSky
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are met:
**
** 1.Redistributions of source code must retain the above copyright notice, this
** list of conditions and the following disclaimer.
** 2.Redistributions in binary form must reproduce the above copyright notice,
** this list of conditions and the following disclaimer in the documentation
** and / or other materials provided with the distribution.
** 3.Neither the name of StepToSky 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.
**
** Contacts: www.steptosky.com
*/
#include "LightSpillCust.h"
#pragma warning(push, 0)
#include <3dsmaxport.h>
#pragma warning(pop)
#include "resource/resource.h"
#include "ui-win/Utils.h"
#include "resource/ResHelper.h"
#include "presenters/Datarefs.h"
namespace ui {
namespace win {
/**************************************************************************************************/
//////////////////////////////////////////* Static area *///////////////////////////////////////////
/**************************************************************************************************/
INT_PTR CALLBACK LightSpillCust::panelProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
LightSpillCust * theDlg;
if (msg == WM_INITDIALOG) {
theDlg = reinterpret_cast<LightSpillCust*>(lParam);
DLSetWindowLongPtr(hWnd, lParam);
theDlg->initWindow(hWnd);
}
else if (msg == WM_DESTROY) {
theDlg = DLGetWindowLongPtr<LightSpillCust*>(hWnd);
theDlg->destroyWindow(hWnd);
}
else {
theDlg = DLGetWindowLongPtr<LightSpillCust *>(hWnd);
if (!theDlg) {
return FALSE;
}
}
//--------------------------------------
switch (msg) {
case WM_COMMAND: {
switch (LOWORD(wParam)) {
case IDC_BTN_DATAREF: {
MSTR str;
Utils::getText(theDlg->cEdtDataRef, str);
str = presenters::Datarefs::selectData(str);
theDlg->cEdtDataRef->SetText(str);
theDlg->mData->setDataRef(xobj::fromMStr(str));
theDlg->eventParamChanged(true);
break;
}
default: break;
}
break;
}
case WM_CUSTEDIT_ENTER: {
switch (LOWORD(wParam)) {
case IDC_EDIT_DATAREF: {
theDlg->mData->setDataRef(sts::toMbString(Utils::getText(theDlg->cEdtDataRef)));
theDlg->eventParamChanged(true);
break;
}
default: break;
}
break;
}
case CC_SPINNER_CHANGE: {
switch (LOWORD(wParam)) {
case IDC_R_SPIN: {
xobj::Color color = theDlg->mData->color();
color.setRed(theDlg->mSpnR->GetFVal());
theDlg->mData->setColor(color);
theDlg->eventParamChanged(true);
break;
}
case IDC_G_SPIN: {
xobj::Color color = theDlg->mData->color();
color.setGreen(theDlg->mSpnG->GetFVal());
theDlg->mData->setColor(color);
theDlg->eventParamChanged(true);
break;
}
case IDC_B_SPIN: {
xobj::Color color = theDlg->mData->color();
color.setBlue(theDlg->mSpnB->GetFVal());
theDlg->mData->setColor(color);
theDlg->eventParamChanged(true);
break;
}
case IDC_A_SPIN: {
xobj::Color color = theDlg->mData->color();
color.setAlpha(theDlg->mSpnA->GetFVal());
theDlg->mData->setColor(color);
theDlg->eventParamChanged(true);
break;
}
case IDC_SIZE_SPIN: {
theDlg->mData->setSize(theDlg->mSpnSize->GetFVal());
theDlg->eventParamChanged(true);
break;
}
default: break;
}
break;
}
default: break;
}
return FALSE;
}
/**************************************************************************************************/
////////////////////////////////////* Constructors/Destructor */////////////////////////////////////
/**************************************************************************************************/
LightSpillCust::LightSpillCust() {
mData = nullptr;
}
LightSpillCust::~LightSpillCust() {
LightSpillCust::destroy();
}
/**************************************************************************************************/
///////////////////////////////////////////* Functions *////////////////////////////////////////////
/**************************************************************************************************/
void LightSpillCust::show(xobj::ObjLightSpillCust * inData) {
mData = inData;
toWindow();
mHwnd.show();
}
void LightSpillCust::hide() {
mHwnd.hide();
}
void LightSpillCust::create(HWND inParent) {
assert(inParent);
mHwnd.setup(CreateDialogParam(ResHelper::hInstance,
MAKEINTRESOURCE(IDD_ROLL_LIGHT_SPILLCUST_OBJ),
inParent, panelProc,
reinterpret_cast<LPARAM>(this)));
assert(mHwnd);
}
void LightSpillCust::destroy() {
assert(mHwnd);
DestroyWindow(mHwnd.hwnd());
mHwnd.release();
mData = nullptr;
}
/**************************************************************************************************/
///////////////////////////////////////////* Functions *////////////////////////////////////////////
/**************************************************************************************************/
void LightSpillCust::initWindow(HWND hWnd) {
mSpnR = SetupFloatSpinner(hWnd, IDC_R_SPIN, IDC_R_EDIT, 0.0f, 1.0f, 0.5f, 0.1f);
mSpnG = SetupFloatSpinner(hWnd, IDC_G_SPIN, IDC_G_EDIT, 0.0f, 1.0f, 0.5f, 0.1f);
mSpnB = SetupFloatSpinner(hWnd, IDC_B_SPIN, IDC_B_EDIT, 0.0f, 1.0f, 0.5f, 0.1f);
mSpnA = SetupFloatSpinner(hWnd, IDC_A_SPIN, IDC_A_EDIT, 0.0f, 1.0f, 0.5f, 0.1f);
mSpnSize = SetupFloatSpinner(hWnd, IDC_SIZE_SPIN, IDC_SIZE_EDIT, 0.0f, 100.0f, 1.0f, 0.1f);
cBtnDataRef.setup(hWnd, IDC_BTN_DATAREF);
cEdtDataRef = GetICustEdit(GetDlgItem(hWnd, IDC_EDIT_DATAREF));
assert(mSpnR);
assert(mSpnG);
assert(mSpnB);
assert(mSpnA);
assert(mSpnSize);
assert(cEdtDataRef);
assert(cBtnDataRef);
}
void LightSpillCust::destroyWindow(HWND /*hWnd*/) {
ReleaseISpinner(mSpnR);
ReleaseISpinner(mSpnG);
ReleaseISpinner(mSpnB);
ReleaseISpinner(mSpnA);
ReleaseISpinner(mSpnSize);
cBtnDataRef.release();
ReleaseICustEdit(cEdtDataRef);
}
void LightSpillCust::toWindow() {
if (mData) {
enableControls();
const xobj::Color & color = mData->color();
mSpnR->SetValue(color.red(), FALSE);
mSpnG->SetValue(color.green(), FALSE);
mSpnB->SetValue(color.blue(), FALSE);
mSpnA->SetValue(color.alpha(), FALSE);
mSpnSize->SetValue(mData->size(), FALSE);
cEdtDataRef->SetText(xobj::toMStr(mData->dataRef()));
}
else {
disableControls();
}
}
void LightSpillCust::toData() {
xobj::Color color(mSpnR->GetFVal(), mSpnG->GetFVal(), mSpnB->GetFVal(), mSpnA->GetFVal());
mData->setColor(color);
mData->setSize(mSpnSize->GetFVal());
mData->setDataRef(sts::toMbString(Utils::getText(cEdtDataRef)));
}
/**************************************************************************************************/
///////////////////////////////////////////* Functions *////////////////////////////////////////////
/**************************************************************************************************/
void LightSpillCust::enableControls() {
mSpnR->Enable();
mSpnG->Enable();
mSpnB->Enable();
mSpnA->Enable();
mSpnSize->Enable();
cBtnDataRef.enable();
cEdtDataRef->Enable();
}
void LightSpillCust::disableControls() {
mSpnR->Disable();
mSpnG->Disable();
mSpnB->Disable();
mSpnA->Disable();
mSpnSize->Disable();
cBtnDataRef.disable();
cEdtDataRef->Disable();
}
/********************************************************************************************************/
//////////////////////////////////////////////////////////////////////////////////////////////////////////
/********************************************************************************************************/
}
}
| 39.488889 | 110 | 0.450291 | steptosky |
74f880678a1f202c00c1f5643fcb9c6449eec575 | 699 | cpp | C++ | saori.cpp | Taromati2/OICQ-saori | 179ade6088df59ad985909da8eb82161c46902c3 | [
"WTFPL"
] | null | null | null | saori.cpp | Taromati2/OICQ-saori | 179ade6088df59ad985909da8eb82161c46902c3 | [
"WTFPL"
] | null | null | null | saori.cpp | Taromati2/OICQ-saori | 179ade6088df59ad985909da8eb82161c46902c3 | [
"WTFPL"
] | null | null | null | #include <iostream>
// 使用静态库必须要在引入 mirai.h 前定义这个宏
#define MIRAICPP_STATICLIB
#include <mirai.h>
int main()
{
using namespace std;
using namespace Cyan;
using namespace SSTP_link_n;
system("chcp 65001");
SSTP_link_t linker({{L"Charset",L"UTF-8"},{L"Sender",L"OICQ-saori"}});
MiraiBot bot("127.0.0.1", 539);
bot.Auth("INITKEY7A3O1a9v", 1589588851_qq);
cout << "成功登录 bot" << endl;
GroupConfig group_config = bot.GetGroupConfig(1029259687_gid);
group_config.Name = "New Name 2";
bot.SetGroupConfig(1029259687_gid, group_config);
cout << group_config.Name << endl;
// 记录轮询事件时的错误
bot.EventLoop([](const char* errMsg)
{
cout << "获取事件时出错: " << errMsg << endl;
});
return 0;
} | 18.394737 | 71 | 0.692418 | Taromati2 |
74f95a4140e7343ef28c0f77de78b8c2c37bf314 | 254 | cpp | C++ | src/default/aw_vibratorfactory_default.cpp | angelsware/aw-plugin-vibrator | 23c6106f25ff32147c5f79388f5c4b1e8f428622 | [
"MIT"
] | null | null | null | src/default/aw_vibratorfactory_default.cpp | angelsware/aw-plugin-vibrator | 23c6106f25ff32147c5f79388f5c4b1e8f428622 | [
"MIT"
] | null | null | null | src/default/aw_vibratorfactory_default.cpp | angelsware/aw-plugin-vibrator | 23c6106f25ff32147c5f79388f5c4b1e8f428622 | [
"MIT"
] | null | null | null | #include <vibrator/aw_vibratorfactory.h>
#include "aw_vibrator_default.h"
namespace Vibrator {
IVibrator* CVibratorFactory::create() {
return new CVibrator_Default();
}
void CVibratorFactory::destroy(IVibrator* vibrator) {
delete vibrator;
}
}
| 19.538462 | 54 | 0.759843 | angelsware |
2d0043b6fa999d1f02a31bcbaa29ec9b6160ace6 | 1,229 | hpp | C++ | lib/xpath_ctxt.hpp | timeout/xml_named_entity_miner | 0d3c6f59b7cb1c2f585b25d86eb0cc8a6a532839 | [
"0BSD"
] | null | null | null | lib/xpath_ctxt.hpp | timeout/xml_named_entity_miner | 0d3c6f59b7cb1c2f585b25d86eb0cc8a6a532839 | [
"0BSD"
] | null | null | null | lib/xpath_ctxt.hpp | timeout/xml_named_entity_miner | 0d3c6f59b7cb1c2f585b25d86eb0cc8a6a532839 | [
"0BSD"
] | null | null | null | #pragma once
#include "xml_doc.hpp"
#include "libxml2_error_handlers.hpp"
#include <libxml/xpath.h>
#include <memory>
class XPathQuery;
class FreeXPathCtxt {
public:
auto operator( )( xmlXPathContext *xpathCtxt ) const -> void;
};
class XPathCtxt {
friend class XPathQuery;
public:
XPathCtxt( );
explicit XPathCtxt( const XmlDoc &xml );
XPathCtxt( const XPathCtxt &xpathCtxt );
XPathCtxt( XPathCtxt &&xpathCtxt );
auto operator=( const XPathCtxt &rhs ) -> XPathCtxt &;
auto operator=( XPathCtxt &&xpathCtxt ) -> XPathCtxt &;
explicit operator bool( ) const;
friend auto operator>>( const XmlDoc &xml, XPathCtxt &xpathCtxt ) -> XPathCtxt &;
auto errorHandler( ) -> IErrorHandler &;
auto makeQuery( ) const -> XPathQuery;
private:
using XPathCtxtT = std::unique_ptr<xmlXPathContext, FreeXPathCtxt>;
XPathCtxtT xpathCtxt_;
XmlDoc xml_;
XPathErrorHandler xpathHandler_;
};
inline auto operator>>( const XmlDoc &xml, XPathCtxt &xpathCtxt ) -> XPathCtxt & {
xpathCtxt.xml_ = xml;
xpathCtxt.xpathCtxt_.reset( xmlXPathNewContext( xpathCtxt.xml_.get( ) ) );
xpathCtxt.xpathHandler_.registerHandler( xpathCtxt.xpathCtxt_.get( ) );
return xpathCtxt;
}
| 27.931818 | 85 | 0.702197 | timeout |
2d0505cbf28fc9c5a243c1fafbfd158dd50d5ebb | 499 | cpp | C++ | src/ast/try_statement.cpp | alekratz/matlab2r | 2089fbebadd5036ec1747db7bd750eb9ad18e6bb | [
"0BSD"
] | 4 | 2016-02-21T16:44:35.000Z | 2019-08-10T13:11:24.000Z | src/ast/try_statement.cpp | alekratz/matlab2r | 2089fbebadd5036ec1747db7bd750eb9ad18e6bb | [
"0BSD"
] | null | null | null | src/ast/try_statement.cpp | alekratz/matlab2r | 2089fbebadd5036ec1747db7bd750eb9ad18e6bb | [
"0BSD"
] | null | null | null | #include "ast.hpp"
namespace ast
{
void try_statement::children_accept(visitor_p guest)
{
base_t::children_accept(guest);
catch_statement->accept(guest);
}
void try_statement::traverse_top_down(visitor_p guest)
{
accept(guest);
base_t::traverse_top_down(guest);
catch_statement->traverse_top_down(guest);
}
void try_statement::traverse_bottom_up(visitor_p guest)
{
catch_statement->traverse_bottom_up(guest);
base_t::traverse_bottom_up(guest);
accept(guest);
}
} | 19.192308 | 55 | 0.749499 | alekratz |
2d0669c40142c25e97d522001f9d7fcb1bcc1668 | 4,593 | cc | C++ | content/browser/service_worker/payment_handler_support.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/browser/service_worker/payment_handler_support.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/browser/service_worker/payment_handler_support.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2021-01-05T23:43:46.000Z | 2021-01-07T23:36:34.000Z | // Copyright 2018 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 "content/browser/service_worker/payment_handler_support.h"
#include "base/bind.h"
#include "base/task/post_task.h"
#include "content/browser/service_worker/service_worker_context_core.h"
#include "content/browser/service_worker/service_worker_context_wrapper.h"
#include "content/browser/storage_partition_impl.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/common/content_client.h"
namespace content {
namespace {
// An instance of this class is created and passed ownership into
// ContentBrowserClient::ShowPaymentHandlerWindow(), to handle these 2 different
// scenarios:
// - If the embedder supports opening Payment Handler window,
// ContentBrowserClient::ShowPaymentHandlerWindow() returns true and tries to
// open the window, then finally invokes
// ShowPaymentHandlerWindowReplier::Run() to notify the result. In such a
// case, the response callback |response_callback| of Mojo call
// ServiceWorkerHost.OpenPaymentHandlerWindow() is bound into |callback| and
// invoked there.
// - Otherwise ContentBrowserClient::ShowPaymentHandlerWindow() just returns
// false and does nothing else, then |this| will be dropped silently without
// invoking Run(). In such a case, dtor of |this| invokes |fallback| (which
// e.g. opens a normal window), |response_callback| is bound into |fallback|
// and invoked there.
class ShowPaymentHandlerWindowReplier {
public:
ShowPaymentHandlerWindowReplier(
PaymentHandlerSupport::ShowPaymentHandlerWindowCallback callback,
PaymentHandlerSupport::OpenWindowFallback fallback,
blink::mojom::ServiceWorkerHost::OpenPaymentHandlerWindowCallback
response_callback)
: callback_(std::move(callback)),
fallback_(std::move(fallback)),
response_callback_(std::move(response_callback)) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
}
~ShowPaymentHandlerWindowReplier() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (response_callback_) {
DCHECK(fallback_);
base::PostTask(
FROM_HERE, {ServiceWorkerContext::GetCoreThreadId()},
base::BindOnce(std::move(fallback_), std::move(response_callback_)));
}
}
void Run(bool success, int render_process_id, int render_frame_id) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
RunOrPostTaskOnThread(
FROM_HERE, ServiceWorkerContext::GetCoreThreadId(),
base::BindOnce(std::move(callback_), std::move(response_callback_),
success, render_process_id, render_frame_id));
}
private:
PaymentHandlerSupport::ShowPaymentHandlerWindowCallback callback_;
PaymentHandlerSupport::OpenWindowFallback fallback_;
blink::mojom::ServiceWorkerHost::OpenPaymentHandlerWindowCallback
response_callback_;
DISALLOW_COPY_AND_ASSIGN(ShowPaymentHandlerWindowReplier);
};
void ShowPaymentHandlerWindowOnUI(
scoped_refptr<ServiceWorkerContextWrapper> context_wrapper,
const GURL& url,
PaymentHandlerSupport::ShowPaymentHandlerWindowCallback callback,
PaymentHandlerSupport::OpenWindowFallback fallback,
blink::mojom::ServiceWorkerHost::OpenPaymentHandlerWindowCallback
response_callback) {
GetContentClient()->browser()->ShowPaymentHandlerWindow(
context_wrapper->storage_partition()->browser_context(), url,
base::BindOnce(&ShowPaymentHandlerWindowReplier::Run,
std::make_unique<ShowPaymentHandlerWindowReplier>(
std::move(callback), std::move(fallback),
std::move(response_callback))));
}
} // namespace
// static
void PaymentHandlerSupport::ShowPaymentHandlerWindow(
const GURL& url,
ServiceWorkerContextCore* context,
ShowPaymentHandlerWindowCallback callback,
OpenWindowFallback fallback,
blink::mojom::ServiceWorkerHost::OpenPaymentHandlerWindowCallback
response_callback) {
DCHECK_CURRENTLY_ON(ServiceWorkerContext::GetCoreThreadId());
DCHECK(context);
RunOrPostTaskOnThread(
FROM_HERE, BrowserThread::UI,
base::BindOnce(&ShowPaymentHandlerWindowOnUI,
base::WrapRefCounted(context->wrapper()), url,
std::move(callback), std::move(fallback),
std::move(response_callback)));
}
} // namespace content
| 41.008929 | 80 | 0.744829 | sarang-apps |
2d07795c7a925ca206dca3ca11fe4b2c197d1c5c | 9,503 | cpp | C++ | src/planning/lanelet2_global_planner_nodes/src/lanelet2_global_planner_node.cpp | Nova-UTD/navigator | 1db2c614f9c53fb012842b8653ae1bed58a7ffdf | [
"Apache-2.0"
] | 11 | 2021-11-26T14:06:51.000Z | 2022-03-18T16:49:33.000Z | src/planning/lanelet2_global_planner_nodes/src/lanelet2_global_planner_node.cpp | Nova-UTD/navigator | 1db2c614f9c53fb012842b8653ae1bed58a7ffdf | [
"Apache-2.0"
] | 222 | 2021-10-29T22:00:27.000Z | 2022-03-29T20:56:34.000Z | src/planning/lanelet2_global_planner_nodes/src/lanelet2_global_planner_node.cpp | Nova-UTD/navigator | 1db2c614f9c53fb012842b8653ae1bed58a7ffdf | [
"Apache-2.0"
] | 1 | 2021-12-10T18:05:03.000Z | 2021-12-10T18:05:03.000Z | /*
* Package: lanelet2_global_planner_nodes
* Filename: lanelet2_global_planner_node.cpp
* Author: Egan Johnson
* Email: egan.johnson@utdallas.edu
* Copyright: 2021, Nova UTD
* License: MIT License
*/
#include <rclcpp/node_options.hpp>
#include <rclcpp_components/register_node_macro.hpp>
#include <tf2/buffer_core.h>
#include <tf2_geometry_msgs/tf2_geometry_msgs.h>
#include <tf2_ros/transform_listener.h>
#include <tf2/utils.h>
#include <time_utils/time_utils.hpp>
#include <motion_common/motion_common.hpp>
#include <autoware_auto_msgs/msg/complex32.hpp>
#include <geometry_msgs/msg/quaternion.hpp>
#include <lanelet2_global_planner_nodes/lanelet2_global_planner_node.hpp>
#include <std_msgs/msg/string.hpp>
#include <common/types.hpp>
#include <chrono>
#include <cmath>
#include <string>
#include <memory>
#include <vector>
using namespace std::chrono_literals;
using autoware::common::types::bool8_t;
using autoware::common::types::float32_t;
using autoware::common::types::float64_t;
using autoware::common::types::TAU;
using autoware::planning::lanelet2_global_planner::Lanelet2GlobalPlanner;
using autoware::planning::lanelet2_global_planner::LaneRouteCosts;
using std::placeholders::_1;
using voltron_msgs::msg::RouteCost;
using voltron_msgs::msg::RouteCosts;
namespace autoware
{
namespace planning
{
namespace lanelet2_global_planner_nodes
{
autoware_auto_msgs::msg::TrajectoryPoint convertToTrajectoryPoint(
const geometry_msgs::msg::Pose &pose)
{
autoware_auto_msgs::msg::TrajectoryPoint pt;
pt.x = static_cast<float>(pose.position.x);
pt.y = static_cast<float>(pose.position.y);
const auto angle = tf2::getYaw(pose.orientation);
pt.heading = ::motion::motion_common::from_angle(angle);
return pt;
}
Lanelet2GlobalPlannerNode::Lanelet2GlobalPlannerNode(
const rclcpp::NodeOptions &node_options)
: Node("lanelet2_global_planner_node", node_options),
tf_listener(tf_buffer, std::shared_ptr<rclcpp::Node>(this, [](auto) {}), false)
{
current_pose_init = false;
// Global planner instance init
lanelet2_global_planner = std::make_shared<Lanelet2GlobalPlanner>();
// Subcribers Goal Pose
goal_pose_sub_ptr =
this->create_subscription<geometry_msgs::msg::PoseStamped>(
"goal_pose", rclcpp::QoS(10),
std::bind(&Lanelet2GlobalPlannerNode::goal_pose_cb, this, _1));
// Subcribers Current Pose
current_pose_sub_ptr =
this->create_subscription<autoware_auto_msgs::msg::VehicleKinematicState>(
"vehicle_kinematic_state", rclcpp::QoS(10),
std::bind(&Lanelet2GlobalPlannerNode::current_pose_cb, this, _1));
// Global path publisher
route_costs_pub_ptr = this->create_publisher<RouteCosts>("route_costs", rclcpp::QoS(10));
// Update loop
// TODO: pull timer period value from param file?
update_loop_timer = this->create_wall_timer(
1000ms, std::bind(&Lanelet2GlobalPlannerNode::update_loop_cb, this));
// Create map client
map_client = this->create_client<autoware_auto_msgs::srv::HADMapService>("HAD_Map_Client");
// Request binary map from the map loader node
this->request_osm_binary_map();
}
void Lanelet2GlobalPlannerNode::request_osm_binary_map()
{
while (rclcpp::ok() && !map_client->wait_for_service(1s))
{
RCLCPP_WARN(this->get_logger(), "HAD map service not available yet. Waiting...");
}
if (!rclcpp::ok())
{
RCLCPP_ERROR(
this->get_logger(),
"Client interrupted while waiting for map service to appear. Exiting.");
}
auto request = std::make_shared<autoware_auto_msgs::srv::HADMapService_Request>();
request->requested_primitives.push_back(
autoware_auto_msgs::srv::HADMapService_Request::FULL_MAP);
auto result = map_client->async_send_request(request);
if (rclcpp::spin_until_future_complete(this->get_node_base_interface(), result) !=
rclcpp::executor::FutureReturnCode::SUCCESS)
{
RCLCPP_ERROR(this->get_logger(), "Service call failed");
throw std::runtime_error("Lanelet2GlobalPlannerNode: Map service call fail");
}
// copy message to map
autoware_auto_msgs::msg::HADMapBin msg = result.get()->map;
// Convert binary map msg to lanelet2 map and set the map for global path planner
lanelet2_global_planner->osm_map = std::make_shared<lanelet::LaneletMap>();
autoware::common::had_map_utils::fromBinaryMsg(msg, lanelet2_global_planner->osm_map);
// parse lanelet global path planner elements
lanelet2_global_planner->parse_lanelet_element();
}
/**
* Called every time the route planner needs to send a new message
*
*/
void Lanelet2GlobalPlannerNode::update_loop_cb()
{
if (!goal_pose_init)
{
RCLCPP_WARN(this->get_logger(), "Awaiting goal pose before setting route");
return;
}
if (!current_pose_init)
{
RCLCPP_WARN(this->get_logger(), "Awaiting current pose before setting route");
return;
}
LaneRouteCosts costs;
auto start = convertToTrajectoryPoint(current_pose.pose);
lanelet2_global_planner->fetch_routing_costs(start, costs);
publish_route_costs(costs);
}
void Lanelet2GlobalPlannerNode::goal_pose_cb(
const geometry_msgs::msg::PoseStamped::SharedPtr msg)
{
// transform and set the starting and goal point in the map frame
goal_pose.header = msg->header;
goal_pose.pose = msg->pose;
geometry_msgs::msg::PoseStamped goal_pose_map = goal_pose;
if (goal_pose.header.frame_id != "map")
{
if (!transform_pose_to_map(goal_pose, goal_pose_map))
{
// return: nothing happen
return;
}
else
{
goal_pose = goal_pose_map;
}
}
auto end = convertToTrajectoryPoint(goal_pose.pose);
lanelet2_global_planner->set_destination(end);
goal_pose_init = true;
}
void Lanelet2GlobalPlannerNode::current_pose_cb(
const autoware_auto_msgs::msg::VehicleKinematicState::SharedPtr msg)
{
// convert msg to geometry_msgs::msg::Pose
current_pose.pose.position.x = msg->state.x;
current_pose.pose.position.y = msg->state.y;
current_pose.pose.position.z = 0.0;
current_pose.pose.orientation =
motion::motion_common::to_quat<geometry_msgs::msg::Quaternion>(
msg->state.heading);
current_pose.header = msg->header;
// transform to "map" frame if needed
if (current_pose.header.frame_id != "map")
{
geometry_msgs::msg::PoseStamped current_pose_map = current_pose;
if (transform_pose_to_map(current_pose, current_pose_map))
{
// transform ok: set current_pose to the pose in map
current_pose = current_pose_map;
current_pose_init = true;
}
else
{
// transform failed
current_pose_init = false;
}
}
else
{
// No transform required
current_pose_init = true;
}
}
void Lanelet2GlobalPlannerNode::publish_route_costs(LaneRouteCosts &costs)
{
RouteCosts route_msg;
route_msg.header.set__frame_id("map");
route_msg.header.set__stamp(now());
// add costs to msg
for (auto cost : costs)
{
RouteCost cost_msg;
cost_msg.lane_id = cost.first;
cost_msg.cost = cost.second;
route_msg.costs.push_back(cost_msg);
}
route_costs_pub_ptr->publish(route_msg);
}
bool8_t Lanelet2GlobalPlannerNode::transform_pose_to_map(
const geometry_msgs::msg::PoseStamped &pose_in,
geometry_msgs::msg::PoseStamped &pose_out)
{
std::string source_frame = pose_in.header.frame_id;
// lookup transform validity
if (!tf_buffer.canTransform("map", source_frame, tf2::TimePointZero))
{
RCLCPP_ERROR(this->get_logger(), "Failed to transform Pose to map frame");
return false;
}
// transform pose into map frame
geometry_msgs::msg::TransformStamped tf_map;
try
{
tf_map = tf_buffer.lookupTransform(
"map", source_frame,
time_utils::from_message(pose_in.header.stamp));
}
catch (const tf2::ExtrapolationException &)
{
// currently falls back to retrive newest transform available for availability,
// Do validation of time stamp in the future
tf_map = tf_buffer.lookupTransform("map", source_frame, tf2::TimePointZero);
}
// apply transform
tf2::doTransform(pose_in, pose_out, tf_map);
return true;
}
} // namespace lanelet2_global_planner_nodes
} // namespace planning
} // namespace autoware
RCLCPP_COMPONENTS_REGISTER_NODE(
autoware::planning::lanelet2_global_planner_nodes::Lanelet2GlobalPlannerNode)
| 34.183453 | 99 | 0.645901 | Nova-UTD |
2d0c42246893e8ef34b9b1a5931801b2ca8e88f2 | 282 | cpp | C++ | src/linker.cpp | TartanLlama/li1I | 51b2305566b273ebc57e07e8787d8c806f0a2386 | [
"MIT"
] | 4 | 2018-05-07T10:59:28.000Z | 2021-06-19T17:56:17.000Z | src/linker.cpp | TartanLlama/li1I | 51b2305566b273ebc57e07e8787d8c806f0a2386 | [
"MIT"
] | null | null | null | src/linker.cpp | TartanLlama/li1I | 51b2305566b273ebc57e07e8787d8c806f0a2386 | [
"MIT"
] | null | null | null | #include <vector>
#include <memory>
#include <exception>
#include <llvm/Support/Program.h>
#include "linker.hpp"
using std::string;
void li1I::Linker::link(string input_object, string output_file)
{
throw std::runtime_error{"Not implemented yet, use your system linker"};
}
| 18.8 | 76 | 0.737589 | TartanLlama |
2d0d85f2a0738acad3798b737d26b87ed2c72cce | 23,249 | cpp | C++ | kuntar.cpp | ridgeware/dekaf2 | b914d880d1a5b7f5c8f89dedd36b13b7f4b0ee33 | [
"MIT"
] | null | null | null | kuntar.cpp | ridgeware/dekaf2 | b914d880d1a5b7f5c8f89dedd36b13b7f4b0ee33 | [
"MIT"
] | null | null | null | kuntar.cpp | ridgeware/dekaf2 | b914d880d1a5b7f5c8f89dedd36b13b7f4b0ee33 | [
"MIT"
] | 1 | 2021-08-20T16:15:01.000Z | 2021-08-20T16:15:01.000Z | /*
//
// DEKAF(tm): Lighter, Faster, Smarter (tm)
//
// Copyright (c) 2018, Ridgeware, Inc.
//
// +-------------------------------------------------------------------------+
// | /\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\|
// |/+---------------------------------------------------------------------+/|
// |/| |/|
// |\| ** THIS NOTICE MUST NOT BE REMOVED FROM THE SOURCE CODE MODULE ** |\|
// |/| |/|
// |\| OPEN SOURCE LICENSE |\|
// |/| |/|
// |\| 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. |\|
// |/| |/|
// |/+---------------------------------------------------------------------+/|
// |\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ |
// +-------------------------------------------------------------------------+
// large portions of this code are taken from
// https://github.com/JoachimSchurig/CppCDDB/blob/master/untar.cpp
// which is under a BSD style open source license
// Copyright © 2016 Joachim Schurig. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
*/
// I learned about the tar format and the various representations in the wild
// by reading through the code of the following fine projects:
//
// https://github.com/abergmeier/tarlib
//
// and
//
// https://techoverflow.net/blog/2013/03/29/reading-tar-files-in-c/
//
// The below code is another implementation, based on that information
// but following neither of the above implementations in the resulting
// code, particularly because this is a pure C++11 implementation for untar.
// So please do not blame those for any errors this code may cause or have.
#include "kuntar.h"
#include "kfilesystem.h"
#include "kstringutils.h"
#include "klog.h"
#include "kexception.h"
#include <cstring>
#include <array>
#include <boost/iostreams/filter/gzip.hpp>
#include <boost/iostreams/filter/bzip2.hpp>
namespace dekaf2 {
KUnTar::iterator::iterator(KUnTar* UnTar) noexcept
: m_UnTar(UnTar)
{
operator++();
}
//-----------------------------------------------------------------------------
KUnTar::iterator::reference KUnTar::iterator::operator*() const
//-----------------------------------------------------------------------------
{
if (m_UnTar)
{
return *m_UnTar;
}
else
{
throw KError("KUnTar::iterator out of range");
}
}
//-----------------------------------------------------------------------------
KUnTar::iterator& KUnTar::iterator::operator++() noexcept
//-----------------------------------------------------------------------------
{
if (m_UnTar)
{
if (m_UnTar->Next() == false)
{
m_UnTar = nullptr;
}
}
return *this;
} // operator++
//-----------------------------------------------------------------------------
void KUnTar::Decoded::Reset()
//-----------------------------------------------------------------------------
{
if (!m_bKeepMembersOnce)
{
m_sFilename.clear();
m_sLinkname.clear();
m_sUser.clear();
m_sGroup.clear();
m_iMode = 0;
m_iUserId = 0;
m_iGroupId = 0;
m_iFilesize = 0;
m_tModificationTime = 0;
m_bIsEnd = false;
m_bIsUstar = false;
m_EntryType = tar::Unknown;
}
else
{
m_bKeepMembersOnce = false;
}
} // Reset
//-----------------------------------------------------------------------------
void KUnTar::Decoded::clear()
//-----------------------------------------------------------------------------
{
m_bKeepMembersOnce = false;
Reset();
} // clear
//-----------------------------------------------------------------------------
uint64_t KUnTar::Decoded::FromNumbers(const char* pStart, uint16_t iSize)
//-----------------------------------------------------------------------------
{
// check if the null byte came before the end of the array
iSize = static_cast<uint16_t>(::strnlen(pStart, iSize));
KStringView sView(pStart, iSize);
auto chFirst = sView.front();
if (DEKAF2_UNLIKELY(m_bIsUstar && ((chFirst & 0x80) != 0)))
{
// MSB is set, this is a binary encoding
if (DEKAF2_UNLIKELY((chFirst & 0x7F) != 0))
{
// create a local copy with removed MSB bit
KString sBuffer(sView);
sBuffer[0] = (chFirst & 0x7f);
return kToInt<uint64_t>(sBuffer, 256);
}
else
{
sView.remove_prefix(1);
return kToInt<uint64_t>(sView, 256);
}
}
else
{
// this is an octal encoding
return kToInt<uint64_t>(sView, 8);
}
} // FromNumbers
#if (__GNUC__ > 10)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstringop-overread"
#endif
//-----------------------------------------------------------------------------
bool KUnTar::Decoded::Decode(const tar::TarHeader& TarHeader)
//-----------------------------------------------------------------------------
{
Reset();
// check for end header
if (TarHeader.raw[0] == 0)
{
// check if full header is 0, then this is the end header of an archive
m_bIsEnd = true;
for (auto ch : TarHeader.raw)
{
if (ch)
{
m_bIsEnd = false;
break;
}
}
if (m_bIsEnd)
{
return true;
}
}
// keep this on top before calling FromNumbers(), which has a dependency
m_bIsUstar = (std::memcmp("ustar", TarHeader.extension.ustar.indicator, 5) == 0);
// validate checksum
{
uint64_t header_checksum = FromNumbers(TarHeader.checksum, 8);
uint64_t sum { 0 };
// we calculate with unsigned chars first, as that is what today's
// tars typically do
for (uint16_t iPos = 0; iPos < 148; ++iPos)
{
sum += static_cast<uint8_t>(TarHeader.raw[iPos]);
}
for (uint16_t iPos = 0; iPos < 8; ++iPos)
{
sum += ' ';
}
for (uint16_t iPos = 148 + 8; iPos < tar::HeaderLen; ++iPos)
{
sum += static_cast<uint8_t>(TarHeader.raw[iPos]);
}
if (header_checksum != sum)
{
// try again with signed chars, which were used by some implementations
sum = 0;
for (uint16_t iPos = 0; iPos < 148; ++iPos)
{
sum += TarHeader.raw[iPos];
}
for (uint16_t iPos = 0; iPos < 8; ++iPos)
{
sum += ' ';
}
for (uint16_t iPos = 148 + 8; iPos < tar::HeaderLen; ++iPos)
{
sum += TarHeader.raw[iPos];
}
if (header_checksum != sum)
{
// that failed, too
kDebug(2, "invalid header checksum");
return false;
}
}
}
m_iMode = static_cast<uint32_t>(FromNumbers(TarHeader.mode, 8));
m_iUserId = static_cast<uint32_t>(FromNumbers(TarHeader.owner_ids.user, 8));
m_iGroupId = static_cast<uint32_t>(FromNumbers(TarHeader.owner_ids.group, 8));
if (m_bIsUstar)
{
// copy user and group
m_sUser.assign(TarHeader.extension.ustar.owner_names.user,
::strnlen(TarHeader.extension.ustar.owner_names.user, 32));
m_sGroup.assign(TarHeader.extension.ustar.owner_names.group,
::strnlen(TarHeader.extension.ustar.owner_names.group, 32));
// check if there is a filename prefix
auto plen = ::strnlen(TarHeader.extension.ustar.filename_prefix, 155);
// insert the prefix before the existing filename
if (plen)
{
m_sFilename.assign(TarHeader.extension.ustar.filename_prefix, plen);
m_sFilename += '/';
}
}
// append file name to a prefix (or none)
m_sFilename.append(TarHeader.file_name, ::strnlen(TarHeader.file_name, 100));
auto TypeFlag = TarHeader.extension.ustar.type_flag;
if (!m_sFilename.empty() && m_sFilename.back() == '/')
{
// make sure we detect also pre-1988 directory names :)
if (!TypeFlag)
{
TypeFlag = '5';
}
}
// now analyze the entry type
switch (TypeFlag)
{
case 0:
case '0':
// treat contiguous file as normal
case '7':
// normal file
if (m_EntryType == tar::Longname1)
{
// this is a subsequent read on GNU tar long names
// the current block contains only the filename and the next block contains metadata
// set the filename from the current header
m_sFilename.assign(TarHeader.file_name,
::strnlen(TarHeader.file_name, tar::HeaderLen));
// the next header contains the metadata, so replace the header before reading the metadata
m_EntryType = tar::Longname2;
m_bKeepMembersOnce = true;
return true;
}
m_EntryType = tar::File;
m_iFilesize = FromNumbers(TarHeader.file_bytes, 12);
m_tModificationTime = FromNumbers(TarHeader.modification_time , 12);
break;
case '1':
// link
m_EntryType = tar::Hardlink;
m_sLinkname.assign(TarHeader.extension.ustar.linked_file_name,
::strnlen(TarHeader.file_name, 100));
break;
case '2':
// symlink
m_EntryType = tar::Symlink;
m_sLinkname.assign(TarHeader.extension.ustar.linked_file_name,
::strnlen(TarHeader.file_name, 100));
break;
case '5':
// directory
m_EntryType = tar::Directory;
m_iFilesize = 0;
m_tModificationTime = FromNumbers(TarHeader.modification_time, 12);
break;
case '6':
// fifo
m_EntryType = tar::Fifo;
break;
case 'L':
// GNU long filename
m_EntryType = tar::Longname1;
m_bKeepMembersOnce = true;
return true;
default:
m_EntryType = tar::Unknown;
break;
}
return true;
} // Decode
#if (__GNUC__ > 10)
#pragma GCC diagnostic pop
#endif
//-----------------------------------------------------------------------------
KUnTar::KUnTar(KInStream& Stream, int AcceptedTypes, bool bSkipAppleResourceForks)
//-----------------------------------------------------------------------------
: m_Stream(Stream)
, m_AcceptedTypes(AcceptedTypes)
, m_bSkipAppleResourceForks(bSkipAppleResourceForks)
{
}
//-----------------------------------------------------------------------------
KUnTar::KUnTar(KStringView sArchiveFilename, int AcceptedTypes, bool bSkipAppleResourceForks)
//-----------------------------------------------------------------------------
: m_File(std::make_unique<KInFile>(sArchiveFilename))
, m_Stream(*m_File)
, m_AcceptedTypes(AcceptedTypes)
, m_bSkipAppleResourceForks(bSkipAppleResourceForks)
{
}
//-----------------------------------------------------------------------------
bool KUnTar::Read(void* buf, size_t len)
//-----------------------------------------------------------------------------
{
size_t rb = m_Stream.Read(buf, len);
if (rb != len)
{
return SetError(kFormat("unexpected end of input stream, trying to read {} bytes, but got only {}", len, rb));
}
return true;
} // Read
//-----------------------------------------------------------------------------
size_t KUnTar::CalcPadding()
//-----------------------------------------------------------------------------
{
if (Filesize() > 0)
{
// check if we have to skip some padding bytes (tar files have a block size of 512)
return (tar::HeaderLen - (Filesize() % tar::HeaderLen)) % tar::HeaderLen;
}
return 0;
} // CalcPadding
//-----------------------------------------------------------------------------
bool KUnTar::ReadPadding()
//-----------------------------------------------------------------------------
{
size_t padding = CalcPadding();
if (padding)
{
std::array<char, tar::HeaderLen> Padding;
if (!Read(Padding.data(), padding))
{
return SetError("cannot read block padding");
}
}
return true;
} // ReadPadding
//-----------------------------------------------------------------------------
bool KUnTar::Next()
//-----------------------------------------------------------------------------
{
// delete a previous error
m_Error.clear();
do
{
if (!m_bIsConsumed && (Filesize() > 0))
{
if (!SkipCurrentFile())
{
return false;
}
}
tar::TarHeader TarHeader;
if (!Read(&TarHeader, tar::HeaderLen))
{
return SetError("cannot not read tar header");
}
if (!m_Header.Decode(TarHeader))
{
// the only false return from Decode happens on a bad checksum compare
return SetError("invalid tar header (bad checksum)");
}
// this is the only valid exit condition from reading a tar archive - end header reached
if (m_Header.IsEnd())
{
// no error!
return false;
}
if (Filesize() > 0)
{
m_bIsConsumed = false;
}
} while ((Type() & m_AcceptedTypes) == 0
|| (m_bSkipAppleResourceForks && kBasename(Filename()).starts_with("._")));
return true;
} // Entry
//-----------------------------------------------------------------------------
bool KUnTar::Skip(size_t iSize)
//-----------------------------------------------------------------------------
{
if (!iSize)
{
return true;
}
enum { SKIP_BUFSIZE = 4096 };
std::array<char, SKIP_BUFSIZE> sBuffer;
size_t iRead = 0;
for (auto iRemain = iSize; iRemain;)
{
auto iChunk = std::min(sBuffer.size(), iRemain);
if (!Read(sBuffer.data(), iChunk))
{
break;
}
iRead += iChunk;
iRemain -= iChunk;
}
if (iRead == iSize)
{
return true;
}
else
{
return SetError("cannot not skip file");
}
} // Skip
//-----------------------------------------------------------------------------
bool KUnTar::SkipCurrentFile()
//-----------------------------------------------------------------------------
{
return Skip(Filesize() + CalcPadding());
} // SkipCurrentFile
//-----------------------------------------------------------------------------
bool KUnTar::Read(KOutStream& OutStream)
//-----------------------------------------------------------------------------
{
if (Type() != tar::File)
{
return SetError("cannot read - current tar entry is not a file");
}
if (!OutStream.Write(m_Stream, Filesize()).Good())
{
return SetError("cannot write to output stream");
}
if (!ReadPadding())
{
return false;
}
m_bIsConsumed = true;
return true;
} // Read
//-----------------------------------------------------------------------------
bool KUnTar::Read(KString& sBuffer)
//-----------------------------------------------------------------------------
{
sBuffer.clear();
if (Type() != tar::File)
{
return SetError("cannot read - current tar entry is not a file");
}
// resize the buffer to be able to read the file size
sBuffer.resize_uninitialized(Filesize());
// read the file into the buffer
if (!Read(&sBuffer[0], Filesize()))
{
return false;
}
if (!ReadPadding())
{
return false;
}
m_bIsConsumed = true;
return true;
} // Read
//-----------------------------------------------------------------------------
bool KUnTar::ReadFile(KStringViewZ sFilename)
//-----------------------------------------------------------------------------
{
KOutFile File(sFilename, std::ios_base::out & std::ios_base::trunc);
if (!File.is_open())
{
return SetError(kFormat("cannot create file {}", sFilename));
}
return Read(File);
} // ReadFile
//-----------------------------------------------------------------------------
KString KUnTar::CreateTargetDirectory(KStringViewZ sBaseDir, KStringViewZ sEntry, bool bWithSubdirectories)
//-----------------------------------------------------------------------------
{
KString sName = sBaseDir;
sName += kDirSep;
if (bWithSubdirectories)
{
KString sSafePath = kMakeSafePathname(sEntry, false);
KStringView sDirname = kDirname(sSafePath);
if (sDirname != ".")
{
sName += sDirname;
if (!kCreateDir(sName))
{
SetError(kFormat("cannot create directory: {}", sName));
return KString{};
}
sName += kDirSep;
}
sName += kBasename(sSafePath);
}
else
{
sName += kMakeSafeFilename(kBasename(sEntry), false);
}
return sName;
} // CreateTargetDirectory
//-----------------------------------------------------------------------------
bool KUnTar::ReadAll(KStringViewZ sTargetDirectory, bool bWithSubdirectories)
//-----------------------------------------------------------------------------
{
if (!kDirExists(sTargetDirectory))
{
if (!kCreateDir(sTargetDirectory))
{
return SetError(kFormat("cannot create directory: {}", sTargetDirectory));
}
}
for (auto& File : *this)
{
switch (File.Type())
{
case tar::Directory:
case tar::File:
{
auto sName = CreateTargetDirectory(sTargetDirectory, SafePath(), bWithSubdirectories);
if (sName.empty())
{
// error is already set
return false;
}
if (File.Type() == tar::File)
{
if (!ReadFile(sName))
{
// error is already set
return false;
}
}
}
break;
case tar::Hardlink:
case tar::Symlink:
{
auto sLink = CreateTargetDirectory(sTargetDirectory, SafePath(), bWithSubdirectories);
if (sLink.empty())
{
// error is already set
return false;
}
KString sOrigin = (bWithSubdirectories) ? File.SafeLinkPath() : File.SafeLinkName();
if (File.Type() == tar::Symlink)
{
if (!kCreateSymlink(sOrigin, sLink))
{
return SetError(kFormat("cannot create symlink {} > {}", sOrigin, sLink));
}
}
else
{
if (!kCreateHardlink(sOrigin, sLink))
{
return SetError(kFormat("cannot create hardlink {} > {}", sOrigin, sLink));
}
}
}
break;
default:
break;
}
}
return true;
} // ReadAll
//-----------------------------------------------------------------------------
bool KUnTar::File(KString& sName, KString& sBuffer)
//-----------------------------------------------------------------------------
{
sName.clear();
sBuffer.clear();
if (!Next())
{
return false;
}
if (Type() == tar::File)
{
if (!Read(sBuffer))
{
return false;
}
}
sName = Filename();
return true;
} // File
//-----------------------------------------------------------------------------
bool KUnTar::SetError(KString sError)
//-----------------------------------------------------------------------------
{
m_Error = std::move(sError);
kDebug(2, m_Error);
return false;
} // SetError
//-----------------------------------------------------------------------------
KUnTarCompressed::KUnTarCompressed(COMPRESSION Compression,
KInStream& InStream,
int AcceptedTypes,
bool bSkipAppleResourceForks)
//-----------------------------------------------------------------------------
: KUnTar(m_FilteredInStream, AcceptedTypes, bSkipAppleResourceForks)
{
SetupFilter(Compression, InStream);
} // ctor
//-----------------------------------------------------------------------------
KUnTarCompressed::KUnTarCompressed(COMPRESSION Compression,
KStringView sArchiveFilename,
int AcceptedTypes,
bool bSkipAppleResourceForks)
//-----------------------------------------------------------------------------
: KUnTar(m_FilteredInStream, AcceptedTypes, bSkipAppleResourceForks)
{
m_File = std::make_unique<KInFile>(sArchiveFilename);
if (Compression == AUTODETECT)
{
KString sSuffix = kExtension(sArchiveFilename).ToLower();
if (sSuffix == "tar")
{
Compression = NONE;
}
else if (sSuffix == "tgz" || sSuffix == "gz" || sSuffix == "gzip")
{
Compression = GZIP;
}
else if (sSuffix == "tbz" || sSuffix == "tbz2" || sSuffix == "bz2" || sSuffix == "bzip2")
{
Compression = BZIP2;
}
else
{
Compression = NONE;
}
}
SetupFilter(Compression, *m_File);
} // ctor
//-----------------------------------------------------------------------------
void KUnTarCompressed::SetupFilter(COMPRESSION Compression, KInStream& InStream)
//-----------------------------------------------------------------------------
{
switch (Compression)
{
case AUTODETECT:
case NONE:
break;
case GZIP:
m_Filter.push(boost::iostreams::gzip_decompressor());
break;
case BZIP2:
m_Filter.push(boost::iostreams::bzip2_decompressor());
break;
}
m_Filter.push(InStream.InStream());
} // SetupFilter
} // end of namespace dekaf2
| 27.383981 | 112 | 0.503678 | ridgeware |
2d101d27bd25729bdbd00f556345f40ac5a982ba | 1,800 | hpp | C++ | iehl/src/forward_rendering/vertex_array.hpp | the-last-willy/id3d | dc0d22e7247ac39fbc1fd8433acae378b7610109 | [
"MIT"
] | null | null | null | iehl/src/forward_rendering/vertex_array.hpp | the-last-willy/id3d | dc0d22e7247ac39fbc1fd8433acae378b7610109 | [
"MIT"
] | null | null | null | iehl/src/forward_rendering/vertex_array.hpp | the-last-willy/id3d | dc0d22e7247ac39fbc1fd8433acae378b7610109 | [
"MIT"
] | null | null | null | #pragma once
#include "scene/vertex_attribute/all.hpp"
#include "forward_renderer.hpp"
inline
gl::VertexArray vertex_array(
const ForwardRenderer&,
const VertexAttributeGroup& vag)
{
auto vao = gl::VertexArray();
if(gl::GetNamedBufferParameter(vag.normal_buffer, GL_BUFFER_SIZE) > 0) {
auto attribindex = GLuint(0);
auto bindingindex = GLuint(0);
auto size = GLint(3);
glVertexArrayAttribBinding(vao,
attribindex, bindingindex);
glVertexArrayAttribFormat(vao,
attribindex, size, GL_FLOAT, GL_FALSE, 0);
glVertexArrayVertexBuffer(vao,
bindingindex, vag.normal_buffer, 0, 4 * size);
glEnableVertexArrayAttrib(vao, attribindex);
}
if(gl::GetNamedBufferParameter(vag.position_buffer, GL_BUFFER_SIZE) > 0) {
auto attribindex = GLuint(1);
auto bindingindex = GLuint(1);
auto size = GLint(3);
glVertexArrayAttribBinding(vao,
attribindex, bindingindex);
glVertexArrayAttribFormat(vao,
attribindex, size, GL_FLOAT, GL_FALSE, 0);
glVertexArrayVertexBuffer(vao,
bindingindex, vag.position_buffer, 0, 4 * size);
glEnableVertexArrayAttrib(vao, attribindex);
}
if(gl::GetNamedBufferParameter(vag.texcoords_buffer, GL_BUFFER_SIZE) > 0) {
auto attribindex = GLuint(2);
auto bindingindex = GLuint(2);
auto size = GLint(2);
glVertexArrayAttribBinding(vao,
attribindex, bindingindex);
glVertexArrayAttribFormat(vao,
attribindex, size, GL_FLOAT, GL_FALSE, 0);
glVertexArrayVertexBuffer(vao,
bindingindex, vag.texcoords_buffer, 0, 4 * size);
glEnableVertexArrayAttrib(vao, attribindex);
}
return vao;
}
| 36 | 79 | 0.654444 | the-last-willy |
2d130e2d0d508c761edb26a276b4619e0b206ce2 | 3,548 | hpp | C++ | MultiSource/Benchmarks/DOE-ProxyApps-C++/miniFE/analytic_soln.hpp | gmlueck/llvm-test-suite | 7ff842b8fec970561fed78c9347e496538cf74f5 | [
"Apache-2.0"
] | 692 | 2015-11-12T13:56:43.000Z | 2022-03-30T03:45:59.000Z | MultiSource/Benchmarks/DOE-ProxyApps-C++/miniFE/analytic_soln.hpp | gmlueck/llvm-test-suite | 7ff842b8fec970561fed78c9347e496538cf74f5 | [
"Apache-2.0"
] | 1,096 | 2015-11-12T09:08:22.000Z | 2022-03-31T21:48:41.000Z | MultiSource/Benchmarks/DOE-ProxyApps-C++/miniFE/analytic_soln.hpp | gmlueck/llvm-test-suite | 7ff842b8fec970561fed78c9347e496538cf74f5 | [
"Apache-2.0"
] | 224 | 2015-11-12T21:17:03.000Z | 2022-03-30T00:57:48.000Z | #ifndef _analytic_soln_hpp_
#define _analytic_soln_hpp_
//@HEADER
// ************************************************************************
//
// MiniFE: Simple Finite Element Assembly and Solve
// Copyright (2006-2013) Sandia Corporation
//
// Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive
// license for use of this work by or on behalf of the U.S. Government.
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation; either version 2.1 of the
// License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
// USA
//
// ************************************************************************
//@HEADER
#include <cmath>
#ifndef MINIFE_SCALAR
#define MINIFE_SCALAR double;
#endif
namespace miniFE {
typedef MINIFE_SCALAR Scalar;
// The 'soln' function below computes the analytic solution for
// steady state temperature in a brick-shaped domain (formally called
// a rectangular parallelepiped). The inputs to the function are
// the x,y,z coordinates of the point at which temperature is to be
// computed, and the number of terms p,q in the series expansion.
//
// The equations used for the temperature solution are equations 9 and 10
// in section 6.2 of Carslaw & Jaeger, "Conduction of Heat in Solids".
//
// The paralellepiped being used is defined by this domain:
// 0 <= x <= 1.0
// 0 <= y <= 1.0
// 0 <= z <= 1.0
//
// With boundary conditions prescribing the temperature to be 1.0 on
// the x==1.0 face, and 0.0 on all other faces.
//
// Thus, in the equations from Carslaw & Jaeger, the following constants
// are used:
//
// a == b == c == 1.0 (the extents of the domain)
// v1 == 0.0 (temperature at x == 0.0)
// v2 == 1.0 (temperature at x == 1.0)
//
const Scalar PI = 3.141592653589793238462;
const Scalar PI_SQR = PI*PI;
const Scalar term0 = 16.0/(PI_SQR);
inline Scalar fcn_l(int p, int q)
{
return std::sqrt((2*p+1)*(2*p+1)*PI_SQR + (2*q+1)*(2*q+1)*PI_SQR);
}
inline Scalar fcn(int n, Scalar u)
{
return (2*n+1)*PI*u;
}
inline Scalar soln(Scalar x, Scalar y, Scalar z, int max_p, int max_q)
{
Scalar sum = 0;
for(int p=0; p<=max_p; ++p) {
const Scalar p21y = fcn(p, y);
const Scalar sin_py = std::sin(p21y)/(2*p+1);
for(int q=0; q<=max_q; ++q) {
const Scalar q21z = fcn(q, z);
const Scalar sin_qz = std::sin(q21z)/(2*q+1);
const Scalar l = fcn_l(p, q);
const Scalar sinh1 = std::sinh(l*x);
const Scalar sinh2 = std::sinh(l);
const Scalar tmp = (sinh1*sin_py)*(sin_qz/sinh2);
//if the scalar l gets too big, sinh(l) becomes inf.
//if that happens, tmp is a NaN.
//crude check for NaN:
//if tmp != tmp, tmp is NaN
if (tmp == tmp) {
sum += tmp;
}
else {
//if we got a NaN, break out of this inner loop and go to
//the next iteration of the outer loop.
break;
}
}
}
return term0*sum;
}
}//namespace miniFE
#endif /* _analytic_soln_hpp_ */
| 30.324786 | 75 | 0.636415 | gmlueck |
2d13dc676ee0c7d01385dc380c2b56596ab770d3 | 14,805 | cpp | C++ | RadeonGPUAnalyzerGUI/Src/rgMenuVulkan.cpp | jeongjoonyoo/AMD_RGA | 26c6bfdf83f372eeadb1874420aa2ed55569d50f | [
"MIT"
] | 2 | 2019-05-18T11:39:59.000Z | 2019-05-18T11:40:05.000Z | RadeonGPUAnalyzerGUI/Src/rgMenuVulkan.cpp | Acidburn0zzz/RGA | 35cd028602e21f6b8853fdc86b16153b693acb72 | [
"MIT"
] | null | null | null | RadeonGPUAnalyzerGUI/Src/rgMenuVulkan.cpp | Acidburn0zzz/RGA | 35cd028602e21f6b8853fdc86b16153b693acb72 | [
"MIT"
] | null | null | null | // C++.
#include <cassert>
#include <sstream>
// Local.
#include <RadeonGPUAnalyzerGUI/Include/Qt/rgMenuBuildSettingsItem.h>
#include <RadeonGPUAnalyzerGUI/Include/Qt/rgMenuVulkan.h>
#include <RadeonGPUAnalyzerGUI/Include/Qt/rgMenuFileItemGraphics.h>
#include <RadeonGPUAnalyzerGUI/Include/Qt/rgMenuPipelineStateItem.h>
#include <RadeonGPUAnalyzerGUI/Include/rgStringConstants.h>
#include <RadeonGPUAnalyzerGUI/Include/rgUtils.h>
rgMenuVulkan::rgMenuVulkan(QWidget* pParent)
: rgMenuGraphics(pParent)
{
}
void rgMenuVulkan::ConnectDefaultItemSignals()
{
// Handler invoked when the "Build settings" button is clicked.
assert(m_pBuildSettingsMenuItem != nullptr);
if (m_pBuildSettingsMenuItem != nullptr)
{
bool isConnected = connect(m_pBuildSettingsMenuItem->GetBuildSettingsButton(), &QPushButton::clicked, this, &rgMenu::HandleBuildSettingsButtonClicked);
assert(isConnected);
}
}
void rgMenuVulkan::ConnectMenuFileItemSignals(rgMenuFileItem* pMenuItem)
{
// Connect the file menu item selection handler for each new item.
bool isConnected = connect(pMenuItem, &rgMenuFileItemGraphics::MenuItemSelected, this, &rgMenu::MenuItemClicked);
assert(isConnected);
// Connect the file menu item rename handler for each new item.
isConnected = connect(pMenuItem, &rgMenuFileItem::FileRenamed, this, &rgMenu::HandleRenamedFile);
assert(isConnected);
}
void rgMenuVulkan::DeselectItems()
{
rgMenu::DeselectItems();
assert(m_pPipelineStateItem);
if (m_pPipelineStateItem != nullptr)
{
m_pPipelineStateItem->SetCurrent(false);
}
}
void rgMenuVulkan::ClearStageSourceFile(rgPipelineStage stage)
{
// Find the target stage item and update the attached shader file.
rgMenuFileItemGraphics* pStageItem = GetStageItem(stage);
assert(pStageItem != nullptr);
if (pStageItem != nullptr)
{
// Erase the file path from the path to menu item map.
const std::string& pathBeingRemoved = pStageItem->GetFilename();
auto filePathToItemMapIter = m_fullFilepathToMenuItem.find(pathBeingRemoved);
if (filePathToItemMapIter != m_fullFilepathToMenuItem.end())
{
m_fullFilepathToMenuItem.erase(filePathToItemMapIter);
}
// Clear out the filepath for the stage item.
pStageItem->SetShaderFile("", rgVulkanInputType::Unknown);
// Set the "occupied" property for this file item.
pStageItem->SetStageIsOccupied(false);
// Set the "current" property for this file item.
pStageItem->SetCurrent(false);
// Set the cursor type to arrow cursor.
pStageItem->SetCursor(Qt::ArrowCursor);
// Set the "+" sub button as selected.
RemoveSubButtonFocus();
HideRemoveFilePushButton();
pStageItem->SetButtonHighlighted(GraphicsMenuTabFocusItems::AddExistingFileButton);
m_hasTabFocus = GraphicsMenuTabFocusItems::AddExistingFileButton;
// Also set the tab focus index and focus index.
// Find out if one of the buttons is currently selected.
// If so, do not update the focus index.
if (!IsButtonPressed())
{
if (stage == rgPipelineStage::Compute)
{
m_focusIndex = 0;
}
else
{
m_focusIndex = static_cast<int>(stage);
}
m_tabFocusIndex = m_focusIndex;
}
// Remove the item from the list.
for (auto it = m_menuItems.begin(); it != m_menuItems.end(); it++)
{
if (*it == pStageItem)
{
m_menuItems.erase(it);
break;
}
}
}
// Emit a signal that indicates that the number of items in the menu change,
// and specify that the menu is not empty.
emit FileMenuItemCountChanged(false);
}
bool rgMenuVulkan::IsButtonPressed() const
{
bool buttonPressed = false;
assert(m_pBuildSettingsMenuItem != nullptr);
assert(m_pPipelineStateItem != nullptr);
if (m_pBuildSettingsMenuItem != nullptr && m_pPipelineStateItem != nullptr)
{
buttonPressed = m_pBuildSettingsMenuItem->IsCurrent() || m_pPipelineStateItem->IsCurrent();
}
return buttonPressed;
}
bool rgMenuVulkan::SetStageSourceFile(rgPipelineStage stage, const std::string& fullPath, rgVulkanInputType fileType, bool isNewFileItem)
{
bool ret = false;
// If a file with that name hasn't been added.
if (!IsFileInMenu(fullPath))
{
// Find the target stage item and update the attached shader file.
rgMenuFileItemGraphics* pStageItem = GetStageItem(stage);
assert(pStageItem != nullptr);
if (pStageItem != nullptr)
{
pStageItem->SetShaderFile(fullPath, fileType);
// Since users may add shader files to the pipeline stages in any order they choose, in
// order to use the Up/Down arrow keys to navigate through shader stage items, a linear
// list of menu items must be reconstructed.
RebuildMenuItemsList();
// Set the "occupied" property for this file item.
pStageItem->SetStageIsOccupied(true);
// Set the cursor for this item.
UpdateCursor(pStageItem);
// Hide the "Remove" button.
pStageItem->RemoveSubButtonFocus();
pStageItem->HideRemoveFilePushButton();
ret = true;
}
// Emit a signal that indicates that the number of items in the menu change,
// and specify that the menu is not empty.
emit FileMenuItemCountChanged(false);
// Add the file name and its full path to the map.
m_fullFilepathToMenuItem[fullPath] = pStageItem;
// Connect signals for the new file menu item.
ConnectMenuFileItemSignals(pStageItem);
// Select the file that was just opened.
HandleSelectedFileChanged(pStageItem);
if (isNewFileItem)
{
// If a file was newly-created (as opposed to being opened), display the
// item's renaming control immediately so the user can choose a new filename.
pStageItem->ShowRenameControls(true);
}
}
else
{
// Report the error.
std::stringstream msg;
msg << STR_ERR_CANNOT_ADD_FILE_A << fullPath << STR_ERR_CANNOT_ADD_FILE_B;
rgUtils::ShowErrorMessageBox(msg.str().c_str(), this);
// Remove the highlight.
rgMenuFileItemGraphics* pStageItem = GetStageItem(stage);
assert(pStageItem != nullptr);
if (pStageItem != nullptr)
{
pStageItem->SetCurrent(false);
pStageItem->SetHovered(false);
}
// Set the highlight for the current stage.
pStageItem = GetCurrentFileMenuItem();
assert(pStageItem != nullptr);
if (pStageItem != nullptr)
{
pStageItem->SetCurrent(true);
pStageItem->SetHovered(true);
}
}
return ret;
}
bool rgMenuVulkan::ReplaceStageFile(rgPipelineStage stage, const std::string& newFilePath, rgVulkanInputType fileType)
{
bool ret = false;
rgMenuFileItemGraphics* pFileItem = GetStageItem(stage);
assert(pFileItem != nullptr);
if (pFileItem != nullptr)
{
// Replace the file path in the file to item map.
const std::string& oldFilePath = pFileItem->GetFilename();
auto it = m_fullFilepathToMenuItem.find(oldFilePath);
if (it != m_fullFilepathToMenuItem.end())
{
assert(it->second == pFileItem);
if (it->second == pFileItem)
{
m_fullFilepathToMenuItem.erase(it);
m_fullFilepathToMenuItem[newFilePath] = pFileItem;
ret = true;
}
}
// Replace the file path in the item.
pFileItem->SetShaderFile(newFilePath, fileType);
}
return ret;
}
void rgMenuVulkan::HandleActivateItemAction()
{
// If focus index is in the range of the menu file items, select the appropriate file item.
const size_t totalStages = GetTotalPipelineStages();
if (m_pipelineType == rgPipelineType::Graphics && m_tabFocusIndex < totalStages ||
m_pipelineType == rgPipelineType::Compute && m_tabFocusIndex <= totalStages)
{
// See if a sub button is selected,
// and then execute accordingly.
if (m_hasTabFocus != GraphicsMenuTabFocusItems::NoButton)
{
// If the user hit enter when one of the sub-buttons were highlighted,
// process accordingly.
ProcessSubButtonAction();
}
else if (m_focusIndex < m_menuItems.size())
{
SelectFile(m_menuItems[m_focusIndex]);
m_pBuildSettingsMenuItem->SetCurrent(false);
m_pPipelineStateItem->SetCurrent(false);
}
else
{
// Local index: this is the index of the relevant
// item within the menu items after filtering out
// the file items (leaving only the other buttons:
// pipeline state and build settings).
const int PIPELINE_STATE_ITEM_LOCAL_INDEX = 0;
const int BUILD_SETTINGS_ITEM_LOCAL_INDEX = 1;
// Calculate the index of the relevant item.
const int buttonCount = GetButtonCount();
const size_t numOfFileItems = m_menuItems.size();
size_t targetItemIndex = static_cast<size_t>(m_tabFocusIndex) - numOfFileItems;
assert(targetItemIndex == 0 || targetItemIndex == 1);
if (targetItemIndex == PIPELINE_STATE_ITEM_LOCAL_INDEX)
{
// This is the pipeline state button - simulate a click.
m_pPipelineStateItem->ClickMenuItem();
}
else if(targetItemIndex == BUILD_SETTINGS_ITEM_LOCAL_INDEX)
{
// This is the build settings button - simulate a click.
m_pBuildSettingsMenuItem->ClickMenuItem();
}
else
{
// We shouldn't get here.
assert(false);
}
}
RemoveFileMenuButtonFocus();
}
else
{
// Deselect graphics menu file items.
for (rgMenuFileItem* pItem : m_menuItems)
{
rgMenuFileItemGraphics* pItemGraphics = static_cast<rgMenuFileItemGraphics*>(pItem);
assert(pItemGraphics != nullptr);
if (pItemGraphics != nullptr)
{
pItemGraphics->SetHovered(false);
pItemGraphics->SetCurrent(false);
}
}
// If out of range, special case handle the last focus items.
// Get index excluding file items.
size_t index = m_focusIndex - totalStages;
// Handle special cases for pipeline state and build settings item.
switch (index)
{
case static_cast<size_t>(GraphicsMenuFocusItems::BuildSettingsButton) :
m_pBuildSettingsMenuItem->GetBuildSettingsButton()->setStyleSheet(s_BUTTON_FOCUS_IN_STYLESHEET);
m_pBuildSettingsMenuItem->GetBuildSettingsButton()->click();
break;
case static_cast<size_t>(GraphicsMenuFocusItems::PipelineStateButton) :
GetPipelineStateItem()->GetPipelineStateButton()->setStyleSheet(s_BUTTON_FOCUS_IN_STYLESHEET);
GetPipelineStateItem()->GetPipelineStateButton()->click();
break;
default:
// Should never get here.
assert(false);
break;
}
}
}
void rgMenuVulkan::ProcessSubButtonAction()
{
const size_t totalStages = GetTotalPipelineStages();
assert(m_tabFocusIndex < totalStages);
if (m_tabFocusIndex < totalStages)
{
rgMenuFileItemGraphics* pItem = GetCurrentFileMenuItem();
assert(pItem != nullptr);
if (pItem != nullptr)
{
switch (m_hasTabFocus)
{
case (GraphicsMenuTabFocusItems::RemoveButton):
pItem->ProcessRemoveButtonClick();
break;
case (GraphicsMenuTabFocusItems::AddExistingFileButton):
pItem->ProcessAddExistingFileButtonClick();
break;
default:
// Do not assert here.
// Doing so will cause asserts any time the user
// clicks on a file menu item, or hits enter when
// a file menu item has the focus.
break;
}
}
}
}
void rgMenuVulkan::HandleSelectedFileChanged(rgMenuFileItem* pSelected)
{
rgMenuFileItemGraphics* pGraphicsItem = qobject_cast<rgMenuFileItemGraphics*>(pSelected);
assert(pGraphicsItem != nullptr);
// Set focus index to newly selected item.
for (size_t i = 0; i < m_menuItems.size() && pGraphicsItem != nullptr; i++)
{
if (m_menuItems[i] == pSelected)
{
// Update the focus and tab indices. Compute indices are always
// 0 because there's only 1 item in the compute pipeline menu.
rgPipelineStage stageType = pGraphicsItem->GetStage();
if (stageType != rgPipelineStage::Compute)
{
m_focusIndex = static_cast<size_t>(stageType);
m_tabFocusIndex = static_cast<size_t>(stageType);
}
else
{
m_focusIndex = 0;
m_tabFocusIndex = 0;
}
break;
}
}
// Update the current stage value.
if (pGraphicsItem != nullptr)
{
m_currentStage = pGraphicsItem->GetStage();
}
// Display the currently selected file in the source editor.
DisplayFileInEditor(pSelected);
// Update button selection values.
m_pPipelineStateItem->SetCurrent(false);
m_pBuildSettingsMenuItem->SetCurrent(false);
// Set the pipeline state and build settings buttons to have focus out style sheets.
assert(m_pBuildSettingsMenuItem);
assert(m_pPipelineStateItem);
if (m_pBuildSettingsMenuItem != nullptr && m_pPipelineStateItem != nullptr)
{
m_pBuildSettingsMenuItem->GetBuildSettingsButton()->setStyleSheet(s_BUTTON_FOCUS_OUT_STYLESHEET);
m_pBuildSettingsMenuItem->GetBuildSettingsButton()->setCursor(Qt::PointingHandCursor);
m_pPipelineStateItem->GetPipelineStateButton()->setStyleSheet(s_BUTTON_FOCUS_OUT_STYLESHEET);
m_pPipelineStateItem->GetPipelineStateButton()->setCursor(Qt::PointingHandCursor);
}
}
void rgMenuVulkan::UpdateFocusIndex()
{
m_focusIndex = static_cast<size_t>(m_currentStage);
m_tabFocusIndex = static_cast<size_t>(m_currentStage);
} | 35.25 | 159 | 0.633705 | jeongjoonyoo |
2d163d84d0674c9e91ced56d3de3a8c83605802a | 1,386 | cpp | C++ | hw/2019-11-15/D.cpp | Riteme/test | b511d6616a25f4ae8c3861e2029789b8ee4dcb8d | [
"BSD-Source-Code"
] | 3 | 2018-08-30T09:43:20.000Z | 2019-12-03T04:53:43.000Z | hw/2019-11-15/D.cpp | Riteme/test | b511d6616a25f4ae8c3861e2029789b8ee4dcb8d | [
"BSD-Source-Code"
] | null | null | null | hw/2019-11-15/D.cpp | Riteme/test | b511d6616a25f4ae8c3861e2029789b8ee4dcb8d | [
"BSD-Source-Code"
] | null | null | null | #include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
#define NMAX 100000
static int n, q;
static vector<int> G[NMAX + 10];
static int ans[NMAX + 10];
static int dist[NMAX + 10];
void dfs(int x, int f) {
for (int i = 0; i < G[x].size(); i++) {
int v = G[x][i];
if (v == f) continue;
dist[v] = dist[x] + 1;
dfs(v, x);
}
}
int main() {
int T;
scanf("%d", &T);
while (T--) {
scanf("%d%d", &n, &q);
for (int i = 1; i <= n; i++)
G[i].clear();
for (int i = 1; i < n; i++) {
int u, v;
scanf("%d%d", &u, &v);
G[u].push_back(v);
G[v].push_back(u);
}
memset(dist + 1, 0, sizeof(int) * n);
dfs(1, 0);
int mx = 0, mp;
for (int u = 1; u <= n; u++) if (dist[u] > mx) {
mx = dist[u];
mp = u;
}
memset(dist + 1, 0, sizeof(int) * n);
dfs(mp, 0);
int len = 0;
for (int i = 1; i <= n; i++)
len = max(len, dist[i]);
for (int i = 1; i <= len + 1; i++)
ans[i] = i - 1;
for (int i = len + 2; i <= n; i++)
ans[i] = ans[i - 1] + 2;
while (q--) {
int K;
scanf("%d", &K);
printf("%d\n", ans[K]);
}
}
return 0;
}
| 22.354839 | 56 | 0.382395 | Riteme |
2d167a9cf4824caebe65c82b788698d5b5c7d84d | 5,780 | cpp | C++ | osquery/sql/benchmarks/sql_benchmarks.cpp | trizt/osquery | 9256819b8161ab1e02ea0d7eb55da132f197723d | [
"BSD-3-Clause"
] | 1 | 2018-10-30T03:58:24.000Z | 2018-10-30T03:58:24.000Z | osquery/sql/benchmarks/sql_benchmarks.cpp | trizt/osquery | 9256819b8161ab1e02ea0d7eb55da132f197723d | [
"BSD-3-Clause"
] | null | null | null | osquery/sql/benchmarks/sql_benchmarks.cpp | trizt/osquery | 9256819b8161ab1e02ea0d7eb55da132f197723d | [
"BSD-3-Clause"
] | 2 | 2020-09-23T04:49:23.000Z | 2022-03-29T17:32:31.000Z | /*
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <benchmark/benchmark.h>
#include <osquery/core.h>
#include <osquery/registry.h>
#include <osquery/sql.h>
#include <osquery/tables.h>
#include "osquery/sql/virtual_table.h"
namespace osquery {
class BenchmarkTablePlugin : public TablePlugin {
private:
TableColumns columns() const {
return {
std::make_tuple("test_int", INTEGER_TYPE, ColumnOptions::DEFAULT),
std::make_tuple("test_text", TEXT_TYPE, ColumnOptions::DEFAULT),
};
}
QueryData generate(QueryContext& ctx) {
QueryData results;
results.push_back({{"test_int", "0"}});
results.push_back({{"test_int", "0"}, {"test_text", "hello"}});
return results;
}
};
static void SQL_virtual_table_registry(benchmark::State& state) {
// Add a sample virtual table plugin.
// Profile calling the plugin's column data.
Registry::add<BenchmarkTablePlugin>("table", "benchmark");
while (state.KeepRunning()) {
PluginResponse res;
Registry::call("table", "benchmark", {{"action", "generate"}}, res);
}
}
BENCHMARK(SQL_virtual_table_registry);
static void SQL_virtual_table_internal(benchmark::State& state) {
Registry::add<BenchmarkTablePlugin>("table", "benchmark");
PluginResponse res;
Registry::call("table", "benchmark", {{"action", "columns"}}, res);
// Attach a sample virtual table.
auto dbc = SQLiteDBManager::get();
attachTableInternal("benchmark", columnDefinition(res), dbc);
while (state.KeepRunning()) {
QueryData results;
queryInternal("select * from benchmark", results, dbc->db());
}
}
BENCHMARK(SQL_virtual_table_internal);
static void SQL_virtual_table_internal_global(benchmark::State& state) {
Registry::add<BenchmarkTablePlugin>("table", "benchmark");
PluginResponse res;
Registry::call("table", "benchmark", {{"action", "columns"}}, res);
while (state.KeepRunning()) {
// Get a connection to the persistent database.
auto dbc = SQLiteDBManager::get();
attachTableInternal("benchmark", columnDefinition(res), dbc);
QueryData results;
queryInternal("select * from benchmark", results, dbc->db());
}
}
BENCHMARK(SQL_virtual_table_internal_global);
static void SQL_virtual_table_internal_unique(benchmark::State& state) {
Registry::add<BenchmarkTablePlugin>("table", "benchmark");
PluginResponse res;
Registry::call("table", "benchmark", {{"action", "columns"}}, res);
while (state.KeepRunning()) {
// Get a new database connection (to a unique database).
auto dbc = SQLiteDBManager::getUnique();
attachTableInternal("benchmark", columnDefinition(res), dbc);
QueryData results;
queryInternal("select * from benchmark", results, dbc->db());
}
}
BENCHMARK(SQL_virtual_table_internal_unique);
class BenchmarkLongTablePlugin : public TablePlugin {
private:
TableColumns columns() const {
return {
std::make_tuple("test_int", INTEGER_TYPE, ColumnOptions::DEFAULT),
std::make_tuple("test_text", TEXT_TYPE, ColumnOptions::DEFAULT),
};
}
QueryData generate(QueryContext& ctx) {
QueryData results;
for (int i = 0; i < 1000; i++) {
results.push_back({{"test_int", "0"}, {"test_text", "hello"}});
}
return results;
}
};
static void SQL_virtual_table_internal_long(benchmark::State& state) {
Registry::add<BenchmarkLongTablePlugin>("table", "long_benchmark");
PluginResponse res;
Registry::call("table", "long_benchmark", {{"action", "columns"}}, res);
// Attach a sample virtual table.
auto dbc = SQLiteDBManager::getUnique();
attachTableInternal("long_benchmark", columnDefinition(res), dbc);
while (state.KeepRunning()) {
QueryData results;
queryInternal("select * from long_benchmark", results, dbc->db());
}
}
BENCHMARK(SQL_virtual_table_internal_long);
class BenchmarkWideTablePlugin : public TablePlugin {
private:
TableColumns columns() const override {
TableColumns cols;
for (int i = 0; i < 20; i++) {
cols.push_back(std::make_tuple(
"test_" + std::to_string(i), INTEGER_TYPE, ColumnOptions::DEFAULT));
}
return cols;
}
QueryData generate(QueryContext& ctx) override {
QueryData results;
for (int k = 0; k < 50; k++) {
Row r;
for (int i = 0; i < 20; i++) {
r["test_" + std::to_string(i)] = "0";
}
results.push_back(r);
}
return results;
}
};
static void SQL_virtual_table_internal_wide(benchmark::State& state) {
Registry::add<BenchmarkWideTablePlugin>("table", "wide_benchmark");
PluginResponse res;
Registry::call("table", "wide_benchmark", {{"action", "columns"}}, res);
// Attach a sample virtual table.
auto dbc = SQLiteDBManager::getUnique();
attachTableInternal("wide_benchmark", columnDefinition(res), dbc);
while (state.KeepRunning()) {
QueryData results;
queryInternal("select * from wide_benchmark", results, dbc->db());
}
}
BENCHMARK(SQL_virtual_table_internal_wide);
static void SQL_select_metadata(benchmark::State& state) {
auto dbc = SQLiteDBManager::get();
while (state.KeepRunning()) {
QueryData results;
queryInternal(
"select count(*) from sqlite_temp_master;", results, dbc->db());
}
}
BENCHMARK(SQL_select_metadata);
static void SQL_select_basic(benchmark::State& state) {
// Profile executing a query against an internal, already attached table.
while (state.KeepRunning()) {
auto results = SQLInternal("select * from benchmark");
}
}
BENCHMARK(SQL_select_basic);
}
| 29.191919 | 79 | 0.692907 | trizt |
2d1776aac2e4aea98a712e4896a4aad4c598364a | 2,658 | cpp | C++ | visual/kinect2/kinect2.cpp | TimothyYong/Tachikoma-Project | c7af70f2c58fe43f25331fd03589845480ae0f16 | [
"MIT"
] | 1 | 2016-02-02T23:13:54.000Z | 2016-02-02T23:13:54.000Z | visual/kinect2/kinect2.cpp | TimothyYong/Tachikoma-Project | c7af70f2c58fe43f25331fd03589845480ae0f16 | [
"MIT"
] | null | null | null | visual/kinect2/kinect2.cpp | TimothyYong/Tachikoma-Project | c7af70f2c58fe43f25331fd03589845480ae0f16 | [
"MIT"
] | null | null | null | #include <cstdio>
#include <cmath>
#include <opencv2/imgproc/imgproc.hpp>
#include "kinect.h"
using namespace cv;
using namespace std;
/* This file accesses the Kinect Device and gets its video and depth frames. If a depth frame is deteced, a new distance frame is created as well */
KinectDevice::KinectDevice(freenect_context *_ctx, int _index) :
Freenect::FreenectDevice(_ctx, _index),
depth_buffer(FREENECT_DEPTH_11BIT),
video_buffer(FREENECT_VIDEO_RGB),
gamma_buffer(2048),
new_depth_frame(false),
new_video_frame(false),
depthMat(Size(640, 480), CV_16UC1),
videoMat(Size(640, 480), CV_8UC3),
new_distance_frame(false),
distanceMat(Size(640, 480), CV_64F),
rows(640),
cols(480) {
for (uint32_t i = 0; i < 2048; i++) {
float v = i / 2048.0;
v = pow(v, 3) * 6;
this->gamma_buffer[i] = v * 6 * 256;
}
}
KinectDevice::~KinectDevice() {
}
void KinectDevice::DepthCallback(void *data, uint32_t timestamp) {
this->depth_lock.lock();
this->depthMat.data = (uint8_t *)data;
this->new_depth_frame = true;
this->new_distance_frame = true;
this->depth_lock.unlock();
}
void KinectDevice::VideoCallback(void *data, uint32_t timestamp) {
this->video_lock.lock();
this->videoMat.data = (uint8_t *)data;
this->new_video_frame = true;
this->video_lock.unlock();
}
bool KinectDevice::getDepth(Mat& output) {
this->depth_lock.lock();
if (this->new_depth_frame) {
this->depthMat.copyTo(output);
this->new_depth_frame = false;
this->depth_lock.unlock();
return true;
} else {
this->depthMat.copyTo(output);
this->depth_lock.unlock();
return false;
}
}
bool KinectDevice::getVideo(Mat& output) {
this->video_lock.lock();
if (this->new_video_frame) {
cvtColor(this->videoMat, output, COLOR_RGB2BGR);
this->new_video_frame = false;
this->video_lock.unlock();
return true;
} else {
cvtColor(this->videoMat, output, COLOR_RGB2BGR);
this->video_lock.unlock();
return false;
}
}
bool KinectDevice::getDistance(Mat &output) {
this->depth_lock.lock();
if (this->new_distance_frame) {
for (int y = 0; y < this->depthMat.rows; y++) {
for (int x = 0; x < this->depthMat.cols; x++) {
this->distanceMat.at<double>(y, x) = raw2meters(this->depthMat.at<uint16_t>(y, x));
}
}
this->new_distance_frame = false;
this->depth_lock.unlock();
return true;
} else {
this->distanceMat.copyTo(output);
this->depth_lock.unlock();
return false;
}
}
double KinectDevice::raw2meters(uint16_t raw) {
// stephane maganate
return (0.1236 * tan((double)raw / 2842.5 + 1.1863));
}
| 26.848485 | 148 | 0.667043 | TimothyYong |
2d17d6530567c0559aa09a34e9e6baf500cc795f | 1,581 | cc | C++ | peridot/lib/testing/module_resolver_fake.cc | OpenTrustGroup/fuchsia | 647e593ea661b8bf98dcad2096e20e8950b24a97 | [
"BSD-3-Clause"
] | 1 | 2019-04-21T18:02:26.000Z | 2019-04-21T18:02:26.000Z | peridot/lib/testing/module_resolver_fake.cc | OpenTrustGroup/fuchsia | 647e593ea661b8bf98dcad2096e20e8950b24a97 | [
"BSD-3-Clause"
] | 16 | 2020-09-04T19:01:11.000Z | 2021-05-28T03:23:09.000Z | peridot/lib/testing/module_resolver_fake.cc | OpenTrustGroup/fuchsia | 647e593ea661b8bf98dcad2096e20e8950b24a97 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2018 The Fuchsia 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 "peridot/lib/testing/module_resolver_fake.h"
namespace modular {
ModuleResolverFake::ModuleResolverFake() { find_modules_response_.results.resize(0); }
ModuleResolverFake::~ModuleResolverFake() = default;
void ModuleResolverFake::SetStatus(fuchsia::modular::FindModulesStatus status) {
find_modules_response_.status = status;
}
void ModuleResolverFake::FindModules(fuchsia::modular::FindModulesQuery query,
FindModulesCallback callback) {
if (find_modules_validate_fn_) {
find_modules_validate_fn_(query);
}
callback(std::move(find_modules_response_));
}
void ModuleResolverFake::Connect(fidl::InterfaceRequest<fuchsia::modular::ModuleResolver> request) {
bindings_.AddBinding(this, std::move(request));
}
void ModuleResolverFake::SetManifest(fuchsia::modular::ModuleManifestPtr manifest) {
manifest_ = std::move(manifest);
}
void ModuleResolverFake::AddFindModulesResult(fuchsia::modular::FindModulesResult result) {
find_modules_response_.results.push_back(std::move(result));
}
void ModuleResolverFake::SetFindModulesValidation(
fit::function<void(const fuchsia::modular::FindModulesQuery&)> fn) {
find_modules_validate_fn_ = std::move(fn);
}
void ModuleResolverFake::SetGetModuleManifestValidation(
fit::function<void(const fidl::StringPtr&)> fn) {
get_module_manifest_validate_fn_ = std::move(fn);
}
} // namespace modular
| 32.9375 | 100 | 0.767868 | OpenTrustGroup |
2d231710ec68724b796f73830cb079d37898b1a9 | 2,406 | hpp | C++ | modules/core/combinatorial/include/nt2/toolbox/combinatorial/functions/scalar/gcd.hpp | timblechmann/nt2 | 6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce | [
"BSL-1.0"
] | 2 | 2016-09-14T00:23:53.000Z | 2018-01-14T12:51:18.000Z | modules/core/combinatorial/include/nt2/toolbox/combinatorial/functions/scalar/gcd.hpp | timblechmann/nt2 | 6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce | [
"BSL-1.0"
] | null | null | null | modules/core/combinatorial/include/nt2/toolbox/combinatorial/functions/scalar/gcd.hpp | timblechmann/nt2 | 6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce | [
"BSL-1.0"
] | null | null | null | //==============================================================================
// Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II
// Copyright 2009 - 2011 LRI UMR 8623 CNRS/Univ Paris Sud XI
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef NT2_TOOLBOX_COMBINATORIAL_FUNCTIONS_SCALAR_GCD_HPP_INCLUDED
#define NT2_TOOLBOX_COMBINATORIAL_FUNCTIONS_SCALAR_GCD_HPP_INCLUDED
#include <nt2/toolbox/combinatorial/functions/gcd.hpp>
#include <nt2/include/functions/scalar/is_flint.hpp>
#include <nt2/include/functions/scalar/is_not_finite.hpp>
#include <nt2/include/functions/scalar/is_nez.hpp>
#include <nt2/include/functions/scalar/rem.hpp>
#include <nt2/include/constants/real.hpp>
/////////////////////////////////////////////////////////////////////////////
// Implementation when type A0 is arithmetic_
/////////////////////////////////////////////////////////////////////////////
namespace nt2 { namespace ext
{
NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::gcd_, tag::cpu_
, (A0)
, (scalar_< integer_<A0> >)(scalar_< integer_<A0> >)
)
{
typedef A0 result_type;
NT2_FUNCTOR_CALL_REPEAT(2)
{
result_type a(a0);
result_type b(a1);
while (b) {
const result_type r = a % b;
a = b;
b = r;
}
return a;
}
};
} }
/////////////////////////////////////////////////////////////////////////////
//Implementation when type A0 is floating_
/////////////////////////////////////////////////////////////////////////////
namespace nt2 { namespace ext
{
NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::gcd_, tag::cpu_
, (A0)
, (scalar_< floating_<A0> >)(scalar_< floating_<A0> >)
)
{
typedef A0 result_type;
NT2_FUNCTOR_CALL_REPEAT(2)
{
result_type a(a0);
result_type b(a1);
if (!b) return a;
if (!is_flint(a)||!is_flint(b)) return Nan<result_type>();
while (b) {
result_type r = rem(a, b);
a = b;
b = r;
}
return a;
}
};
} }
#endif
| 32.958904 | 82 | 0.471322 | timblechmann |
2d25bd97f5de8c170c7d94ce038e3042e8cce6f2 | 3,396 | cc | C++ | core/gen/server.grpc.pb.cc | dishanphilips/Jade | abefc34ec81b5c2f69e68f10ec1309fb1d786aba | [
"MIT"
] | null | null | null | core/gen/server.grpc.pb.cc | dishanphilips/Jade | abefc34ec81b5c2f69e68f10ec1309fb1d786aba | [
"MIT"
] | null | null | null | core/gen/server.grpc.pb.cc | dishanphilips/Jade | abefc34ec81b5c2f69e68f10ec1309fb1d786aba | [
"MIT"
] | null | null | null | // Generated by the gRPC C++ plugin.
// If you make any local change, they will be lost.
// source: server.proto
#include "server.pb.h"
#include "server.grpc.pb.h"
#include <functional>
#include <grpcpp/impl/codegen/async_stream.h>
#include <grpcpp/impl/codegen/async_unary_call.h>
#include <grpcpp/impl/codegen/channel_interface.h>
#include <grpcpp/impl/codegen/client_unary_call.h>
#include <grpcpp/impl/codegen/client_callback.h>
#include <grpcpp/impl/codegen/message_allocator.h>
#include <grpcpp/impl/codegen/method_handler.h>
#include <grpcpp/impl/codegen/rpc_service_method.h>
#include <grpcpp/impl/codegen/server_callback.h>
#include <grpcpp/impl/codegen/server_callback_handlers.h>
#include <grpcpp/impl/codegen/server_context.h>
#include <grpcpp/impl/codegen/service_type.h>
#include <grpcpp/impl/codegen/sync_stream.h>
namespace JadeCore {
static const char* RpcBase_method_names[] = {
"/JadeCore.RpcBase/Handle",
};
std::unique_ptr< RpcBase::Stub> RpcBase::NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel, const ::grpc::StubOptions& options) {
(void)options;
std::unique_ptr< RpcBase::Stub> stub(new RpcBase::Stub(channel));
return stub;
}
RpcBase::Stub::Stub(const std::shared_ptr< ::grpc::ChannelInterface>& channel)
: channel_(channel), rpcmethod_Handle_(RpcBase_method_names[0], ::grpc::internal::RpcMethod::BIDI_STREAMING, channel)
{}
::grpc::ClientReaderWriter< ::JadeCore::Command, ::JadeCore::Command>* RpcBase::Stub::HandleRaw(::grpc::ClientContext* context) {
return ::grpc_impl::internal::ClientReaderWriterFactory< ::JadeCore::Command, ::JadeCore::Command>::Create(channel_.get(), rpcmethod_Handle_, context);
}
void RpcBase::Stub::experimental_async::Handle(::grpc::ClientContext* context, ::grpc::experimental::ClientBidiReactor< ::JadeCore::Command,::JadeCore::Command>* reactor) {
::grpc_impl::internal::ClientCallbackReaderWriterFactory< ::JadeCore::Command,::JadeCore::Command>::Create(stub_->channel_.get(), stub_->rpcmethod_Handle_, context, reactor);
}
::grpc::ClientAsyncReaderWriter< ::JadeCore::Command, ::JadeCore::Command>* RpcBase::Stub::AsyncHandleRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag) {
return ::grpc_impl::internal::ClientAsyncReaderWriterFactory< ::JadeCore::Command, ::JadeCore::Command>::Create(channel_.get(), cq, rpcmethod_Handle_, context, true, tag);
}
::grpc::ClientAsyncReaderWriter< ::JadeCore::Command, ::JadeCore::Command>* RpcBase::Stub::PrepareAsyncHandleRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq) {
return ::grpc_impl::internal::ClientAsyncReaderWriterFactory< ::JadeCore::Command, ::JadeCore::Command>::Create(channel_.get(), cq, rpcmethod_Handle_, context, false, nullptr);
}
RpcBase::Service::Service() {
AddMethod(new ::grpc::internal::RpcServiceMethod(
RpcBase_method_names[0],
::grpc::internal::RpcMethod::BIDI_STREAMING,
new ::grpc::internal::BidiStreamingHandler< RpcBase::Service, ::JadeCore::Command, ::JadeCore::Command>(
std::mem_fn(&RpcBase::Service::Handle), this)));
}
RpcBase::Service::~Service() {
}
::grpc::Status RpcBase::Service::Handle(::grpc::ServerContext* context, ::grpc::ServerReaderWriter< ::JadeCore::Command, ::JadeCore::Command>* stream) {
(void) context;
(void) stream;
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
} // namespace JadeCore
| 45.891892 | 179 | 0.746466 | dishanphilips |
2d26b1a96815542357f0887e0615d0e1fca59309 | 6,313 | cpp | C++ | lightstep/src/ngx_http_lightstep_module.cpp | SEJeff/nginx-opentracing | 2cea68b20c744842171533b10385576f8380a8a4 | [
"Apache-2.0"
] | 2 | 2019-06-17T22:54:04.000Z | 2019-06-18T10:50:01.000Z | lightstep/src/ngx_http_lightstep_module.cpp | SEJeff/nginx-opentracing | 2cea68b20c744842171533b10385576f8380a8a4 | [
"Apache-2.0"
] | null | null | null | lightstep/src/ngx_http_lightstep_module.cpp | SEJeff/nginx-opentracing | 2cea68b20c744842171533b10385576f8380a8a4 | [
"Apache-2.0"
] | null | null | null | #include <lightstep/tracer.h>
#include <opentracing/tracer.h>
#include <cstdlib>
extern "C" {
#include <nginx.h>
#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_http.h>
extern ngx_module_t ngx_http_lightstep_module;
}
//------------------------------------------------------------------------------
// to_string
//------------------------------------------------------------------------------
static inline std::string to_string(const ngx_str_t &ngx_str) {
return {reinterpret_cast<char *>(ngx_str.data), ngx_str.len};
}
//------------------------------------------------------------------------------
// lightstep_main_conf_t
//------------------------------------------------------------------------------
struct lightstep_main_conf_t {
ngx_str_t access_token;
ngx_str_t component_name;
ngx_str_t collector_host;
ngx_flag_t collector_plaintext = NGX_CONF_UNSET;
ngx_str_t collector_port;
};
//------------------------------------------------------------------------------
// lightstep_module_init
//------------------------------------------------------------------------------
static ngx_int_t lightstep_module_init(ngx_conf_t *cf) {
auto main_conf = static_cast<lightstep_main_conf_t *>(
ngx_http_conf_get_module_main_conf(cf, ngx_http_lightstep_module));
// Validate the configuration
if (!main_conf->access_token.data) {
ngx_log_error(NGX_LOG_ERR, cf->log, 0,
"`lighstep_access_token` must be specified");
return NGX_ERROR;
}
return NGX_OK;
}
//------------------------------------------------------------------------------
// lightstep_init_worker
//------------------------------------------------------------------------------
static ngx_int_t lightstep_init_worker(ngx_cycle_t *cycle) {
auto main_conf = static_cast<lightstep_main_conf_t *>(
ngx_http_cycle_get_module_main_conf(cycle, ngx_http_lightstep_module));
lightstep::LightStepTracerOptions tracer_options;
if (!main_conf->access_token.data) {
ngx_log_error(NGX_LOG_ERR, cycle->log, 0,
"`lighstep_access_token` must be specified");
return NGX_ERROR;
}
tracer_options.access_token = to_string(main_conf->access_token);
if (main_conf->collector_host.data)
tracer_options.collector_host = to_string(main_conf->collector_host);
if (main_conf->collector_port.data)
// TODO: Check for errors here?
tracer_options.collector_port =
std::stoi(to_string(main_conf->collector_port));
if (main_conf->collector_plaintext != NGX_CONF_UNSET)
tracer_options.collector_plaintext = main_conf->collector_plaintext;
if (main_conf->component_name.data)
tracer_options.component_name = to_string(main_conf->component_name);
else
tracer_options.component_name = "nginx";
auto tracer = lightstep::MakeLightStepTracer(std::move(tracer_options));
if (!tracer) {
ngx_log_error(NGX_LOG_ERR, cycle->log, 0,
"Failed to create LightStep tracer");
return NGX_OK;
}
opentracing::Tracer::InitGlobal(std::move(tracer));
return NGX_OK;
}
//------------------------------------------------------------------------------
// create_lightstep_main_conf
//------------------------------------------------------------------------------
static void *create_lightstep_main_conf(ngx_conf_t *conf) {
auto main_conf = static_cast<lightstep_main_conf_t *>(
ngx_pcalloc(conf->pool, sizeof(lightstep_main_conf_t)));
// Default initialize members.
*main_conf = lightstep_main_conf_t();
if (!main_conf) return nullptr;
return main_conf;
}
//------------------------------------------------------------------------------
// lightstep_module_ctx
//------------------------------------------------------------------------------
static ngx_http_module_t lightstep_module_ctx = {
nullptr, /* preconfiguration */
lightstep_module_init, /* postconfiguration */
create_lightstep_main_conf, /* create main configuration */
nullptr, /* init main configuration */
nullptr, /* create server configuration */
nullptr, /* merge server configuration */
nullptr, /* create location configuration */
nullptr /* merge location configuration */
};
//------------------------------------------------------------------------------
// lightstep_commands
//------------------------------------------------------------------------------
static ngx_command_t lightstep_commands[] = {
{ngx_string("lightstep_access_token"), NGX_HTTP_MAIN_CONF | NGX_CONF_TAKE1,
ngx_conf_set_str_slot, NGX_HTTP_MAIN_CONF_OFFSET,
offsetof(lightstep_main_conf_t, access_token), nullptr},
{ngx_string("lightstep_component_name"),
NGX_HTTP_MAIN_CONF | NGX_CONF_TAKE1, ngx_conf_set_str_slot,
NGX_HTTP_MAIN_CONF_OFFSET, offsetof(lightstep_main_conf_t, component_name),
nullptr},
{ngx_string("lightstep_collector_host"),
NGX_HTTP_MAIN_CONF | NGX_CONF_TAKE1, ngx_conf_set_str_slot,
NGX_HTTP_MAIN_CONF_OFFSET, offsetof(lightstep_main_conf_t, collector_host),
nullptr},
{ngx_string("lightstep_collector_plaintext"),
NGX_HTTP_MAIN_CONF | NGX_CONF_TAKE1, ngx_conf_set_flag_slot,
NGX_HTTP_MAIN_CONF_OFFSET,
offsetof(lightstep_main_conf_t, collector_plaintext), nullptr},
{ngx_string("lightstep_collector_port"),
NGX_HTTP_MAIN_CONF | NGX_CONF_TAKE1, ngx_conf_set_str_slot,
NGX_HTTP_MAIN_CONF_OFFSET, offsetof(lightstep_main_conf_t, collector_port),
nullptr}};
//------------------------------------------------------------------------------
// ngx_http_lightstep_module
//------------------------------------------------------------------------------
ngx_module_t ngx_http_lightstep_module = {
NGX_MODULE_V1,
&lightstep_module_ctx, /* module context */
lightstep_commands, /* module directives */
NGX_HTTP_MODULE, /* module type */
nullptr, /* init master */
nullptr, /* init module */
lightstep_init_worker, /* init process */
nullptr, /* init thread */
nullptr, /* exit thread */
nullptr, /* exit process */
nullptr, /* exit master */
NGX_MODULE_V1_PADDING};
| 42.655405 | 80 | 0.569301 | SEJeff |
2d291cac9b621afceb0a49f76d6cbb67dd2bf702 | 4,508 | cpp | C++ | bltail.cpp | brendane/bltools | b25906c46d30339b5a009bddeeeb6b1de6700048 | [
"MIT"
] | 1 | 2021-05-19T11:35:47.000Z | 2021-05-19T11:35:47.000Z | bltail.cpp | brendane/bltools | b25906c46d30339b5a009bddeeeb6b1de6700048 | [
"MIT"
] | null | null | null | bltail.cpp | brendane/bltools | b25906c46d30339b5a009bddeeeb6b1de6700048 | [
"MIT"
] | null | null | null | /*
* Equivalent of tail for biological sequences.
*
*/
#include <iostream>
#include <queue>
#include <string>
#include <vector>
#include <seqan/seq_io.h>
#include <tclap/CmdLine.h>
#include <SeqFileInWrapper.h>
using std::cerr;
using std::cin;
using std::cout;
using std::endl;
using std::ifstream;
using std::istream;
using std::queue;
using std::stoi;
using std::string;
using std::vector;
using namespace seqan;
using namespace bltools;
int main(int argc, char * argv[]) {
TCLAP::CmdLine cmd("Equivalent of `tail' for sequence files", ' ', "0.0");
TCLAP::ValueArg<string> format_arg("o", "output-format",
"Output format: fasta or fastq; fasta is default",
false, "fasta", "fast[aq]", cmd);
TCLAP::ValueArg<string> nlines_arg("n", "lines",
"print the last n lines of each file or all lines but the first +n",
false, "10", "[+]int", cmd);
TCLAP::UnlabeledMultiArg<string> files("FILE(s)", "filenames", false,
"file name(s)", cmd, false);
cmd.parse(argc, argv);
string format = format_arg.getValue();
vector<string> infiles = files.getValue();
if(infiles.size() == 0) infiles.push_back("-");
string nlines_string = nlines_arg.getValue();
int nskip = 0;
int nlines = 0;
if(nlines_string[0] == '+') {
nlines_string.erase(0, 1);
nskip = stoi(nlines_string);
nlines = 0;
} else {
nlines = stoi(nlines_string);
nskip = 0;
}
if(nlines < 0 || nskip < 0) {
cerr << "Can't have a negative number of lines" << endl;
return 1;
}
SeqFileOut out_handle(cout, Fasta());
if(format == "fasta") {
setFormat(out_handle, Fasta());
} else if(format == "fastq") {
setFormat(out_handle, Fastq());
} else {
cerr << "Unrecognized output format";
return 1;
}
CharString id;
queue<CharString> ids;
CharString seq; // CharString more flexible than Dna5String
queue<CharString> seqs;
CharString qual;
queue<CharString> quals;
SeqFileInWrapper seq_handle;
for(string& infile: infiles) {
try {
seq_handle.open(infile);
} catch(Exception const &e) {
cerr << "Could not open " << infile << endl;
seq_handle.close();
return 1;
}
int nrecs_read = 0;
// Fill up seqs, quals, ids until look_ahead is reached, then for
// every additional record, pop one off of seqs, quals, and ids, and
// push the new one on until the end of the file is reached.
while(!seq_handle.atEnd()) {
try {
readRecord(id, seq, qual, seq_handle.sqh);
nrecs_read++;
} catch (Exception const &e) {
cerr << "Error: " << e.what() << endl;
seq_handle.close();
close(out_handle);
return 1;
} // End try-catch for record reading.
// If nskip > 0, just continue until nrecs_read > nskip, then write
// output as file is read.
//
// Otherwise, keep pushing to the queue (after queue.size() == nlines,
// also pop a record each time). Then, after the while loop, write all
// the records in the queue.
if(nskip > 0) {
if(nrecs_read >= nskip) {
try {
writeRecord(out_handle, id, seq, qual);
} catch (Exception const &e) {
cerr << "Error writing output";
seq_handle.close();
return 1;
}
} else {
continue;
}
} // End if(nskip > 0)
else if(nlines > 0) {
seqs.push(seq); ids.push(id); quals.push(qual);
if(seqs.size() > (unsigned) nlines) {
ids.pop(); seqs.pop(); quals.pop();
}
} // End if(nlines > 0)
} // End single file reading loop
// Write output if nlines > 0
// Can we do for(StringChar id: ids; StringChar seq:seqs...)?
if(nlines > 0) {
for(int i=0; i < nlines; i++) {
try {
writeRecord(out_handle, ids.front(), seqs.front(),
quals.front());
ids.pop(); seqs.pop(); quals.pop();
} catch (Exception const &e) {
cerr << "Error writing output";
seq_handle.close();
return 1;
}
}
}
if(!seq_handle.close()) {
cerr << "Problem closing " << infile << endl;
close(out_handle);
return 1;
}
} // End loop over files
close(out_handle);
return 0;
}
| 27.156627 | 105 | 0.557453 | brendane |
2d29db343eab27a9ba849c7e277ab1bc148e2850 | 1,923 | cpp | C++ | aws-cpp-sdk-iot/source/model/DescribeThingResult.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-01-05T18:20:03.000Z | 2022-01-05T18:20:03.000Z | aws-cpp-sdk-iot/source/model/DescribeThingResult.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-iot/source/model/DescribeThingResult.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-12-30T04:25:33.000Z | 2021-12-30T04:25:33.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/iot/model/DescribeThingResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <utility>
using namespace Aws::IoT::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;
DescribeThingResult::DescribeThingResult() :
m_version(0)
{
}
DescribeThingResult::DescribeThingResult(const Aws::AmazonWebServiceResult<JsonValue>& result) :
m_version(0)
{
*this = result;
}
DescribeThingResult& DescribeThingResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
JsonView jsonValue = result.GetPayload().View();
if(jsonValue.ValueExists("defaultClientId"))
{
m_defaultClientId = jsonValue.GetString("defaultClientId");
}
if(jsonValue.ValueExists("thingName"))
{
m_thingName = jsonValue.GetString("thingName");
}
if(jsonValue.ValueExists("thingId"))
{
m_thingId = jsonValue.GetString("thingId");
}
if(jsonValue.ValueExists("thingArn"))
{
m_thingArn = jsonValue.GetString("thingArn");
}
if(jsonValue.ValueExists("thingTypeName"))
{
m_thingTypeName = jsonValue.GetString("thingTypeName");
}
if(jsonValue.ValueExists("attributes"))
{
Aws::Map<Aws::String, JsonView> attributesJsonMap = jsonValue.GetObject("attributes").GetAllObjects();
for(auto& attributesItem : attributesJsonMap)
{
m_attributes[attributesItem.first] = attributesItem.second.AsString();
}
}
if(jsonValue.ValueExists("version"))
{
m_version = jsonValue.GetInt64("version");
}
if(jsonValue.ValueExists("billingGroupName"))
{
m_billingGroupName = jsonValue.GetString("billingGroupName");
}
return *this;
}
| 21.852273 | 106 | 0.719709 | Neusoft-Technology-Solutions |
2d2aeb20eed84e0379156857e5ef51efd04f18fb | 2,586 | cpp | C++ | REDSI_1160929_1161573/boost_1_67_0/libs/interprocess/example/doc_named_mutex.cpp | Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo | eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8 | [
"MIT"
] | 198 | 2015-01-13T05:47:18.000Z | 2022-03-09T04:46:46.000Z | libs/boost/libs/interprocess/example/doc_named_mutex.cpp | flingone/frameworks_base_cmds_remoted | 4509d9f0468137ed7fd8d100179160d167e7d943 | [
"Apache-2.0"
] | 9 | 2015-01-28T16:33:19.000Z | 2020-04-12T23:03:28.000Z | libs/boost/libs/interprocess/example/doc_named_mutex.cpp | flingone/frameworks_base_cmds_remoted | 4509d9f0468137ed7fd8d100179160d167e7d943 | [
"Apache-2.0"
] | 139 | 2015-01-15T20:09:31.000Z | 2022-01-31T15:21:16.000Z | //////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2006-2012. 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)
//
// See http://www.boost.org/libs/interprocess for documentation.
//
//////////////////////////////////////////////////////////////////////////////
#include <boost/interprocess/detail/config_begin.hpp>
//[doc_named_mutex
#include <boost/interprocess/sync/scoped_lock.hpp>
#include <boost/interprocess/sync/named_mutex.hpp>
#include <fstream>
#include <iostream>
#include <cstdio>
//<-
#include "../test/get_process_id_name.hpp"
//->
int main ()
{
using namespace boost::interprocess;
try{
struct file_remove
{
//<-
#if 1
file_remove() { std::remove(test::get_process_id_name()); }
~file_remove(){ std::remove(test::get_process_id_name()); }
#else
//->
file_remove() { std::remove("file_name"); }
~file_remove(){ std::remove("file_name"); }
//<-
#endif
//->
} file_remover;
struct mutex_remove
{
//<-
#if 1
mutex_remove() { named_mutex::remove(test::get_process_id_name()); }
~mutex_remove(){ named_mutex::remove(test::get_process_id_name()); }
#else
//->
mutex_remove() { named_mutex::remove("fstream_named_mutex"); }
~mutex_remove(){ named_mutex::remove("fstream_named_mutex"); }
//<-
#endif
//->
} remover;
//<-
(void)remover;
//->
//Open or create the named mutex
//<-
#if 1
named_mutex mutex(open_or_create, test::get_process_id_name());
#else
//->
named_mutex mutex(open_or_create, "fstream_named_mutex");
//<-
#endif
//->
//<-
#if 1
std::ofstream file(test::get_process_id_name());
#else
//->
std::ofstream file("file_name");
//<-
#endif
//->
for(int i = 0; i < 10; ++i){
//Do some operations...
//Write to file atomically
scoped_lock<named_mutex> lock(mutex);
file << "Process name, ";
file << "This is iteration #" << i;
file << std::endl;
}
}
catch(interprocess_exception &ex){
std::cout << ex.what() << std::endl;
return 1;
}
return 0;
}
//]
#include <boost/interprocess/detail/config_end.hpp>
| 26.387755 | 79 | 0.516628 | Wultyc |
2d2b8fb09f3dcac354336c220e8c8ea2216af230 | 8,395 | hpp | C++ | src/ndnSIM/helper/ndn-stack-helper.hpp | NDNLink/NDN-Chord | cfabf8f56eea2c4ba47052ce145a939ebdc21e57 | [
"MIT"
] | 1 | 2021-09-07T04:12:15.000Z | 2021-09-07T04:12:15.000Z | src/ndnSIM/helper/ndn-stack-helper.hpp | NDNLink/NDN-Chord | cfabf8f56eea2c4ba47052ce145a939ebdc21e57 | [
"MIT"
] | null | null | null | src/ndnSIM/helper/ndn-stack-helper.hpp | NDNLink/NDN-Chord | cfabf8f56eea2c4ba47052ce145a939ebdc21e57 | [
"MIT"
] | 1 | 2020-07-15T06:21:03.000Z | 2020-07-15T06:21:03.000Z | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2011-2015 Regents of the University of California.
*
* This file is part of ndnSIM. See AUTHORS for complete list of ndnSIM authors and
* contributors.
*
* ndnSIM 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.
*
* ndnSIM 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
* ndnSIM, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
**/
#ifndef NDNSIM_HELPER_NDN_STACK_HELPER_HPP
#define NDNSIM_HELPER_NDN_STACK_HELPER_HPP
#include "ns3/ndnSIM/model/ndn-common.hpp"
#include "ns3/ptr.h"
#include "ns3/object-factory.h"
#include "ns3/node.h"
#include "ns3/node-container.h"
#include "ndn-face-container.hpp"
#include "ndn-fib-helper.hpp"
#include "ndn-strategy-choice-helper.hpp"
namespace nfd {
namespace cs {
class Policy;
} // namespace cs
} // namespace nfd
namespace ns3 {
class Node;
namespace ndn {
class L3Protocol;
/**
* @ingroup ndn
* @defgroup ndn-helpers Helpers
*/
/**
* @ingroup ndn-helpers
* @brief Helper class to install NDN stack and configure its parameters
*/
class StackHelper : boost::noncopyable {
public:
/**
* \brief Create a new NdnStackHelper with a default NDN_FLOODING forwarding stategy
*/
StackHelper();
/**
* \brief Destroy the NdnStackHelper
*/
virtual ~StackHelper();
/**
* @brief Set parameters of NdnL3Protocol
*/
void
SetStackAttributes(const std::string& attr1 = "", const std::string& value1 = "",
const std::string& attr2 = "", const std::string& value2 = "",
const std::string& attr3 = "", const std::string& value3 = "",
const std::string& attr4 = "", const std::string& value4 = "");
/**
* @brief Set maximum size for NFD's Content Store (in number of packets)
*/
void
setCsSize(size_t maxSize);
/**
* @brief Set the cache replacement policy for NFD's Content Store
*/
void
setPolicy(const std::string& policy);
/**
* @brief Set ndnSIM 1.0 content store implementation and its attributes
* @param contentStoreClass string, representing class of the content store
* @note ndnSIM 1.0 content store implementation have limited support for Interest selectors
* Do not use these implementations if your scenario relies on proper selector processing.
*/
void
SetOldContentStore(const std::string& contentStoreClass, const std::string& attr1 = "",
const std::string& value1 = "", const std::string& attr2 = "",
const std::string& value2 = "", const std::string& attr3 = "",
const std::string& value3 = "", const std::string& attr4 = "",
const std::string& value4 = "");
typedef Callback<shared_ptr<Face>, Ptr<Node>, Ptr<L3Protocol>, Ptr<NetDevice>>
FaceCreateCallback;
/**
* @brief Add callback to create and configure instance of the face, based on supplied Ptr<Node>
*and Ptr<NetDevice>
*
* It is possible to set up several callbacks for different NetDevice types.
*
* If none of the callbacks fit the TypeId of NetDevice, a default callback is used
*(DefaultNetDeviceCallback)
*/
void
AddFaceCreateCallback(TypeId netDeviceType, FaceCreateCallback callback);
/**
* @brief Update callback to create and configure instance of the face, based on supplied
*Ptr<Node> and Ptr<NetDevice>
*
* It is possible to set up several callbacks for different NetDevice types.
*
* Using this method, it is possible to override Face creation for PointToPointNetDevices
*/
void
UpdateFaceCreateCallback(TypeId netDeviceType, FaceCreateCallback callback);
/**
* @brief Remove callback to create and configure instance of the face, based on supplied
* Ptr<Node> and Ptr<NetDevice>
*/
void
RemoveFaceCreateCallback(TypeId netDeviceType, FaceCreateCallback callback);
/**
* \brief Install Ndn stack on the node
*
* This method will assert if called on a node that already has Ndn object
* installed on it
*
* \param nodeName The name of the node on which to install the stack.
*
* \returns list of installed faces in the form of a smart pointer
* to NdnFaceContainer object
*/
Ptr<FaceContainer>
Install(const std::string& nodeName) const;
/**
* \brief Install Ndn stack on the node
*
* This method will assert if called on a node that already has Ndn object
* installed on it
*
* \param node The node on which to install the stack.
*
* \returns list of installed faces in the form of a smart pointer
* to FaceContainer object
*/
Ptr<FaceContainer>
Install(Ptr<Node> node) const;
/**
* \brief Install Ndn stack on each node in the input container
*
* The program will assert if this method is called on a container with a node
* that already has an ndn object aggregated to it.
*
* \param c NodeContainer that holds the set of nodes on which to install the
* new stacks.
*
* \returns list of installed faces in the form of a smart pointer
* to FaceContainer object
*/
Ptr<FaceContainer>
Install(const NodeContainer& c) const;
/**
* \brief Install Ndn stack on all nodes in the simulation
*
* \returns list of installed faces in the form of a smart pointer
* to FaceContainer object
*/
Ptr<FaceContainer>
InstallAll() const;
/**
* \brief Set flag indicating necessity to install default routes in FIB
*/
void
SetDefaultRoutes(bool needSet);
static KeyChain&
getKeyChain();
/**
* \brief Update Ndn stack on a given node (Add faces for new devices)
*
* \param node The node on which to update the stack.
*/
void
Update(Ptr<Node> node);
/**
*\brief Update Ndn stack on given nodes (Add faces for new devices)
*
* \param c The nodes on which to update the stack.
*/
void
Update(const NodeContainer& c);
/**
*\brief Update Ndn stack on a given node name (Add faces for new devices)
*
* \param nodeName The name of the node on which to update the stack.
*/
void
Update(const std::string& nodeName);
/**
*\brief Update Ndn stack on all the nodes (Add faces for new devices)
*/
void
UpdateAll();
/**
*\brief Disable the RIB manager of NFD
*/
void
disableRibManager();
// Cannot be disabled for now
// /**
// * \brief Disable Face Manager
// */
// void
// disableFaceManager();
/**
* \brief Disable Strategy Choice Manager
*/
void
disableStrategyChoiceManager();
/**
* \brief Disable Forwarder Status Manager
*/
void
disableForwarderStatusManager();
/**
* @brief Set face metric of all faces connected through PointToPoint channel to channel latency
*/
static void
SetLinkDelayAsFaceMetric();
private:
shared_ptr<Face>
DefaultNetDeviceCallback(Ptr<Node> node, Ptr<L3Protocol> ndn, Ptr<NetDevice> netDevice) const;
shared_ptr<Face>
PointToPointNetDeviceCallback(Ptr<Node> node, Ptr<L3Protocol> ndn,
Ptr<NetDevice> netDevice) const;
shared_ptr<Face>
createAndRegisterFace(Ptr<Node> node, Ptr<L3Protocol> ndn, Ptr<NetDevice> device) const;
bool m_isRibManagerDisabled;
// bool m_isFaceManagerDisabled;
bool m_isForwarderStatusManagerDisabled;
bool m_isStrategyChoiceManagerDisabled;
public:
void
setCustomNdnCxxClocks();
private:
ObjectFactory m_ndnFactory;
ObjectFactory m_contentStoreFactory;
bool m_needSetDefaultRoutes;
size_t m_maxCsSize;
typedef std::function<std::unique_ptr<nfd::cs::Policy>()> PolicyCreationCallback;
PolicyCreationCallback m_csPolicyCreationFunc;
std::map<std::string, PolicyCreationCallback> m_csPolicies;
typedef std::list<std::pair<TypeId, FaceCreateCallback>> NetDeviceCallbackList;
NetDeviceCallbackList m_netDeviceCallbacks;
};
} // namespace ndn
} // namespace ns3
#endif // NDNSIM_HELPER_NDN_STACK_HELPER_HPP
| 28.361486 | 98 | 0.692912 | NDNLink |
2d2cca0e5fa20914f6211d594622f29f905f2164 | 201 | cpp | C++ | Challenges/Challenge29/src/main.cpp | GamesTrap/PracticeChallenges | 46ad8b2c18515a9740910162381a3dea18be72ab | [
"MIT"
] | null | null | null | Challenges/Challenge29/src/main.cpp | GamesTrap/PracticeChallenges | 46ad8b2c18515a9740910162381a3dea18be72ab | [
"MIT"
] | null | null | null | Challenges/Challenge29/src/main.cpp | GamesTrap/PracticeChallenges | 46ad8b2c18515a9740910162381a3dea18be72ab | [
"MIT"
] | null | null | null | #include <cstdint>
constexpr uint32_t Summation(const uint32_t num)
{
return num * (num + 1) / 2;
}
int main()
{
static_assert(Summation(1) == 1);
static_assert(Summation(8) == 36);
return 0;
} | 14.357143 | 48 | 0.661692 | GamesTrap |
2d2f4cf9f43fc1da7d37989ff39241f8e2c78714 | 960 | inl | C++ | app/src/main/cpp/jni/platform.inl | JoseskVolpe/J2ME-Loader | ad7c9505d980eb542e7458f17a717b7ffdb68109 | [
"Apache-2.0"
] | 1,227 | 2017-06-11T21:15:36.000Z | 2022-03-31T13:04:52.000Z | app/src/main/cpp/jni/platform.inl | lqfy-jhc/J2ME-Loader | 992a0feacc4c0e43996a15431553e706a671a826 | [
"Apache-2.0"
] | 747 | 2017-07-28T10:24:22.000Z | 2022-03-29T09:59:40.000Z | app/src/main/cpp/jni/platform.inl | lqfy-jhc/J2ME-Loader | 992a0feacc4c0e43996a15431553e706a671a826 | [
"Apache-2.0"
] | 233 | 2017-06-13T11:50:36.000Z | 2022-03-25T14:02:32.000Z | /*
* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description:
*
*/
#include "javax_microedition_m3g_Platform.h"
/*
* Must be excuted in UI thread
*/
JNIEXPORT void JNICALL Java_javax_microedition_m3g_Platform_finalizeInterface
(JNIEnv* aEnv, jclass, jlong aHObj)
{
M3G_DO_LOCK
m3gDeleteInterface((M3GInterface)aHObj);
M3G_DO_UNLOCK(aEnv)
}
/*
* Must be excuted in UI thread
*/
JNIEXPORT void JNICALL Java_javax_microedition_m3g_Platform__1finalizeObject
(JNIEnv* aEnv, jclass, jlong aHObj)
{
M3G_DO_LOCK
m3gDeleteObject((M3GObject)aHObj);
M3G_DO_UNLOCK(aEnv)
}
| 24 | 77 | 0.759375 | JoseskVolpe |
2d31247fdfcc2131decf9f6f5ffd3298aa07f94e | 8,282 | cpp | C++ | src/glwidget.cpp | udit01/qGL | 81aa4cdc7a271099c9ba8bee53e6aeba33c2901c | [
"MIT"
] | null | null | null | src/glwidget.cpp | udit01/qGL | 81aa4cdc7a271099c9ba8bee53e6aeba33c2901c | [
"MIT"
] | null | null | null | src/glwidget.cpp | udit01/qGL | 81aa4cdc7a271099c9ba8bee53e6aeba33c2901c | [
"MIT"
] | null | null | null | #include "glwidget.h"
//#include "ui_glwidget.h"
#include <iostream>
#include <vector>
#include <cstdlib>
#include <QMainWindow>
#include <QtGui>
#include <QtWidgets>
#include <QtOpenGL>
#include <QGLWidget>
#include <QGL>
#include "mainwindow.h"
#include "model.h"
#include "samplemodels.h"
Glwidget::Glwidget(QWidget *parent)
: QGLWidget( QGLFormat(QGL::SampleBuffers), parent)
{
xRot = 0;
yRot = 0;
zRot = 0;
scl = 20.0f;
// model = SampleModels::SquareBasedPyramid(1.0);
//Application crashes on doing what's below
// model = ((MainWindow*)parent)->model ;
}
Glwidget::~Glwidget()
{
}
void Glwidget::setWireframe(bool b){
this->wireframe = b;
// updateGL();
}
void Glwidget::update(){
updateGL();
}
void Glwidget::setModel(Model *m){
this->model = m;
}
QSize Glwidget::minimumSizeHint() const
{
return QSize(50, 50);
}
QSize Glwidget::sizeHint() const
{
return QSize(400, 400);
}
static void qNormalizeAngle(int &angle)
{
while (angle < 0)
angle += 360 * 16;
while (angle > 5760)
angle -= 360 * 16;
}
void Glwidget::setXRotation(int angle)
{
qNormalizeAngle(angle);
if (angle != xRot) {
xRot = angle;
emit xRotationChanged(angle);
updateGL();
}
}
void Glwidget::setYRotation(int angle)
{
qNormalizeAngle(angle);
if (angle != yRot) {
yRot = angle;
emit yRotationChanged(angle);
updateGL();
}
}
void Glwidget::setZRotation(int angle)
{
qNormalizeAngle(angle);
if (angle != zRot) {
zRot = angle;
emit zRotationChanged(angle);
updateGL();
}
}
void Glwidget::setScale(int factor){
if(factor != 1){
scl = factor;
emit scaleChanged(factor);
updateGL();
}
}
void Glwidget::initializeGL()
{
qglClearColor(Qt::black);
// static GLfloat lightPosition[4] = { 0, 0, 10, 1.0 };
// glLightfv(GL_LIGHT0, GL_POSITION, lightPosition);
// static GLfloat lightPosition2[4] = { 10, 0, 0 , 1.0 };
// glLightfv(GL_LIGHT1, GL_POSITION, lightPosition2);
// static GLfloat lightPosition3[4] = { 0, 10, 0, 1.0 };
// glLightfv(GL_LIGHT2, GL_POSITION, lightPosition3);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glShadeModel(GL_SMOOTH);
glColorMaterial ( GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE );
glEnable ( GL_COLOR_MATERIAL );
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-4.0, 4.0, -4.0, 4.0, -4.0, 4.0);
glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER,GL_TRUE);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
GLfloat qaAmbL[] = {0.2,0.2,0.2,1.0};
GLfloat qaDifL[] = {0.8,0.8,0.8,1.0};
GLfloat qaSpcL[] = {1.0,1.0,1.0,1.0};
glLightfv(GL_LIGHT0, GL_AMBIENT, qaAmbL);
glLightfv(GL_LIGHT0, GL_DIFFUSE, qaDifL);
glLightfv(GL_LIGHT0, GL_SPECULAR, qaSpcL);
GLfloat qaLpos[] = {1.0,0.0,0.0,1.0};
glLightfv(GL_LIGHT0, GL_POSITION, qaLpos);
// GLfloat mat_specular[] = { 0.5, 0.5, 0.5, 1.0 };
// GLfloat mat_shininess[] = { 50.0 };
// GLfloat light_position[] = { -1.0, -1.0, -1.0, 0.0 };
// glClearColor (0.0, 0.0, 0.0, 0.0);
// glShadeModel (GL_SMOOTH);
// glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
// glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);
// glLightfv(GL_LIGHT1, GL_POSITION, light_position);
// glRotatef(30, 0.0,1.0,0.0);
// glRotatef(320,1.0,0.0,0.0);
// glRotatef(0 ,0.0,0.0,1.0);
}
void Glwidget::paintGL()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glTranslatef(0.0, 0.0, -10.0);
glRotatef(xRot / 16.0, 1.0, 0.0, 0.0);
glRotatef(yRot / 16.0, 0.0, 1.0, 0.0);
glRotatef(zRot / 16.0, 0.0, 0.0, 1.0);
if(scl > 0){
float sc = (scl) / 20.0f;
glScalef(sc, sc, sc);
}
draw();
}
void Glwidget::resizeGL(int width, int height)
{
int side = qMin(width, height);
glViewport((width - side) / 2, (height - side) / 2, side, side);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
#ifdef QT_OPENGL_ES_1
glOrthof(-2, +2, -2, +2, 1.0, 15.0);
#else
glOrtho(-2, +2, -2, +2, 1.0, 15.0);
#endif
glMatrixMode(GL_MODELVIEW);
}
void Glwidget::mousePressEvent(QMouseEvent *event)
{
lastPos = event->pos();
}
void Glwidget::mouseMoveEvent(QMouseEvent *event)
{
int dx = event->x() - lastPos.x();
int dy = event->y() - lastPos.y();
if (event->buttons() & Qt::LeftButton) {
setXRotation(xRot + 8 * dy);
setYRotation(yRot + 8 * dx);
} else if (event->buttons() & Qt::RightButton) {
setXRotation(xRot + 8 * dy);
setZRotation(zRot + 8 * dx);
}
lastPos = event->pos();
}
void Glwidget::draw()
{
//Drawing the Axis lines
glLineWidth(4);
Model* axes = SampleModels::Axes(4.0);
float r[] = {1.0,0.0,0.0};
int k=0;
for(int i = 0 ; i < axes->numPoints; i++){
for(int j = i ; j < axes->numPoints ; j++){
// std::cout << axes->edges[i][j] << " Edges "<<i <<" " << j <<" Glwidget Line 180\n";
if(axes->edges[i][j]){
// a new array each time, to construct the line
// Randomness
// r1 = ((float) rand() / (RAND_MAX)) ;
// r2 = ((float) rand() / (RAND_MAX)) ;
// r3 = ((float) rand() / (RAND_MAX)) ;
glColor3f(r[ k%3 ],r[(k+1)%3],r[(k+2)%3]);
k++;
float* verti = new float [3*2];
std::copy(axes->points + i,axes->points + i +3,verti);
std::copy(axes->points + j,axes->points + j +3,verti+3);
//chose a random colour here
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer( 3, GL_FLOAT, 0 , verti);
glDrawArrays(GL_LINES, 0, 2);
glDisableClientState(GL_VERTEX_ARRAY);
}
}
}
/*
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
for (int i = 0 ; i < axes->faces.size() ; i++){
r1 = ((float) rand() / (RAND_MAX)) ;
r2 = ((float) rand() / (RAND_MAX)) ;
r3 = ((float) rand() / (RAND_MAX)) ;
glColor3f(r1,r2,r3);
Face* f = axes->faces[i];
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer( 3, GL_FLOAT, 0 , f->points);
glDrawArrays(GL_POLYGON, 0, f->npts);
glDisableClientState(GL_VERTEX_ARRAY);
}
*/
// Drawing the model
if(!this->model){
return;
}
glLineWidth(5);
glColor3f(1.0, 0.0, 1.0);
if(wireframe){
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
}
else{
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
}
for (int i = 0 ; i < this->model->faces.size() ; i++){
Face* f = this->model->faces[i];
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer( 3, GL_FLOAT, 0 , f->points);
glDrawArrays(GL_POLYGON, 0, f->npts);
glDisableClientState(GL_VERTEX_ARRAY);
}
// Code to draw wireframe of the model
// or in the above code, you can directly sepecify the drawing mode of polygon. IMPORTANT
// for(int i = 0 ; i < axes->numPoints; i++){
// for(int j = i ; j < axes->numPoints ; j++){
// std::cout << axes->edges[i][j] << " Edges "<<i <<" " << j <<" Glwidget Line 180\n";
// if(axes->edges[i][j]){
// // a new array each time, to construct the line
//// Randomness
// r1 = ((float) rand() / (RAND_MAX)) ;
// r2 = ((float) rand() / (RAND_MAX)) ;
// r3 = ((float) rand() / (RAND_MAX)) ;
// glColor3f(r1,r2,r3);
// float* verti = new float [3*2];
// std::copy(axes->points + i,axes->points + i +3,verti);
// std::copy(axes->points + j,axes->points + j +3,verti+3);
// //chose a random colour here
// glEnableClientState(GL_VERTEX_ARRAY);
// glVertexPointer( 3, GL_FLOAT, 0 , verti);
// glDrawArrays(GL_LINES, 0, 2);
// glDisableClientState(GL_VERTEX_ARRAY);
// }
// }
// }
//Why is the lighting and shaders so erratic?
}
| 25.720497 | 98 | 0.557353 | udit01 |
2d3232def81d485798f2ee7da6b978e9ec8917cf | 13,860 | cpp | C++ | FEBioMech/FEReactiveViscoelastic.cpp | wzaylor/FEBio | 5444c06473dd66dc0bfdf6e3b2c79d3c0cd0b7a6 | [
"MIT"
] | null | null | null | FEBioMech/FEReactiveViscoelastic.cpp | wzaylor/FEBio | 5444c06473dd66dc0bfdf6e3b2c79d3c0cd0b7a6 | [
"MIT"
] | null | null | null | FEBioMech/FEReactiveViscoelastic.cpp | wzaylor/FEBio | 5444c06473dd66dc0bfdf6e3b2c79d3c0cd0b7a6 | [
"MIT"
] | null | null | null | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2020 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
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 "stdafx.h"
#include "FEReactiveViscoelastic.h"
#include "FECore/FECoreKernel.h"
#include <FECore/FEModel.h>
#include <FECore/log.h>
#include <limits>
///////////////////////////////////////////////////////////////////////////////
//
// FEReactiveViscoelasticMaterial
//
///////////////////////////////////////////////////////////////////////////////
// Material parameters for the FEMultiphasic material
BEGIN_FECORE_CLASS(FEReactiveViscoelasticMaterial, FEElasticMaterial)
ADD_PARAMETER(m_wmin , FE_RANGE_CLOSED(0.0, 1.0), "wmin");
ADD_PARAMETER(m_btype, FE_RANGE_CLOSED(1,2), "kinetics");
ADD_PARAMETER(m_ttype, FE_RANGE_CLOSED(0,2), "trigger");
// set material properties
ADD_PROPERTY(m_pBase, "elastic");
ADD_PROPERTY(m_pBond, "bond");
ADD_PROPERTY(m_pRelx, "relaxation");
END_FECORE_CLASS();
//-----------------------------------------------------------------------------
//! constructor
FEReactiveViscoelasticMaterial::FEReactiveViscoelasticMaterial(FEModel* pfem) : FEElasticMaterial(pfem)
{
m_wmin = 0;
m_btype = 0;
m_ttype = 0;
m_pBase = 0;
m_pBond = 0;
m_pRelx = 0;
}
//-----------------------------------------------------------------------------
//! data initialization
bool FEReactiveViscoelasticMaterial::Init()
{
FEUncoupledMaterial* m_pMat = dynamic_cast<FEUncoupledMaterial*>((FEElasticMaterial*)m_pBase);
if (m_pMat != nullptr) {
feLogError("Elastic material should not be of type uncoupled");
return false;
}
m_pMat = dynamic_cast<FEUncoupledMaterial*>((FEElasticMaterial*)m_pBond);
if (m_pMat != nullptr) {
feLogError("Bond material should not be of type uncoupled");
return false;
}
return FEElasticMaterial::Init();
}
//-----------------------------------------------------------------------------
//! Create material point data for this material
FEMaterialPoint* FEReactiveViscoelasticMaterial::CreateMaterialPointData()
{
return new FEReactiveVEMaterialPoint(m_pBase->CreateMaterialPointData(), this);
}
//-----------------------------------------------------------------------------
//! detect new generation
bool FEReactiveViscoelasticMaterial::NewGeneration(FEMaterialPoint& mp)
{
double d;
double eps = std::numeric_limits<double>::epsilon();
// get the elastic material poit data
FEElasticMaterialPoint& pe = *mp.ExtractData<FEElasticMaterialPoint>();
// get the reactive viscoelastic point data
FEReactiveVEMaterialPoint& pt = *mp.ExtractData<FEReactiveVEMaterialPoint>();
// check if the current deformation gradient is different from that of
// the last generation, in which case store the current state
// evaluate the relative deformation gradient
mat3d F = pe.m_F;
int lg = (int)pt.m_Fi.size() - 1;
mat3d Fi = (lg > -1) ? pt.m_Fi[lg] : mat3d(mat3dd(1));
mat3d Fu = F*Fi;
switch (m_ttype) {
case 0:
{
// trigger in response to any strain
// evaluate the Lagrangian strain
mat3ds E = ((Fu.transpose()*Fu).sym() - mat3dd(1))/2;
d = E.norm();
}
break;
case 1:
{
// trigger in response to distortional strain
// evaluate spatial Hencky (logarithmic) strain
mat3ds Bu = (Fu*Fu.transpose()).sym();
double l[3];
vec3d v[3];
Bu.eigen2(l,v);
mat3ds h = (dyad(v[0])*log(l[0]) + dyad(v[1])*log(l[1]) + dyad(v[2])*log(l[2]))/2;
// evaluate distortion magnitude (always positive)
d = (h.dev()).norm();
}
break;
case 2:
{
// trigger in response to dilatational strain
d = fabs(log(Fu.det()));
}
break;
default:
d = 0;
break;
}
if (d > eps) return true;
return false;
}
//-----------------------------------------------------------------------------
//! evaluate bond mass fraction
double FEReactiveViscoelasticMaterial::BreakingBondMassFraction(FEMaterialPoint& mp, const int ig, const mat3ds D)
{
// get the reactive viscoelastic point data
FEReactiveVEMaterialPoint& pt = *mp.ExtractData<FEReactiveVEMaterialPoint>();
// bond mass fraction
double w = 0;
// current time
double time = GetFEModel()->GetTime().currentTime;
switch (m_btype) {
case 1:
{
// time when this generation started breaking
double v = pt.m_v[ig];
if (time >= v)
w = pt.m_w[ig]*m_pRelx->Relaxation(mp, time - v, D);
}
break;
case 2:
{
double tu, tv;
if (ig == 0) {
tv = time - pt.m_v[ig];
w = m_pRelx->Relaxation(mp, tv, D);
}
else
{
tu = time - pt.m_v[ig-1];
tv = time - pt.m_v[ig];
w = m_pRelx->Relaxation(mp, tv, D) - m_pRelx->Relaxation(mp, tu, D);
}
}
break;
default:
break;
}
assert((w >= 0) && (w <= 1));
return w;
}
//-----------------------------------------------------------------------------
//! evaluate bond mass fraction of reforming generation
double FEReactiveViscoelasticMaterial::ReformingBondMassFraction(FEMaterialPoint& mp)
{
// get the elastic part
FEElasticMaterialPoint& ep = *mp.ExtractData<FEElasticMaterialPoint>();
// get the reactive viscoelastic point data
FEReactiveVEMaterialPoint& pt = *mp.ExtractData<FEReactiveVEMaterialPoint>();
mat3ds D = ep.RateOfDeformation();
// keep safe copy of deformation gradient
mat3d F = ep.m_F;
double J = ep.m_J;
// get current number of generations
int ng = (int)pt.m_Fi.size();
double w = 1;
for (int ig=0; ig<ng-1; ++ig)
{
// evaluate relative deformation gradient for this generation Fu(v)
ep.m_F = pt.m_Fi[ig+1].inverse()*pt.m_Fi[ig];
ep.m_J = pt.m_Ji[ig]/pt.m_Ji[ig+1];
// evaluate the breaking bond mass fraction for this generation
w -= BreakingBondMassFraction(mp, ig, D);
}
// restore safe copy of deformation gradient
ep.m_F = F;
ep.m_J = J;
assert((w >= 0) && (w <= 1));
// return the bond mass fraction of the reforming generation
return w;
}
//-----------------------------------------------------------------------------
//! Stress function
mat3ds FEReactiveViscoelasticMaterial::Stress(FEMaterialPoint& mp)
{
double dt = GetFEModel()->GetTime().timeIncrement;
if (dt == 0) return mat3ds(0, 0, 0, 0, 0, 0);
// get the elastic part
FEElasticMaterialPoint& ep = *mp.ExtractData<FEElasticMaterialPoint>();
// get the reactive viscoelastic point data
FEReactiveVEMaterialPoint& pt = *mp.ExtractData<FEReactiveVEMaterialPoint>();
mat3ds D = ep.RateOfDeformation();
// calculate the base material Cauchy stress
mat3ds s = m_pBase->Stress(mp);
// current number of breaking generations
int ng = (int)pt.m_Fi.size();
// no bonds have broken
if (ng == 0) {
s += m_pBond->Stress(mp);
}
// bonds have broken
else {
// keep safe copy of deformation gradient
mat3d F = ep.m_F;
double J = ep.m_J;
double w;
mat3ds sb;
// calculate the bond stresses for breaking generations
for (int ig=0; ig<ng; ++ig) {
// evaluate relative deformation gradient for this generation
ep.m_F = F*pt.m_Fi[ig];
ep.m_J = J*pt.m_Ji[ig];
// evaluate bond mass fraction for this generation
w = BreakingBondMassFraction(mp, ig, D);
// evaluate bond stress
sb = m_pBond->Stress(mp);
// add bond stress to total stress
s += sb*(w*pt.m_Ji[ig]);
}
// restore safe copy of deformation gradient
ep.m_F = F;
ep.m_J = J;
}
// return the total Cauchy stress
return s;
}
//-----------------------------------------------------------------------------
//! Material tangent
tens4ds FEReactiveViscoelasticMaterial::Tangent(FEMaterialPoint& mp)
{
CullGenerations(mp);
// get the elastic part
FEElasticMaterialPoint& ep = *mp.ExtractData<FEElasticMaterialPoint>();
// get the reactive viscoelastic point data
FEReactiveVEMaterialPoint& pt = *mp.ExtractData<FEReactiveVEMaterialPoint>();
mat3ds D = ep.RateOfDeformation();
// calculate the base material tangent
tens4ds c = m_pBase->Tangent(mp);
// current number of breaking generations
int ng = (int)pt.m_Fi.size();
// no bonds have broken
if (ng == 0) {
c += m_pBond->Tangent(mp);
}
// bonds have broken
else {
// keep safe copy of deformation gradient
mat3d F = ep.m_F;
double J = ep.m_J;
double w;
tens4ds cb;
// calculate the bond tangents for breaking generations
for (int ig=0; ig<ng; ++ig) {
// evaluate relative deformation gradient for this generation
ep.m_F = F*pt.m_Fi[ig];
ep.m_J = J*pt.m_Ji[ig];
// evaluate bond mass fraction for this generation
w = BreakingBondMassFraction(mp, ig, D);
// evaluate bond tangent
cb = m_pBond->Tangent(mp);
// add bond tangent to total tangent
c += cb*(w*pt.m_Ji[ig]);
}
// restore safe copy of deformation gradient
ep.m_F = F;
ep.m_J = J;
}
// return the total tangent
return c;
}
//-----------------------------------------------------------------------------
//! strain energy density function
double FEReactiveViscoelasticMaterial::StrainEnergyDensity(FEMaterialPoint& mp)
{
double dt = GetFEModel()->GetTime().timeIncrement;
if (dt == 0) return 0;
// get the elastic part
FEElasticMaterialPoint& ep = *mp.ExtractData<FEElasticMaterialPoint>();
// get the reactive viscoelastic point data
FEReactiveVEMaterialPoint& pt = *mp.ExtractData<FEReactiveVEMaterialPoint>();
// get the viscous point data
mat3ds D = ep.RateOfDeformation();
// calculate the base material Cauchy stress
double sed = m_pBase->StrainEnergyDensity(mp);
// current number of breaking generations
int ng = (int)pt.m_Fi.size();
// no bonds have broken
if (ng == 0) {
sed += m_pBond->StrainEnergyDensity(mp);
}
// bonds have broken
else {
// keep safe copy of deformation gradient
mat3d F = ep.m_F;
double J = ep.m_J;
double w;
double sedb;
// calculate the strain energy density for breaking generations
for (int ig=0; ig<ng; ++ig) {
// evaluate relative deformation gradient for this generation
ep.m_F = F*pt.m_Fi[ig];
ep.m_J = J*pt.m_Ji[ig];
// evaluate bond mass fraction for this generation
w = BreakingBondMassFraction(mp, ig, D);
// evaluate bond stress
sedb = m_pBond->StrainEnergyDensity(mp);
// add bond stress to total stress
sed += sedb*w;
}
// restore safe copy of deformation gradient
ep.m_F = F;
ep.m_J = J;
}
// return the total Cauchy stress
return sed;
}
//-----------------------------------------------------------------------------
//! Cull generations that have relaxed below a threshold
void FEReactiveViscoelasticMaterial::CullGenerations(FEMaterialPoint& mp)
{
// get the elastic part
FEElasticMaterialPoint& ep = *mp.ExtractData<FEElasticMaterialPoint>();
// get the reactive viscoelastic point data
FEReactiveVEMaterialPoint& pt = *mp.ExtractData<FEReactiveVEMaterialPoint>();
mat3ds D = ep.RateOfDeformation();
if (pt.m_Fi.empty()) return;
// culling termination flag
bool done = false;
// always check oldest generation
while (!done) {
double w = BreakingBondMassFraction(mp, 0, D);
if ((w > m_wmin) || (pt.m_Fi.size() == 1))
done = true;
else {
pt.m_Fi.pop_front();
pt.m_Ji.pop_front();
pt.m_v.pop_front();
pt.m_w.pop_front();
}
}
return;
}
| 31.216216 | 114 | 0.571934 | wzaylor |
2d3234ac80649d190768ace625b253d8215ddcdd | 641 | cpp | C++ | App/Lib/Bal/Test/test/testModule.cpp | belmayze/bal | 710a96d011855fdab4e4b6962a2ba5b6b6b35aae | [
"MIT"
] | null | null | null | App/Lib/Bal/Test/test/testModule.cpp | belmayze/bal | 710a96d011855fdab4e4b6962a2ba5b6b6b35aae | [
"MIT"
] | null | null | null | App/Lib/Bal/Test/test/testModule.cpp | belmayze/bal | 710a96d011855fdab4e4b6962a2ba5b6b6b35aae | [
"MIT"
] | null | null | null | /*!
* @file testModule.cpp
* @brief
* @author belmayze
*
* Copyright (c) 2020 belmayze. All rights reserved.
*/
// app
#include <test/testModule.h>
#include <test/container/testList.h>
#include <test/container/testTreeMap.h>
namespace app::test {
// ----------------------------------------------------------------------------
void Module::exec()
{
// container
{
// list
{
List v;
v.exec();
}
// treemap
{
TreeMap v;
v.exec();
}
}
}
// ----------------------------------------------------------------------------
}
| 16.868421 | 79 | 0.365055 | belmayze |
2d358d1710c8bf8d55d8a399037848d9c84c8b0b | 4,959 | cpp | C++ | src/post/main/Path.cpp | ucd-plse/mpi-error-prop | 4367df88bcdc4d82c9a65b181d0e639d04962503 | [
"BSD-3-Clause"
] | 3 | 2020-05-22T04:17:23.000Z | 2020-07-17T04:14:25.000Z | src/post/main/Path.cpp | ucd-plse/mpi-error-prop | 4367df88bcdc4d82c9a65b181d0e639d04962503 | [
"BSD-3-Clause"
] | null | null | null | src/post/main/Path.cpp | ucd-plse/mpi-error-prop | 4367df88bcdc4d82c9a65b181d0e639d04962503 | [
"BSD-3-Clause"
] | null | null | null | /*!
* @author Cindy Rubio Gonzalez
*/
#include <sstream>
#include <algorithm>
#include "Main.hpp"
#include "Path.hpp"
#include "ProgramPoint.hpp"
// Following the convention of the flags,
// selected_formatter is global from Main.hpp
Path::Path(MsgRef msg)
: complete(false)
{
pathMsgs.push_back(msg);
sliceMsgs.push_back(msg);
}
Path::~Path() {}
void Path::add(MsgRef msg, bool slice) {
pathMsgs.appendIfChanged(msg);
if (slice) {
sliceMsgs.appendIfChanged(msg);
}
return;
}
void Path::printPath(std::ostream& out) {
if (print == Forward) {
list<MsgRef>::reverse_iterator it = pathMsgs.rbegin();
for(; it != pathMsgs.rend(); it++) {
string msg = (*it)->format();
if (!msg.empty()) {
out << msg;
}
}
}
else {
list<MsgRef>::iterator it = pathMsgs.begin();
for(; it != pathMsgs.end(); it++) {
string msg = (*it)->format();
if (!msg.empty()) {
out << msg;
}
if (selected_formatter != Message::Formatters::TRACES) {
out << endl;
}
}
}
return;
}
void Path::printSlice(std::ostream& out) {
if (print == Forward) {
list<MsgRef>::reverse_iterator it = sliceMsgs.rbegin();
for(; it != sliceMsgs.rend(); it++) {
string msg = (*it)->format();
if (!msg.empty()) {
out << msg << endl;
}
}
}
else {
list<MsgRef>::iterator it = sliceMsgs.begin();
for(; it != sliceMsgs.end(); it++) {
out << (*it)->format();
if (*it != sliceMsgs.back())
out << endl;
}
}
return;
}
void Path::printReport(std::ostream& out, bool slice) {
Message::Types frontTy = pathMsgs.front()->type;
if (selected_formatter == Message::Formatters::STANDARD &&
frontTy != Message::Types::RETURN_FN &&
frontTy != Message::Types::DEREFERENCE &&
frontTy != Message::Types::HANDLED &&
frontTy != Message::Types::ISERR &&
frontTy != Message::Types::ISERRWARN &&
frontTy != Message::Types::OPERAND) {
out << "Error codes: ";
out << pathMsgs.front()->getErrorCodeStr(true);
out << endl << endl;
}
filter(pathMsgs);
printPath(out);
if (slice && selected_formatter == Message::Formatters::STANDARD) {
out << endl;
filter(sliceMsgs);
printSlice(out);
out << endl;
}
if (selected_formatter == Message::Formatters::STANDARD) {
out << "====" << endl;
}
return;
}
int Path::size() {
return pathMsgs.size();
}
bool Path::isComplete() {
return complete;
}
void Path::setComplete(bool c) {
complete = c;
return;
}
void Path::MessageList::appendIfChanged(MsgRef message) {
if (empty() || (*back() != *message)) {
push_back(message);
}
}
// Predicate for list erase in Path::filter
bool removeMsg(MsgRef msg ) {
if (msg->target.find("__cil") != string::npos) {
return true;
}
return false;
}
void Path::filter(MessageList &list) {
// Update line number of message to match __cil var message
// Not entirely sure why the line number fix needs to be made,
// but it should match previous filter.
// If there is a bug, could be here :)
// --- (Daniel)
int line_update = -1;
for (MessageList::reverse_iterator it = list.rbegin(); it != list.rend(); ++it) {
if ((*it)->target.find("__cil") != string::npos && line_update == -1) {
// Set update line number
line_update = (*it)->line_number;
} else if ((*it)->target.find("__cil") == string::npos && line_update != -1) {
(*it)->line_number = line_update;
line_update = -1;
}
}
// Two loops, scalvage what clarity we can in lieu of small efficiency gains.
// Remove __cil messages
// Determines membership by removeMsg()
list.erase(remove_if(++(list.begin()), list.end(), removeMsg), list.end());
}
// void Path::MessageList::filter() {
//
// // Special handling for unsaved errors
// if (front().find("saved", 0) != string::npos) {
//
// // saving first message
// MessageList::iterator it = begin();
// string::size_type p1 = it->find(':', 0);
// string::size_type p2 = it->find(':', p1+1);
// string file = it->substr(0, p1);
// string line = it->substr(p1+1, p2-p1-1);
// string msg = it->substr(p2+1, it->size()-p2-1);
// pop_front();
//
// MessageList temp;
//
// // Deciding which messages to keep
// for(it = begin(); it != end(); it++) {
// if (it->find("__cil") == string::npos) {
// temp.push_back(*it);
// }
// else {
// p1 = it->find(':', 0);
// p2 = it->find(':', p1+1);
// line = (it->substr(p1+1, p2-p1-1)).c_str();
// }
// }
//
// clear();
//
// // Copying back to pathMsgs
//
// // first new message
// string newMessage = file + ':' + line + ':' + msg;
// push_back(newMessage);
//
// for(it = temp.begin(); it != temp.end(); it++) {
// push_back(*it);
// }
//
// } // end if
// return;
// }
/* Yo, Emacs!
;;; Local Variables: ***
;;; tab-width: 4 ***
;;; End: ***
*/
| 22.540909 | 83 | 0.57068 | ucd-plse |
2d367d9d35a41e486d6bbcb8a6b74243ccc03b33 | 553 | cpp | C++ | Cplus/CountNumberofTexts.cpp | Jum1023/leetcode | d8248aa84452cb1ea768d9b05ecd72a6746c0016 | [
"MIT"
] | 1 | 2018-01-22T12:06:28.000Z | 2018-01-22T12:06:28.000Z | Cplus/CountNumberofTexts.cpp | Jum1023/leetcode | d8248aa84452cb1ea768d9b05ecd72a6746c0016 | [
"MIT"
] | null | null | null | Cplus/CountNumberofTexts.cpp | Jum1023/leetcode | d8248aa84452cb1ea768d9b05ecd72a6746c0016 | [
"MIT"
] | null | null | null | #include <string>
#include <vector>
using namespace std;
class Solution
{
public:
int countTexts(string pressedKeys)
{
int N = pressedKeys.length();
vector<int> keys = {0, 0, 3, 3, 3, 3, 3, 4, 3, 4};
vector<int> dp(N + 1);
dp[N] = 1;
for (int i = N - 1; i >= 0; --i)
{
dp[i] = dp[i + 1];
int index = pressedKeys[i] - '0';
for (int j = 1; j + 1 <= keys[index] && i + j < N && pressedKeys[i + j] == pressedKeys[i]; ++j)
dp[i] = (dp[i] + dp[i + j + 1]) % MOD;
}
return dp[0];
}
private:
static const int MOD = 1e9 + 7;
}; | 21.269231 | 98 | 0.528029 | Jum1023 |
2d387a5f8e3bb0a84f8ee21de2a5fc29af7539d8 | 1,928 | cpp | C++ | Aufgabe03/aufgabe2/main.cpp | Freshman83/mos.idk | 2e8f4065228b98b612a0b284f9e552c46a5d1c04 | [
"Apache-2.0"
] | 1 | 2020-06-14T22:47:58.000Z | 2020-06-14T22:47:58.000Z | Aufgabe03/aufgabe2/main.cpp | Freshman83/mos.idk | 2e8f4065228b98b612a0b284f9e552c46a5d1c04 | [
"Apache-2.0"
] | null | null | null | Aufgabe03/aufgabe2/main.cpp | Freshman83/mos.idk | 2e8f4065228b98b612a0b284f9e552c46a5d1c04 | [
"Apache-2.0"
] | null | null | null | // --------------------------------------------------------------------------
// DashBoard - Aufgabe 3.2
//
// Bearbeitet von:
// Sascha Niklas, 257146
// David Rotärmel, 258201
//
// --------------------------------------------------------------------------
// Header
#include <stdio.h> // printf, fprintf
#include <stdlib.h> // exit
#include <unistd.h> // sleep
#include <math.h> // z.B. M_PI, cos(), sin()
#include <GL/glut.h>
#include "../lib/gles.h" // struct opengles, gles*-Funktionen
#include "../lib/tile.h" // struct tile, loadPngTile
GLfloat kmh2deg(GLfloat kmh)
{
if (0.0f < kmh && kmh <= 150.0f)
{
return 135.0f - kmh * 1.5f;
}
else if (kmh > 150.0f)
{
return 150.0f;
}
else
{
return 0.0;
}
}
int main(void)
{
// OpenGL ES initialisieren
struct opengles opengles;
glesInitialize(&opengles);
// Textur für Dashboard laden
struct tile dashboard = TILE_ZEROINIT;
tileLoadPng(&opengles, &dashboard, "../bilder/dashboard.png");
// Textur für Tachonadel laden
struct tile needle = TILE_ZEROINIT;
tileLoadPng(&opengles, &needle, "../bilder/needle.png");
GLfloat angle = kmh2deg(30);
do
{
// Framebuffer löschen.
glClear(GL_COLOR_BUFFER_BIT);
// Dashboard zeichnen
tileDraw(&dashboard);
// ---- Linke Tachonadel zeichnen ---------------------------
glPushMatrix();
// Tachonadel verschieben.
glTranslatef(-1.0,0.0,0.0);
// Tachonadel rotieren.
// 135.0° = 0 km/h; 0.0° = 90 km/h => 1,5° = 1 km/h
glRotatef(angle,0.0,0.0,1.0);
// Tachonadel verschieben.
glTranslatef(0.0,0.25,0.0);
// Tachonadel zeichnen.
tileDraw(&needle);
glPopMatrix();
// ---- Das gezeichnete Bild sichtbar machen ----------------
glesDraw(&opengles);
usleep(16 * 1000);
}
while(glesRun(&opengles));
// OpenGL ES Ressourcen freigeben.
glesDestroy(&opengles);
return 0;
}
/*
Push/Pop: Der letzte Befehl wird zuerst ausgeführt
*/
| 20.083333 | 77 | 0.576245 | Freshman83 |
2d38a8bf5dea1ea1cbc894d89a5e22143297500d | 6,706 | cpp | C++ | DeviceCode/pal/OpenSSL/OpenSSL_1_0_0/crypto/x509v3/v3_akey.cpp | Sirokujira/MicroFrameworkPK_v4_3 | a0d80b4fd8eeda6dbdb58f6f7beb4f07f7ef563e | [
"Apache-2.0"
] | 4 | 2019-01-21T11:47:53.000Z | 2020-06-09T02:14:15.000Z | DeviceCode/pal/OpenSSL/OpenSSL_1_0_0/crypto/x509v3/v3_akey.cpp | yisea123/NetmfSTM32 | 62ddb8aa0362b83d2e73f3621a56593988e3620f | [
"Apache-2.0"
] | null | null | null | DeviceCode/pal/OpenSSL/OpenSSL_1_0_0/crypto/x509v3/v3_akey.cpp | yisea123/NetmfSTM32 | 62ddb8aa0362b83d2e73f3621a56593988e3620f | [
"Apache-2.0"
] | 6 | 2017-11-09T11:48:10.000Z | 2020-05-24T09:43:07.000Z | /* v3_akey.c */
/* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
* project 1999.
*/
/* ====================================================================
* Copyright (c) 1999 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* licensing@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include "cryptlib.h"
#include <openssl/conf.h>
#include <openssl/asn1.h>
#include <openssl/asn1t.h>
#include <openssl/x509v3.h>
#ifdef OPENSSL_SYS_WINDOWS
#include <stdio.h>
#endif
#ifdef __cplusplus
extern "C" {
#endif
static STACK_OF(CONF_VALUE) *i2v_AUTHORITY_KEYID(X509V3_EXT_METHOD *method,
AUTHORITY_KEYID *akeyid, STACK_OF(CONF_VALUE) *extlist);
static AUTHORITY_KEYID *v2i_AUTHORITY_KEYID(X509V3_EXT_METHOD *method,
X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *values);
extern X509V3_EXT_METHOD v3_akey_id =
{
NID_authority_key_identifier,
X509V3_EXT_MULTILINE, ASN1_ITEM_ref(AUTHORITY_KEYID),
0,0,0,0,
0,0,
(X509V3_EXT_I2V)i2v_AUTHORITY_KEYID,
(X509V3_EXT_V2I)v2i_AUTHORITY_KEYID,
0,0,
NULL
};
static STACK_OF(CONF_VALUE) *i2v_AUTHORITY_KEYID(X509V3_EXT_METHOD *method,
AUTHORITY_KEYID *akeyid, STACK_OF(CONF_VALUE) *extlist)
{
char *tmp;
if(akeyid->keyid) {
tmp = hex_to_string(akeyid->keyid->data, akeyid->keyid->length);
X509V3_add_value("keyid", tmp, &extlist);
OPENSSL_free(tmp);
}
if(akeyid->issuer)
extlist = i2v_GENERAL_NAMES(NULL, akeyid->issuer, extlist);
if(akeyid->serial) {
tmp = hex_to_string(akeyid->serial->data,
akeyid->serial->length);
X509V3_add_value("serial", tmp, &extlist);
OPENSSL_free(tmp);
}
return extlist;
}
/* Currently two options:
* keyid: use the issuers subject keyid, the value 'always' means its is
* an error if the issuer certificate doesn't have a key id.
* issuer: use the issuers cert issuer and serial number. The default is
* to only use this if keyid is not present. With the option 'always'
* this is always included.
*/
static AUTHORITY_KEYID *v2i_AUTHORITY_KEYID(X509V3_EXT_METHOD *method,
X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *values)
{
char keyid=0, issuer=0;
int i;
CONF_VALUE *cnf;
ASN1_OCTET_STRING *ikeyid = NULL;
X509_NAME *isname = NULL;
GENERAL_NAMES * gens = NULL;
GENERAL_NAME *gen = NULL;
ASN1_INTEGER *serial = NULL;
X509_EXTENSION *ext;
X509 *cert;
AUTHORITY_KEYID *akeyid;
for(i = 0; i < sk_CONF_VALUE_num(values); i++)
{
cnf = sk_CONF_VALUE_value(values, i);
if(!TINYCLR_SSL_STRCMP(cnf->name, "keyid"))
{
keyid = 1;
if(cnf->value && !TINYCLR_SSL_STRCMP(cnf->value, "always"))
keyid = 2;
}
else if(!TINYCLR_SSL_STRCMP(cnf->name, "issuer"))
{
issuer = 1;
if(cnf->value && !TINYCLR_SSL_STRCMP(cnf->value, "always"))
issuer = 2;
}
else
{
X509V3err(X509V3_F_V2I_AUTHORITY_KEYID,X509V3_R_UNKNOWN_OPTION);
ERR_add_error_data(2, "name=", cnf->name);
return NULL;
}
}
if(!ctx || !ctx->issuer_cert)
{
if(ctx && (ctx->flags==CTX_TEST))
return AUTHORITY_KEYID_new();
X509V3err(X509V3_F_V2I_AUTHORITY_KEYID,X509V3_R_NO_ISSUER_CERTIFICATE);
return NULL;
}
cert = ctx->issuer_cert;
if(keyid)
{
i = X509_get_ext_by_NID(cert, NID_subject_key_identifier, -1);
if((i >= 0) && (ext = X509_get_ext(cert, i)))
ikeyid = (ASN1_OCTET_STRING*)X509V3_EXT_d2i(ext);
if(keyid==2 && !ikeyid)
{
X509V3err(X509V3_F_V2I_AUTHORITY_KEYID,X509V3_R_UNABLE_TO_GET_ISSUER_KEYID);
return NULL;
}
}
if((issuer && !ikeyid) || (issuer == 2))
{
isname = X509_NAME_dup(X509_get_issuer_name(cert));
serial = M_ASN1_INTEGER_dup(X509_get_serialNumber(cert));
if(!isname || !serial)
{
X509V3err(X509V3_F_V2I_AUTHORITY_KEYID,X509V3_R_UNABLE_TO_GET_ISSUER_DETAILS);
goto err;
}
}
if(!(akeyid = AUTHORITY_KEYID_new())) goto err;
if(isname)
{
if(!(gens = sk_GENERAL_NAME_new_null())
|| !(gen = GENERAL_NAME_new())
|| !sk_GENERAL_NAME_push(gens, gen))
{
X509V3err(X509V3_F_V2I_AUTHORITY_KEYID,ERR_R_MALLOC_FAILURE);
goto err;
}
gen->type = GEN_DIRNAME;
gen->d.dirn = isname;
}
akeyid->issuer = gens;
akeyid->serial = serial;
akeyid->keyid = ikeyid;
return akeyid;
err:
X509_NAME_free(isname);
M_ASN1_INTEGER_free(serial);
M_ASN1_OCTET_STRING_free(ikeyid);
return NULL;
}
#ifdef __cplusplus
}
#endif
| 30.621005 | 81 | 0.708619 | Sirokujira |
2d38c85537fa297ad9e4784b32fe7d26c072ff9f | 2,401 | cpp | C++ | src/CGeomCylinder3D.cpp | colinw7/CGeometry3D | 15c009b57bfcdcc5ca13ef2acfe94b6831a4c865 | [
"MIT"
] | 1 | 2021-12-23T02:21:22.000Z | 2021-12-23T02:21:22.000Z | src/CGeomCylinder3D.cpp | colinw7/CGeometry3D | 15c009b57bfcdcc5ca13ef2acfe94b6831a4c865 | [
"MIT"
] | null | null | null | src/CGeomCylinder3D.cpp | colinw7/CGeometry3D | 15c009b57bfcdcc5ca13ef2acfe94b6831a4c865 | [
"MIT"
] | null | null | null | #include <CGeomCylinder3D.h>
#include <CGeomTexture.h>
#include <CGeomMask.h>
CGeomCylinder3D::
CGeomCylinder3D(CGeomScene3D *pscene, const std::string &name,
double xc, double yc, double zc, double w, double h) :
CGeomObject3D(pscene, name)
{
addGeometry(this, xc, yc, zc, w, h, num_patches_);
}
void
CGeomCylinder3D::
addGeometry(CGeomObject3D *object, double xc, double yc, double zc,
double w, double h, uint num_patches)
{
double x[4], y[4];
x[0] = 0; y[0] = -h/2;
x[1] = +w/2; y[1] = -h/2;
x[2] = +w/2; y[2] = +h/2;
x[3] = 0; y[3] = +h/2;
object->addBodyRev(x, y, 4, num_patches);
object->moveBy(CPoint3D(xc, yc, zc));
}
void
CGeomCylinder3D::
mapTexture(CGeomTexture *texture)
{
FaceList &faces = getFaces();
int twidth, theight;
texture->getImageSize(&twidth, &theight);
double dx = (twidth - 1)/double(num_patches_);
double dy = (theight - 1);
double y1 = 0;
double y2 = y1 + dy;
double x1 = 0;
for (uint i = num_patches_; i < 2*num_patches_; ++i) {
double x2 = x1 + dx;
faces[i]->setTexture(texture);
std::vector<CPoint2D> points;
points.push_back(CPoint2D(double(int(x2)), double(int(y2))));
points.push_back(CPoint2D(double(int(x2)), double(int(y1))));
points.push_back(CPoint2D(double(int(x1)), double(int(y1))));
points.push_back(CPoint2D(double(int(x1)), double(int(y2))));
faces[i]->setTextureMapping(points);
x1 = x2;
}
}
void
CGeomCylinder3D::
mapTexture(CImagePtr image)
{
CGeomObject3D::mapTexture(image);
}
void
CGeomCylinder3D::
mapMask(CGeomMask *mask)
{
FaceList &faces = getFaces();
uint twidth, theight;
mask->getImageSize(&twidth, &theight);
double dx = (twidth - 1)/double(num_patches_);
double dy = (theight - 1);
double y1 = 0;
double y2 = y1 + dy;
double x1 = 0;
for (uint i = num_patches_; i < 2*num_patches_; ++i) {
double x2 = x1 + dx;
faces[i]->setMask(mask);
std::vector<CPoint2D> points;
points.push_back(CPoint2D(double(int(x2)), double(int(y2))));
points.push_back(CPoint2D(double(int(x2)), double(int(y1))));
points.push_back(CPoint2D(double(int(x1)), double(int(y1))));
points.push_back(CPoint2D(double(int(x1)), double(int(y2))));
faces[i]->setMaskMapping(points);
x1 = x2;
}
}
void
CGeomCylinder3D::
mapMask(CImagePtr image)
{
CGeomObject3D::mapMask(image);
}
| 20.878261 | 70 | 0.641399 | colinw7 |
2d38e46592f54c07ca1e7bff0fe34a6d11224604 | 6,534 | cpp | C++ | SDKs/CryCode/3.6.15/CryEngine/CryAction/MaterialEffects/MFXDecalEffect.cpp | amrhead/FireNET | 34d439aa0157b0c895b20b2b664fddf4f9b84af1 | [
"BSD-2-Clause"
] | 4 | 2017-12-18T20:10:16.000Z | 2021-02-07T21:21:24.000Z | SDKs/CryCode/3.6.15/CryEngine/CryAction/MaterialEffects/MFXDecalEffect.cpp | amrhead/FireNET | 34d439aa0157b0c895b20b2b664fddf4f9b84af1 | [
"BSD-2-Clause"
] | null | null | null | SDKs/CryCode/3.6.15/CryEngine/CryAction/MaterialEffects/MFXDecalEffect.cpp | amrhead/FireNET | 34d439aa0157b0c895b20b2b664fddf4f9b84af1 | [
"BSD-2-Clause"
] | 3 | 2019-03-11T21:36:15.000Z | 2021-02-07T21:21:26.000Z | ////////////////////////////////////////////////////////////////////////////
//
// Crytek Engine Source File.
// Copyright (C), Crytek Studios, 2006.
// -------------------------------------------------------------------------
// File name: MFXDecalEffect.cpp
// Version: v1.00
// Created: 28/11/2006 by JohnN/AlexL
// Compilers: Visual Studio.NET
// Description: Decal effect
// -------------------------------------------------------------------------
// History:
//
////////////////////////////////////////////////////////////////////////////
#include "StdAfx.h"
#include "MFXDecalEffect.h"
CMFXDecalEffect::CMFXDecalEffect() : m_material(0)
{
}
CMFXDecalEffect::~CMFXDecalEffect()
{
ReleaseMaterial();
}
void CMFXDecalEffect::ReadXMLNode(XmlNodeRef &node)
{
IMFXEffect::ReadXMLNode(node);
XmlNodeRef material = node->findChild("Material");
if (material)
{
m_decalParams.material = material->getContent();
// preloading is done during level loading itself
}
m_decalParams.minscale = 1.f;
m_decalParams.maxscale = 1.f;
m_decalParams.rotation = -1.f;
m_decalParams.growTime = 0.f;
m_decalParams.assemble = false;
m_decalParams.lifetime = 10.0f;
m_decalParams.forceedge = false;
XmlNodeRef scalenode = node->findChild("Scale");
if (scalenode)
{
m_decalParams.minscale = (float)atof(scalenode->getContent());
m_decalParams.maxscale = m_decalParams.minscale;
}
node->getAttr("minscale", m_decalParams.minscale);
node->getAttr("maxscale", m_decalParams.maxscale);
node->getAttr("rotation", m_decalParams.rotation);
m_decalParams.rotation = DEG2RAD(m_decalParams.rotation);
node->getAttr("growTime", m_decalParams.growTime);
node->getAttr("assembledecals", m_decalParams.assemble);
node->getAttr("forceedge", m_decalParams.forceedge);
node->getAttr("lifetime", m_decalParams.lifetime);
}
IMFXEffectPtr CMFXDecalEffect::Clone()
{
CMFXDecalEffect* clone = new CMFXDecalEffect();
clone->m_decalParams.material = m_decalParams.material;
clone->m_decalParams.minscale = m_decalParams.minscale;
clone->m_decalParams.maxscale = m_decalParams.maxscale;
clone->m_decalParams.rotation = m_decalParams.rotation;
clone->m_decalParams.growTime = m_decalParams.growTime;
clone->m_decalParams.assemble = m_decalParams.assemble;
clone->m_decalParams.forceedge = m_decalParams.forceedge;
clone->m_decalParams.lifetime = m_decalParams.lifetime;
clone->m_effectParams = m_effectParams;
return clone;
}
void CMFXDecalEffect::PreLoadAssets()
{
IMFXEffect::PreLoadAssets();
if (m_decalParams.material.c_str())
{
// store as smart pointer
m_material = gEnv->p3DEngine->GetMaterialManager()->LoadMaterial(
m_decalParams.material.c_str(),false);
}
}
void CMFXDecalEffect::ReleasePreLoadAssets()
{
IMFXEffect::ReleasePreLoadAssets();
ReleaseMaterial();
}
void CMFXDecalEffect::ReleaseMaterial()
{
// Release material (smart pointer)
m_material = 0;
}
void CMFXDecalEffect::Execute(SMFXRunTimeEffectParams ¶ms)
{
FUNCTION_PROFILER(gEnv->pSystem, PROFILE_ACTION);
if (!(params.playflags & MFX_PLAY_DECAL))
return;
// not on a static object or entity
const float angle = (params.angle != MFX_INVALID_ANGLE) ? params.angle : Random(0.f, gf_PI2);
if (!params.trgRenderNode && !params.trg)
{
CryEngineDecalInfo terrainDecal;
{ // 2d terrain
const float terrainHeight( gEnv->p3DEngine->GetTerrainElevation(params.pos.x, params.pos.y) );
const float terrainDelta( params.pos.z - terrainHeight );
if (terrainDelta > 2.0f || terrainDelta < -0.5f)
return;
terrainDecal.vPos = Vec3(params.decalPos.x, params.decalPos.y, terrainHeight);
}
terrainDecal.vNormal = params.normal;
terrainDecal.vHitDirection = params.dir[0].GetNormalized();
terrainDecal.fLifeTime = m_decalParams.lifetime;
terrainDecal.fGrowTime = m_decalParams.growTime;
if (!m_decalParams.material.empty())
strcpy(terrainDecal.szMaterialName, m_decalParams.material.c_str());
else
CryWarning(VALIDATOR_MODULE_3DENGINE, VALIDATOR_WARNING, "CMFXDecalEffect::Execute: Decal material name is not specified");
terrainDecal.fSize = Random(m_decalParams.minscale, m_decalParams.maxscale);
if(m_decalParams.rotation>=0.f)
terrainDecal.fAngle = m_decalParams.rotation;
else
terrainDecal.fAngle = angle;
if(terrainDecal.fSize <= params.fDecalPlacementTestMaxSize)
gEnv->p3DEngine->CreateDecal(terrainDecal);
}
else
{
CryEngineDecalInfo decal;
IEntity *pEnt = gEnv->pEntitySystem->GetEntity(params.trg);
IRenderNode* pRenderNode = NULL;
if (pEnt)
{
IEntityRenderProxy *pRenderProxy = (IEntityRenderProxy*)pEnt->GetProxy(ENTITY_PROXY_RENDER);
if (pRenderProxy)
pRenderNode = pRenderProxy->GetRenderNode();
}
else
{
pRenderNode = params.trgRenderNode;
}
// filter out ropes
if (pRenderNode && pRenderNode->GetRenderNodeType() == eERType_Rope)
return;
decal.ownerInfo.pRenderNode = pRenderNode;
decal.vPos = params.pos;
decal.vNormal = params.normal;
decal.vHitDirection = params.dir[0].GetNormalized();
decal.fLifeTime = m_decalParams.lifetime;
decal.fGrowTime = m_decalParams.growTime;
decal.bAssemble = m_decalParams.assemble;
decal.bForceEdge = m_decalParams.forceedge;
if (!m_decalParams.material.empty())
strcpy(decal.szMaterialName, m_decalParams.material.c_str());
else
CryWarning(VALIDATOR_MODULE_3DENGINE, VALIDATOR_WARNING, "CMFXDecalEffect::Execute: Decal material name is not specified");
decal.fSize = Random(m_decalParams.minscale, m_decalParams.maxscale);
if(m_decalParams.rotation>=0.f)
decal.fAngle = m_decalParams.rotation;
else
decal.fAngle = angle;
if(decal.fSize <= params.fDecalPlacementTestMaxSize)
gEnv->p3DEngine->CreateDecal(decal);
}
}
void CMFXDecalEffect::GetResources(SMFXResourceList &rlist)
{
SMFXDecalListNode *listNode = SMFXDecalListNode::Create();
listNode->m_decalParams.material = m_decalParams.material.c_str();
listNode->m_decalParams.minscale = m_decalParams.minscale;
listNode->m_decalParams.maxscale = m_decalParams.maxscale;
listNode->m_decalParams.rotation = m_decalParams.rotation;
listNode->m_decalParams.assemble = m_decalParams.assemble;
listNode->m_decalParams.forceedge = m_decalParams.forceedge;
listNode->m_decalParams.lifetime = m_decalParams.lifetime;
SMFXDecalListNode* next = rlist.m_decalList;
if (!next)
rlist.m_decalList = listNode;
else
{
while (next->pNext)
next = next->pNext;
next->pNext = listNode;
}
} | 29.7 | 129 | 0.712274 | amrhead |
2d3a0a2484293d048802d79d028148f3ee3ac812 | 4,752 | cc | C++ | src/shared/imc/nacl_imc_test_server.cc | eseidel/native_client_patches | c699f77e085b91fcc1684ecb63e2e211733afbde | [
"BSD-3-Clause"
] | 4 | 2015-10-27T04:43:02.000Z | 2021-08-13T08:21:45.000Z | src/shared/imc/nacl_imc_test_server.cc | eseidel/native_client_patches | c699f77e085b91fcc1684ecb63e2e211733afbde | [
"BSD-3-Clause"
] | null | null | null | src/shared/imc/nacl_imc_test_server.cc | eseidel/native_client_patches | c699f77e085b91fcc1684ecb63e2e211733afbde | [
"BSD-3-Clause"
] | 1 | 2015-11-08T10:18:42.000Z | 2015-11-08T10:18:42.000Z | /*
* Copyright 2008 The Native Client Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can
* be found in the LICENSE file.
*/
// NaCl inter-module communication primitives.
// TODO(shiki): Make this program a unit test.
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include "native_client/src/shared/imc/nacl_imc.h"
nacl::SocketAddress server_address = {
"imc-server"
};
nacl::SocketAddress client_address = {
"imc-client"
};
namespace {
nacl::Handle g_front;
void CleanUp() {
nacl::Close(g_front);
}
// Writes the last error message to the standard error.
void PrintError(const char* message) {
char buffer[256];
if (nacl::GetLastErrorString(buffer, sizeof buffer) == 0) {
fprintf(stderr, "%s: %s\n", message, buffer);
}
}
} // namespace
int main() {
int result;
g_front = nacl::BoundSocket(&server_address);
if (g_front == nacl::kInvalidHandle) {
PrintError("BoundSocket");
exit(EXIT_FAILURE);
}
atexit(CleanUp);
// Test name collision.
nacl::Handle front2 = nacl::BoundSocket(&server_address);
assert(front2 == nacl::kInvalidHandle);
if (front2 == nacl::kInvalidHandle) {
PrintError("BoundSocket");
}
nacl::Handle handles[8];
nacl::MessageHeader header;
nacl::IOVec vec[3];
char buffer[64];
// Receive a handle connected to the client.
nacl::Handle client_handle = nacl::kInvalidHandle;
vec[0].base = buffer;
vec[0].length = sizeof buffer;
header.iov = vec;
header.iov_length = 1;
header.handles = handles;
header.handle_count = sizeof handles / sizeof handles[0];
result = nacl::ReceiveDatagram(g_front, &header, 0);
if (0 < result && header.handle_count == 1) {
client_handle = handles[0];
printf("%.*s: %d\n", result, buffer, client_handle);
} else {
PrintError("ReceiveDatagram");
exit(EXIT_FAILURE);
}
// Test kDontWait for a socket created by socketpair().
vec[0].base = buffer;
vec[0].length = sizeof buffer;
header.iov = vec;
header.iov_length = 1;
header.handles = NULL;
header.handle_count = 0;
result = nacl::ReceiveDatagram(client_handle, &header, nacl::kDontWait);
assert(result == -1);
PrintError("ReceiveDatagram");
assert(nacl::WouldBlock());
// Test an empty message.
vec[0].base = buffer;
vec[0].length = 0;
header.iov = vec;
header.iov_length = 1;
header.handles = NULL;
header.handle_count = 0;
result = nacl::SendDatagram(client_handle, &header, 0);
assert(result == 0);
// Test scatter/gather.
for (unsigned int i = 0; i < sizeof vec / sizeof vec[0]; ++i) {
buffer[i] = "ABC"[i];
vec[i].base = buffer + i;
vec[i].length = 1;
}
header.iov = vec;
header.iov_length = sizeof vec / sizeof vec[0];
header.handles = &client_handle;
header.handle_count = 1;
result = nacl::SendDatagram(client_handle, &header, 0);
assert(result == sizeof vec / sizeof vec[0]);
// Test Receive().
result = nacl::Receive(client_handle, buffer, sizeof buffer, 0);
if (result == -1) {
PrintError("ReceiveDatagram");
}
assert(result == 2);
if (0 < result) {
printf("%.*s\n", result, buffer);
}
// Test shared memory.
nacl::Handle shared_memory =
nacl::CreateMemoryObject(1024 * 1024, /* executable= */ false);
if (shared_memory != nacl::kInvalidHandle) {
void* shared_region = nacl::Map(0, 1024 * 1024,
nacl::kProtRead | nacl::kProtWrite,
nacl::kMapShared,
shared_memory, 0);
if (shared_region) {
memset(shared_region, 0, 1024 * 1024);
header.iov = vec;
header.iov_length = 2;
header.handles = &shared_memory;
header.handle_count = 1;
nacl::SendDatagram(client_handle, &header, 0);
memset(shared_region, 0xff, 1024 * 1024);
while (*static_cast<volatile unsigned int*>(shared_region) ==
0xffffffff) {
}
printf("server: shm ok.\n");
}
nacl::Unmap(shared_region, 1024 * 1024);
nacl::Close(shared_memory);
}
// Test kDontWait for a large message.
vec[0].base = buffer;
vec[0].length = sizeof buffer;
header.iov = vec;
header.iov_length = 1;
header.handles = NULL;
header.handle_count = 0;
result = nacl::ReceiveDatagram(client_handle, &header, nacl::kDontWait);
assert(result == sizeof buffer);
// Test close detection.
vec[0].base = buffer;
vec[0].length = sizeof buffer;
header.iov = vec;
header.iov_length = 1;
header.handles = NULL;
header.handle_count = 0;
result = nacl::ReceiveDatagram(client_handle, &header, 0);
assert(result <= 0);
nacl::Close(client_handle);
return 0;
}
| 26.254144 | 74 | 0.644992 | eseidel |
2d3a3b17293c2d7f25afbaf9187889901e2b026e | 251 | cpp | C++ | main.cpp | UCLA-Rocket-Project/daq-sampler | 56846b4fd5ca79028e6795f112f1f95188a0694b | [
"MIT"
] | null | null | null | main.cpp | UCLA-Rocket-Project/daq-sampler | 56846b4fd5ca79028e6795f112f1f95188a0694b | [
"MIT"
] | null | null | null | main.cpp | UCLA-Rocket-Project/daq-sampler | 56846b4fd5ca79028e6795f112f1f95188a0694b | [
"MIT"
] | null | null | null | #include "src/Logfile.h"
#include <spdlog/spdlog.h>
using namespace std;
int main() {
spdlog::error("Have a nice day");
LogFile logger;
const char* id = "abcd";
uint32_t *idPtr = (uint32_t*)id;
logger.logNameChange(ADC, 4, *idPtr);
return 0;
}
| 19.307692 | 38 | 0.681275 | UCLA-Rocket-Project |
2d3bb4ef8e93d2b8d86ac5bb77b0e7864bcde0bc | 5,309 | hh | C++ | DetectorModel/DetElem.hh | brownd1978/FastSim | 05f590d72d8e7f71856fd833114a38b84fc7fd48 | [
"Apache-2.0"
] | null | null | null | DetectorModel/DetElem.hh | brownd1978/FastSim | 05f590d72d8e7f71856fd833114a38b84fc7fd48 | [
"Apache-2.0"
] | null | null | null | DetectorModel/DetElem.hh | brownd1978/FastSim | 05f590d72d8e7f71856fd833114a38b84fc7fd48 | [
"Apache-2.0"
] | null | null | null | // ------------------------------------------------------------------------------
// File and Version Information:
// $Id: DetElem.hh,v 1.32 2004/12/14 07:10:17 bartoldu Exp $
//
// Description:
// Base Class to define a specific element of the tracking detector. The types
// must exist before elements can be created from them. Also the subclasses
// are responsable for providing the HepTransformation* to the base class
// (note: the DetElem HepTransformation pointer MUST point to a valid
// transform, which is owned (perhaps indirectly) by the element itself).
// This class is the main interface between abstract
// track representations (hits and fit parameters) and the 3-D material
// model.
//
// Copyright Information:
// Copyright (C) 1996 Lawrence Berkeley Laboratory
//
// Authors: Dave Brown, 7/17/96
// ------------------------------------------------------------------------------
#ifndef DETECTORELEMENT_HH
#define DETECTORELEMENT_HH
//----------------
// BaBar header --
//----------------
#if defined( HP1022 ) && !defined( BABAR_HH )
#include "BaBar/BaBar.hh"
#include "ErrLogger/ErrLog.hh"
#endif // HP1022 && !BABAR_HH
//
// global includes
//
#include <iostream>
#include <string>
#include "CLHEP/Geometry/HepPoint.h"
#include <vector>
//
// Local includes
//
#include "DetectorModel/DetType.hh"
#include "PDT/PdtPid.hh"
#include "TrkBase/TrkDirection.hh"
//
class TrkDifTraj;
class Trajectory;
class DetType;
class DetElem;
class DetAlignElem;
class HepTransformation;
class DetIntersection;
class GnuPlot;
//
// Define the class
//
class DetElem{
public:
//
// Constructors
//
DetElem();
DetElem(const DetType*,const char*,int);
// Assignment operator
DetElem& operator = (const DetElem&);
// equality operator (needed for old templates)
bool operator == (const DetElem& other) const;
// see if an align elem matches this element
bool match(const DetAlignElem& ae) const;
//
// Destructor
//
virtual ~DetElem();
//
// Geometric functions
//
// Intersect a trajectory with this detector element. The DetIntersection
// reference range limits initially define the search range and start value, but
// are returned as the entrance and exit point of the intersection. If the input
// lower limit is >= the upper limit, the range is ignored.
//
virtual int intersect(const Trajectory*,DetIntersection&) const = 0;
//
// Material information from an intersection. Default base class versions
// are provided which assume any given intersection goes through only
// one type of material. If this is not the case, the element subclass
// must overwrite these functions. The user interface is only the second
// function, which calls the first in the base class implementation. This
// allows subclasses which are not homogenous but still have only one
// material type for a given intersection to use the base implementation
// of materialInfo, only overwriting the base of material.
//
// Note, this function now returns the (dimensionless) fractional
// change in momentum associated with energy loss, not the energy
// loss itself (ditto for the energy loss RMS).
//
// DNB 3/13/00 Added the particle direction as an argument to materialInfo;
// trkIn means the particle is passing inwards (pfrac>0),
// trkOut for passing outwards (pfrac<0) through the material.
public:
virtual const DetMaterial& material(const DetIntersection&) const;
virtual void materialInfo(const DetIntersection&,
double momentum,
PdtPid::PidType pid,
double& deflectRMS,
double& pFractionRMS,
double& pFraction,
trkDirection dedxdir=trkOut) const;
//
// Alignment functions. The name and ID number of the local DetAlignElem
// must match that of the DetElem.
//
void applyGlobal(const DetAlignElem&);// apply global alignment
void applyLocal(const DetAlignElem&); // apply local alignment
void removeGlobal(const DetAlignElem&);// unapply global alignment
void removeLocal(const DetAlignElem&); // unapply local alignment
virtual void updateCache(); // update an elements cache (used for subclasses)
//
// Access functions
//
virtual void print(std::ostream& os) const;
virtual void printAll(std::ostream& os ) const;
const DetType* detectorType() const { return _dtype; }
int elementNumber() const {return _ielem; }
const std::string& elementName() const {return _ename; }
const HepTransformation& transform() const { return *_etrans; }
//
// Outline function
//
virtual void physicalOutline(std::vector<HepPoint>&) const;
virtual void gnuPlot( GnuPlot* ) const;
protected:
virtual HepPoint coordToPoint( const TypeCoord* aCoord ) const = 0;
// the ElemPointIterator class must be able to access coordToPoint function
friend class DetElemPointIterator;
// Following is so derived classes can set transform through method
HepTransformation*& myTransf() { return _etrans; }
HepTransformation& transf() { return *_etrans; } // nonconst transform
// private:
int _ielem; // integer identifier; this is controled by the sub-class
const std::string _ename; // name
const DetType* _dtype; // pointer to the type
HepTransformation* _etrans; // spatial transform
// this is used in the DetElemSet subclass of DetSet
friend class DetElemSet;
};
#endif
| 36.363014 | 81 | 0.70955 | brownd1978 |
2d3f52c0e5774d7b23a26448ba4d68899d0c1413 | 5,489 | cpp | C++ | clessc/src/Selector.cpp | shoichikaji/CSS-clessc | 194be6f00ad6f9277efedd7cadab76c6f69a540e | [
"Artistic-1.0"
] | 1 | 2015-03-17T06:27:25.000Z | 2015-03-17T06:27:25.000Z | clessc/src/Selector.cpp | shoichikaji/CSS-clessc | 194be6f00ad6f9277efedd7cadab76c6f69a540e | [
"Artistic-1.0"
] | null | null | null | clessc/src/Selector.cpp | shoichikaji/CSS-clessc | 194be6f00ad6f9277efedd7cadab76c6f69a540e | [
"Artistic-1.0"
] | null | null | null | /*
* Copyright 2012 Bram van der Kroef
*
* This file is part of LESS CSS Compiler.
*
* LESS CSS Compiler 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.
*
* LESS CSS Compiler 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 LESS CSS Compiler. If not, see <http://www.gnu.org/licenses/>.
*
* Author: Bram van der Kroef <bram@vanderkroef.net>
*/
#include "Selector.h"
#include <iostream>
#ifdef WITH_LIBGLOG
#include <glog/logging.h>
#endif
Selector::~Selector() {
clear();
}
void Selector::addPrefix(const Selector &prefix) {
list<Selector> prefixParts;
list<Selector> sepParts;
list<Selector>::iterator prefixIt;
list<Selector>::iterator sepIt;
Selector* tmp, *prefixPart;
TokenList::iterator i;
bool containsAmp;
Token space(" ", Token::WHITESPACE),
comma(",", Token::OTHER);
split(sepParts);
prefix.split(prefixParts);
clear();
for (sepIt = sepParts.begin();
sepIt != sepParts.end(); sepIt++) {
tmp = &(*sepIt);
tmp->ltrim();
containsAmp = tmp->contains(Token::OTHER, "&");
for (prefixIt = prefixParts.begin();
prefixIt != prefixParts.end(); prefixIt++) {
prefixPart = &(*prefixIt);
if (containsAmp) {
for (i = tmp->begin(); i != tmp->end(); i++) {
if (*i == "&")
insert(end(), prefixPart->begin(), prefixPart->end());
else
push_back(*i);
}
} else {
insert(end(), prefixPart->begin(), prefixPart->end());
push_back(space);
insert(end(), tmp->begin(), tmp->end());
}
push_back(comma);
}
}
pop_back();
}
void Selector::split(std::list<Selector> &l) const {
TokenList::const_iterator first, last;
Selector current;
for (first = begin(); first != end(); ) {
last = findComma(first);
current.assign(first, last);
#ifdef WITH_LIBGLOG
VLOG(3) << "Split: " << current.toString();
#endif
l.push_back(current);
first = last;
if (first != end())
first++;
}
}
TokenList::const_iterator Selector::findComma(const_iterator offset)
const {
return findComma(offset, end());
}
TokenList::const_iterator Selector::findComma(const_iterator offset,
const_iterator limit) const {
unsigned int parentheses = 0;
for (; offset != limit; offset++) {
if (parentheses == 0 &&
(*offset).type == Token::OTHER &&
*offset == ",") {
return offset;
} else {
if (*offset == "(")
parentheses++;
else if (*offset == ")")
parentheses--;
}
}
return offset;
}
bool Selector::match(const Selector &list) const {
TokenList::const_iterator first, last;
TokenList::const_iterator l_first, l_last;
for (first = begin(); first != end(); ) {
last = findComma(first);
for (l_first = list.begin(); l_first != list.end(); ) {
l_last = list.findComma(l_first);
if (walk(l_first, l_last, first) == last)
return true;
l_first = l_last;
if (l_first != list.end()) {
l_first++;
while (l_first != list.end() && (*l_first).type == Token::WHITESPACE)
l_first++;
}
}
first = last;
if (first != end()) {
first++;
while (first != end() && (*first).type == Token::WHITESPACE)
first++;
}
}
return false;
}
TokenList::const_iterator Selector::walk(const Selector &list,
const_iterator offset) const {
TokenList::const_iterator first, last, pos;
for (first = list.begin(); first != list.end(); ) {
last = list.findComma(first);
pos = walk(first, last, offset);
if (pos != begin())
return pos;
first = last;
if (first != list.end()) {
first++;
while (first != list.end() && (*first).type == Token::WHITESPACE)
first++;
}
}
return begin();
}
TokenList::const_iterator Selector::walk(const const_iterator &list_begin,
const const_iterator &list_end,
const_iterator offset) const {
TokenList::const_iterator li = list_begin;
while (offset != end() && li != list_end) {
if (*offset != *li)
return begin();
offset++;
li++;
if (offset != end() && *offset == ">") {
offset++;
if (offset != end() && (*offset).type == Token::WHITESPACE)
offset++;
}
if (li != list_end && *li == ">") {
li++;
if (li != list_end && (*li).type == Token::WHITESPACE)
li++;
}
}
if (li != list_end)
offset = begin();
return offset;
}
TokenList::const_iterator Selector::find(const TokenList &list,
TokenList::const_iterator offset,
TokenList::const_iterator limit) const {
for (; offset != limit; offset++) {
if (walk(list.begin(), list.end(), offset) != begin())
return offset;
}
return limit;
}
| 25.178899 | 81 | 0.567316 | shoichikaji |
2d40c823abad0b3150f26d75a6c8104b4e125ce6 | 322 | cpp | C++ | MLSA Event-101/C++/check_pow_of_2.cpp | rswalia/open-source-contribution-for-beginners | 1ea29479c6d949760c83926b4c43a6b0d33ad0a0 | [
"MIT"
] | 35 | 2021-12-20T13:37:01.000Z | 2022-03-22T20:52:36.000Z | MLSA Event-101/C++/check_pow_of_2.cpp | rswalia/open-source-contribution-for-beginners | 1ea29479c6d949760c83926b4c43a6b0d33ad0a0 | [
"MIT"
] | 152 | 2021-11-01T06:00:11.000Z | 2022-03-20T11:40:00.000Z | MLSA Event-101/C++/check_pow_of_2.cpp | rswalia/open-source-contribution-for-beginners | 1ea29479c6d949760c83926b4c43a6b0d33ad0a0 | [
"MIT"
] | 71 | 2021-11-01T06:02:37.000Z | 2022-03-20T04:49:30.000Z | /*
This program checks whether the given number is a power of 2 or not
*/
#include<iostream>
using namespace std;
int main(){
long long int n;
cin>>n;
if( !(n & n-1)){
cout<<"Yes given number is power of 2"<<endl;
}
else {
cout<<"No given number is not the power of 2"<<endl;
}
} | 21.466667 | 70 | 0.580745 | rswalia |
2d40e9d2a5dd8d0b7d0a30d5b57c75c3acc3dead | 1,240 | cpp | C++ | Game/GameEngine/Events/EventMove.cpp | arthurChennetier/R-Type | bac6f8cf6502f74798181181a819d609b1d82e3a | [
"MIT"
] | 1 | 2018-07-22T13:45:47.000Z | 2018-07-22T13:45:47.000Z | Game/GameEngine/Events/EventMove.cpp | arthurChennetier/R-Type | bac6f8cf6502f74798181181a819d609b1d82e3a | [
"MIT"
] | null | null | null | Game/GameEngine/Events/EventMove.cpp | arthurChennetier/R-Type | bac6f8cf6502f74798181181a819d609b1d82e3a | [
"MIT"
] | 1 | 2018-07-20T12:52:42.000Z | 2018-07-20T12:52:42.000Z | //
// Created by chauvin on 28/01/18.
//
#include "EventMove.hpp"
#include "../Rigidbody/Rigidbody.hpp"
#include "../Input/Input.h"
TacosEngine::EventMove::EventMove(const std::shared_ptr<TacosEngine::GameObject> &obj, const Vector2 &dir)
{
this->_object = obj;
this->_dir = dir;
std::cout << "X :" << dir.get_x() << "Y :" << dir.get_y() << std::endl;
}
void TacosEngine::EventMove::onEvent()
{
std::cout << "MOVE" << std::endl;
auto rb = this->_object->getComponent<Rigidbody>();
CheckWindowCollide(_dir);
_object->getTransform().setDirection(_dir);
_object->getTransform().setSpeed(2.5);
rb->addForce(_dir * _object->getTransform().getSpeed());
}
TacosEngine::Vector2 &TacosEngine::EventMove::CheckWindowCollide(TacosEngine::Vector2 &dir)
{
if (dir.get_x() < 0 && _object->getTransform().getPosition().get_x() <= 0.5 ||
dir.get_x() > 0 && _object->getTransform().getPosition().get_x() >= (799.5 - _object->getScene()->getWindowSize().get_x()))
dir.set_x(0);
if (dir.get_y() > 0 && _object->getTransform().getPosition().get_y() >= (399.5 - _object->getScene()->getWindowSize().get_y()) ||
dir.get_y() < 0 && _object->getTransform().getPosition().get_y() <= 0.5)
dir.set_y(0);
return dir;
} | 33.513514 | 131 | 0.651613 | arthurChennetier |
2d438f7c51dd615adffd85f9b5201eab1a437bbc | 863 | hpp | C++ | src/cipher/DummyCipher.hpp | devktor/libbitcrypto | 1b08fb75e6884a622f3a646bfb7bf22609f968ea | [
"MIT"
] | 1 | 2016-01-31T14:16:41.000Z | 2016-01-31T14:16:41.000Z | src/cipher/DummyCipher.hpp | BitProfile/libethcrypto | 1b08fb75e6884a622f3a646bfb7bf22609f968ea | [
"MIT"
] | null | null | null | src/cipher/DummyCipher.hpp | BitProfile/libethcrypto | 1b08fb75e6884a622f3a646bfb7bf22609f968ea | [
"MIT"
] | null | null | null | #pragma once
#include <algorithm>
#include <stdexcept>
#include "../detail/Data.hpp"
#include "../key/PrivateKey.hpp"
#include "EncryptedData.hpp"
#include "ScryptParams.hpp"
#include "ScryptParamsGenerator.hpp"
namespace Ethereum{
class DummyKey
{};
class DummyCipher
{
public:
typedef ScryptParams KdfParams;
public:
DummyCipher();
DummyCipher(const Data &, const ScryptParams &);
template<class Key>
PrivateKey decrypt(const EncryptedData &, const Key &) const;
template<class Key>
EncryptedData encrypt(const PrivateKey &, const Key &) const;
const Data & getIV() const;
const ScryptParams & getParams() const;
DummyCipher & operator = (const DummyCipher &);
private:
Data _iv;
ScryptParams _params;
};
}
#include "DummyCipher.ipp"
| 17.26 | 69 | 0.651217 | devktor |
2d447e613227b259a125f4b36a313c3bfd481354 | 4,256 | cpp | C++ | GameObjects/SkyBox.cpp | yuwenhuisama/A-Simple-Direct3D-Demo | 6cfcc4fea157a93118295f28d97ca6ebeb23318b | [
"MIT"
] | null | null | null | GameObjects/SkyBox.cpp | yuwenhuisama/A-Simple-Direct3D-Demo | 6cfcc4fea157a93118295f28d97ca6ebeb23318b | [
"MIT"
] | null | null | null | GameObjects/SkyBox.cpp | yuwenhuisama/A-Simple-Direct3D-Demo | 6cfcc4fea157a93118295f28d97ca6ebeb23318b | [
"MIT"
] | null | null | null | #include "SkyBox.h"
#include "DxUtils/RenderCommandQueue/RenderCommandQueueManager.h"
#include "DxUtils/Vertex.h"
#include "DxUtils/Direct3DManager.h"
#include "GameUtils/GameConfigure.h"
#include "DxUtils/D3DHelper.hpp"
#include "GameObject.h"
#include <functional>
SkyBox::~SkyBox() {
D3DHelper::SafeRelease(m_pIndexedBuffer);
D3DHelper::SafeRelease(m_pVertexBuffer);
}
constexpr UINT c_arrIndices[] = {
0, 1, 2,
0, 2, 3,
4, 5, 6,
4, 6, 7,
8, 9, 10,
8, 10, 11,
12, 13, 14,
12, 14, 15,
16, 17, 18,
16, 18, 19,
20, 21, 22,
20, 22, 23,
};
bool SkyBox::_InitializeBuffer() {
const float uWidth = GameConfigure::Instance().GetSkyBoxConfigure().m_f3Size.x;
SkyBoxVertex c_arrVertecies[] = {
{ DirectX::XMFLOAT3(-uWidth, -uWidth, -uWidth)},
{ DirectX::XMFLOAT3(-uWidth, +uWidth, -uWidth)},
{ DirectX::XMFLOAT3(+uWidth, +uWidth, -uWidth)},
{ DirectX::XMFLOAT3(+uWidth, -uWidth, -uWidth)},
{ DirectX::XMFLOAT3(-uWidth, -uWidth, +uWidth)},
{ DirectX::XMFLOAT3(+uWidth, -uWidth, +uWidth)},
{ DirectX::XMFLOAT3(+uWidth, +uWidth, +uWidth)},
{ DirectX::XMFLOAT3(-uWidth, +uWidth, +uWidth)},
{ DirectX::XMFLOAT3(-uWidth, +uWidth, -uWidth)},
{ DirectX::XMFLOAT3(-uWidth, +uWidth, +uWidth)},
{ DirectX::XMFLOAT3(+uWidth, +uWidth, +uWidth)},
{ DirectX::XMFLOAT3(+uWidth, +uWidth, -uWidth)},
{ DirectX::XMFLOAT3(-uWidth, -uWidth, +uWidth)},
{ DirectX::XMFLOAT3(-uWidth, +uWidth, +uWidth)},
{ DirectX::XMFLOAT3(-uWidth, +uWidth, -uWidth)},
{ DirectX::XMFLOAT3(-uWidth, -uWidth, -uWidth)},
{ DirectX::XMFLOAT3(-uWidth, -uWidth, -uWidth)},
{ DirectX::XMFLOAT3(+uWidth, -uWidth, -uWidth)},
{ DirectX::XMFLOAT3(+uWidth, -uWidth, +uWidth)},
{ DirectX::XMFLOAT3(-uWidth, -uWidth, +uWidth)},
{ DirectX::XMFLOAT3(+uWidth, -uWidth, -uWidth)},
{ DirectX::XMFLOAT3(+uWidth, +uWidth, -uWidth)},
{ DirectX::XMFLOAT3(+uWidth, +uWidth, +uWidth)},
{ DirectX::XMFLOAT3(+uWidth, -uWidth, +uWidth)},
};
// --------------- Vertex Buffer ----------------
D3D11_BUFFER_DESC bdDesc;
bdDesc.Usage = D3D11_USAGE_IMMUTABLE;
bdDesc.ByteWidth = sizeof(c_arrVertecies);
bdDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
bdDesc.CPUAccessFlags = 0;
bdDesc.MiscFlags = 0;
bdDesc.StructureByteStride = 0;
D3D11_SUBRESOURCE_DATA ssInitData;
ssInitData.pSysMem = c_arrVertecies;
auto result = Direct3DManager::Instance().CreateBuffer(bdDesc, ssInitData, m_pVertexBuffer);
if (!result) {
throw("Error when create buffer.");
}
// --------------- Index Buffer ----------------
D3D11_BUFFER_DESC bdiDesc;
bdiDesc.Usage = D3D11_USAGE_IMMUTABLE;
bdiDesc.ByteWidth = sizeof(c_arrIndices);
bdiDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
bdiDesc.CPUAccessFlags = 0;
bdiDesc.MiscFlags = 0;
bdiDesc.StructureByteStride = 0;
D3D11_SUBRESOURCE_DATA ssiInitData;
ssiInitData.pSysMem = c_arrIndices;
result = Direct3DManager::Instance().CreateBuffer(bdiDesc, ssiInitData, m_pIndexedBuffer);
if (!result) {
throw("Error when create buffer.");
}
return true;
}
bool SkyBox::Initialize() {
if (!_InitializeBuffer()) {
return false;
}
return true;
}
void SkyBox::Render() {
std::function<DirectX::XMMATRIX(void)> fCallBack = [this]() -> DirectX::XMMATRIX {
if (this->GetBoundObject()) {
return DirectX::XMMatrixTranslation(
this->GetBoundObject()->Position().x,
this->GetBoundObject()->Position().y,
this->GetBoundObject()->Position().z
);
} else {
return DirectX::XMMatrixIdentity();
}
};
RenderCommandQueueManager::Instance().Push(RenderCommand {
RenderCommandType::SetTexture,
m_pTexture
});
RenderCommandQueueManager::Instance().Push(RenderCommand {
RenderCommandType::RenderSkyBox,
std::make_tuple(m_pVertexBuffer, m_pIndexedBuffer, sizeof(SkyBoxVertex), std::size(c_arrIndices), m_pVertexShader, m_pPixelShader, fCallBack)
});
}
| 29.555556 | 149 | 0.620066 | yuwenhuisama |
2d46502e1d9b352d3463d56fac513789432ed23b | 649 | cpp | C++ | tools/clang/test/CXX/temp/temp.decls/temp.alias/p3.cpp | clayne/DirectXShaderCompiler | 0ef9b702890b1d45f0bec5fa75481290323e14dc | [
"NCSA"
] | 3,102 | 2015-01-04T02:28:35.000Z | 2022-03-30T12:53:41.000Z | tools/clang/test/CXX/temp/temp.decls/temp.alias/p3.cpp | clayne/DirectXShaderCompiler | 0ef9b702890b1d45f0bec5fa75481290323e14dc | [
"NCSA"
] | 3,740 | 2019-01-23T15:36:48.000Z | 2022-03-31T22:01:13.000Z | tools/clang/test/CXX/temp/temp.decls/temp.alias/p3.cpp | clayne/DirectXShaderCompiler | 0ef9b702890b1d45f0bec5fa75481290323e14dc | [
"NCSA"
] | 1,868 | 2015-01-03T04:27:11.000Z | 2022-03-25T13:37:35.000Z | // RUN: %clang_cc1 -std=c++11 -fsyntax-only -verify %s
// The example given in the standard (this is rejected for other reasons anyway).
template<class T> struct A;
template<class T> using B = typename A<T>::U; // expected-error {{no type named 'U' in 'A<T>'}}
template<class T> struct A {
typedef B<T> U; // expected-note {{in instantiation of template type alias 'B' requested here}}
};
B<short> b;
template<typename T> using U = int;
template<typename ...T> void f(U<T> ...xs);
void g() { f<void,void,void>(1, 2, 3); }
// FIXME: This is illegal, but probably only because CWG1044 missed this paragraph.
template<typename T> using U = U<T>;
| 36.055556 | 97 | 0.681048 | clayne |
2d49ff767b458df873b340612eb33a84a441084b | 3,542 | cpp | C++ | lang/C++/top-rank-per-group.cpp | ethansaxenian/RosettaDecode | 8ea1a42a5f792280b50193ad47545d14ee371fb7 | [
"MIT"
] | 5 | 2021-01-29T20:08:05.000Z | 2022-03-22T06:16:05.000Z | lang/C++/top-rank-per-group.cpp | ethansaxenian/RosettaDecode | 8ea1a42a5f792280b50193ad47545d14ee371fb7 | [
"MIT"
] | null | null | null | lang/C++/top-rank-per-group.cpp | ethansaxenian/RosettaDecode | 8ea1a42a5f792280b50193ad47545d14ee371fb7 | [
"MIT"
] | 1 | 2021-04-13T04:19:31.000Z | 2021-04-13T04:19:31.000Z | #include <string>
#include <set>
#include <list>
#include <map>
#include <iostream>
struct Employee
{
std::string Name;
std::string ID;
unsigned long Salary;
std::string Department;
Employee(std::string _Name = "", std::string _ID = "", unsigned long _Salary = 0, std::string _Department = "")
: Name(_Name), ID(_ID), Salary(_Salary), Department(_Department)
{ }
void display(std::ostream& out) const
{
out << Name << "\t" << ID << "\t" << Salary << "\t" << Department << std::endl;
}
};
// We'll tell std::set to use this to sort our employees.
struct CompareEarners
{
bool operator()(const Employee& e1, const Employee& e2)
{
return (e1.Salary > e2.Salary);
}
};
// A few typedefs to make the code easier to type, read and maintain.
typedef std::list<Employee> EMPLOYEELIST;
// Notice the CompareEarners; We're telling std::set to user our specified comparison mechanism
// to sort its contents.
typedef std::set<Employee, CompareEarners> DEPARTMENTPAYROLL;
typedef std::map<std::string, DEPARTMENTPAYROLL> DEPARTMENTLIST;
void initialize(EMPLOYEELIST& Employees)
{
// Initialize our employee list data source.
Employees.push_back(Employee("Tyler Bennett", "E10297", 32000, "D101"));
Employees.push_back(Employee("John Rappl", "E21437", 47000, "D050"));
Employees.push_back(Employee("George Woltman", "E21437", 53500, "D101"));
Employees.push_back(Employee("Adam Smith", "E21437", 18000, "D202"));
Employees.push_back(Employee("Claire Buckman", "E39876", 27800, "D202"));
Employees.push_back(Employee("David McClellan", "E04242", 41500, "D101"));
Employees.push_back(Employee("Rich Holcomb", "E01234", 49500, "D202"));
Employees.push_back(Employee("Nathan Adams", "E41298", 21900, "D050"));
Employees.push_back(Employee("Richard Potter", "E43128", 15900, "D101"));
Employees.push_back(Employee("David Motsinger", "E27002", 19250, "D202"));
Employees.push_back(Employee("Tim Sampair", "E03033", 27000, "D101"));
Employees.push_back(Employee("Kim Arlich", "E10001", 57000, "D190"));
Employees.push_back(Employee("Timothy Grove", "E16398", 29900, "D190"));
}
void group(EMPLOYEELIST& Employees, DEPARTMENTLIST& Departments)
{
// Loop through all of our employees.
for( EMPLOYEELIST::iterator iEmployee = Employees.begin();
Employees.end() != iEmployee;
++iEmployee )
{
DEPARTMENTPAYROLL& groupSet = Departments[iEmployee->Department];
// Add our employee to this group.
groupSet.insert(*iEmployee);
}
}
void present(DEPARTMENTLIST& Departments, unsigned int N)
{
// Loop through all of our departments
for( DEPARTMENTLIST::iterator iDepartment = Departments.begin();
Departments.end() != iDepartment;
++iDepartment )
{
std::cout << "In department " << iDepartment->first << std::endl;
std::cout << "Name\t\tID\tSalary\tDepartment" << std::endl;
// Get the top three employees for each employee
unsigned int rank = 1;
for( DEPARTMENTPAYROLL::iterator iEmployee = iDepartment->second.begin();
( iDepartment->second.end() != iEmployee) && (rank <= N);
++iEmployee, ++rank )
{
iEmployee->display(std::cout);
}
std::cout << std::endl;
}
}
int main(int argc, char* argv[])
{
// Our container for our list of employees.
EMPLOYEELIST Employees;
// Fill our list of employees
initialize(Employees);
// Our departments.
DEPARTMENTLIST Departments;
// Sort our employees into their departments.
// This will also rank them.
group(Employees, Departments);
// Display the top 3 earners in each department.
present(Departments, 3);
return 0;
}
| 30.8 | 112 | 0.702993 | ethansaxenian |
2d4a525f107c2b72b03cc24ddd09e71ed1cc6962 | 618 | cpp | C++ | 1098_Sequence IJ 4.cpp | Aunkon/URI | 668181ba977d44823d228b6ac01dfed16027d524 | [
"RSA-MD"
] | null | null | null | 1098_Sequence IJ 4.cpp | Aunkon/URI | 668181ba977d44823d228b6ac01dfed16027d524 | [
"RSA-MD"
] | null | null | null | 1098_Sequence IJ 4.cpp | Aunkon/URI | 668181ba977d44823d228b6ac01dfed16027d524 | [
"RSA-MD"
] | null | null | null | /**** Md. Walid Bin khalid Aunkon ****/
/**** Daffodil International University ****/
/**** ID: 121-15-1669 ****/
/**** Email: mdwalidbinkhalidaunkon@gmail.com ****/
/**** Mobile No: +88-01916-492926 ****/
#include<bits/stdc++.h>
using namespace std;
int main()
{
double i,j=1;
for(i=0;i<=2;i+=.2)
{
cout << "I=" << i << " " << "J=" << j+i << "\n";
cout << "I=" << i << " " << "J=" << j+i+1 << "\n";
cout << "I=" << i << " " << "J=" << j+i+2 << "\n";
}
return 0;
}
| 32.526316 | 62 | 0.351133 | Aunkon |
2d4d91501f4073ae4acd194f5d365eee47cf6b21 | 380 | cc | C++ | nofx/nofx_ofTexture/nofx_ofEnableNormalizedTexCoords.cc | sepehr-laal/nofx | 7abc9da3d4fc0f5b72c6b3d591a08cf44d00277e | [
"MIT"
] | null | null | null | nofx/nofx_ofTexture/nofx_ofEnableNormalizedTexCoords.cc | sepehr-laal/nofx | 7abc9da3d4fc0f5b72c6b3d591a08cf44d00277e | [
"MIT"
] | null | null | null | nofx/nofx_ofTexture/nofx_ofEnableNormalizedTexCoords.cc | sepehr-laal/nofx | 7abc9da3d4fc0f5b72c6b3d591a08cf44d00277e | [
"MIT"
] | null | null | null | #include "nofx_ofEnableNormalizedTexCoords.h"
#include "ofTexture.h"
namespace nofx
{
namespace ClassWrappers
{
NAN_METHOD(nofx_ofEnableNormalizedTexCoords)
{
ofEnableNormalizedTexCoords();
NanReturnUndefined();
} // !nofx_ofEnableNormalizedTexCoords
} // !namespace ClassWrappers
} // !namespace nofx | 23.75 | 52 | 0.647368 | sepehr-laal |
2d4ead78b6f36256d743d50dc37c620698b52f7c | 1,030 | cpp | C++ | CPP/Common/Sort/HeapSort/HeapSort.cpp | Insofan/LeetCode | d6722601886e181745a2e9c31cb146bc0826c906 | [
"Apache-2.0"
] | null | null | null | CPP/Common/Sort/HeapSort/HeapSort.cpp | Insofan/LeetCode | d6722601886e181745a2e9c31cb146bc0826c906 | [
"Apache-2.0"
] | null | null | null | CPP/Common/Sort/HeapSort/HeapSort.cpp | Insofan/LeetCode | d6722601886e181745a2e9c31cb146bc0826c906 | [
"Apache-2.0"
] | null | null | null | //
// Created by Insomnia on 2018/8/31.
// MIT License
//
#include <iostream>
#include <vector>
using namespace std;
void out(vector<int> &vec) {
for (vector<int>::const_iterator it = vec.begin(); it != vec.end(); it++) {
cout << (*it) << " ";
}
cout << endl;
}
vector<int> randomVec(int len, int maxNum) {
vector<int> tempVec;
srand((unsigned) time(NULL));
for (int i = 0; i < len; ++i) {
int x = rand() % maxNum;
tempVec.push_back(x);
}
return tempVec;
}
class Solution {
public:
void heapSort(vector<int> &vec) {
int len = vec.size();
for (int i = (len - 2) / 2; i >= 0; i--) {
filterDown(vec, i, len - 1);
}
for (int i = len - 1; i > 0; i--) {
swap(vec, 0, i);
filterDown(vec, 0, i - 1);
}
}
private:
void filterDown(vector<int> &vec, int current, int last) {
}
};
int main() {
vector<int> vec = randomVec(10, 50);
out(vec);
out(vec);
return 0;
} | 17.166667 | 79 | 0.500971 | Insofan |
2d5225576ac1d2d3f5792952d502119f6e6c8e99 | 14,512 | cpp | C++ | src/c++/lib/align/Alignment.cpp | nh13/hap.py | fd67904f7a68981e76c12301aa2add2718b30120 | [
"BSL-1.0"
] | 315 | 2015-07-21T13:53:30.000Z | 2022-03-17T02:01:19.000Z | src/c++/lib/align/Alignment.cpp | nh13/hap.py | fd67904f7a68981e76c12301aa2add2718b30120 | [
"BSL-1.0"
] | 147 | 2015-11-26T03:06:24.000Z | 2022-03-28T18:22:33.000Z | src/c++/lib/align/Alignment.cpp | nh13/hap.py | fd67904f7a68981e76c12301aa2add2718b30120 | [
"BSL-1.0"
] | 124 | 2015-07-21T13:55:14.000Z | 2022-03-23T17:34:31.000Z | // -*- mode: c++; indent-tabs-mode: nil; -*-
//
//
// Copyright (c) 2010-2015 Illumina, 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:
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
/**
* \brief Alignment and Factory implementation
*
* \file Alignment.cpp
* \author Peter Krusche
* \email pkrusche@illumina.com
*
*/
#include "Alignment.hh"
#include <cstdlib>
#include <cstring>
#include <sstream>
#include "Klib.hh"
#include "KlibGlobal.hh"
#include "helpers/Genetics.hh"
#include "Error.hh"
using namespace variant;
using namespace genetics;
Alignment::~Alignment() {}
/* get the best possible score for comparing two sequences of length len */
int Alignment::bestScore(int len)
{
AlignmentParameters ap;
getParameters(ap);
return len*ap.maxScore();
}
Alignment * makeAlignment(const char * type)
{
if(strstr(type, "klibg") == type)
{
return new KlibGlobalAlignment();
}
else if(strstr(type, "klib") == type)
{
return new KlibAlignment();
}
else
{
error("Unknown alignment type '%s'", type);
}
return NULL;
}
/**
* @brief Format int encoded Cigar string
*
* @param tb for padding with "S" : begin
* @param te for padding with "S" : end
* @param altlen for padding with "S" : length of alternate sequence
* @param ncigar length of cigar
* @param cigar int* to cigar entries
*
*/
std::string makeCigar(int tb, int te, int altlen, int ncigar, uint32_t * cigar)
{
std::string cig;
if (ncigar > 0)
{
std::ostringstream cigar_string;
if (tb > 0)
{
cigar_string << tb << 'S';
}
for (int i = 0; i < ncigar; ++i)
{
cigar_string << (cigar[i] >> 4);
uint8_t op = cigar[i] & 0x000f;
switch(op)
{
case 0: cigar_string << 'M'; break;
case 1: cigar_string << 'I'; break;
case 2: cigar_string << 'D'; break;
}
}
int end = altlen - te - 1;
if (end > 0)
{
cigar_string << end << 'S';
}
cig = cigar_string.str();
}
return cig;
}
/** make variants from a cigar string */
void getVariantsFromCigar(std::string const & ref, std::string const & alt,
int r0, int a0,
uint32_t * cigar, int ncigar,
std::list<variant::RefVar> & target)
{
bool have_rv = false;
RefVar rv;
rv.start = -1;
rv.end = -1;
rv.alt = "";
int refpos = r0;
int altpos = a0;
for (int i = 0; i < ncigar; ++i)
{
uint32_t count = cigar[i] >> 4;
uint8_t op = cigar[i] & 0x000f;
switch(op)
{
case 0: // 'M'
case 7: // '='
case 8: // 'X'
for(uint32_t j = 0; j < count; ++j)
{
// check match / mismatch because ksw doesn't give this to us
if(ref[refpos] != alt[altpos])
{
// push a previous block which we can't append to
if(have_rv && rv.end < refpos-1)
{
target.push_back(rv);
have_rv = false;
rv.start = -1;
rv.end = -1;
rv.alt = "";
}
if(rv.start < 0)
{
rv.start = refpos;
}
rv.end = refpos;
rv.alt += alt[altpos];
have_rv = true;
}
else if(have_rv)
{
target.push_back(rv);
have_rv = false;
rv.start = -1;
rv.end = -1;
rv.alt = "";
}
++refpos;
++altpos;
}
break;
case 1: // 'I' -> REF insertion in ALT = ALT deletion
if(have_rv)
{
target.push_back(rv);
have_rv = false;
rv.start = -1;
rv.end = -1;
rv.alt = "";
}
rv.start = refpos;
rv.end = refpos + count - 1;
rv.alt = "";
have_rv = true;
// shift the reference position
refpos += count;
break;
case 2: // 'D' -> REF deletion = ALT insertion;
if(have_rv)
{
target.push_back(rv);
have_rv = false;
rv.start = -1;
rv.end = -1;
rv.alt = "";
}
// insert before reference pos
// reference length = end - start + 1 == refpos-1 - refpos + 1 == 0
// this is interpreted as an insertion before pos.
rv.start = refpos;
rv.end = refpos-1;
rv.alt = alt.substr(altpos, count);
have_rv = true;
// shift the reference position up by one
altpos += count;
break;
}
}
if(have_rv)
{
target.push_back(rv);
}
}
/** get stats from a cigar string */
void getCigarStats(std::string const & ref, std::string const & alt,
int r0, int a0,
uint32_t * cigar, int ncigar,
int & softclipped, int & matches,
int & mismatches, int & ins, int & del)
{
softclipped = r0;
matches = 0;
mismatches = 0;
ins = 0;
del = 0;
int refpos = r0;
int altpos = a0;
for (int i = 0; i < ncigar; ++i)
{
uint32_t count = cigar[i] >> 4;
uint8_t op = cigar[i] & 0x000f;
switch(op)
{
case 0: // 'M'
case 7: // '='
case 8: // 'X'
for(uint32_t j = 0; j < count; ++j)
{
// check match / mismatch because ksw doesn't give this to us
if(ref[refpos] != alt[altpos])
{
++mismatches;
}
else
{
++matches;
}
++refpos;
++altpos;
}
break;
case 1: // 'I' -> REF insertion in ALT = ALT deletion
del += count;
// shift the reference position
refpos += count;
break;
case 2: // 'D' -> REF deletion = ALT insertion;
ins += count;
// shift the reference position up by one
altpos += count;
break;
}
}
// TODO we might want to check if we're at the end of alt here.
softclipped += ref.size() - refpos;
}
/**
* @brief Decompose a RefVar into primitive variants (subst / ins / del) by means of realigning
*
* @param f reference sequence fasta
* @param chr the chromosome to use
* @param in_rv the RefVar record
* @param aln the alignment interface to use
* @param vars the primitive records
*/
void realignRefVar(FastaFile const & f, const char * chr, RefVar const & in_rv, Alignment * aln,
std::list<variant::RefVar> & vars)
{
int64_t rstart = in_rv.start, rend = in_rv.end, reflen = rend - rstart + 1;
int64_t altlen = (int64_t)in_rv.alt.size();
if(reflen < 2 || altlen < 2) // || reflen == altlen)
{
// no complex ref / alt => use fast and simple function
toPrimitives(f, chr, in_rv, vars);
return;
}
std::string refseq = f.query(chr, rstart, rend);
std::string altseq = in_rv.alt;
aln->setRef(refseq.c_str());
aln->setQuery(altseq.c_str());
uint32_t * icigar;
int r0, r1, a0, a1;
int ncigar = 0;
aln->getCigar(r0, r1, a0, a1, ncigar, icigar);
RefVar rv;
rv.start = -1;
rv.end = -1;
rv.alt = "";
int refpos = r0;
int altpos = a0;
for (int i = 0; i < ncigar; ++i)
{
uint32_t count = icigar[i] >> 4;
uint8_t op = (uint8_t) (icigar[i] & 0x000f);
switch(op)
{
case 0: // 'M'
case 7: // '='
case 8: // 'X'
for(uint32_t j = 0; j < count; ++j)
{
// check match / mismatch because ksw doesn't give this to us
if(refseq[refpos] != altseq[altpos])
{
rv.start = rstart + refpos;
rv.end = rstart + refpos;
rv.alt = altseq[altpos];
vars.push_back(rv);
}
++refpos;
++altpos;
}
break;
case 1: // 'I' -> REF insertion in ALT = ALT deletion
rv.start = rstart + refpos;
rv.end = rstart + refpos + count - 1;
rv.alt = "";
vars.push_back(rv);
// shift the reference position
refpos += count;
break;
case 2: // 'D' -> REF deletion = ALT insertion;
// insert before reference pos
// reference length = end - start + 1 == refpos-1 - refpos + 1 == 0
// this is interpreted as an insertion before pos.
rv.start = rstart + refpos;
rv.end = rstart + refpos - 1;
rv.alt = altseq.substr((unsigned long) altpos, count);
vars.push_back(rv);
altpos += count;
break;
default:break;
}
}
}
/**
* @brief Decompose a RefVar into primitive variants (subst / ins / del) by means of realigning
*
* @param f reference sequence fasta
* @param chr the chromosome to use
* @param in_rv the RefVar record
* @param snps the number of snps
* @param ins the number of insertions
* @param dels the number of deletions
* @param homref the number of calls with no variation
*/
void realignRefVar(FastaFile const & f, const char * chr, variant::RefVar const & in_rv, Alignment * aln,
size_t & snps, size_t & ins, size_t & dels, size_t & homref,
size_t& transitions, size_t& transversions)
{
int64_t rstart = in_rv.start, rend = in_rv.end, reflen = rend - rstart + 1;
int64_t altlen = (int64_t)in_rv.alt.size();
if(reflen < 2 || altlen < 2)
{
// no complex ref / alt => use fast and simple function
countRefVarPrimitives(f, chr, in_rv, snps, ins, dels, homref,
transitions, transversions);
return;
}
std::string refseq = f.query(chr, rstart, rend);
std::string altseq = in_rv.alt;
aln->setRef(refseq.c_str());
aln->setQuery(altseq.c_str());
uint32_t * icigar;
int r0, r1, a0, a1;
int ncigar = 0;
aln->getCigar(r0, r1, a0, a1, ncigar, icigar);
int refpos = r0;
int altpos = a0;
bool isValidSnv(false);
for (int i = 0; i < ncigar; ++i)
{
uint32_t count = icigar[i] >> 4;
uint8_t op = (uint8_t) (icigar[i] & 0x000f);
switch(op)
{
case 0: // 'M'
case 7: // '='
case 8: // 'X'
for(uint32_t j = 0; j < count; ++j)
{
// check match / mismatch because ksw doesn't give this to us
const char refBase(refseq[refpos]);
const char altBase(altseq[altpos]);
if (altBase != refBase)
{
++snps;
const bool
isTransversion(snvIsTransversion(refBase, altBase,
isValidSnv));
if (isValidSnv) {
if (isTransversion) {
++transversions;
} else {
++transitions;
}
}
}
else
{
++homref;
}
++refpos;
++altpos;
}
break;
case 1: // 'I' -> REF insertion in ALT = ALT deletion
dels += count;
// shift the reference position
refpos += count;
break;
case 2: // 'D' -> REF deletion = ALT insertion;
// insert before reference pos
// reference length = end - start + 1 == refpos-1 - refpos + 1 == 0
// this is interpreted as an insertion before pos.
ins+= count;
altpos += count;
break;
default:break;
}
}
}
| 30.487395 | 105 | 0.469887 | nh13 |
2d5484871292df699cffd6926ea3afb2238d9dc3 | 18,529 | cpp | C++ | SOURCES/sim/digi/sfusion.cpp | IsraelyFlightSimulator/Negev-Storm | 86de63e195577339f6e4a94198bedd31833a8be8 | [
"Unlicense"
] | 1 | 2021-02-19T06:06:31.000Z | 2021-02-19T06:06:31.000Z | src/sim/digi/sfusion.cpp | markbb1957/FFalconSource | 07b12e2c41a93fa3a95b912a2433a8056de5bc4d | [
"BSD-2-Clause"
] | null | null | null | src/sim/digi/sfusion.cpp | markbb1957/FFalconSource | 07b12e2c41a93fa3a95b912a2433a8056de5bc4d | [
"BSD-2-Clause"
] | 2 | 2019-08-20T13:35:13.000Z | 2021-04-24T07:32:04.000Z | #include "stdhdr.h"
#include "classtbl.h"
#include "digi.h"
#include "sensors.h"
#include "simveh.h"
#include "missile.h"
#include "object.h"
#include "sensclas.h"
#include "Entity.h"
#include "team.h"
#include "Aircrft.h"
/* 2001-03-15 S.G. */#include "campbase.h"
/* 2001-03-21 S.G. */#include "flight.h"
/* 2001-03-21 S.G. */#include "atm.h"
#include "RWR.h" // 2002-02-11 S.G.
#include "Radar.h" // 2002-02-11 S.G.
#include "simdrive.h" // 2002-02-17 S.G.
#define MAX_NCTR_RANGE (60.0F * NM_TO_FT) // 2002-02-12 S.G. See RadarDoppler.h
/* 2001-09-07 S.G. RP5 */ extern bool g_bRP5Comp;
extern int g_nLowestSkillForGCI; // 2002-03-12 S.G. Replaces the hardcoded '3' for skill test
extern bool g_bUseNewCanEnage; // 2002-03-11 S.G.
int GuestimateCombatClass(AircraftClass *self, FalconEntity *baseObj); // 2002-03-11 S.G.
FalconEntity* SpikeCheck (AircraftClass* self, FalconEntity *byHim = NULL, int *data = NULL);// 2002-02-10 S.G.
void DigitalBrain::SensorFusion(void)
{
SimObjectType* obj = targetList;
float turnTime=0.0F,timeToRmax=0.0F,rmax=0.0F,tof=0.0F,totV=0.0F;
SimObjectLocalData* localData=NULL;
int relation=0, pcId= ID_NONE, canSee=FALSE, i=0;
FalconEntity* baseObj=NULL;
// 2002-04-18 REINSTATED BY S.G. After putting back '||' instead of '&&' before "localData->sensorLoopCount[self->sensorArray[i]->Type()] > delayTime" below, this is no longer required
// 2002-02-17 MODIFIED BY S.G. Sensor routines for AI runs less often than SensorFusion therefore the AI will time out his target after this delayTime as elapsed.
// By using the highest of both, I'm sure this will not happen...
int delayTime = SimLibElapsedTime - 6*SEC_TO_MSEC*(SkillLevel() + 1);
/* int delayTime;
unsigned int fromSkill = 6 * SEC_TO_MSEC * (SkillLevel() + 1);
if (fromSkill > self->targetUpdateRate)
delayTime = SimLibElapsedTime - fromSkill;
else
delayTime = SimLibElapsedTime - self->targetUpdateRate;
*/
/*--------------------*/
/* do for all objects */
/*--------------------*/
while (obj)
{
localData = obj->localData;
baseObj = obj->BaseData();
//if (F4IsBadCodePtr((FARPROC) baseObj)) // JB 010223 CTD
if (F4IsBadCodePtr((FARPROC) baseObj) || F4IsBadReadPtr(baseObj, sizeof(FalconEntity))) // JB 010305 CTD
break; // JB 010223 CTD
// Check all sensors for contact
canSee = FALSE;//PUt to true for testing only
//Cobra Begin rebuilding this function.
//GCI Code
CampBaseClass *campBaseObj = (CampBaseClass *)baseObj;
if (baseObj->IsSim())
campBaseObj = ((SimBaseClass*)baseObj)->GetCampaignObject();
// If the object is a weapon, don't do GCI on it
if (baseObj->IsWeapon())
campBaseObj = NULL;
// Only if we have a valid base object...
// This code is to make sure our GCI targets are prioritized, just like other targets
if (campBaseObj)
if (campBaseObj->GetSpotted(self->GetTeam()))
canSee = TRUE;
if (localData->sensorState[SensorClass::RWR] >= SensorClass::SensorTrack)
{
canSee = TRUE;
detRWR = 1;
}
else
detRWR = 0;
if (localData->sensorState[SensorClass::Radar] >= SensorClass::SensorTrack)
{
canSee = TRUE;
detRAD = 1;
}
else
detRAD = 0;
if (localData->sensorState[SensorClass::Visual] >= SensorClass::SensorTrack)
{
canSee = TRUE;
detVIS = 1;
}
else
detVIS = 0;
//End
/* if (!g_bRP5Comp) {
// Aces get to use GCI
// Idiots find out about you inside 1 mile anyway
if (localData->range > 3.0F * NM_TO_FT && // gci is crap inside 3nm
(SkillLevel() >= 2 &&
localData->range < 25.0F * NM_TO_FT||
SkillLevel() >=3 &&
localData->range < 35.0F * NM_TO_FT||
SkillLevel() >=4 &&
localData->range < 55.0F * NM_TO_FT)
)//me123 not if no sensor has seen it || localData->range < 1.0F * NM_TO_FT)
{
canSee = TRUE;
}
// You can always see your designated target
if (baseObj->Id() == mDesignatedObject && localData->range > 8.0F * NM_TO_FT)
{
canSee = TRUE;//me123
}
for (i = 0; i<self->numSensors && !canSee; i++)
{
if (localData->sensorState[self->sensorArray[i]->Type()] > SensorClass::NoTrack ||
localData->sensorLoopCount[self->sensorArray[i]->Type()] > delayTime)
{
canSee = TRUE;
break;
}
}
}
else {*/
// 2001-03-21 REDONE BY S.G. SO SIM AIRPLANE WIL FLAG FLIGHT/AIRPLANE AS DETECTED AND WILL PROVIDE GCI
/*#if 0
// Aces get to use GCI
// Idiots find out about you inside 1 mile anyway
if (SkillLevel() >= 3 && localData->range < 15.0F * NM_TO_FT || localData->range < 1.0F * NM_TO_FT)
{
canSee = TRUE;
}
// You can always see your designated target
if (baseObj->Id() == mDesignatedObject && localData->range > 8.0F * NM_TO_FT)
{
canSee = TRUE;
}
for (i = 0; i<self->numSensors && !canSee; i++)
{
if (localData->sensorState[self->sensorArray[i]->Type()] > SensorClass::NoTrack ||
localData->sensorLoopCount[self->sensorArray[i]->Type()] > delayTime)
{
canSee = TRUE;
break;
}
}
#else */
// First I'll get the campaign object if it's for a sim since I use it at many places...
/*CampBaseClass *campBaseObj = (CampBaseClass *)baseObj;
if (baseObj->IsSim())
campBaseObj = ((SimBaseClass*)baseObj)->GetCampaignObject();
// If the object is a weapon, don't do GCI on it
if (baseObj->IsWeapon())
campBaseObj = NULL;
// This is our GCI implementation... Ace and Veteran gets to use GCI.
// Only if we have a valid base object...
// This code is to make sure our GCI targets are prioritized, just like other targets
if (campBaseObj && SkillLevel() >= g_nLowestSkillForGCI && localData->range < 30.0F * NM_TO_FT)
if (campBaseObj->GetSpotted(self->GetTeam()))
canSee = TRUE;
// You can always see your designated target
if (baseObj->Id() == mDesignatedObject && localData->range > 8.0F * NM_TO_FT)
canSee = TRUE;*/
//if (SimDriver.RunningDogfight()) // 2002-02-17 ADDED BY S.G. If in dogfight, don't loose sight of your opponent.
//canSee = TRUE; //Cobra removed to test
// Go through all your sensors. If you 'see' the target and are bright enough, flag it as spotted and ask for an intercept if this FLIGHT is spotted for the first time...
//for (i = 0; i<self->numSensors; i++) {
//if (localData->sensorState[self->sensorArray[i]->Type()] > SensorClass::NoTrack || localData->sensorLoopCount[self->sensorArray[i]->Type()] > delayTime) { // 2002-04-18 MODIFIED BY S.G. Reverted to && instead of ||. *MY* logic was flawed. It gaves a 'delay' (grace period) after the sensor becomes 'NoLock'.
//if (campBaseObj && /*&& SkillLevel() >= g_nLowestSkillForGCI &&*/ !((UnitClass *)self->GetCampaignObject())->Broken()) {//Cobra removed GCI test here...not needed
//if (!campBaseObj->GetSpotted(self->GetTeam()) && campBaseObj->IsFlight())
//RequestIntercept((FlightClass *)campBaseObj, self->GetTeam());
// 2002-02-11 ADDED BY S.G. If the sensor can identify the target, mark it identified as well
/*int identified = FALSE;
if (self->sensorArray[i]->Type() == SensorClass::RWR) {
if (((RwrClass *)self->sensorArray[i])->GetTypeData()->flag & RWR_EXACT_TYPE)
identified = TRUE;
}
else if (self->sensorArray[i]->Type() == SensorClass::Radar) {
if (((RadarClass *)self->sensorArray[i])->GetRadarDatFile() && (((RadarClass *)self->sensorArray[i])->radarData->flag & RAD_NCTR) && localData->ataFrom < 45.0f * DTR && localData->range < ((RadarClass *)self->sensorArray[i])->GetRadarDatFile()->MaxNctrRange / (2.0f * (16.0f - (float)SkillLevel()) / 16.0f)) // 2002-03-05 MODIFIED BY S.G. target's aspect and skill used in the equation
identified = TRUE;
}
else
identified = TRUE;
campBaseObj->SetSpotted(self->GetTeam(),TheCampaign.CurrentTime, identified);
}
//canSee = TRUE; //Cobra we are removing these to test, this gave everything can see!
//break;
continue;
}
}
//#endif
}*/
/*--------------------------------------------------*/
/* Sensor id state */
/* RWR ids coming from RWR_INTERP can be incorrect. */
/* Visual identification is 100% correct. */
/*--------------------------------------------------*/
if (canSee)
{
//Cobra moved spotted stuff here
CampBaseClass *campBaseObj = (CampBaseClass *)baseObj;
if (baseObj->IsSim())
{
campBaseObj = ((SimBaseClass*)baseObj)->GetCampaignObject();
if (campBaseObj)
campBaseObj->SetSpotted(self->GetTeam(),TheCampaign.CurrentTime, 1);
}
if (baseObj->IsMissile())
{
pcId = ID_MISSILE;
}
else if (baseObj->IsBomb())
{
pcId = ID_NEUTRAL;
}
else
{
if (TeamInfo[self->GetTeam()]) // JB 010617 CTD
{
relation = TeamInfo[self->GetTeam()]->TStance(obj->BaseData()->GetTeam());
switch (relation)
{
case Hostile:
case War:
pcId = ID_HOSTILE;
break;
case Allied:
case Friendly:
pcId = ID_FRIENDLY;
break;
case Neutral:
pcId = ID_NEUTRAL;
break;
}
}
}
}
//Cobra Rewrite. Score threats
if (canSee)
{
int hisCombatClass = -1;
bool isHelo = FALSE;
float threatRng = 0.0f;
int totalThreat = 0;
if (baseObj)
{
hisCombatClass = baseObj->CombatClass();
if (baseObj->IsHelicopter())
isHelo = TRUE;
}
if (pcId == ID_HOSTILE)//Something we can shoot at
{
//Score combatclass
if (hisCombatClass <=4 && hisCombatClass >= 2)
totalThreat += 50;
else
totalThreat += 30;
if (localData->ataFrom > 90*DTR)
totalThreat = totalThreat/2;
if (localData->range < maxAAWpnRange)
totalThreat += 20;
if (missionType == AMIS_BARCAP || missionType == AMIS_BARCAP2 || missionComplete
|| (missionClass == AGMission && !IsSetATC(HasAGWeapon)))
{
if (isHelo || hisCombatClass >= 7)
totalThreat = 5;
}
else if (isHelo || hisCombatClass >= 7)
totalThreat = 0;
//is this our target?
CampBaseClass *campObj;
if (baseObj->IsSim())
campObj = ((SimBaseClass *)baseObj)->GetCampaignObject();
else
campObj = (CampBaseClass *)baseObj;
int isMissionTarget = campObj && (((FlightClass *)(self->GetCampaignObject()))-> GetUnitMissionTargetID() == campObj->Id() ||
((FlightClass *)(self->GetCampaignObject()))->GetAssignedTarget() == campObj->Id());
if (isMissionTarget)
totalThreat += 10;
localData->threatScore = totalThreat;
}
else if (pcId == ID_MISSILE)
{
if (obj->BaseData()->GetTeam() == self->GetTeam())
{
localData->threatScore = 0;
}
else
{
localData->threatScore = 90;
}
}
else
localData->threatScore = 0;
}//end cobra
/*----------------------------------------------------*/
/* Threat determination */
/* Assume threat has your own longest range missile. */
/* Hypothetical time before we're in the mort locker. */
/* If its a missile calculate time to impact. */
/*---------------------------------------------------*/
/*
localData->threatTime = 2.0F * MAX_THREAT_TIME;
if (canSee)
{
if (baseObj->IsMissile())
{
if (pcId == ID_MISSILE)
{
if (obj->BaseData()->GetTeam() == self->GetTeam())
{
localData->threatTime = 2.0F * MAX_THREAT_TIME;
}
else
{
if (localData->sensorState[SensorClass::RWR] >= SensorClass::SensorTrack)
localData->threatTime = localData->range / AVE_AIM120_VEL;
else
localData->threatTime = localData->range / AVE_AIM9L_VEL;
}
}
else localData->threatTime = MAX_THREAT_TIME;
}
else if ((baseObj->IsAirplane() || (baseObj->IsFlight() && !baseObj->IsHelicopter())) && pcId != ID_NONE && pcId < ID_NEUTRAL && GuestimateCombatClass(self, baseObj) < MnvrClassA10)
{
//TJL 11/07/03 VO log says there is an radian error in this code
// I think it is here. ataFrom is in radians
//turnTime = localData->ataFrom / FIVE_G_TURN_RATE;
turnTime = localData->ataFrom*RTD / FIVE_G_TURN_RATE;// 15.9f degrees per second
//TJL 11/07/03 Cos takes radians, thus no *DTR
//totV = obj->BaseData()->GetVt() + self->GetVt()*(float)cos(localData->ata*DTR);
totV = obj->BaseData()->GetVt() + self->GetVt()*(float)cos(localData->ata);
if (SpikeCheck(self) == obj->BaseData())//me123 addet
rmax = 2.5f*60762.11F;
else
rmax = 60762.11F;
if (localData->range > rmax)
{
if ( totV <= 0.0f )
{
timeToRmax = MAX_THREAT_TIME * 2.0f;
}
else
{
timeToRmax = (localData->range - rmax) / totV;
tof = rmax / AVE_AIM120_VEL;
}
}
else
{
timeToRmax = 0.0F;
tof = localData->range / AVE_AIM120_VEL;
}
localData->threatTime = turnTime + timeToRmax + tof;
}
else
{
localData->threatTime = 2.0F * MAX_THREAT_TIME;
}
}
*/
/*----------------------------------------------------*/
/* Targetability determination */
/* Use the longest range missile currently on board */
/* Hypothetical time before the tgt ac can be morted */
/* */
/* Aircraft on own team are returned SENSOR_UNK */
/*----------------------------------------------------*/
// 2002-03-05 MODIFIED BY S.G. CombatClass is defined for FlightClass and AircraftClass now and is virtual in FalconEntity which will return 999
// This code restrict the calculation of the missile range to either planes, chopper or flights. An aggregated chopper flight will have 'IsFlight' set so check if the 'AirUnitClass::IsHelicopter' function returned TRUE to screen them out from aircraft type test
// Have to be at war against us
// Chopper must be our assigned or mission target or we must be on sweep (not a AMIS_SWEEP but still has OnSweep set)
// Must be worth shooting at, unless it's our assigned or mission target (new addition so AI can go after an AWACS for example if it's their target...
// if (canSee && baseObj->IsAirplane() && pcId < ID_NEUTRAL &&
// (IsSetATC(OnSweep) || ((AircraftClass*)baseObj)->CombatClass() < MnvrClassA10))
// 2002-03-11 MODIFIED BY S.G. Don't call CombatClass directly but through GuestimateCombatClass which doesn't assume you have an ID on the target
// Since I'm going to check for this twice in the next if statement, do it once here but also do the 'canSee' test which is not CPU intensive and will prevent the test from being performed if can't see.
/*
CampBaseClass *campObj;
if (baseObj->IsSim())
campObj = ((SimBaseClass *)baseObj)->GetCampaignObject();
else
campObj = (CampBaseClass *)baseObj;
int isMissionTarget = canSee && campObj && (((FlightClass *)(self->GetCampaignObject()))->GetUnitMissionTargetID() == campObj->Id() || ((FlightClass *)(self->GetCampaignObject()))->GetAssignedTarget() == campObj->Id());
if (canSee &&
(baseObj->IsAirplane() || (baseObj->IsFlight() && !baseObj->IsHelicopter()) || (baseObj->IsHelicopter() && ((missionType != AMIS_SWEEP && IsSetATC(OnSweep)) || isMissionTarget))) &&
pcId < ID_NEUTRAL &&
(GuestimateCombatClass(self, baseObj) < MnvrClassA10 || IsSetATC(OnSweep) || isMissionTarget)) // 2002-03-11 Don't assume you know the combat class
// END OF MODIFIED SECTION 2002-03-05
{
// TJL 11/07/03 Cos takes Radians thus no *DTR
//totV = obj->BaseData()->GetVt()*(float)cos(localData->ataFrom*DTR) + self->GetVt();
totV = obj->BaseData()->GetVt()*(float)cos(localData->ataFrom) + self->GetVt();
//TJL 11/07/03 VO log says there is an radian error in this code
// I think it is here. ataFrom is in radians
//turnTime = localData->ataFrom / FIVE_G_TURN_RATE;
turnTime = localData->ataFrom*RTD / FIVE_G_TURN_RATE;// 15.9f degrees per second
rmax = maxAAWpnRange;//me123 60762.11F;
if (localData->range > rmax)
{
if ( totV <= 0.0f )
{
timeToRmax = MAX_TARGET_TIME * 2.0f;
}
else
{
timeToRmax = (localData->range - rmax) / totV;
tof = rmax / AVE_AIM120_VEL;
}
}
else
{
timeToRmax = 0.0F;
tof = localData->range / AVE_AIM120_VEL;
}
localData->targetTime = turnTime + timeToRmax + tof;
}
else
{
localData->targetTime = 2.0F * MAX_TARGET_TIME;
}
*/
obj = obj->next;
}
}
int GuestimateCombatClass(AircraftClass *self, FalconEntity *baseObj)
{
// Fail safe
if (!baseObj)
return 8;
// If asked to use the old code, then honor the request
if (!g_bUseNewCanEnage)
return baseObj->CombatClass();
// First I'll get the campaign object if it's for a sim since I use it at many places...
CampBaseClass *campBaseObj;
if (baseObj->IsSim())
campBaseObj = ((SimBaseClass*)baseObj)->GetCampaignObject();
else
campBaseObj = ((CampBaseClass *)baseObj);
// If the object is a weapon, no point
if (baseObj->IsWeapon())
return 8;
// If it doesn't have a campaign object or it's identified...
if (!campBaseObj || campBaseObj->GetIdentified(self->GetTeam())) {
// Yes, now you can get its combat class!
return baseObj->CombatClass();
}
else {
// No :-( Then guestimate it... (from RIK's BVR code)
if ((baseObj->GetVt() * FTPSEC_TO_KNOTS > 300.0f || baseObj->ZPos() < -10000.0f)) {
//this might be a combat jet.. asume the worst
return 4;
}
else if (baseObj->GetVt() * FTPSEC_TO_KNOTS > 250.0f) {
// this could be a a-a capable thingy, but if it's is it's low level so it's a-a long range shoot capabilitys are not great
return 1;
}
else {
// this must be something unthreatening...it's below 250 knots but it's still unidentified so...
return 0;
}
}
}
| 34.504655 | 391 | 0.602407 | IsraelyFlightSimulator |
2d572796767c5b5c3f6a92da7af6a57744d884f4 | 3,395 | cc | C++ | mts/src/model/QueryFpImportResultResult.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | null | null | null | mts/src/model/QueryFpImportResultResult.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | null | null | null | mts/src/model/QueryFpImportResultResult.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 1 | 2020-11-27T09:13:12.000Z | 2020-11-27T09:13:12.000Z | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/mts/model/QueryFpImportResultResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Mts;
using namespace AlibabaCloud::Mts::Model;
QueryFpImportResultResult::QueryFpImportResultResult() :
ServiceResult()
{}
QueryFpImportResultResult::QueryFpImportResultResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
QueryFpImportResultResult::~QueryFpImportResultResult()
{}
void QueryFpImportResultResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto allFpResultLogInfoListNode = value["FpResultLogInfoList"]["FpResultLogInfo"];
for (auto valueFpResultLogInfoListFpResultLogInfo : allFpResultLogInfoListNode)
{
FpResultLogInfo fpResultLogInfoListObject;
if(!valueFpResultLogInfoListFpResultLogInfo["LogPath"].isNull())
fpResultLogInfoListObject.logPath = valueFpResultLogInfoListFpResultLogInfo["LogPath"].asString();
if(!valueFpResultLogInfoListFpResultLogInfo["LogName"].isNull())
fpResultLogInfoListObject.logName = valueFpResultLogInfoListFpResultLogInfo["LogName"].asString();
if(!valueFpResultLogInfoListFpResultLogInfo["LogStartTime"].isNull())
fpResultLogInfoListObject.logStartTime = std::stol(valueFpResultLogInfoListFpResultLogInfo["LogStartTime"].asString());
if(!valueFpResultLogInfoListFpResultLogInfo["LogEndTime"].isNull())
fpResultLogInfoListObject.logEndTime = std::stol(valueFpResultLogInfoListFpResultLogInfo["LogEndTime"].asString());
if(!valueFpResultLogInfoListFpResultLogInfo["LogSize"].isNull())
fpResultLogInfoListObject.logSize = std::stol(valueFpResultLogInfoListFpResultLogInfo["LogSize"].asString());
if(!valueFpResultLogInfoListFpResultLogInfo["CreateTime"].isNull())
fpResultLogInfoListObject.createTime = std::stol(valueFpResultLogInfoListFpResultLogInfo["CreateTime"].asString());
fpResultLogInfoList_.push_back(fpResultLogInfoListObject);
}
auto pageInfoNode = value["PageInfo"];
if(!pageInfoNode["PageIndex"].isNull())
pageInfo_.pageIndex = std::stol(pageInfoNode["PageIndex"].asString());
if(!pageInfoNode["PageSize"].isNull())
pageInfo_.pageSize = std::stol(pageInfoNode["PageSize"].asString());
if(!pageInfoNode["Total"].isNull())
pageInfo_.total = std::stol(pageInfoNode["Total"].asString());
if(!value["LogCount"].isNull())
logCount_ = std::stol(value["LogCount"].asString());
}
QueryFpImportResultResult::PageInfo QueryFpImportResultResult::getPageInfo()const
{
return pageInfo_;
}
std::vector<QueryFpImportResultResult::FpResultLogInfo> QueryFpImportResultResult::getFpResultLogInfoList()const
{
return fpResultLogInfoList_;
}
long QueryFpImportResultResult::getLogCount()const
{
return logCount_;
}
| 39.022989 | 122 | 0.788807 | iamzken |
2d5a9693443c446abe97ab6844e8633fc6be3fde | 11,025 | cpp | C++ | 1_Widgets-examples/1_4_Widgets_Surfing/src/ofApp.cpp | Daandelange/ofxSurfingImGui | 122241ebcb900d30a5fa6b548de41b2910a27401 | [
"MIT"
] | null | null | null | 1_Widgets-examples/1_4_Widgets_Surfing/src/ofApp.cpp | Daandelange/ofxSurfingImGui | 122241ebcb900d30a5fa6b548de41b2910a27401 | [
"MIT"
] | null | null | null | 1_Widgets-examples/1_4_Widgets_Surfing/src/ofApp.cpp | Daandelange/ofxSurfingImGui | 122241ebcb900d30a5fa6b548de41b2910a27401 | [
"MIT"
] | null | null | null | #include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup_ImGui()
{
ImGuiConfigFlags flags = ImGuiConfigFlags_DockingEnable;
bool bRestore = true;
bool bMouse = false;
bool bAutoDraw = true;
// NOTE: it seems that must be false when multiple ImGui instances created!
gui.setup(nullptr, bAutoDraw, flags, bRestore, bMouse);
//-
// font
auto &io = ImGui::GetIO();
auto normalCharRanges = io.Fonts->GetGlyphRangesDefault();
std::string fontName;
float fontSize;
fontSize = 16;
fontName = "overpass-mono-bold.otf";
std::string _path = "assets/fonts/"; // assets folder
ofFile fileToRead(_path + fontName); // a file that exists
bool b = fileToRead.exists();
if (b) {
customFont = gui.addFont(_path + fontName, fontSize, nullptr, normalCharRanges);
}
if (customFont != nullptr) io.FontDefault = customFont;
//-
// theme
ofxImGuiSurfing::ImGui_ThemeMoebiusSurfing();
}
//--------------------------------------------------------------
void ofApp::setup() {
ofSetFrameRate(60);
setup_ImGui();
// parameters
params.setName("paramsGroup1");// main container
params2.setName("paramsGroup2");// nested
params3.setName("paramsGroup3");// nested
params.add(indexPreset.set("Preset", 0, 0, 8));
params.add(bPrevious.set("<", false));
params.add(bNext.set(">", false));
params.add(bEnable1.set("Enable1", false));
params.add(bEnable2.set("Enable2", false));
params.add(bEnable3.set("Enable3", false));
params.add(lineWidth.set("lineWidth", 0.5, 0, 1));
params.add(separation.set("separation", 50, 1, 100));
params.add(speed.set("speed", 0.5, 0, 1));
params.add(shapeType.set("shapeType", 0, -50, 50));
params.add(size.set("size", 100, 0, 100));
params2.add(shapeType2.set("shapeType2", 0, -50, 50));
params2.add(size2.set("size2", 100, 0, 100));
params2.add(amount2.set("amount2", 10, 0, 25));
params3.add(lineWidth3.set("lineWidth3", 0.5, 0, 1));
params3.add(separation3.set("separation3", 50, 1, 100));
params3.add(speed3.set("speed3", 0.5, 0, 1));
params2.add(params3);
params.add(params2);
listener = indexPreset.newListener([this](int &i) {
ofLogNotice("loadGradient: ") << i;
loadGradient(indexPreset);
});
//--
// gradient
gradient.getMarks().clear();
gradient.addMark(0.0f, ImColor(ofColor(0)));
gradient.addMark(1.0f, ImColor(ofColor(255)));
}
//--------------------------------------------------------------
void ofApp::draw() {
ofBackground(color);
//-
gui.begin();
{
ImGuiColorEditFlags _flagw;
string name;
{
// surfing widgets 1
_flagw = ImGuiWindowFlags_None;
name = "SurfingWidgets 1";
ImGui::Begin(name.c_str(), NULL, _flagw);
{
//static float f1 = -0.5f, f2 = 0.75f;
//ofxImGuiSurfing::RangeSliderFloat2("range slider float", &f1, &f2, -1.0f, 1.0f, "(%.3f, %.3f)");
// v sliders
ofxImGuiSurfing::AddVSlider2(valueKnob1, ImVec2(20, 100), false);
ImGui::SameLine();
ofxImGuiSurfing::AddVSlider2(valueKnob2, ImVec2(20, 100));
//ImGui::SameLine();
//ofxImGuiSurfing::AddVSlider2(valueKnob2, ImVec2(20, 100));
//ImGui::SameLine();
//ofxImGuiSurfing::AddVSlider2(valueKnob2, ImVec2(20, 100));
//ImGui::SameLine();
//ofxImGuiSurfing::AddVSlider2(valueKnob1, ImVec2(20, 100));
// knobs
ofxImGuiSurfing::AddKnob(valueKnob1);
//ImGui::SameLine();
//ofxImGuiSurfing::AddKnob(valueKnob2, true);
// more
draw_SurfingWidgets1();
}
ImGui::End();
//-
// surfing widgets 2
_flagw = ImGuiWindowFlags_None;
name = "SurfingWidgets 2";
ImGui::Begin(name.c_str(), NULL, _flagw);
{
draw_SurfingWidgets2();
}
ImGui::End();
}
}
gui.end();
}
//--------------------------------------------------------------
void ofApp::draw_SurfingWidgets1() {
// Common width sizes from 1 (_w1) to 4 (_w4) widgets per row
// Precalculate common widgets % sizes to fit current window "to be responsive"
// we will update the sizes on any gui drawing point, like inside a new foldered sub-window that could be indendeted and full size is being smaller.
// Internally takes care of ImGui spacing between widgets.
float _w1;
float _w2;
float _w3;
float _w4;
float _h;
_w1 = ofxImGuiSurfing::getWidgetsWidth(1); // 1 widget full width
_w2 = ofxImGuiSurfing::getWidgetsWidth(2); // 2 widgets half width
_w3 = ofxImGuiSurfing::getWidgetsWidth(3); // 3 widgets third width
_w4 = ofxImGuiSurfing::getWidgetsWidth(4); // 4 widgets quarter width
_h = WIDGETS_HEIGHT;
//--
// 1. An in index selector with a clickable preset matrix
{
bool bOpen = true;
ImGuiTreeNodeFlags _flagt = (bOpen ? ImGuiTreeNodeFlags_DefaultOpen : ImGuiTreeNodeFlags_None);
_flagt |= ImGuiTreeNodeFlags_Framed;
if (ImGui::TreeNodeEx("An Index Selector", _flagt))
{
// 1.1 Two buttons on same line
if (ImGui::Button("<", ImVec2(_w2, _h / 2)))
{
indexPreset--;
indexPreset = ofClamp(indexPreset, indexPreset.getMin(), indexPreset.getMax()); // clamp parameter
}
ImGui::SameLine();
if (ImGui::Button(">", ImVec2(_w2, _h / 2)))
{
indexPreset++;
indexPreset = ofClamp(indexPreset, indexPreset.getMin(), indexPreset.getMax()); // clamp parameter
}
// 1.2 Slider: the master int ofParam!
ofxImGuiSurfing::AddParameter(indexPreset);
ofxImGuiSurfing::HelpMarker("The master int ofParam!");
// 1.3 Matrix button clicker
AddMatrixClicker(indexPreset, true, 3); // responsive with 3 widgets per row
// 1.4 Spin arrows
int intSpin = indexPreset;
if (ofxImGuiSurfing::SpinInt("SpinInt", &intSpin))
{
intSpin = ofClamp(intSpin, indexPreset.getMin(), indexPreset.getMax()); // clamp to parameter
indexPreset = intSpin;
}
// 1.5 A tooltip over prev widget
if (ImGui::IsItemHovered()) {
ImGui::BeginTooltip();
ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
ImGui::TextUnformatted("This is not an ofParam. Just an int!");
ImGui::PopTextWrapPos();
ImGui::EndTooltip();
}
// 1.6 An external url link
ofxImGuiSurfing::ObjectInfo("ofxSurfingImGui @ github.com", "https://github.com/moebiussurfing/ofxSurfingImGui");
ImGui::TreePop();
}
}
ImGui::Dummy(ImVec2(0, 10)); // spacing
//--
// 2. an ofParameterGroup
ImGuiTreeNodeFlags flagst;
flagst = ImGuiTreeNodeFlags_None;
flagst |= ImGuiTreeNodeFlags_DefaultOpen;
flagst |= ImGuiTreeNodeFlags_Framed;
ofxImGuiSurfing::AddGroup(params3, flagst); // -> force to be expanded
//ofxImGuiSurfing::AddGroup(params3); // -> by default appears collapsed
}
//--------------------------------------------------------------
void ofApp::draw_SurfingWidgets2()
{
if (ImGui::TreeNode("ofParams Widgets"))
{
ofxImGuiSurfing::AddParameter(size2);
ofxImGuiSurfing::AddParameter(amount2);
ofxImGuiSurfing::AddParameter(separation3);
ImGui::TreePop();
}
ImGui::Dummy(ImVec2(0, 10)); // spacing
//--
// A gradient color tool
bool bOpen = true;
ImGuiTreeNodeFlags _flagt = (bOpen ? ImGuiTreeNodeFlags_DefaultOpen : ImGuiTreeNodeFlags_None);
_flagt |= ImGuiTreeNodeFlags_Framed;
if (ImGui::TreeNodeEx("A Gradient Widget", _flagt))
{
float _h = WIDGETS_HEIGHT;
float _w100 = ofxImGuiSurfing::getWidgetsWidth(1); // 1 widget full width
float _w50 = ofxImGuiSurfing::getWidgetsWidth(2); // 2 widgets half width
float _w33 = ofxImGuiSurfing::getWidgetsWidth(3); // 3 widgets per row
//-
static bool bEditGrad = false;
if (ImGui::GradientButton(&gradient))
{
//set show editor flag to true/false
bEditGrad = !bEditGrad;
}
//::EDITOR::
if (bEditGrad)
{
static ImGradientMark* draggingMark = nullptr;
static ImGradientMark* selectedMark = nullptr;
bool updated = ImGui::GradientEditor(&gradient, draggingMark, selectedMark);
}
//-
ImGui::Dummy(ImVec2(0, 5)); // spacing
// selector
ImGui::PushItemWidth(_w50); // make smaller bc too long label
if (ImGui::SliderFloat("SELECT COLOR PERCENT", &prcGrad, 0, 1))
{
//::GET A COLOR::
float _color[3];
gradient.getColorAt(prcGrad, _color); // position from 0 to 1
color.set(_color[0], _color[1], _color[2], 1.0f);
}
ImGui::PopItemWidth();
ImGui::Dummy(ImVec2(0, 5)); // spacing
//// presets
//if (ImGui::Button("Gradient1", ImVec2(_w3, _h / 2)))
//{
// indexPreset = 0;
//}
//ImGui::SameLine();
//if (ImGui::Button("Gradient2", ImVec2(_w3, _h / 2)))
//{
// indexPreset = 2;
//}
//ImGui::SameLine();
//if (ImGui::Button("Gradient3", ImVec2(_w3, _h / 2)))
//{
// indexPreset = 3;
//}
ImGui::TreePop();
}
}
//--------------------------------------------------------------
void ofApp::loadGradient(int index) {
int i = index;
if (i == 0) {
gradient.getMarks().clear();
gradient.addMark(0.0f, ImColor(ofColor::blue));
gradient.addMark(0.3f, ImColor(ofColor::blueViolet));
gradient.addMark(0.6f, ImColor(ofColor::yellow));
gradient.addMark(1.0f, ImColor(ofColor::orangeRed));
}
else if (i == 1) {
gradient.getMarks().clear();
gradient.addMark(0.0f, ImColor(0xA0, 0x79, 0x3D));
//gradient.addMark(0.2f, ImColor(0xAA, 0x83, 0x47));
gradient.addMark(0.3f, ImColor(0xB4, 0x8D, 0x51));
//gradient.addMark(0.4f, ImColor(0xBE, 0x97, 0x5B));
//gradient.addMark(0.6f, ImColor(0xC8, 0xA1, 0x65));
gradient.addMark(0.7f, ImColor(0xD2, 0xAB, 0x6F));
gradient.addMark(0.8f, ImColor(0xDC, 0xB5, 0x79));
gradient.addMark(1.0f, ImColor(0xE6, 0xBF, 0x83));
}
else if (i == 2) {
gradient.getMarks().clear();
gradient.addMark(0.0f, ImColor(ofColor::red));
gradient.addMark(0.3f, ImColor(ofColor::yellowGreen));
gradient.addMark(1.0f, ImColor(ofColor::green));
}
else if (i == 3) {
gradient.getMarks().clear();
gradient.addMark(0.0f, ImColor(ofColor::blueSteel));
gradient.addMark(0.3f, ImColor(ofColor::blueViolet));
gradient.addMark(0.7f, ImColor(ofColor::cornflowerBlue));
gradient.addMark(1.0f, ImColor(ofColor::cadetBlue));
}
else if (i == 4) {
gradient.getMarks().clear();
gradient.addMark(0.0f, ImColor(ofColor::yellow));
gradient.addMark(0.5f, ImColor(ofColor::lightYellow));
gradient.addMark(1.0f, ImColor(ofColor::lightGoldenRodYellow));
}
else if (i == 5) {
gradient.getMarks().clear();
gradient.addMark(0.0f, ImColor(ofColor::red));
gradient.addMark(0.5f, ImColor(ofColor::orangeRed));
gradient.addMark(1.0f, ImColor(ofColor::blueViolet));
}
else if (i == 6) {
gradient.getMarks().clear();
gradient.addMark(0.0f, ImColor(ofColor::lightYellow));
gradient.addMark(0.5f, ImColor(ofColor::floralWhite));
gradient.addMark(1.0f, ImColor(ofColor::whiteSmoke));
}
// repeat some if index is too big. just for testing..
else {
gradient.getMarks().clear();
gradient.addMark(0.0f, ImColor(ofColor::paleVioletRed));
gradient.addMark(0.3f, ImColor(ofColor::red));
gradient.addMark(0.7f, ImColor(ofColor::darkRed));
gradient.addMark(1.0f, ImColor(ofColor::black));
}
//refresh
float _color[3];
gradient.getColorAt(prcGrad, _color); // position from 0 to 1
color.set(_color[0], _color[1], _color[2], 1.0f);
} | 29.637097 | 149 | 0.655964 | Daandelange |
2d5beed9a2b8139f1e89c0b2a37b75774f14f85f | 14,455 | cpp | C++ | Source/SupportGLUT/Viewer/ScreenBase.cpp | GoTamura/KVS | 121ede0b9b81da56e9ea698a45ccfd71ff64ed41 | [
"BSD-3-Clause"
] | null | null | null | Source/SupportGLUT/Viewer/ScreenBase.cpp | GoTamura/KVS | 121ede0b9b81da56e9ea698a45ccfd71ff64ed41 | [
"BSD-3-Clause"
] | null | null | null | Source/SupportGLUT/Viewer/ScreenBase.cpp | GoTamura/KVS | 121ede0b9b81da56e9ea698a45ccfd71ff64ed41 | [
"BSD-3-Clause"
] | null | null | null | /*****************************************************************************/
/**
* @file ScreenBase.cpp
* @author Naohisa Sakamoto
*/
/*----------------------------------------------------------------------------
*
* Copyright (c) Visualization Laboratory, Kyoto University.
* All rights reserved.
* See http://www.viz.media.kyoto-u.ac.jp/kvs/copyright/ for details.
*
* $Id$
*/
/*****************************************************************************/
#include "ScreenBase.h"
#include <kvs/Message>
#include <kvs/Assert>
#include <kvs/MouseEvent>
#include <kvs/KeyEvent>
#include <kvs/WheelEvent>
#include <kvs/TimerEventListener>
#include <kvs/glut/GLUT>
#include <kvs/glut/Application>
#include <kvs/glut/Timer>
#include <SupportGLUT/Viewer/KVSMouseButton.h>
#include <SupportGLUT/Viewer/KVSKey.h>
#include <cstdlib>
namespace
{
const size_t MaxNumberOfScreens = 256;
kvs::glut::ScreenBase* Context[ MaxNumberOfScreens ] = {};
#if defined( KVS_GL_HAS_LAYER_BACKED_VIEW )
int ResizeOnce[ MaxNumberOfScreens ] = {};
#endif
/*===========================================================================*/
/**
* @brief Function that is called when the application is terminated.
*/
/*===========================================================================*/
void ExitFunction()
{
for ( size_t i = 0; i < MaxNumberOfScreens; i++)
{
if ( Context[i] ) Context[i]->~ScreenBase();
}
}
}
namespace kvs
{
namespace glut
{
/*===========================================================================*/
/**
* @brief Display function for glutDisplayFunc.
*/
/*===========================================================================*/
void DisplayFunction()
{
const int id = glutGetWindow();
::Context[id]->paintEvent();
}
/*===========================================================================*/
/**
* @brief Resize function for glutReshapeFunc.
* @param width [in] window width
* @param height [in] window height
*/
/*===========================================================================*/
void ResizeFunction( int width, int height )
{
const int id = glutGetWindow();
#if defined( KVS_GL_HAS_LAYER_BACKED_VIEW )
if ( ::ResizeOnce[id] == 0 )
{
glutReshapeWindow( width + 1, height + 1 );
::ResizeOnce[id] = 1;
}
#endif
::Context[id]->resizeEvent( width, height );
}
/*===========================================================================*/
/**
* @brief Mouse function for glutMouseFunc.
* @param button [in] button ID
* @param state [in] state ID
* @param x [in] x coordinate of the mouse on the window coordinate
* @param y [in] y coordinate of the mouse on the window coordinate
*/
/*===========================================================================*/
void MouseFunction( int button, int state, int x, int y )
{
const int id = glutGetWindow();
const int modifier = kvs::glut::KVSKey::Modifier( glutGetModifiers() );
button = kvs::glut::KVSMouseButton::Button( button );
state = kvs::glut::KVSMouseButton::State( state );
::Context[id]->m_mouse_event->setButton( button );
::Context[id]->m_mouse_event->setState( state );
::Context[id]->m_mouse_event->setPosition( x, y );
::Context[id]->m_mouse_event->setModifiers( modifier );
switch ( state )
{
case kvs::MouseButton::Down:
::Context[id]->m_elapse_time_counter.stop();
if ( ::Context[id]->m_elapse_time_counter.sec() < 0.2f )
{
::Context[id]->m_mouse_event->setAction( kvs::MouseButton::DoubleClicked );
::Context[id]->mouseDoubleClickEvent( ::Context[id]->m_mouse_event );
}
else
{
::Context[id]->m_mouse_event->setAction( kvs::MouseButton::Pressed );
::Context[id]->mousePressEvent( ::Context[id]->m_mouse_event );
}
::Context[id]->m_elapse_time_counter.start();
break;
case kvs::MouseButton::Up:
::Context[id]->m_mouse_event->setAction( kvs::MouseButton::Released );
::Context[id]->mouseReleaseEvent( ::Context[id]->m_mouse_event );
break;
default: break;
}
::Context[id]->m_wheel_event->setPosition( x, y );
switch( button )
{
case kvs::MouseButton::WheelUp:
::Context[id]->m_wheel_event->setDirection( 1 );
::Context[id]->wheelEvent( ::Context[id]->m_wheel_event );
break;
case kvs::MouseButton::WheelDown:
::Context[id]->m_wheel_event->setDirection( -1 );
::Context[id]->wheelEvent( ::Context[id]->m_wheel_event );
break;
default: break;
}
}
/*===========================================================================*/
/**
* @brief Mouse move function for glutMotionFunc.
* @param x [in] x coordinate value of the mouse cursor on the window coordinate
* @param y [in] y coordinate value of the mouse cursor on the window coordinate
*/
/*===========================================================================*/
void MouseMoveFunction( int x, int y )
{
const int id = glutGetWindow();
::Context[id]->m_mouse_event->setPosition( x, y );
::Context[id]->m_mouse_event->setAction( kvs::MouseButton::Moved );
::Context[id]->mouseMoveEvent( ::Context[id]->m_mouse_event );
}
/*===========================================================================*/
/**
* @brief Key press function for glutKeyboardFunc.
* @param key [in] key code
* @param x [in] x coordinate value of the mouse cursor on the window coordinate
* @param y [in] y coordinate value of the mouse cursor on the window coordinate
*/
/*===========================================================================*/
void KeyPressFunction( unsigned char key, int x, int y )
{
const int id = glutGetWindow();
const int code = kvs::glut::KVSKey::ASCIICode( key );
::Context[id]->m_key_event->setKey( code );
::Context[id]->m_key_event->setPosition( x, y );
::Context[id]->keyPressEvent( ::Context[id]->m_key_event );
}
/*===========================================================================*/
/**
* @brief Special key press function for glutSpecialFunc.
* @param key [in] key code
* @param x [in] x coordinate value of the mouse cursor on the window coordinate
* @param y [in] y coordinate value of the mouse cursor on the window coordinate
*/
/*===========================================================================*/
void SpecialKeyPressFunction( int key, int x, int y )
{
const int id = glutGetWindow();
const int code = kvs::glut::KVSKey::SpecialCode( key );
::Context[id]->m_key_event->setKey( code );
::Context[id]->m_key_event->setPosition( x, y );
::Context[id]->keyPressEvent( ::Context[id]->m_key_event );
}
/*===========================================================================*/
/**
* @brief Constructs a new ScreenBase class.
* @param application [in] pointer to the application
*/
/*===========================================================================*/
ScreenBase::ScreenBase( kvs::glut::Application* application ):
m_id( -1 ),
m_mouse_event( 0 ),
m_key_event( 0 ),
m_wheel_event( 0 ),
m_is_fullscreen( false )
{
if ( application ) application->attach( this );
m_mouse_event = new kvs::MouseEvent();
m_key_event = new kvs::KeyEvent();
m_wheel_event = new kvs::WheelEvent();
m_elapse_time_counter.start();
}
/*===========================================================================*/
/**
* @brief Destructs the ScreenBase class.
*/
/*===========================================================================*/
ScreenBase::~ScreenBase()
{
delete m_mouse_event;
delete m_key_event;
delete m_wheel_event;
::Context[ m_id ] = NULL;
glutDestroyWindow( m_id );
}
/*===========================================================================*/
/**
* @brief Creates the screen.
*/
/*===========================================================================*/
void ScreenBase::create()
{
KVS_ASSERT( m_id == -1 );
// Initialize display mode.
unsigned int mode = 0;
if ( displayFormat().doubleBuffer() ) mode |= GLUT_DOUBLE; else mode |= GLUT_SINGLE;
if ( displayFormat().colorBuffer() ) mode |= GLUT_RGBA; else mode |= GLUT_INDEX;
if ( displayFormat().depthBuffer() ) mode |= GLUT_DEPTH;
if ( displayFormat().accumulationBuffer() ) mode |= GLUT_ACCUM;
if ( displayFormat().stencilBuffer() ) mode |= GLUT_STENCIL;
if ( displayFormat().stereoBuffer() ) mode |= GLUT_STEREO;
if ( displayFormat().multisampleBuffer() ) mode |= GLUT_MULTISAMPLE;
if ( displayFormat().alphaChannel() ) mode |= GLUT_ALPHA;
glutInitDisplayMode( mode );
// Set screen geometry.
glutInitWindowPosition( BaseClass::x(), BaseClass::y() );
#if defined( KVS_GL_HAS_LAYER_BACKED_VIEW )
glutInitWindowSize( BaseClass::width() - 1, BaseClass::height() - 1 );
#else
glutInitWindowSize( BaseClass::width(), BaseClass::height() );
#endif
// Create window.
glutCreateWindow( BaseClass::title().c_str() );
// Set to the global context.
m_id = glutGetWindow();
::Context[ m_id ] = this;
// Initialize GLEW.
#if defined( KVS_ENABLE_GLEW )
GLenum result = glewInit();
if ( result != GLEW_OK )
{
const GLubyte* message = glewGetErrorString( result );
kvsMessageError( "GLEW initialization failed: %s.", message );
}
#endif
// Create paint device.
BaseClass::paintDevice()->create();
// Register the exit function.
static bool flag = true;
if ( flag ) { atexit( ::ExitFunction ); flag = false; }
// Register callback functions.
glutMouseFunc( MouseFunction );
glutMotionFunc( MouseMoveFunction );
glutKeyboardFunc( KeyPressFunction );
glutSpecialFunc( SpecialKeyPressFunction );
glutDisplayFunc( DisplayFunction );
glutReshapeFunc( ResizeFunction );
}
/*===========================================================================*/
/**
* @brief Shows the screen.
* @return window ID
*/
/*===========================================================================*/
void ScreenBase::show()
{
#if 1 // KVS_ENABLE_DEPRECATED
if ( m_id == -1 ) this->create();
else {
#endif
glutSetWindow( m_id );
glutShowWindow();
#if 1 // KVS_ENABLE_DEPRECATED
}
#endif
}
/*===========================================================================*/
/**
* @brief Shows the window as full-screen.
*/
/*===========================================================================*/
void ScreenBase::showFullScreen()
{
if ( m_is_fullscreen ) return;
m_is_fullscreen = true;
const int x = glutGet( (GLenum)GLUT_WINDOW_X );
const int y = glutGet( (GLenum)GLUT_WINDOW_Y );
BaseClass::setPosition( x, y );
glutFullScreen();
}
/*===========================================================================*/
/**
* @brief Shows the window as normal screen.
*/
/*===========================================================================*/
void ScreenBase::showNormal()
{
if ( !m_is_fullscreen ) return;
m_is_fullscreen = false;
glutReshapeWindow( BaseClass::width(), BaseClass::height() );
glutPositionWindow( BaseClass::x(), BaseClass::y() );
glutPopWindow();
}
/*===========================================================================*/
/**
* @brief Hides the window.
*/
/*===========================================================================*/
void ScreenBase::hide()
{
glutSetWindow( m_id );
glutHideWindow();
}
/*===========================================================================*/
/**
* @brief Pops up the window.
*/
/*===========================================================================*/
void ScreenBase::popUp()
{
glutPopWindow();
}
/*===========================================================================*/
/**
* @brief Pushes down the window.
*/
/*===========================================================================*/
void ScreenBase::pushDown()
{
glutPushWindow();
}
/*===========================================================================*/
/**
* @brief Redraws the window.
*/
/*===========================================================================*/
void ScreenBase::redraw()
{
const int id = glutGetWindow();
glutSetWindow( m_id );
glutPostRedisplay();
glutSetWindow( id );
}
/*===========================================================================*/
/**
* @brief Resizes the window.
* @param width [in] resized window width
* @param height [in] resized window height
*/
/*===========================================================================*/
void ScreenBase::resize( int width, int height )
{
BaseClass::setSize( width, height );
glutReshapeWindow( BaseClass::width(), BaseClass::height() );
}
/*===========================================================================*/
/**
* @brief Checks whether the window is full-screen or not.
* @return true, if the window is full-screen
*/
/*===========================================================================*/
bool ScreenBase::isFullScreen() const
{
return m_is_fullscreen;
}
void ScreenBase::enable(){}
void ScreenBase::disable(){}
void ScreenBase::reset(){}
void ScreenBase::initializeEvent(){}
void ScreenBase::paintEvent(){}
void ScreenBase::resizeEvent( int, int ){}
void ScreenBase::mousePressEvent( kvs::MouseEvent* ){}
void ScreenBase::mouseMoveEvent( kvs::MouseEvent* ){}
void ScreenBase::mouseReleaseEvent( kvs::MouseEvent* ){}
void ScreenBase::mouseDoubleClickEvent( kvs::MouseEvent* ){}
void ScreenBase::wheelEvent( kvs::WheelEvent* ){}
void ScreenBase::keyPressEvent( kvs::KeyEvent* ){}
std::list<kvs::glut::Timer*>& ScreenBase::timerEventHandler()
{
return m_timer_event_handler;
}
/*===========================================================================*/
/**
* @brief Adds a timer event listener.
* @param event [in] pointer to a timer event listener
* @param timer [in] pointer to timer
*/
/*===========================================================================*/
void ScreenBase::addTimerEvent( kvs::TimerEventListener* event, kvs::glut::Timer* timer )
{
event->setScreen( this );
timer->setEventListener( event );
m_timer_event_handler.push_back( timer );
}
} // end of namespace glut
} // end of namespace kvs
| 31.699561 | 89 | 0.499896 | GoTamura |
2d5bfd3aa2596cf710d4c1672e818b1c94d8d81f | 1,967 | hh | C++ | src/mem/cache/c_dynamic_cache.hh | xiaoyaozi5566/DynamicCache | 250e7a901f3244f69d0c8de4d3f525a92dbfaac5 | [
"BSD-3-Clause"
] | null | null | null | src/mem/cache/c_dynamic_cache.hh | xiaoyaozi5566/DynamicCache | 250e7a901f3244f69d0c8de4d3f525a92dbfaac5 | [
"BSD-3-Clause"
] | null | null | null | src/mem/cache/c_dynamic_cache.hh | xiaoyaozi5566/DynamicCache | 250e7a901f3244f69d0c8de4d3f525a92dbfaac5 | [
"BSD-3-Clause"
] | 1 | 2021-07-05T18:02:56.000Z | 2021-07-05T18:02:56.000Z | #include "mem/cache/base.hh"
#include "mem/cache/blk.hh"
#include "mem/cache/cache.hh"
#include "params/BaseCache.hh"
#include "stdio.h"
typedef BaseCacheParams Params;
template <class TagStore>
class C_DynamicCache : public SplitRPortCache<TagStore>
{
public:
C_DynamicCache( const Params *p, TagStore *tags );
/** Define the type of cache block to use. */
typedef typename TagStore::BlkType BlkType;
/** A typedef for a list of BlkType pointers. */
typedef typename TagStore::BlkList BlkList;
protected:
virtual void incMissCount(PacketPtr pkt)
{
if(pkt->threadID == 0) this->missCounter++;
}
void adjustPartition();
uint64_t array_avg(uint64_t* array, int count)
{
assert(count != 0);
uint64_t sum = 0;
for(int i = 0; i < count; i++){
sum += array[i];
}
return sum/count;
}
void update_history(uint64_t* array, int count, uint64_t curr_misses)
{
assert(count != 0);
for(int i = 0; i < count-1; i++){
array[i] = array[i+1];
}
array[count-1] = curr_misses;
}
void inc_size();
void dec_size();
EventWrapper<C_DynamicCache<TagStore>, &C_DynamicCache<TagStore>::adjustPartition> adjustEvent;
private:
// Time interval to change partition size (ticks)
uint64_t interval;
// Thresholds for changing partition size
float th_inc, th_dec;
// Window size
uint64_t window_size;
// Moving average
uint64_t *miss_history;
// Explore flag and stable flag
bool explore_phase, explore_inc, explore_dec, stable_phase;
// Stable length
uint64_t stable_length, stable_counter;
// Static miss curve
float *miss_curve;
unsigned assoc;
// protected:
// virtual bool access(PacketPtr pkt, BlkType *&blk,
// int &lat, PacketList &writebacks);
//
// virtual bool timingAccess(PacketPtr pkt);
//
// virtual void handleResponse(PacketPtr pkt);
//
// virtual BlkType *handleFill(PacketPtr pkt, BlkType *blk,
// PacketList &writebacks);
};
| 25.217949 | 96 | 0.685308 | xiaoyaozi5566 |
2d5f5558224e023aec9b9a7ab47971122f40f8f8 | 2,023 | hh | C++ | src/random/distributions/ReciprocalDistribution.i.hh | amandalund/celeritas | c631594b00c040d5eb4418fa2129f88c01e29316 | [
"Apache-2.0",
"MIT"
] | null | null | null | src/random/distributions/ReciprocalDistribution.i.hh | amandalund/celeritas | c631594b00c040d5eb4418fa2129f88c01e29316 | [
"Apache-2.0",
"MIT"
] | null | null | null | src/random/distributions/ReciprocalDistribution.i.hh | amandalund/celeritas | c631594b00c040d5eb4418fa2129f88c01e29316 | [
"Apache-2.0",
"MIT"
] | null | null | null | //----------------------------------*-C++-*----------------------------------//
// Copyright 2021 UT-Battelle, LLC, and other Celeritas developers.
// See the top-level COPYRIGHT file for details.
// SPDX-License-Identifier: (Apache-2.0 OR MIT)
//---------------------------------------------------------------------------//
//! \file ReciprocalDistribution.i.hh
//---------------------------------------------------------------------------//
#include <cmath>
#include "base/Assert.hh"
#include "GenerateCanonical.hh"
namespace celeritas
{
//---------------------------------------------------------------------------//
/*!
* Construct on the interval [a, 1).
*
* The distribution is equivalent to switching a and b, and using
* \f$ \xi' = 1 - \xi \f$.
*/
template<class RealType>
CELER_FUNCTION
ReciprocalDistribution<RealType>::ReciprocalDistribution(real_type a)
: ReciprocalDistribution(1, a)
{
}
//---------------------------------------------------------------------------//
/*!
* Construct on the interval [a, b).
*
* As with UniformRealDistribution, it is allowable for the two bounds to be
* out of order.
*
* Note that writing as \code (1/a) * b \endcode allows the compiler to
* optimize better for the constexpr case a=1.
*/
template<class RealType>
CELER_FUNCTION
ReciprocalDistribution<RealType>::ReciprocalDistribution(real_type a,
real_type b)
: a_(a), logratio_(std::log((1 / a) * b))
{
CELER_EXPECT(a > 0);
CELER_EXPECT(b > 0);
}
//---------------------------------------------------------------------------//
/*!
* Sample a random number according to the distribution.
*/
template<class RealType>
template<class Generator>
CELER_FUNCTION auto
ReciprocalDistribution<RealType>::operator()(Generator& rng) const
-> result_type
{
return a_ * std::exp(logratio_ * generate_canonical<RealType>(rng));
}
//---------------------------------------------------------------------------//
} // namespace celeritas
| 31.609375 | 79 | 0.499259 | amandalund |
2d5fd58d1f97ac9c3c8d2e42c7a9249bafa07e07 | 1,174 | hpp | C++ | DnsUdpStateMachine.hpp | luotuo44/ADNS | ccc85b11c9a3fc7250493451429a44abc81bec39 | [
"BSD-2-Clause"
] | 3 | 2016-04-10T04:58:37.000Z | 2020-09-07T05:54:51.000Z | DnsUdpStateMachine.hpp | luotuo44/ADNS | ccc85b11c9a3fc7250493451429a44abc81bec39 | [
"BSD-2-Clause"
] | null | null | null | DnsUdpStateMachine.hpp | luotuo44/ADNS | ccc85b11c9a3fc7250493451429a44abc81bec39 | [
"BSD-2-Clause"
] | null | null | null | //Filename:
//Date: 2015-8-11
//Author: luotuo44 http://blog.csdn.net/luotuo44
//Copyright 2015, luotuo44. All rights reserved.
//Use of this source code is governed by a BSD-style license
#ifndef DNSUDPSTATEMACHINE
#define DNSUDPSTATEMACHINE
#include<map>
#include<memory>
#include"typedef.hpp"
#include"typedef-internal.hpp"
namespace ADNS
{
class DnsUdpStateMachine
{
public:
DnsUdpStateMachine(EventCreater &ev_creater);
~DnsUdpStateMachine();
DnsUdpStateMachine(const DnsUdpStateMachine& )=delete;
DnsUdpStateMachine& operator = (const DnsUdpStateMachine& )=delete;
void setResCB(DnsExplorerResCB &cb);
void addQuery(const DnsQuery_t &query);
void eventCB(int fd, int events, void *arg);
private:
struct QueryPacket;
using QueryPacketPtr = std::shared_ptr<QueryPacket>;
private:
void updateEvent(QueryPacketPtr &q, int events, int milliseconds =-1);
void replyResult(QueryPacketPtr &q, bool success);
bool getDNSQueryPacket(QueryPacketPtr &query);
protected:
EventCreater m_ev_creater;
DnsExplorerResCB m_res_cb;
std::map<int, QueryPacketPtr> m_querys;
};
}
#endif // DNSUDPSTATEMACHINE
| 20.241379 | 74 | 0.741908 | luotuo44 |
2d606efdc116af519b0d2ab303197fc526f1aba6 | 20,057 | cc | C++ | src/stirling/source_connectors/dynamic_tracer/dynamic_tracing/code_gen_test.cc | hangqiu/pixie | 1dd4af47d40ff856c4d52a1d6de81f78a76ff31e | [
"Apache-2.0"
] | 1,821 | 2020-04-08T00:45:27.000Z | 2021-09-01T14:56:25.000Z | src/stirling/source_connectors/dynamic_tracer/dynamic_tracing/code_gen_test.cc | hangqiu/pixie | 1dd4af47d40ff856c4d52a1d6de81f78a76ff31e | [
"Apache-2.0"
] | 142 | 2020-04-09T06:23:46.000Z | 2021-08-24T06:02:12.000Z | src/stirling/source_connectors/dynamic_tracer/dynamic_tracing/code_gen_test.cc | hangqiu/pixie | 1dd4af47d40ff856c4d52a1d6de81f78a76ff31e | [
"Apache-2.0"
] | 105 | 2021-09-08T10:26:50.000Z | 2022-03-29T09:13:36.000Z | /*
* Copyright 2018- The Pixie Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
#include "src/stirling/source_connectors/dynamic_tracer/dynamic_tracing/code_gen.h"
#include <google/protobuf/text_format.h>
#include "src/common/testing/testing.h"
constexpr std::string_view kBinaryPath =
"src/stirling/obj_tools/testdata/go/test_go_binary_/test_go_binary";
namespace px {
namespace stirling {
namespace dynamic_tracing {
using ::google::protobuf::TextFormat;
using ::px::stirling::dynamic_tracing::ir::physical::Field;
using ::px::stirling::dynamic_tracing::ir::physical::MapStashAction;
using ::px::stirling::dynamic_tracing::ir::physical::PerfBufferOutputAction;
using ::px::stirling::dynamic_tracing::ir::physical::Register;
using ::px::stirling::dynamic_tracing::ir::physical::ScalarVariable;
using ::px::stirling::dynamic_tracing::ir::physical::Struct;
using ::px::stirling::dynamic_tracing::ir::physical::StructVariable;
using ::px::stirling::dynamic_tracing::ir::shared::BPFHelper;
using ::px::stirling::dynamic_tracing::ir::shared::ScalarType;
using ::testing::ElementsAre;
using ::testing::ElementsAreArray;
using ::testing::StrEq;
TEST(GenStructTest, Output) {
Struct st;
st.set_name("socket_data_event_t");
Field* field = nullptr;
field = st.add_fields();
field->set_name("i32");
field->set_type(ScalarType::INT32);
field = st.add_fields();
field->set_name("i64");
field->set_type(ScalarType::INT64);
field = st.add_fields();
field->set_name("double_val");
field->set_type(ScalarType::DOUBLE);
field = st.add_fields();
field->set_name("msg");
field->set_type(ScalarType::VOID_POINTER);
ASSERT_OK_AND_THAT(GenStruct(st, /*indent_size*/ 4),
ElementsAre("struct socket_data_event_t {", " int32_t i32;",
" int64_t i64;", " double double_val;", " void* msg;",
"} __attribute__((packed, aligned(1)));"));
}
TEST(GenVariableTest, Register) {
ScalarVariable var;
var.set_name("var");
var.set_type(ScalarType::VOID_POINTER);
var.set_reg(Register::SP);
ASSERT_OK_AND_THAT(GenScalarVariable(var), ElementsAre("void* var = (void*)PT_REGS_SP(ctx);"));
var.set_type(ScalarType::INT);
var.set_reg(Register::RC);
ASSERT_OK_AND_THAT(GenScalarVariable(var), ElementsAre("int var = (int)PT_REGS_RC(ctx);"));
var.set_type(ScalarType::VOID_POINTER);
var.set_reg(Register::RC);
ASSERT_OK_AND_THAT(GenScalarVariable(var), ElementsAre("void* var = (void*)PT_REGS_RC(ctx);"));
var.set_type(ScalarType::INT64);
var.set_reg(Register::RC_PTR);
ASSERT_OK_AND_THAT(GenScalarVariable(var), ElementsAre("uint64_t rc___[2];"
"rc___[0] = ctx->ax;"
"rc___[1] = ctx->dx;"
"void* var = &rc___;"));
var.set_type(ScalarType::INT64);
var.set_reg(Register::RDX);
ASSERT_OK_AND_THAT(GenScalarVariable(var), ElementsAre("int64_t var = (int64_t)ctx->dx;"));
}
TEST(GenVariableTest, MemoryVariable) {
ScalarVariable var;
var.set_name("var");
var.set_type(ScalarType::INT32);
auto* mem_var = var.mutable_memory();
mem_var->set_base("sp");
mem_var->set_offset(123);
ASSERT_OK_AND_THAT(
GenScalarVariable(var),
ElementsAre("int32_t var;", "bpf_probe_read(&var, sizeof(int32_t), sp + 123);"));
}
TEST(GenVariableTest, Builtin) {
ScalarVariable var;
var.set_name("var");
var.set_type(ScalarType::VOID_POINTER);
var.set_builtin(BPFHelper::GOID);
ASSERT_OK_AND_THAT(GenScalarVariable(var), ElementsAre("void* var = pl_goid();"));
var.set_builtin(BPFHelper::TGID);
ASSERT_OK_AND_THAT(GenScalarVariable(var),
ElementsAre("void* var = bpf_get_current_pid_tgid() >> 32;"));
var.set_builtin(BPFHelper::TGID_PID);
ASSERT_OK_AND_THAT(GenScalarVariable(var),
ElementsAre("void* var = bpf_get_current_pid_tgid();"));
var.set_builtin(BPFHelper::KTIME);
var.set_type(ScalarType::UINT64);
ASSERT_OK_AND_THAT(GenScalarVariable(var), ElementsAre("uint64_t var = bpf_ktime_get_ns();"));
var.set_builtin(BPFHelper::TGID_START_TIME);
var.set_type(ScalarType::UINT64);
ASSERT_OK_AND_THAT(GenScalarVariable(var), ElementsAre("uint64_t var = pl_tgid_start_time();"));
}
TEST(GenStructVariableTest, Variables) {
Struct st;
st.set_name("socket_data_event_t");
Field* field = nullptr;
field = st.add_fields();
field->set_name("i32");
field->set_type(ScalarType::INT32);
field = st.add_fields();
field->set_name("i64");
field->set_type(ScalarType::INT64);
StructVariable st_var;
st_var.set_name("st_var");
st_var.set_type("socket_data_event_t");
auto* fa = st_var.add_field_assignments();
fa->set_field_name("i32");
fa->set_variable_name("foo");
fa = st_var.add_field_assignments();
fa->set_field_name("i64");
fa->set_variable_name("bar");
ASSERT_OK_AND_THAT(GenStructVariable(st_var),
ElementsAre("struct socket_data_event_t st_var = {};", "st_var.i32 = foo;",
"st_var.i64 = bar;"));
st_var.set_is_pointer(true);
ASSERT_OK_AND_THAT(GenStructVariable(st_var),
ElementsAre("struct socket_data_event_t st_var = {};", "st_var->i32 = foo;",
"st_var->i64 = bar;"));
}
TEST(GenMapStashActionTest, StashMap) {
MapStashAction action;
action.set_map_name("test");
action.set_key_variable_name("foo");
action.set_value_variable_name("bar");
action.mutable_cond()->set_op(ir::shared::Condition::EQUAL);
action.mutable_cond()->add_vars("foo");
action.mutable_cond()->add_vars("bar");
ASSERT_OK_AND_THAT(GenMapStashAction(action),
ElementsAre("if (foo == bar) {", "test.update(&foo, &bar);", "}"));
}
TEST(GenProgramTest, SpecsAndCode) {
const std::string program_protobuf = R"proto(
deployment_spec {
path: "target_binary_path"
}
language: GOLANG
structs {
name: "socket_data_event_t"
fields {
name: "i32"
type: INT32
}
}
structs {
name: "value_t"
fields {
name: "i32"
type: INT32
}
}
maps {
name: "map"
key_type { scalar: UINT32 }
value_type { struct_type: "value_t" }
}
arrays {
name: "array"
type { struct_type: "socket_data_event_t" }
capacity: 1
}
outputs {
name: "data_events"
struct_type: "socket_data_event_t"
}
outputs {
name: "data_events2"
struct_type: "socket_data_event_t"
}
probes {
name: "probe_entry"
tracepoint {
symbol: "target_symbol"
type: ENTRY
}
vars {
scalar_var {
name: "key"
type: UINT32
builtin: TGID
}
}
vars {
scalar_var {
name: "var"
type: INT32
reg: SP
}
}
vars {
scalar_var {
name: "struct_blob"
type: STRUCT_BLOB
memory {
base: "var"
offset: 16
size: 8
op: DEFINE_ONLY
}
}
}
vars {
struct_var {
name: "st_var"
type: "socket_data_event_t"
field_assignments {
field_name: "i32"
variable_name: "var"
}
}
}
vars {
map_var {
name: "map_var"
type: "value_t"
map_name: "map"
key_variable_name: "key"
}
}
vars {
scalar_var {
name: "index"
type: INT32
constant: "0"
}
}
vars {
map_var {
name: "array_var"
type: "socket_data_event_t"
map_name: "array"
key_variable_name: "index"
}
}
cond_blocks {
cond {
op: EQUAL
vars: "key"
vars: "var"
}
vars {
scalar_var {
name: "struct_blob"
type: STRUCT_BLOB
memory {
base: "var"
offset: 16
size: 8
op: ASSIGN_ONLY
}
}
}
vars {
scalar_var {
name: "inner_var"
type: INT32
reg: SP
}
}
vars {
struct_var {
name: "st_var"
type: "socket_data_event_t"
field_assignments {
field_name: "i32"
variable_name: "inner_var"
}
}
}
return_value: "0"
}
map_stash_actions {
map_name: "test"
key_variable_name: "key"
value_variable_name: "var"
}
output_actions {
perf_buffer_name: "data_events"
data_buffer_array_name: "data_events_value_array"
output_struct_name: "socket_data_event_t"
variable_names: "inner_var"
}
printks { scalar: "var" }
}
probes {
name: "probe_return"
tracepoint {
symbol: "target_symbol"
type: RETURN
}
vars {
scalar_var {
name: "key"
type: UINT32
builtin: TGID
}
}
vars {
scalar_var {
name: "retval"
type: INT
reg: RC
}
}
map_delete_actions {
map_name: "test"
key_variable_name: "key"
}
}
)proto";
ir::physical::Program program;
ASSERT_TRUE(TextFormat::ParseFromString(program_protobuf, &program));
program.mutable_deployment_spec()->set_path(px::testing::BazelBinTestFilePath(kBinaryPath));
ASSERT_OK_AND_ASSIGN(const std::string bcc_code, GenBCCProgram(program));
const std::vector<std::string> expected_code_lines = {
"#include <linux/sched.h>",
"#define __inline inline __attribute__((__always_inline__))",
"static __inline uint64_t pl_nsec_to_clock_t(uint64_t x) {",
"return div_u64(x, NSEC_PER_SEC / USER_HZ);",
"}",
"static __inline uint64_t pl_tgid_start_time() {",
"struct task_struct* task_group_leader = ((struct "
"task_struct*)bpf_get_current_task())->group_leader;",
"#if LINUX_VERSION_CODE >= 328960",
"return pl_nsec_to_clock_t(task_group_leader->start_boottime);",
"#else",
"return pl_nsec_to_clock_t(task_group_leader->real_start_time);",
"#endif",
"}",
"struct blob32 {",
" uint64_t len;",
" uint8_t buf[32-9];",
" uint8_t truncated;",
"};",
"struct blob64 {",
" uint64_t len;",
" uint8_t buf[64-9];",
" uint8_t truncated;",
"};",
"struct struct_blob64 {",
" uint64_t len;",
" int8_t decoder_idx;",
" uint8_t buf[64-10];",
" uint8_t truncated;",
"};",
"struct socket_data_event_t {",
" int32_t i32;",
"} __attribute__((packed, aligned(1)));",
"struct value_t {",
" int32_t i32;",
"} __attribute__((packed, aligned(1)));",
"BPF_HASH(map, uint32_t, struct value_t);",
"BPF_PERCPU_ARRAY(array, struct socket_data_event_t, 1);",
"static __inline int64_t pl_goid() {",
"uint64_t current_pid_tgid = bpf_get_current_pid_tgid();",
"const struct pid_goid_map_value_t* goid_ptr = pid_goid_map.lookup(¤t_pid_tgid);",
"return (goid_ptr == NULL) ? -1 : goid_ptr->goid;",
"}",
"BPF_PERF_OUTPUT(data_events);",
"BPF_PERF_OUTPUT(data_events2);",
"int probe_entry(struct pt_regs* ctx) {",
"uint32_t key = bpf_get_current_pid_tgid() >> 32;",
"int32_t var = (int32_t)PT_REGS_SP(ctx);",
"struct struct_blob64 struct_blob = {};",
"struct socket_data_event_t st_var = {};",
"st_var.i32 = var;",
"struct value_t* map_var = map.lookup(&key);",
"int32_t index = 0;",
"struct socket_data_event_t* array_var = array.lookup(&index);",
"if (key == var) {",
"struct_blob.len = 8;",
"struct_blob.decoder_idx = 0;",
"bpf_probe_read(&struct_blob.buf, 8, var + 16);",
"int32_t inner_var = (int32_t)PT_REGS_SP(ctx);",
"struct socket_data_event_t st_var = {};",
"st_var.i32 = inner_var;",
"return 0;",
"}",
"test.update(&key, &var);",
"uint32_t data_events_value_idx = 0;",
"struct socket_data_event_t* data_events_value = "
"data_events_value_array.lookup(&data_events_value_idx);",
"if (data_events_value == NULL) { return 0; }",
"data_events_value->i32 = inner_var;",
"data_events.perf_submit(ctx, data_events_value, sizeof(*data_events_value));",
R"(bpf_trace_printk("var: %d\n", var);)",
"return 0;",
"}",
"int probe_return(struct pt_regs* ctx) {",
"uint32_t key = bpf_get_current_pid_tgid() >> 32;",
"int retval = (int)PT_REGS_RC(ctx);",
"test.delete(&key);",
"return 0;",
"}"};
std::vector<std::string> bcc_code_lines = absl::StrSplit(bcc_code, "\n");
EXPECT_THAT(bcc_code_lines, ElementsAreArray(expected_code_lines));
}
} // namespace dynamic_tracing
} // namespace stirling
} // namespace px
| 41.612033 | 98 | 0.414568 | hangqiu |
2d60b4d8b1d0f74b28dd9ab79ee33c3a8aad5d31 | 8,456 | cc | C++ | examples/mp.cc | kaishengyao/cnn | a034b837e88f82bd8adf2c5b0a5defb26fd52096 | [
"Apache-2.0"
] | 16 | 2015-09-10T07:50:50.000Z | 2017-09-17T03:02:38.000Z | examples/mp.cc | kaishengyao/cnn | a034b837e88f82bd8adf2c5b0a5defb26fd52096 | [
"Apache-2.0"
] | null | null | null | examples/mp.cc | kaishengyao/cnn | a034b837e88f82bd8adf2c5b0a5defb26fd52096 | [
"Apache-2.0"
] | 10 | 2015-09-08T12:43:13.000Z | 2018-09-26T07:32:47.000Z | #include "cnn/cnn.h"
#include "cnn/training.h"
#include "cnn/expr.h"
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/algorithm/string.hpp>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/shm.h>
#include <iostream>
#include <fstream>
#include <vector>
#include <utility>
#include <sstream>
#include <random>
using namespace std;
using namespace cnn;
using namespace cnn::expr;
struct SharedObject {
cnn::real m;
cnn::real b;
cnn::real loss;
cnn::real temp_m;
cnn::real temp_b;
};
typedef pair<cnn::real, cnn::real> Datum;
const unsigned num_children = 4;
SharedObject* shared_memory = nullptr;
cnn::real ReadReal(int pipe) {
cnn::real v;
read(pipe, &v, sizeof(cnn::real));
return v;
}
void WriteReal(int pipe, cnn::real v) {
write(pipe, &v, sizeof(cnn::real));
}
template <typename T>
void WriteIntVector(int pipe, const vector<T>& vec) {
unsigned length = vec.size();
write(pipe, &length, sizeof(unsigned));
for (T v : vec) {
write(pipe, &v, sizeof(T));
}
}
template<typename T>
vector<T> ReadIntVector(int pipe) {
unsigned length;
read(pipe, &length, sizeof(unsigned));
vector<T> vec(length);
for (unsigned i = 0; i < length; ++i) {
read(pipe, &vec[i], sizeof(T));
}
return vec;
}
cnn::real Mean(const vector<cnn::real>& values) {
return accumulate(values.begin(), values.end(), 0.0) / values.size();
}
struct Workload {
pid_t pid;
int c2p[2]; // Child to parent pipe
int p2c[2]; // Parent to child pipe
};
struct ModelParameters {
Parameters* m;
Parameters* b;
};
void BuildComputationGraph(ComputationGraph& cg, ModelParameters& model_parameters, cnn::real* x_value, cnn::real* y_value) {
Expression m = parameter(cg, model_parameters.m);
Expression b = parameter(cg, model_parameters.b);
Expression x = input(cg, x_value);
Expression y_star = input(cg, y_value);
Expression y = m * x + b;
Expression loss = squared_distance(y, y_star);
}
vector<Datum> ReadData(string filename) {
vector<Datum> data;
ifstream fs(filename);
if (!fs.is_open()) {
cerr << "ERROR: Unable to open " << filename << endl;
exit(1);
}
string line;
while (getline(fs, line)) {
if (line.size() > 0 && line[0] == '#') {
continue;
}
vector<string> parts;
boost::split(parts, line, boost::is_any_of("\t"));
data.push_back(make_pair(atof(parts[0].c_str()), atof(parts[1].c_str())));
}
return data;
}
unsigned SpawnChildren(vector<Workload>& workloads) {
assert (workloads.size() == num_children);
pid_t pid;
unsigned cid;
for (cid = 0; cid < num_children; ++cid) {
pid = fork();
if (pid == -1) {
cerr << "Fork failed. Exiting ...";
return 1;
}
else if (pid == 0) {
// children shouldn't continue looping
break;
}
workloads[cid].pid = pid;
}
return cid;
}
int RunChild(unsigned cid, ComputationGraph& cg, Trainer* trainer, vector<Workload>& workloads,
const vector<Datum>& data, cnn::real& x_value, cnn::real& y_value, ModelParameters& model_params) {
assert (cid >= 0 && cid < num_children);
while (true) {
// Check if the parent wants us to exit
bool cont = false;
read(workloads[cid].p2c[0], &cont, sizeof(bool));
if (!cont) {
break;
}
// Read in our workload and update our local model
vector<unsigned> indices = ReadIntVector<unsigned>(workloads[cid].p2c[0]);
TensorTools::SetElements(model_params.m->values, {shared_memory->m});
TensorTools::SetElements(model_params.b->values, {shared_memory->b});
cnn::real loss = 0;
for (unsigned i : indices) {
assert (i < data.size());
auto p = data[i];
x_value = get<0>(p);
y_value = get<1>(p);
loss += as_scalar(cg.forward());
cg.backward();
trainer->update(1.0);
}
loss /= indices.size();
// Get our final values of each parameter and send them back to the parent,
// along with the current loss value
cnn::real m = as_scalar(model_params.m->values);
cnn::real b = as_scalar(model_params.b->values);
shared_memory->temp_m += m;
shared_memory->temp_b += b;
shared_memory->loss += loss;
/*write(workloads[cid].c2p[1], (char*)&m, sizeof(cnn::real));
write(workloads[cid].c2p[1], (char*)&b, sizeof(cnn::real));
write(workloads[cid].c2p[1], (char*)&loss, sizeof(cnn::real));*/
WriteReal(workloads[cid].c2p[1], 0.0);
}
return 0;
}
void RunParent(vector<Datum>& data, vector<Workload>& workloads, ModelParameters& model_params, Trainer* trainer) {
shared_memory->m = TensorTools::AccessElement(model_params.m->values, {0, 0});
shared_memory->b = TensorTools::AccessElement(model_params.b->values, {0, 0});
for (unsigned iter = 0; iter < 10; ++iter) {
shared_memory->loss = 0.0;
shared_memory->temp_m = 0.0;
shared_memory->temp_b = 0.0;
/*vector<cnn::real> m_values;
vector<cnn::real> b_values;
vector<cnn::real> loss_values;*/
for(unsigned cid = 0; cid < num_children; ++cid) {
unsigned start = (unsigned)(1.0 * cid / num_children * data.size() + 0.5);
unsigned end = (unsigned)(1.0 * (cid + 1) / num_children * data.size() + 0.5);
vector<unsigned> indices;
indices.reserve(end - start);
for (unsigned i = start; i < end; ++i) {
indices.push_back(i);
}
bool cont = true;
write(workloads[cid].p2c[1], &cont, sizeof(bool));
WriteIntVector(workloads[cid].p2c[1], indices);
/*cnn::real m = ReadReal(workloads[cid].c2p[0]);
cnn::real b = ReadReal(workloads[cid].c2p[0]);
cnn::real loss = ReadReal(workloads[cid].c2p[0]);
m_values.push_back(m);
b_values.push_back(b);
loss_values.push_back(loss);*/
}
for(unsigned cid = 0; cid < num_children; ++cid) {
ReadReal(workloads[cid].c2p[0]);
}
/*cnn::real m = Mean(m_values);
cnn::real b = 0.0;
cnn::real loss = 0.0;
for (unsigned i = 0; i < m_values.size(); ++i) {
b += b_values[i];
loss += loss_values[i];
}
b /= b_values.size();*/
shared_memory->m = shared_memory->temp_m / num_children;
shared_memory->b = shared_memory->temp_b / num_children;
// Update parameters to use the new m and b values
//TensorTools::SetElements(model_params.m->values, {m});
//TensorTools::SetElements(model_params.b->values, {b});
trainer->update_epoch();
//cerr << shared_memory->m << "\t" << iter << "\t" << "loss = " << loss << "\tm = " << m << "\tb = " << b << endl;
cerr << iter << "\t" << "loss = " << shared_memory->loss << "\tm = " << shared_memory->m << "\tb = " << shared_memory->b << endl;
}
// Kill all children one by one and wait for them to exit
for (unsigned cid = 0; cid < num_children; ++cid) {
bool cont = false;
write(workloads[cid].p2c[1], &cont, sizeof(cont));
wait(NULL);
}
}
int main(int argc, char** argv) {
cnn::Initialize(argc, argv);
if (argc < 2) {
cerr << "Usage: " << argv[0] << " data.txt" << endl;
cerr << "Where data.txt contains tab-delimited pairs of cnn::reals." << endl;
return 1;
}
vector<Datum> data = ReadData(argv[1]);
vector<Workload> workloads(num_children);
Model model;
AdamTrainer sgd(&model, 0.0);
ComputationGraph cg;
cnn::real x_value, y_value;
Parameters* m_param = model.add_parameters({1, 1});
Parameters* b_param = model.add_parameters({1});
ModelParameters model_params = {m_param, b_param};
BuildComputationGraph(cg, model_params, &x_value, &y_value);
unsigned shm_size = 1024;
assert (sizeof(SharedObject) < shm_size);
key_t shm_key = ftok("/home/austinma/shared", 'R');
if (shm_key == -1) {
cerr << "Unable to get shared memory key" << endl;
return 1;
}
int shm_id = shmget(shm_key, shm_size, 0644 | IPC_CREAT);
if (shm_id == -1) {
cerr << "Unable to create shared memory" << endl;
return 1;
}
void* shm_p = shmat(shm_id, nullptr, 0);
if (shm_p == (void*)-1) {
cerr << "Unable to get shared memory pointer";
return 1;
}
shared_memory = (SharedObject*)shm_p;
for (unsigned cid = 0; cid < num_children; cid++) {
pipe(workloads[cid].p2c);
pipe(workloads[cid].c2p);
}
unsigned cid = SpawnChildren(workloads);
if (cid < num_children) {
return RunChild(cid, cg, &sgd, workloads, data, x_value, y_value, model_params);
}
else {
RunParent(data, workloads, model_params, &sgd);
}
}
| 29.158621 | 133 | 0.629849 | kaishengyao |
2d60f1eced8922d5835cff41a6435663e471a182 | 6,771 | cc | C++ | chromium/components/html_viewer/ax_provider_impl_unittest.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | chromium/components/html_viewer/ax_provider_impl_unittest.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | chromium/components/html_viewer/ax_provider_impl_unittest.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | // 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/html_viewer/ax_provider_impl.h"
#include <stddef.h>
#include <stdint.h>
#include <utility>
#include "base/bind.h"
#include "base/message_loop/message_loop.h"
#include "components/html_viewer/blink_platform_impl.h"
#include "components/scheduler/renderer/renderer_scheduler.h"
#include "gin/v8_initializer.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/WebKit/public/platform/WebData.h"
#include "third_party/WebKit/public/platform/WebURL.h"
#include "third_party/WebKit/public/web/WebFrameClient.h"
#include "third_party/WebKit/public/web/WebKit.h"
#include "third_party/WebKit/public/web/WebLocalFrame.h"
#include "third_party/WebKit/public/web/WebView.h"
#include "third_party/WebKit/public/web/WebViewClient.h"
#include "url/gurl.h"
using blink::WebData;
using blink::WebLocalFrame;
using blink::WebFrameClient;
using blink::WebURL;
using blink::WebView;
using blink::WebViewClient;
using mojo::Array;
using mojo::AxNode;
using mojo::AxNodePtr;
namespace {
class TestWebFrameClient : public WebFrameClient {
public:
~TestWebFrameClient() override {}
void didStopLoading() override {
base::MessageLoop::current()->QuitWhenIdle();
}
};
class TestWebViewClient : public WebViewClient {
public:
bool allowsBrokenNullLayerTreeView() const override { return true; }
virtual ~TestWebViewClient() {}
};
class AxProviderImplTest : public testing::Test {
public:
AxProviderImplTest()
: message_loop_(new base::MessageLoopForUI()),
renderer_scheduler_(scheduler::RendererScheduler::Create()) {
#if defined(V8_USE_EXTERNAL_STARTUP_DATA)
gin::V8Initializer::LoadV8Snapshot();
gin::V8Initializer::LoadV8Natives();
#endif
blink::initialize(
new html_viewer::BlinkPlatformImpl(nullptr, nullptr,
renderer_scheduler_.get()));
}
~AxProviderImplTest() override {
renderer_scheduler_->Shutdown();
message_loop_.reset();
blink::shutdown();
}
private:
scoped_ptr<base::MessageLoopForUI> message_loop_;
scoped_ptr<scheduler::RendererScheduler> renderer_scheduler_;
};
struct NodeCatcher {
void OnNodes(Array<AxNodePtr> nodes) { this->nodes = std::move(nodes); }
Array<AxNodePtr> nodes;
};
AxNodePtr CreateNode(int id,
int parent_id,
int next_sibling_id,
const mojo::RectPtr& bounds,
const std::string& url,
const std::string& text) {
AxNodePtr node(AxNode::New());
node->id = id;
node->parent_id = parent_id;
node->next_sibling_id = next_sibling_id;
node->bounds = bounds.Clone();
if (!url.empty()) {
node->link = mojo::AxLink::New();
node->link->url = url;
}
if (!text.empty()) {
node->text = mojo::AxText::New();
node->text->content = text;
}
return node;
}
} // namespace
TEST_F(AxProviderImplTest, Basic) {
TestWebViewClient web_view_client;
TestWebFrameClient web_frame_client;
WebView* view = WebView::create(&web_view_client);
view->setMainFrame(WebLocalFrame::create(blink::WebTreeScopeType::Document,
&web_frame_client));
view->mainFrame()->loadHTMLString(
WebData(
"<html><body>foo<a "
"href='http://monkey.net'>bar</a>baz</body></html>"),
WebURL(GURL("http://someplace.net")));
base::MessageLoop::current()->Run();
mojo::AxProviderPtr service_ptr;
html_viewer::AxProviderImpl ax_provider_impl(view,
mojo::GetProxy(&service_ptr));
NodeCatcher catcher;
ax_provider_impl.GetTree(
base::Bind(&NodeCatcher::OnNodes, base::Unretained(&catcher)));
std::map<uint32_t, AxNode*> lookup;
for (size_t i = 0; i < catcher.nodes.size(); ++i) {
auto& node = catcher.nodes[i];
lookup[node->id] = node.get();
}
typedef decltype(lookup)::value_type MapEntry;
auto is_link = [](MapEntry pair) { return !pair.second->link.is_null(); };
auto is_text = [](MapEntry pair, const char* content) {
return !pair.second->text.is_null() &&
pair.second->text->content.To<std::string>() == content;
};
auto is_foo = [&is_text](MapEntry pair) { return is_text(pair, "foo"); };
auto is_bar = [&is_text](MapEntry pair) { return is_text(pair, "bar"); };
auto is_baz = [&is_text](MapEntry pair) { return is_text(pair, "baz"); };
EXPECT_EQ(1, std::count_if(lookup.begin(), lookup.end(), is_link));
EXPECT_EQ(1, std::count_if(lookup.begin(), lookup.end(), is_foo));
EXPECT_EQ(1, std::count_if(lookup.begin(), lookup.end(), is_bar));
EXPECT_EQ(1, std::count_if(lookup.begin(), lookup.end(), is_baz));
auto root = lookup[1u];
auto link = std::find_if(lookup.begin(), lookup.end(), is_link)->second;
auto foo = std::find_if(lookup.begin(), lookup.end(), is_foo)->second;
auto bar = std::find_if(lookup.begin(), lookup.end(), is_bar)->second;
auto baz = std::find_if(lookup.begin(), lookup.end(), is_baz)->second;
// Test basic content of each node. The properties we copy (like parent_id)
// here are tested differently below.
EXPECT_TRUE(CreateNode(root->id, 0, 0, root->bounds, "", "")->Equals(*root));
EXPECT_TRUE(CreateNode(foo->id, foo->parent_id, 0, foo->bounds, "", "foo")
->Equals(*foo));
EXPECT_TRUE(CreateNode(bar->id, bar->parent_id, 0, bar->bounds, "", "bar")
->Equals(*bar));
EXPECT_TRUE(CreateNode(baz->id, baz->parent_id, 0, baz->bounds, "", "baz")
->Equals(*baz));
EXPECT_TRUE(CreateNode(link->id,
link->parent_id,
link->next_sibling_id,
link->bounds,
"http://monkey.net/",
"")->Equals(*link));
auto is_descendant_of = [&lookup](uint32_t id, uint32_t ancestor) {
for (; (id = lookup[id]->parent_id) != 0;) {
if (id == ancestor)
return true;
}
return false;
};
EXPECT_TRUE(is_descendant_of(bar->id, link->id));
for (auto pair : lookup) {
AxNode* node = pair.second;
if (node != root)
EXPECT_TRUE(is_descendant_of(node->id, 1u));
if (node != link && node != foo && node != bar && node != baz) {
EXPECT_TRUE(CreateNode(node->id,
node->parent_id,
node->next_sibling_id,
node->bounds,
"",
""));
}
}
// TODO(aa): Test bounds.
// TODO(aa): Test sibling ordering of foo/bar/baz.
view->close();
}
| 34.025126 | 79 | 0.635061 | wedataintelligence |
2d618233e5b4b3acea0715f34078fd454d4e0443 | 6,098 | cc | C++ | content/renderer/history_serialization.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | content/renderer/history_serialization.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | content/renderer/history_serialization.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // 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 "content/renderer/history_serialization.h"
#include <stddef.h>
#include <algorithm>
#include "base/strings/nullable_string16.h"
#include "content/common/page_state_serialization.h"
#include "content/public/common/page_state.h"
#include "content/renderer/history_entry.h"
#include "content/renderer/loader/web_url_request_util.h"
#include "third_party/blink/public/platform/web_data.h"
#include "third_party/blink/public/platform/web_float_point.h"
#include "third_party/blink/public/platform/web_http_body.h"
#include "third_party/blink/public/platform/web_point.h"
#include "third_party/blink/public/platform/web_string.h"
#include "third_party/blink/public/platform/web_vector.h"
#include "third_party/blink/public/web/web_history_item.h"
#include "third_party/blink/public/web/web_serialized_script_value.h"
using blink::WebData;
using blink::WebHTTPBody;
using blink::WebHistoryItem;
using blink::WebSerializedScriptValue;
using blink::WebString;
using blink::WebVector;
namespace content {
namespace {
void ToOptionalString16Vector(
const WebVector<WebString>& input,
std::vector<base::Optional<base::string16>>* output) {
output->reserve(output->size() + input.size());
for (size_t i = 0; i < input.size(); ++i)
output->emplace_back(WebString::ToOptionalString16(input[i]));
}
void GenerateFrameStateFromItem(const WebHistoryItem& item,
ExplodedFrameState* state) {
state->url_string = WebString::ToOptionalString16(item.UrlString());
state->referrer = WebString::ToOptionalString16(item.GetReferrer());
state->referrer_policy = item.GetReferrerPolicy();
state->target = WebString::ToOptionalString16(item.Target());
if (!item.StateObject().IsNull()) {
state->state_object =
WebString::ToOptionalString16(item.StateObject().ToString());
}
state->scroll_restoration_type = item.ScrollRestorationType();
state->visual_viewport_scroll_offset = item.VisualViewportScrollOffset();
state->scroll_offset = item.GetScrollOffset();
state->item_sequence_number = item.ItemSequenceNumber();
state->document_sequence_number = item.DocumentSequenceNumber();
state->page_scale_factor = item.PageScaleFactor();
state->did_save_scroll_or_scale_state = item.DidSaveScrollOrScaleState();
ToOptionalString16Vector(item.GetDocumentState(), &state->document_state);
state->http_body.http_content_type =
WebString::ToOptionalString16(item.HttpContentType());
const WebHTTPBody& http_body = item.HttpBody();
if (!http_body.IsNull()) {
state->http_body.request_body = GetRequestBodyForWebHTTPBody(http_body);
state->http_body.contains_passwords = http_body.ContainsPasswordData();
}
blink::ScrollAnchorData anchor = item.GetScrollAnchorData();
state->scroll_anchor_selector =
WebString::ToOptionalString16(anchor.selector_);
state->scroll_anchor_offset = anchor.offset_;
state->scroll_anchor_simhash = anchor.simhash_;
}
void RecursivelyGenerateHistoryItem(const ExplodedFrameState& state,
HistoryEntry::HistoryNode* node) {
WebHistoryItem item;
item.Initialize();
item.SetURLString(WebString::FromUTF16(state.url_string));
item.SetReferrer(WebString::FromUTF16(state.referrer), state.referrer_policy);
item.SetTarget(WebString::FromUTF16(state.target));
if (state.state_object) {
item.SetStateObject(WebSerializedScriptValue::FromString(
WebString::FromUTF16(*state.state_object)));
}
WebVector<WebString> document_state(state.document_state.size());
std::transform(state.document_state.begin(), state.document_state.end(),
document_state.begin(),
[](const base::Optional<base::string16>& s) {
return WebString::FromUTF16(s);
});
item.SetDocumentState(document_state);
item.SetScrollRestorationType(state.scroll_restoration_type);
if (state.did_save_scroll_or_scale_state) {
item.SetVisualViewportScrollOffset(state.visual_viewport_scroll_offset);
item.SetScrollOffset(state.scroll_offset);
item.SetPageScaleFactor(state.page_scale_factor);
}
// These values are generated at WebHistoryItem construction time, and we
// only want to override those new values with old values if the old values
// are defined. A value of 0 means undefined in this context.
if (state.item_sequence_number)
item.SetItemSequenceNumber(state.item_sequence_number);
if (state.document_sequence_number)
item.SetDocumentSequenceNumber(state.document_sequence_number);
item.SetHTTPContentType(
WebString::FromUTF16(state.http_body.http_content_type));
if (state.http_body.request_body != nullptr) {
item.SetHTTPBody(
GetWebHTTPBodyForRequestBody(*state.http_body.request_body));
}
item.SetScrollAnchorData({WebString::FromUTF16(state.scroll_anchor_selector),
state.scroll_anchor_offset,
state.scroll_anchor_simhash});
node->set_item(item);
for (size_t i = 0; i < state.children.size(); ++i)
RecursivelyGenerateHistoryItem(state.children[i], node->AddChild());
}
} // namespace
PageState SingleHistoryItemToPageState(const WebHistoryItem& item) {
ExplodedPageState state;
ToOptionalString16Vector(item.GetReferencedFilePaths(),
&state.referenced_files);
GenerateFrameStateFromItem(item, &state.top);
std::string encoded_data;
EncodePageState(state, &encoded_data);
return PageState::CreateFromEncodedData(encoded_data);
}
std::unique_ptr<HistoryEntry> PageStateToHistoryEntry(
const PageState& page_state) {
ExplodedPageState state;
if (!DecodePageState(page_state.ToEncodedData(), &state))
return std::unique_ptr<HistoryEntry>();
std::unique_ptr<HistoryEntry> entry(new HistoryEntry());
RecursivelyGenerateHistoryItem(state.top, entry->root_history_node());
return entry;
}
} // namespace content
| 40.118421 | 80 | 0.751066 | zipated |
2d64f0ae05019f03d46947f4a61b6a43c61e0572 | 1,622 | cpp | C++ | poj-3255/poj-3255.cpp | rusucosmin/Cplusplus | 0e95cd01d20b22404aa4166c71d5a9e834a5a21b | [
"MIT"
] | 11 | 2015-08-29T13:41:22.000Z | 2020-01-08T20:34:06.000Z | poj-3255/poj-3255.cpp | rusucosmin/Cplusplus | 0e95cd01d20b22404aa4166c71d5a9e834a5a21b | [
"MIT"
] | null | null | null | poj-3255/poj-3255.cpp | rusucosmin/Cplusplus | 0e95cd01d20b22404aa4166c71d5a9e834a5a21b | [
"MIT"
] | 5 | 2016-01-20T18:17:01.000Z | 2019-10-30T11:57:15.000Z | #include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>
#include <string.h>
using namespace std;
const int maxn = 5005;
const long long oo = (1LL << 60);
int n, m;
long long dist[maxn], dist2[maxn];
bitset <maxn> inq;
vector <pair<int, long long> > g[maxn];
inline void bellmanford() {
for(int i = 1 ; i <= n ; ++ i)
dist[i] = dist2[i] = oo;
queue <int> q;
q.push(1);
inq[1] = 0;
dist[1] = 0;
while(!q.empty()) {
int node = q.front();
q.pop();
inq[node] = 0;
for(vector <pair<int, long long> > :: iterator it = g[node].begin() ; it != g[node].end() ; ++ it) {
if(dist[it->first] > dist[node] + it->second) {
dist2[it->first] = dist[it->first];
dist[it->first] = dist[node] + it->second;
if(inq[it->first])
continue;
q.push(it->first);
inq[it->first] = 1;
}
else if(dist2[it->first] > dist[node] + it->second && dist[it->first] < dist[node] + it->second) {
dist2[it->first] = dist[node] + it->second;
if(inq[it->first])
continue;
q.push(it->first);
inq[it->first] = 1;
}
if(dist2[it->first] > dist2[node] + it->second) {
dist2[it->first] = dist2[node] + it->second;
if(inq[it->first])
continue;
inq[it->first] = 1;
q.push(it->first);
}
}
}
cout << dist2[n] << '\n';
}
int main() {
#ifndef ONLINE_JUDGE
freopen("poj-3255.in", "r", stdin);
freopen("poj-3255.out", "w", stdout);
#endif
cin >> n >> m;
for(int i = 1 ; i <= m ; ++ i) {
int x, y;
long long z;
cin >> x >> y >> z;
g[x].push_back(make_pair(y, z));
g[y].push_back(make_pair(x, z));
}
bellmanford();
}
| 22.527778 | 102 | 0.555487 | rusucosmin |
2d69f8d87d1ae27ea07aa88742e616f842578904 | 2,969 | cpp | C++ | hexl/eltwise/eltwise-cmp-add.cpp | tgonzalez89-intel/hexl | 352e9ed14cb615defa33e4768d156eea3413361a | [
"Apache-2.0"
] | 136 | 2021-03-26T15:24:31.000Z | 2022-03-30T07:50:15.000Z | hexl/eltwise/eltwise-cmp-add.cpp | tgonzalez89-intel/hexl | 352e9ed14cb615defa33e4768d156eea3413361a | [
"Apache-2.0"
] | 24 | 2021-04-03T06:10:47.000Z | 2022-03-24T03:34:50.000Z | hexl/eltwise/eltwise-cmp-add.cpp | tgonzalez89-intel/hexl | 352e9ed14cb615defa33e4768d156eea3413361a | [
"Apache-2.0"
] | 27 | 2021-04-01T07:50:11.000Z | 2022-03-22T00:54:23.000Z | // Copyright (C) 2020-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
#include "hexl/eltwise/eltwise-cmp-add.hpp"
#include "eltwise/eltwise-cmp-add-avx512.hpp"
#include "eltwise/eltwise-cmp-add-internal.hpp"
#include "hexl/logging/logging.hpp"
#include "hexl/number-theory/number-theory.hpp"
#include "hexl/util/check.hpp"
#include "util/cpu-features.hpp"
namespace intel {
namespace hexl {
void EltwiseCmpAdd(uint64_t* result, const uint64_t* operand1, uint64_t n,
CMPINT cmp, uint64_t bound, uint64_t diff) {
HEXL_CHECK(result != nullptr, "Require result != nullptr");
HEXL_CHECK(operand1 != nullptr, "Require operand1 != nullptr");
HEXL_CHECK(n != 0, "Require n != 0");
HEXL_CHECK(diff != 0, "Require diff != 0");
#ifdef HEXL_HAS_AVX512DQ
if (has_avx512dq) {
EltwiseCmpAddAVX512(result, operand1, n, cmp, bound, diff);
return;
}
#endif
EltwiseCmpAddNative(result, operand1, n, cmp, bound, diff);
}
void EltwiseCmpAddNative(uint64_t* result, const uint64_t* operand1, uint64_t n,
CMPINT cmp, uint64_t bound, uint64_t diff) {
HEXL_CHECK(result != nullptr, "Require result != nullptr");
HEXL_CHECK(operand1 != nullptr, "Require operand1 != nullptr");
HEXL_CHECK(n != 0, "Require n != 0");
HEXL_CHECK(diff != 0, "Require diff != 0");
switch (cmp) {
case CMPINT::EQ: {
for (size_t i = 0; i < n; ++i) {
if (operand1[i] == bound) {
result[i] = operand1[i] + diff;
} else {
result[i] = operand1[i];
}
}
break;
}
case CMPINT::LT:
for (size_t i = 0; i < n; ++i) {
if (operand1[i] < bound) {
result[i] = operand1[i] + diff;
} else {
result[i] = operand1[i];
}
}
break;
case CMPINT::LE:
for (size_t i = 0; i < n; ++i) {
if (operand1[i] <= bound) {
result[i] = operand1[i] + diff;
} else {
result[i] = operand1[i];
}
}
break;
case CMPINT::FALSE:
for (size_t i = 0; i < n; ++i) {
result[i] = operand1[i];
}
break;
case CMPINT::NE:
for (size_t i = 0; i < n; ++i) {
if (operand1[i] != bound) {
result[i] = operand1[i] + diff;
} else {
result[i] = operand1[i];
}
}
break;
case CMPINT::NLT:
for (size_t i = 0; i < n; ++i) {
if (operand1[i] >= bound) {
result[i] = operand1[i] + diff;
} else {
result[i] = operand1[i];
}
}
break;
case CMPINT::NLE:
for (size_t i = 0; i < n; ++i) {
if (operand1[i] > bound) {
result[i] = operand1[i] + diff;
} else {
result[i] = operand1[i];
}
}
break;
case CMPINT::TRUE:
for (size_t i = 0; i < n; ++i) {
result[i] = operand1[i] + diff;
}
break;
}
}
} // namespace hexl
} // namespace intel
| 26.990909 | 80 | 0.534187 | tgonzalez89-intel |
062231383872e4d1289bb030778b03619543b79d | 5,365 | cpp | C++ | tc 160+/WarTransportation.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | 3 | 2015-05-25T06:24:37.000Z | 2016-09-10T07:58:00.000Z | tc 160+/WarTransportation.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | null | null | null | tc 160+/WarTransportation.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | 5 | 2015-05-25T06:24:40.000Z | 2021-08-19T19:22:29.000Z | #include <algorithm>
#include <cassert>
#include <cstdio>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <cstring>
#include <queue>
#include <numeric>
using namespace std;
vector<string> cutUp(const string &s, const string &delim=" ") {
int lastPos = 0, pos = 0;
vector<string> ret;
while (pos+delim.size() <= s.size()) {
if (s.substr(pos, delim.size()) == delim) {
ret.push_back(s.substr(lastPos, pos-lastPos));
pos += (int)delim.size()-1;
lastPos = pos+1;
}
++pos;
}
if (lastPos < (int)s.size())
ret.push_back(s.substr(lastPos));
return ret;
}
int worst[100];
const int inf = 1234567890;
int dist[100];
int min_dist(int u, const vector< vector< pair<int, int> > > &G, bool special=false) {
for (int i=0; i<100; ++i) {
dist[i] = inf;
}
dist[u] = 0;
priority_queue< pair<int, int> > Q;
Q.push(make_pair(0, u));
while (!Q.empty()) {
const pair<int, int> t = Q.top();
Q.pop();
u = t.second;
int d = -t.first;
if (d > dist[u]) {
continue;
}
for (int i=0; i<(int)G[u].size(); ++i) {
const int v = G[u][i].first;
const int c = G[u][i].second;
int nd = d + c;
if (special) {
nd = max(nd, worst[v]);
}
if (nd < dist[v]) {
dist[v] = nd;
Q.push(make_pair(-nd, v));
}
}
}
return special ? dist[0] : dist[1];
}
class WarTransportation {
public:
int messenger(int n, vector <string> highways) {
string s = accumulate(highways.begin(), highways.end(), string());
vector<string> t = cutUp(s, ",");
vector< vector< pair<int, int> > > G(n, vector< pair<int, int> >());
for (int i=0; i<(int)t.size(); ++i) {
int a, b, c;
sscanf(t[i].c_str(), "%d %d %d", &a, &b, &c);
G[a-1].push_back(make_pair(b-1, c));
}
worst[1] = 0;
for (int i=0; i<n; ++i) {
if (i == 1) {
continue;
}
if (G[i].size() == 0) {
worst[i] = inf;
} else {
worst[i] = 0;
for (int j=0; j<(int)G[i].size(); ++j) {
const int real = G[i][j].second;
G[i][j].second = inf;
worst[i] = max(worst[i], min_dist(i, G));
G[i][j].second = real;
}
}
}
vector< vector< pair<int, int> > > G2(n, vector< pair<int, int> >());
for (int i=0; i<n; ++i) {
for (int j=0; j<(int)G[i].size(); ++j) {
G2[G[i][j].first].push_back(make_pair(i, G[i][j].second));
}
}
int sol = min_dist(1, G2, true);
return sol<inf ? sol : -1;
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { int Arg0 = 3; string Arr1[] = {"1 2 1,1 3 2,3 2 3"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 5; verify_case(0, Arg2, messenger(Arg0, Arg1)); }
void test_case_1() { int Arg0 = 8; string Arr1[] = {"1 3 1,1 4 1,3 5 1,4 5 1,5 6 1,6 7 1,6 8 1,7 2 1,",
"8 2 1"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = -1; verify_case(1, Arg2, messenger(Arg0, Arg1)); }
void test_case_2() { int Arg0 = 4; string Arr1[] = {"1 3 1,1 3 2,3 2 1,1 4 1,4 2 1"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = -1; verify_case(2, Arg2, messenger(Arg0, Arg1)); }
void test_case_3() { int Arg0 = 4; string Arr1[] = {"1 3 1,3 2 1,1 4 1,4 2 1,3 4 1"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 3; verify_case(3, Arg2, messenger(Arg0, Arg1)); }
void test_case_4() { int Arg0 = 20; string Arr1[] = {"1 13 3,13 4 7,4 3 4,3 10 8,10 18 9,18 12 6,12 2 3,",
"1 17 6,17 13 6,13 9 4,9 10 8,10 7 2,7 5 5,5 19 9,1",
"9 14 6,14 16 9,16 18 7,18 15 5,15 20 3,20 12 9,12 ",
"8 4,8 11 3,11 4 1,4 3 7,3 2 3,20 10 2,1 18 2,16 19",
" 9,4 15 9,13 15 6"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 23; verify_case(4, Arg2, messenger(Arg0, Arg1)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
WarTransportation ___test;
___test.run_test(-1);
}
// END CUT HERE
| 36.746575 | 309 | 0.492265 | ibudiselic |
06253bb386f03467ec4f60d95810e6005dc63aa9 | 438 | cc | C++ | ash/webui/media_app_ui/url_constants.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | ash/webui/media_app_ui/url_constants.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | ash/webui/media_app_ui/url_constants.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2019 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 "ash/webui/media_app_ui/url_constants.h"
namespace ash {
const char kChromeUIMediaAppHost[] = "media-app";
const char kChromeUIMediaAppURL[] = "chrome://media-app/";
const char kChromeUIMediaAppGuestURL[] = "chrome-untrusted://media-app/";
} // namespace ash
| 31.285714 | 73 | 0.748858 | zealoussnow |
062659df20586aaa6578ddfc73c49fe26669c9a2 | 55,471 | cpp | C++ | activemq-cpp/src/test/decaf/util/concurrent/locks/AbstractQueuedSynchronizerTest.cpp | novomatic-tech/activemq-cpp | d6f76ede90d21b7ee2f0b5d4648e440e66d63003 | [
"Apache-2.0"
] | 87 | 2015-03-02T17:58:20.000Z | 2022-02-11T02:52:52.000Z | activemq-cpp/src/test/decaf/util/concurrent/locks/AbstractQueuedSynchronizerTest.cpp | korena/activemq-cpp | e4c56ee4fec75c3284b9167a7215e2d80a9a4dc4 | [
"Apache-2.0"
] | 3 | 2017-05-10T13:16:08.000Z | 2019-01-23T20:21:53.000Z | activemq-cpp/src/test/decaf/util/concurrent/locks/AbstractQueuedSynchronizerTest.cpp | korena/activemq-cpp | e4c56ee4fec75c3284b9167a7215e2d80a9a4dc4 | [
"Apache-2.0"
] | 71 | 2015-04-28T06:04:04.000Z | 2022-03-15T13:34:06.000Z | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "AbstractQueuedSynchronizerTest.h"
#include <decaf/lang/System.h>
#include <decaf/lang/Thread.h>
#include <decaf/lang/Runnable.h>
#include <decaf/util/Date.h>
#include <decaf/util/concurrent/TimeUnit.h>
#include <decaf/util/concurrent/locks/LockSupport.h>
#include <decaf/util/concurrent/locks/AbstractQueuedSynchronizer.h>
using namespace std;
using namespace decaf;
using namespace decaf::lang;
using namespace decaf::lang::exceptions;
using namespace decaf::util;
using namespace decaf::util::concurrent;
using namespace decaf::util::concurrent::locks;
////////////////////////////////////////////////////////////////////////////////
namespace {
class TestMutex : public AbstractQueuedSynchronizer {
public:
TestMutex() {}
virtual ~TestMutex() {}
bool isHeldExclusively() const { return getState() == 1; }
bool tryAcquire(int acquires) {
//CPPUNIT_ASSERT(acquires == 1);
return compareAndSetState(0, 1);
}
bool tryRelease(int releases) {
if (getState() == 0) {
throw IllegalMonitorStateException();
}
setState(0);
return true;
}
AbstractQueuedSynchronizer::ConditionObject* newCondition() {
return AbstractQueuedSynchronizer::createDefaultConditionObject();
}
};
class BooleanLatch : public AbstractQueuedSynchronizer {
public:
BooleanLatch() {}
virtual ~BooleanLatch() {}
bool isSignalled() { return getState() != 0; }
int tryAcquireShared(int ignore) {
return isSignalled()? 1 : -1;
}
bool tryReleaseShared(int ignore) {
setState(1);
return true;
}
};
/**
* A runnable calling acquireInterruptibly
*/
class InterruptibleSyncRunnable : public Runnable {
private:
AbstractQueuedSynchronizerTest* parent;
TestMutex* mutex;
private:
InterruptibleSyncRunnable(const InterruptibleSyncRunnable&);
InterruptibleSyncRunnable operator= (const InterruptibleSyncRunnable&);
public:
InterruptibleSyncRunnable(AbstractQueuedSynchronizerTest* parent,
TestMutex* mutex) : Runnable(), parent(parent), mutex(mutex) {}
virtual ~InterruptibleSyncRunnable() {}
virtual void run() {
try {
mutex->acquireInterruptibly(1);
} catch(InterruptedException& success) {
} catch(Exception& ex) {
parent->threadUnexpectedException(ex);
} catch(std::exception& stdex) {
parent->threadUnexpectedException();
}
}
};
class InterruptedSyncRunnable : public Runnable {
private:
AbstractQueuedSynchronizerTest* parent;
TestMutex* mutex;
private:
InterruptedSyncRunnable(const InterruptedSyncRunnable&);
InterruptedSyncRunnable operator= (const InterruptedSyncRunnable&);
public:
InterruptedSyncRunnable(AbstractQueuedSynchronizerTest* parent,
TestMutex* mutex) : Runnable(), parent(parent), mutex(mutex) {}
virtual ~InterruptedSyncRunnable() {}
void run() {
try {
mutex->acquireInterruptibly(1);
parent->threadFail("Should have been interrupted.");
} catch(InterruptedException& success) {
} catch(Exception& ex) {
parent->threadUnexpectedException(ex);
} catch(std::exception& stdex) {
parent->threadUnexpectedException();
}
}
};
}
////////////////////////////////////////////////////////////////////////////////
AbstractQueuedSynchronizerTest::AbstractQueuedSynchronizerTest() {
}
////////////////////////////////////////////////////////////////////////////////
AbstractQueuedSynchronizerTest::~AbstractQueuedSynchronizerTest() {
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testIsHeldExclusively() {
TestMutex rl;
CPPUNIT_ASSERT(!rl.isHeldExclusively());
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testAcquire() {
TestMutex rl;
rl.acquire(1);
CPPUNIT_ASSERT(rl.isHeldExclusively());
rl.release(1);
CPPUNIT_ASSERT(!rl.isHeldExclusively());
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testTryAcquire() {
TestMutex rl;
CPPUNIT_ASSERT(rl.tryAcquire(1));
CPPUNIT_ASSERT(rl.isHeldExclusively());
rl.release(1);
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testhasQueuedThreads() {
TestMutex mutex;
InterruptedSyncRunnable iSyncRun1(this, &mutex);
InterruptibleSyncRunnable iSyncRun2(this, &mutex);
Thread t1(&iSyncRun1);
Thread t2(&iSyncRun2);
try {
CPPUNIT_ASSERT(!mutex.hasQueuedThreads());
mutex.acquire(1);
t1.start();
Thread::sleep(SHORT_DELAY_MS);
CPPUNIT_ASSERT(mutex.hasQueuedThreads());
t2.start();
Thread::sleep(SHORT_DELAY_MS);
CPPUNIT_ASSERT(mutex.hasQueuedThreads());
t1.interrupt();
Thread::sleep(SHORT_DELAY_MS);
CPPUNIT_ASSERT(mutex.hasQueuedThreads());
mutex.release(1);
Thread::sleep(SHORT_DELAY_MS);
CPPUNIT_ASSERT(!mutex.hasQueuedThreads());
t1.join();
t2.join();
} catch(Exception& e){
unexpectedException();
}
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testIsQueuedNPE() {
TestMutex mutex;
try {
mutex.isQueued(NULL);
shouldThrow();
} catch(NullPointerException& success) {
}
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testIsQueued() {
TestMutex mutex;
InterruptedSyncRunnable iSyncRun1(this, &mutex);
InterruptibleSyncRunnable iSyncRun2(this, &mutex);
Thread t1(&iSyncRun1);
Thread t2(&iSyncRun2);
try {
CPPUNIT_ASSERT(!mutex.isQueued(&t1));
CPPUNIT_ASSERT(!mutex.isQueued(&t2));
mutex.acquire(1);
t1.start();
Thread::sleep(SHORT_DELAY_MS);
CPPUNIT_ASSERT(mutex.isQueued(&t1));
t2.start();
Thread::sleep(SHORT_DELAY_MS);
CPPUNIT_ASSERT(mutex.isQueued(&t1));
CPPUNIT_ASSERT(mutex.isQueued(&t2));
t1.interrupt();
Thread::sleep(SHORT_DELAY_MS);
CPPUNIT_ASSERT(!mutex.isQueued(&t1));
CPPUNIT_ASSERT(mutex.isQueued(&t2));
mutex.release(1);
Thread::sleep(SHORT_DELAY_MS);
CPPUNIT_ASSERT(!mutex.isQueued(&t1));
Thread::sleep(SHORT_DELAY_MS);
CPPUNIT_ASSERT(!mutex.isQueued(&t2));
t1.join();
t2.join();
} catch(Exception& e){
unexpectedException();
} catch(std::exception& ex) {
unexpectedException();
} catch(...) {
unexpectedException();
}
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testGetFirstQueuedThread() {
TestMutex mutex;
InterruptedSyncRunnable iSyncRun1(this, &mutex);
InterruptibleSyncRunnable iSyncRun2(this, &mutex);
Thread t1(&iSyncRun1);
Thread t2(&iSyncRun2);
try {
CPPUNIT_ASSERT(mutex.getFirstQueuedThread() == NULL);
mutex.acquire(1);
t1.start();
Thread::sleep(SHORT_DELAY_MS);
CPPUNIT_ASSERT_EQUAL(&t1, mutex.getFirstQueuedThread());
t2.start();
Thread::sleep(SHORT_DELAY_MS);
CPPUNIT_ASSERT_EQUAL(&t1, mutex.getFirstQueuedThread());
t1.interrupt();
Thread::sleep(SHORT_DELAY_MS);
Thread::sleep(SHORT_DELAY_MS);
CPPUNIT_ASSERT_EQUAL(&t2, mutex.getFirstQueuedThread());
mutex.release(1);
Thread::sleep(SHORT_DELAY_MS);
CPPUNIT_ASSERT(mutex.getFirstQueuedThread() == NULL);
t1.join();
t2.join();
} catch(Exception& e){
unexpectedException();
}
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testHasContended() {
TestMutex mutex;
InterruptedSyncRunnable iSyncRun1(this, &mutex);
InterruptibleSyncRunnable iSyncRun2(this, &mutex);
Thread t1(&iSyncRun1);
Thread t2(&iSyncRun2);
try {
CPPUNIT_ASSERT(!mutex.hasContended());
mutex.acquire(1);
t1.start();
Thread::sleep(SHORT_DELAY_MS);
CPPUNIT_ASSERT(mutex.hasContended());
t2.start();
Thread::sleep(SHORT_DELAY_MS);
CPPUNIT_ASSERT(mutex.hasContended());
t1.interrupt();
Thread::sleep(SHORT_DELAY_MS);
CPPUNIT_ASSERT(mutex.hasContended());
mutex.release(1);
Thread::sleep(SHORT_DELAY_MS);
CPPUNIT_ASSERT(mutex.hasContended());
t1.join();
t2.join();
} catch(Exception& e){
unexpectedException();
}
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testGetQueuedThreads() {
TestMutex mutex;
InterruptedSyncRunnable iSyncRun1(this, &mutex);
InterruptibleSyncRunnable iSyncRun2(this, &mutex);
Thread t1(&iSyncRun1);
Thread t2(&iSyncRun2);
try {
CPPUNIT_ASSERT(std::auto_ptr<Collection<Thread*> >(mutex.getQueuedThreads())->isEmpty());
mutex.acquire(1);
CPPUNIT_ASSERT(std::auto_ptr<Collection<Thread*> >(mutex.getQueuedThreads())->isEmpty());
t1.start();
Thread::sleep(SHORT_DELAY_MS);
CPPUNIT_ASSERT(std::auto_ptr<Collection<Thread*> >(mutex.getQueuedThreads())->contains(&t1));
t2.start();
Thread::sleep(SHORT_DELAY_MS);
CPPUNIT_ASSERT(std::auto_ptr<Collection<Thread*> >(mutex.getQueuedThreads())->contains(&t1));
CPPUNIT_ASSERT(std::auto_ptr<Collection<Thread*> >(mutex.getQueuedThreads())->contains(&t2));
t1.interrupt();
Thread::sleep(SHORT_DELAY_MS);
CPPUNIT_ASSERT(!std::auto_ptr<Collection<Thread*> >(mutex.getQueuedThreads())->contains(&t1));
CPPUNIT_ASSERT(std::auto_ptr<Collection<Thread*> >(mutex.getQueuedThreads())->contains(&t2));
mutex.release(1);
Thread::sleep(SHORT_DELAY_MS);
CPPUNIT_ASSERT(std::auto_ptr<Collection<Thread*> >(mutex.getQueuedThreads())->isEmpty());
t1.join();
t2.join();
} catch(Exception& e){
unexpectedException();
}
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testGetExclusiveQueuedThreads() {
TestMutex mutex;
InterruptedSyncRunnable iSyncRun1(this, &mutex);
InterruptibleSyncRunnable iSyncRun2(this, &mutex);
Thread t1(&iSyncRun1);
Thread t2(&iSyncRun2);
try {
CPPUNIT_ASSERT(std::auto_ptr<Collection<Thread*> >(mutex.getExclusiveQueuedThreads())->isEmpty());
mutex.acquire(1);
CPPUNIT_ASSERT(std::auto_ptr<Collection<Thread*> >(mutex.getExclusiveQueuedThreads())->isEmpty());
t1.start();
Thread::sleep(SHORT_DELAY_MS);
CPPUNIT_ASSERT(std::auto_ptr<Collection<Thread*> >(mutex.getExclusiveQueuedThreads())->contains(&t1));
t2.start();
Thread::sleep(SHORT_DELAY_MS);
CPPUNIT_ASSERT(std::auto_ptr<Collection<Thread*> >(mutex.getExclusiveQueuedThreads())->contains(&t1));
CPPUNIT_ASSERT(std::auto_ptr<Collection<Thread*> >(mutex.getExclusiveQueuedThreads())->contains(&t2));
t1.interrupt();
Thread::sleep(SHORT_DELAY_MS);
CPPUNIT_ASSERT(!std::auto_ptr<Collection<Thread*> >(mutex.getExclusiveQueuedThreads())->contains(&t1));
CPPUNIT_ASSERT(std::auto_ptr<Collection<Thread*> >(mutex.getExclusiveQueuedThreads())->contains(&t2));
mutex.release(1);
Thread::sleep(SHORT_DELAY_MS);
CPPUNIT_ASSERT(std::auto_ptr<Collection<Thread*> >(mutex.getExclusiveQueuedThreads())->isEmpty());
t1.join();
t2.join();
} catch(Exception& e){
unexpectedException();
}
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testGetSharedQueuedThreads() {
TestMutex mutex;
InterruptedSyncRunnable iSyncRun1(this, &mutex);
InterruptibleSyncRunnable iSyncRun2(this, &mutex);
Thread t1(&iSyncRun1);
Thread t2(&iSyncRun2);
try {
CPPUNIT_ASSERT(std::auto_ptr<Collection<Thread*> >(mutex.getSharedQueuedThreads())->isEmpty());
mutex.acquire(1);
CPPUNIT_ASSERT(std::auto_ptr<Collection<Thread*> >(mutex.getSharedQueuedThreads())->isEmpty());
t1.start();
Thread::sleep(SHORT_DELAY_MS);
CPPUNIT_ASSERT(std::auto_ptr<Collection<Thread*> >(mutex.getSharedQueuedThreads())->isEmpty());
t2.start();
Thread::sleep(SHORT_DELAY_MS);
CPPUNIT_ASSERT(std::auto_ptr<Collection<Thread*> >(mutex.getSharedQueuedThreads())->isEmpty());
t1.interrupt();
Thread::sleep(SHORT_DELAY_MS);
CPPUNIT_ASSERT(std::auto_ptr<Collection<Thread*> >(mutex.getSharedQueuedThreads())->isEmpty());
mutex.release(1);
Thread::sleep(SHORT_DELAY_MS);
CPPUNIT_ASSERT(std::auto_ptr<Collection<Thread*> >(mutex.getSharedQueuedThreads())->isEmpty());
t1.join();
t2.join();
} catch(Exception& e){
unexpectedException();
}
}
////////////////////////////////////////////////////////////////////////////////
namespace {
class TestInterruptedException2Runnable : public Runnable {
private:
TestMutex* mutex;
AbstractQueuedSynchronizerTest* parent;
private:
TestInterruptedException2Runnable(const TestInterruptedException2Runnable&);
TestInterruptedException2Runnable operator= (const TestInterruptedException2Runnable&);
public:
TestInterruptedException2Runnable(AbstractQueuedSynchronizerTest* parent, TestMutex* mutex) :
Runnable(), mutex(mutex), parent(parent) {}
virtual ~TestInterruptedException2Runnable() {}
virtual void run() {
try {
mutex->tryAcquireNanos(1, AbstractQueuedSynchronizerTest::MEDIUM_DELAY_MS * 1000 * 1000);
parent->threadShouldThrow();
} catch(InterruptedException& success){}
}
};
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testInterruptedException2() {
TestMutex mutex;
mutex.acquire(1);
TestInterruptedException2Runnable run(this, &mutex);
Thread t(&run);
try {
t.start();
t.interrupt();
} catch(Exception& e){
unexpectedException();
}
}
////////////////////////////////////////////////////////////////////////////////
namespace {
class TestTryAcquireWhenSyncedRunnable : public Runnable {
private:
TestMutex* mutex;
AbstractQueuedSynchronizerTest* parent;
private:
TestTryAcquireWhenSyncedRunnable(const TestTryAcquireWhenSyncedRunnable&);
TestTryAcquireWhenSyncedRunnable operator= (const TestTryAcquireWhenSyncedRunnable&);
public:
TestTryAcquireWhenSyncedRunnable(AbstractQueuedSynchronizerTest* parent, TestMutex* mutex) :
Runnable(), mutex(mutex), parent(parent) {}
virtual ~TestTryAcquireWhenSyncedRunnable() {}
virtual void run() {
parent->threadAssertFalse(mutex->tryAcquire(1));
}
};
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testTryAcquireWhenSynced() {
TestMutex mutex;
mutex.acquire(1);
TestTryAcquireWhenSyncedRunnable run(this, &mutex);
Thread t(&run);
try {
t.start();
t.join();
mutex.release(1);
} catch(Exception& e){
unexpectedException();
}
}
////////////////////////////////////////////////////////////////////////////////
namespace {
class TestAcquireNanosTimeoutRunnable : public Runnable {
private:
TestMutex* mutex;
AbstractQueuedSynchronizerTest* parent;
private:
TestAcquireNanosTimeoutRunnable(const TestAcquireNanosTimeoutRunnable&);
TestAcquireNanosTimeoutRunnable operator= (const TestAcquireNanosTimeoutRunnable&);
public:
TestAcquireNanosTimeoutRunnable(AbstractQueuedSynchronizerTest* parent, TestMutex* mutex) :
Runnable(), mutex(mutex), parent(parent) {}
virtual ~TestAcquireNanosTimeoutRunnable() {}
virtual void run() {
try {
parent->threadAssertFalse(mutex->tryAcquireNanos(1, 1000 * 1000));
} catch(Exception& ex) {
parent->threadUnexpectedException();
}
}
};
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testAcquireNanosTimeout() {
TestMutex mutex;
mutex.acquire(1);
TestAcquireNanosTimeoutRunnable run(this, &mutex);
Thread t(&run);
try {
t.start();
t.join();
mutex.release(1);
} catch(Exception& e){
unexpectedException();
}
}
////////////////////////////////////////////////////////////////////////////////
namespace {
class TestGetStateRunnable : public Runnable {
private:
TestMutex* mutex;
AbstractQueuedSynchronizerTest* parent;
private:
TestGetStateRunnable(const TestGetStateRunnable&);
TestGetStateRunnable operator= (const TestGetStateRunnable&);
public:
TestGetStateRunnable(AbstractQueuedSynchronizerTest* parent, TestMutex* mutex) :
Runnable(), mutex(mutex), parent(parent) {}
virtual ~TestGetStateRunnable() {}
virtual void run() {
mutex->acquire(1);
try {
Thread::sleep(AbstractQueuedSynchronizerTest::SMALL_DELAY_MS);
} catch(Exception& e) {
parent->threadUnexpectedException();
}
mutex->release(1);
}
};
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testGetState() {
TestMutex mutex;
mutex.acquire(1);
CPPUNIT_ASSERT(mutex.isHeldExclusively());
mutex.release(1);
CPPUNIT_ASSERT(!mutex.isHeldExclusively());
TestGetStateRunnable run(this, &mutex);
Thread t(&run);
try {
t.start();
Thread::sleep(SHORT_DELAY_MS);
CPPUNIT_ASSERT(mutex.isHeldExclusively());
t.join();
CPPUNIT_ASSERT(!mutex.isHeldExclusively());
} catch(Exception& e){
unexpectedException();
}
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testAcquireInterruptibly1() {
TestMutex mutex;
mutex.acquire(1);
InterruptedSyncRunnable iSyncRun(this, &mutex);
Thread t(&iSyncRun);
try {
t.start();
Thread::sleep(SHORT_DELAY_MS);
t.interrupt();
Thread::sleep(SHORT_DELAY_MS);
mutex.release(1);
t.join();
} catch(Exception& e){
unexpectedException();
}
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testAcquireInterruptibly2() {
TestMutex mutex;
try {
mutex.acquireInterruptibly(1);
} catch(Exception& e) {
unexpectedException();
}
InterruptedSyncRunnable iSyncRun(this, &mutex);
Thread t(&iSyncRun);
try {
t.start();
t.interrupt();
CPPUNIT_ASSERT(mutex.isHeldExclusively());
t.join();
} catch(Exception& e){
unexpectedException();
}
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testOwns() {
TestMutex mutex;
AbstractQueuedSynchronizer::ConditionObject* c = mutex.newCondition();
TestMutex mutex2;
CPPUNIT_ASSERT(mutex.owns(c));
CPPUNIT_ASSERT(!mutex2.owns(c));
delete c;
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testAwaitIllegalMonitor() {
TestMutex mutex;
AbstractQueuedSynchronizer::ConditionObject* c = mutex.newCondition();
try {
c->await();
shouldThrow();
} catch(IllegalMonitorStateException& success) {
} catch(Exception& ex) {
unexpectedException();
}
delete c;
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testSignalIllegalMonitor() {
TestMutex mutex;
AbstractQueuedSynchronizer::ConditionObject* c = mutex.newCondition();
try {
c->signal();
shouldThrow();
} catch(IllegalMonitorStateException& success) {
} catch(Exception& ex) {
unexpectedException();
}
delete c;
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testAwaitNanosTimeout() {
TestMutex mutex;
AbstractQueuedSynchronizer::ConditionObject* c = mutex.newCondition();
try {
mutex.acquire(1);
long long t = c->awaitNanos(100);
CPPUNIT_ASSERT(t <= 0);
mutex.release(1);
} catch(Exception& ex) {
unexpectedException();
}
delete c;
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testAwaitTimeout() {
TestMutex mutex;
AbstractQueuedSynchronizer::ConditionObject* c = mutex.newCondition();
try {
mutex.acquire(1);
CPPUNIT_ASSERT(!c->await(SHORT_DELAY_MS, TimeUnit::MILLISECONDS));
mutex.release(1);
} catch(Exception& ex) {
unexpectedException();
}
delete c;
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testAwaitUntilTimeout() {
TestMutex mutex;
AbstractQueuedSynchronizer::ConditionObject* c = mutex.newCondition();
try {
mutex.acquire(1);
Date d;
CPPUNIT_ASSERT(!c->awaitUntil((d.getTime() + 15)));
mutex.release(1);
} catch(Exception& ex) {
unexpectedException();
}
delete c;
}
////////////////////////////////////////////////////////////////////////////////
namespace {
class TestAwaitRunnable : public Runnable {
private:
TestMutex* mutex;
AbstractQueuedSynchronizerTest* parent;
Condition* cond;
private:
TestAwaitRunnable(const TestAwaitRunnable&);
TestAwaitRunnable operator= (const TestAwaitRunnable&);
public:
TestAwaitRunnable(AbstractQueuedSynchronizerTest* parent, TestMutex* mutex, Condition* cond) :
Runnable(), mutex(mutex), parent(parent), cond(cond) {}
virtual ~TestAwaitRunnable() {}
virtual void run() {
try {
mutex->acquire(1);
cond->await();
mutex->release(1);
}
catch(InterruptedException& e) {
parent->threadUnexpectedException();
}
}
};
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testAwait() {
TestMutex mutex;
AbstractQueuedSynchronizer::ConditionObject* c = mutex.newCondition();
TestAwaitRunnable run(this, &mutex, c);
Thread t(&run);
try {
t.start();
Thread::sleep(SHORT_DELAY_MS);
mutex.acquire(1);
c->signal();
mutex.release(1);
t.join(SHORT_DELAY_MS);
CPPUNIT_ASSERT(!t.isAlive());
}
catch (Exception& ex) {
unexpectedException();
}
delete c;
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testHasWaitersNPE() {
TestMutex mutex;
try {
mutex.hasWaiters(NULL);
shouldThrow();
} catch(NullPointerException& success) {
} catch(Exception& ex) {
unexpectedException();
}
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testGetWaitQueueLengthNPE() {
TestMutex mutex;
try {
mutex.getWaitQueueLength(NULL);
shouldThrow();
} catch(NullPointerException& success) {
} catch(Exception& ex) {
unexpectedException();
}
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testGetWaitingThreadsNPE() {
TestMutex mutex;
try {
mutex.getWaitingThreads(NULL);
shouldThrow();
} catch(NullPointerException& success) {
} catch(Exception& ex) {
unexpectedException();
}
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testHasWaitersIAE() {
TestMutex mutex;
AbstractQueuedSynchronizer::ConditionObject* c = (mutex.newCondition());
TestMutex mutex2;
try {
mutex2.hasWaiters(c);
shouldThrow();
} catch(IllegalArgumentException& success) {
} catch(Exception& ex) {
unexpectedException();
}
delete c;
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testHasWaitersIMSE() {
TestMutex mutex;
AbstractQueuedSynchronizer::ConditionObject* c = (mutex.newCondition());
try {
mutex.hasWaiters(c);
shouldThrow();
} catch(IllegalMonitorStateException& success) {
} catch(Exception& ex) {
unexpectedException();
}
delete c;
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testGetWaitQueueLengthIAE() {
TestMutex mutex;
AbstractQueuedSynchronizer::ConditionObject* c = (mutex.newCondition());
TestMutex mutex2;
try {
mutex2.getWaitQueueLength(c);
shouldThrow();
} catch(IllegalArgumentException& success) {
} catch(Exception& ex) {
unexpectedException();
}
delete c;
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testGetWaitQueueLengthIMSE() {
TestMutex mutex;
AbstractQueuedSynchronizer::ConditionObject* c = (mutex.newCondition());
try {
mutex.getWaitQueueLength(c);
shouldThrow();
} catch(IllegalMonitorStateException& success) {
} catch(Exception& ex) {
unexpectedException();
}
delete c;
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testGetWaitingThreadsIAE() {
TestMutex mutex;
AbstractQueuedSynchronizer::ConditionObject* c = (mutex.newCondition());
TestMutex mutex2;
try {
mutex2.getWaitingThreads(c);
shouldThrow();
} catch(IllegalArgumentException& success) {
} catch(Exception& ex) {
unexpectedException();
}
delete c;
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testGetWaitingThreadsIMSE() {
TestMutex mutex;
AbstractQueuedSynchronizer::ConditionObject* c = (mutex.newCondition());
try {
mutex.getWaitingThreads(c);
shouldThrow();
} catch(IllegalMonitorStateException& success) {
} catch(Exception& ex) {
unexpectedException();
}
delete c;
}
////////////////////////////////////////////////////////////////////////////////
namespace {
class TestHasWaitersRunnable : public Runnable {
private:
TestMutex* mutex;
AbstractQueuedSynchronizerTest* parent;
AbstractQueuedSynchronizer::ConditionObject* cond;
private:
TestHasWaitersRunnable(const TestHasWaitersRunnable&);
TestHasWaitersRunnable operator= (const TestHasWaitersRunnable&);
public:
TestHasWaitersRunnable(AbstractQueuedSynchronizerTest* parent, TestMutex* mutex, AbstractQueuedSynchronizer::ConditionObject* cond) :
Runnable(), mutex(mutex), parent(parent), cond(cond) {}
virtual ~TestHasWaitersRunnable() {}
virtual void run() {
try {
mutex->acquire(1);
parent->threadAssertFalse(mutex->hasWaiters(cond));
parent->threadAssertEquals(0, mutex->getWaitQueueLength(cond));
cond->await();
mutex->release(1);
}
catch(InterruptedException& e) {
parent->threadUnexpectedException();
}
}
};
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testHasWaiters() {
TestMutex mutex;
AbstractQueuedSynchronizer::ConditionObject* c = mutex.newCondition();
TestHasWaitersRunnable run(this, &mutex, c);
Thread t(&run);
try {
t.start();
Thread::sleep( SHORT_DELAY_MS);
mutex.acquire(1);
CPPUNIT_ASSERT(mutex.hasWaiters(c));
CPPUNIT_ASSERT_EQUAL(1, mutex.getWaitQueueLength(c));
c->signal();
mutex.release(1);
Thread::sleep(SHORT_DELAY_MS);
mutex.acquire(1);
CPPUNIT_ASSERT(!mutex.hasWaiters(c));
CPPUNIT_ASSERT_EQUAL(0, mutex.getWaitQueueLength(c));
mutex.release(1);
t.join(SHORT_DELAY_MS);
CPPUNIT_ASSERT(!t.isAlive());
} catch(Exception& ex) {
unexpectedException();
}
delete c;
}
////////////////////////////////////////////////////////////////////////////////
namespace {
class testGetWaitQueueLengthRunnable1 : public Runnable {
private:
TestMutex* mutex;
AbstractQueuedSynchronizerTest* parent;
AbstractQueuedSynchronizer::ConditionObject* cond;
private:
testGetWaitQueueLengthRunnable1(const testGetWaitQueueLengthRunnable1&);
testGetWaitQueueLengthRunnable1 operator= (const testGetWaitQueueLengthRunnable1&);
public:
testGetWaitQueueLengthRunnable1(AbstractQueuedSynchronizerTest* parent, TestMutex* mutex, AbstractQueuedSynchronizer::ConditionObject* cond) :
Runnable(), mutex(mutex), parent(parent), cond(cond) {}
virtual ~testGetWaitQueueLengthRunnable1() {}
virtual void run() {
try {
mutex->acquire(1);
parent->threadAssertFalse(mutex->hasWaiters(cond));
parent->threadAssertEquals(0, mutex->getWaitQueueLength(cond));
cond->await();
mutex->release(1);
}
catch(InterruptedException& e) {
parent->threadUnexpectedException();
}
}
};
class testGetWaitQueueLengthRunnable2 : public Runnable {
private:
TestMutex* mutex;
AbstractQueuedSynchronizerTest* parent;
AbstractQueuedSynchronizer::ConditionObject* cond;
private:
testGetWaitQueueLengthRunnable2(const testGetWaitQueueLengthRunnable2&);
testGetWaitQueueLengthRunnable2 operator= (const testGetWaitQueueLengthRunnable2&);
public:
testGetWaitQueueLengthRunnable2(AbstractQueuedSynchronizerTest* parent, TestMutex* mutex, AbstractQueuedSynchronizer::ConditionObject* cond) :
Runnable(), mutex(mutex), parent(parent), cond(cond) {}
virtual ~testGetWaitQueueLengthRunnable2() {}
virtual void run() {
try {
mutex->acquire(1);
parent->threadAssertTrue(mutex->hasWaiters(cond));
parent->threadAssertEquals(1, mutex->getWaitQueueLength(cond));
cond->await();
mutex->release(1);
}
catch(InterruptedException& e) {
parent->threadUnexpectedException();
}
}
};
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testGetWaitQueueLength() {
TestMutex mutex;
AbstractQueuedSynchronizer::ConditionObject* c = mutex.newCondition();
testGetWaitQueueLengthRunnable1 run1(this, &mutex, c);
Thread t1(&run1);
testGetWaitQueueLengthRunnable2 run2(this, &mutex, c);
Thread t2(&run2);
try {
t1.start();
Thread::sleep(SHORT_DELAY_MS);
t2.start();
Thread::sleep(SHORT_DELAY_MS);
mutex.acquire(1);
CPPUNIT_ASSERT(mutex.hasWaiters(c));
CPPUNIT_ASSERT_EQUAL(2, mutex.getWaitQueueLength(c));
c->signalAll();
mutex.release(1);
Thread::sleep(SHORT_DELAY_MS);
mutex.acquire(1);
CPPUNIT_ASSERT(!mutex.hasWaiters(c));
CPPUNIT_ASSERT_EQUAL(0, mutex.getWaitQueueLength(c));
mutex.release(1);
t1.join(SHORT_DELAY_MS);
t2.join(SHORT_DELAY_MS);
CPPUNIT_ASSERT(!t1.isAlive());
CPPUNIT_ASSERT(!t2.isAlive());
}
catch (Exception& ex) {
unexpectedException();
}
delete c;
}
////////////////////////////////////////////////////////////////////////////////
namespace {
class TestGetWaitingThreadsRunnable1 : public Runnable {
private:
TestMutex* mutex;
AbstractQueuedSynchronizerTest* parent;
AbstractQueuedSynchronizer::ConditionObject* cond;
private:
TestGetWaitingThreadsRunnable1(const TestGetWaitingThreadsRunnable1&);
TestGetWaitingThreadsRunnable1 operator= (const TestGetWaitingThreadsRunnable1&);
public:
TestGetWaitingThreadsRunnable1(AbstractQueuedSynchronizerTest* parent, TestMutex* mutex, AbstractQueuedSynchronizer::ConditionObject* cond) :
Runnable(), mutex(mutex), parent(parent), cond(cond) {}
virtual ~TestGetWaitingThreadsRunnable1() {}
virtual void run() {
try {
mutex->acquire(1);
std::auto_ptr<Collection<Thread*> > list(mutex->getWaitingThreads(cond));
parent->threadAssertTrue(list->isEmpty());
cond->await();
mutex->release(1);
}
catch(InterruptedException& e) {
parent->threadUnexpectedException();
}
}
};
class TestGetWaitingThreadsRunnable2 : public Runnable {
private:
TestMutex* mutex;
AbstractQueuedSynchronizerTest* parent;
AbstractQueuedSynchronizer::ConditionObject* cond;
private:
TestGetWaitingThreadsRunnable2(const TestGetWaitingThreadsRunnable2&);
TestGetWaitingThreadsRunnable2 operator= (const TestGetWaitingThreadsRunnable2&);
public:
TestGetWaitingThreadsRunnable2(AbstractQueuedSynchronizerTest* parent, TestMutex* mutex, AbstractQueuedSynchronizer::ConditionObject* cond) :
Runnable(), mutex(mutex), parent(parent), cond(cond) {}
virtual ~TestGetWaitingThreadsRunnable2() {}
virtual void run() {
try {
mutex->acquire(1);
std::auto_ptr<Collection<Thread*> > list(mutex->getWaitingThreads(cond));
parent->threadAssertFalse(list->isEmpty());
cond->await();
mutex->release(1);
}
catch(InterruptedException& e) {
parent->threadUnexpectedException();
}
}
};
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testGetWaitingThreads() {
TestMutex mutex;
AbstractQueuedSynchronizer::ConditionObject* c = mutex.newCondition();
TestGetWaitingThreadsRunnable1 run1(this, &mutex, c);
Thread t1(&run1);
TestGetWaitingThreadsRunnable2 run2(this, &mutex, c);
Thread t2(&run2);
try {
mutex.acquire(1);
CPPUNIT_ASSERT(std::auto_ptr<Collection<Thread*> >(mutex.getWaitingThreads(c))->isEmpty());
mutex.release(1);
t1.start();
Thread::sleep(SHORT_DELAY_MS);
t2.start();
Thread::sleep(SHORT_DELAY_MS);
mutex.acquire(1);
CPPUNIT_ASSERT(mutex.hasWaiters(c));
CPPUNIT_ASSERT(std::auto_ptr<Collection<Thread*> >(mutex.getWaitingThreads(c))->contains(&t1));
CPPUNIT_ASSERT(std::auto_ptr<Collection<Thread*> >(mutex.getWaitingThreads(c))->contains(&t2));
c->signalAll();
mutex.release(1);
Thread::sleep(SHORT_DELAY_MS);
mutex.acquire(1);
CPPUNIT_ASSERT(!mutex.hasWaiters(c));
CPPUNIT_ASSERT(std::auto_ptr<Collection<Thread*> >(mutex.getWaitingThreads(c))->isEmpty());
mutex.release(1);
t1.join(SHORT_DELAY_MS);
t2.join(SHORT_DELAY_MS);
CPPUNIT_ASSERT(!t1.isAlive());
CPPUNIT_ASSERT(!t2.isAlive());
}
catch (Exception& ex) {
unexpectedException();
}
delete c;
}
////////////////////////////////////////////////////////////////////////////////
namespace {
class TestAwaitUninterruptiblyRunnable : public Runnable {
private:
TestMutex* mutex;
AbstractQueuedSynchronizerTest* parent;
AbstractQueuedSynchronizer::ConditionObject* cond;
private:
TestAwaitUninterruptiblyRunnable(const TestAwaitUninterruptiblyRunnable&);
TestAwaitUninterruptiblyRunnable operator= (const TestAwaitUninterruptiblyRunnable&);
public:
TestAwaitUninterruptiblyRunnable(AbstractQueuedSynchronizerTest* parent, TestMutex* mutex, AbstractQueuedSynchronizer::ConditionObject* cond) :
Runnable(), mutex(mutex), parent(parent), cond(cond) {}
virtual ~TestAwaitUninterruptiblyRunnable() {}
virtual void run() {
mutex->acquire(1);
cond->awaitUninterruptibly();
mutex->release(1);
}
};
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testAwaitUninterruptibly() {
TestMutex mutex;
AbstractQueuedSynchronizer::ConditionObject* c = mutex.newCondition();
TestAwaitUninterruptiblyRunnable run(this, &mutex, c);
Thread t(&run);
try {
t.start();
Thread::sleep(SHORT_DELAY_MS);
t.interrupt();
mutex.acquire(1);
c->signal();
mutex.release(1);
t.join(SHORT_DELAY_MS);
CPPUNIT_ASSERT(!t.isAlive());
}
catch (Exception& ex) {
unexpectedException();
}
delete c;
}
////////////////////////////////////////////////////////////////////////////////
namespace {
class TestAwaitInterruptRunnable : public Runnable {
private:
TestMutex* mutex;
AbstractQueuedSynchronizerTest* parent;
AbstractQueuedSynchronizer::ConditionObject* cond;
private:
TestAwaitInterruptRunnable(const TestAwaitInterruptRunnable&);
TestAwaitInterruptRunnable operator= (const TestAwaitInterruptRunnable&);
public:
TestAwaitInterruptRunnable(AbstractQueuedSynchronizerTest* parent, TestMutex* mutex, AbstractQueuedSynchronizer::ConditionObject* cond) :
Runnable(), mutex(mutex), parent(parent), cond(cond) {}
virtual ~TestAwaitInterruptRunnable() {}
virtual void run() {
try {
mutex->acquire(1);
cond->await();
mutex->release(1);
parent->threadShouldThrow();
} catch(InterruptedException& success) {
}
}
};
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testAwaitInterrupt() {
TestMutex mutex;
AbstractQueuedSynchronizer::ConditionObject* c = mutex.newCondition();
TestAwaitInterruptRunnable run(this, &mutex, c);
Thread t(&run);
try {
t.start();
Thread::sleep(SHORT_DELAY_MS);
t.interrupt();
t.join(SHORT_DELAY_MS);
CPPUNIT_ASSERT(!t.isAlive());
}
catch (Exception& ex) {
unexpectedException();
}
delete c;
}
////////////////////////////////////////////////////////////////////////////////
namespace {
class TestAwaitNanosInterruptRunnable : public Runnable {
private:
TestMutex* mutex;
AbstractQueuedSynchronizerTest* parent;
AbstractQueuedSynchronizer::ConditionObject* cond;
private:
TestAwaitNanosInterruptRunnable(const TestAwaitNanosInterruptRunnable&);
TestAwaitNanosInterruptRunnable operator= (const TestAwaitNanosInterruptRunnable&);
public:
TestAwaitNanosInterruptRunnable(AbstractQueuedSynchronizerTest* parent, TestMutex* mutex, AbstractQueuedSynchronizer::ConditionObject* cond) :
Runnable(), mutex(mutex), parent(parent), cond(cond) {}
virtual ~TestAwaitNanosInterruptRunnable() {}
virtual void run() {
try {
mutex->acquire(1);
cond->awaitNanos(1000 * 1000 * 1000); // 1 sec
mutex->release(1);
parent->threadShouldThrow();
} catch(InterruptedException& success) {
}
}
};
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testAwaitNanosInterrupt() {
TestMutex mutex;
AbstractQueuedSynchronizer::ConditionObject* c = mutex.newCondition();
TestAwaitNanosInterruptRunnable run(this, &mutex, c);
Thread t(&run);
try {
t.start();
Thread::sleep(SHORT_DELAY_MS);
t.interrupt();
t.join(SHORT_DELAY_MS);
CPPUNIT_ASSERT(!t.isAlive());
}
catch (Exception& ex) {
unexpectedException();
}
delete c;
}
////////////////////////////////////////////////////////////////////////////////
namespace {
class TestAwaitUntilInterruptRunnable : public Runnable {
private:
TestMutex* mutex;
AbstractQueuedSynchronizerTest* parent;
AbstractQueuedSynchronizer::ConditionObject* cond;
private:
TestAwaitUntilInterruptRunnable(const TestAwaitUntilInterruptRunnable&);
TestAwaitUntilInterruptRunnable operator= (const TestAwaitUntilInterruptRunnable&);
public:
TestAwaitUntilInterruptRunnable(AbstractQueuedSynchronizerTest* parent, TestMutex* mutex, AbstractQueuedSynchronizer::ConditionObject* cond) :
Runnable(), mutex(mutex), parent(parent), cond(cond) {}
virtual ~TestAwaitUntilInterruptRunnable() {}
virtual void run() {
try {
mutex->acquire(1);
Date d;
cond->awaitUntil((d.getTime() + 10000));
mutex->release(1);
parent->threadShouldThrow();
} catch(InterruptedException& success) {
}
}
};
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testAwaitUntilInterrupt() {
TestMutex mutex;
AbstractQueuedSynchronizer::ConditionObject* c = mutex.newCondition();
TestAwaitNanosInterruptRunnable run(this, &mutex, c);
Thread t(&run);
try {
t.start();
Thread::sleep(SHORT_DELAY_MS);
t.interrupt();
t.join(SHORT_DELAY_MS);
CPPUNIT_ASSERT(!t.isAlive());
}
catch (Exception& ex) {
unexpectedException();
}
delete c;
}
////////////////////////////////////////////////////////////////////////////////
namespace {
class TestSignalAllRunnable : public Runnable {
private:
TestMutex* mutex;
AbstractQueuedSynchronizerTest* parent;
AbstractQueuedSynchronizer::ConditionObject* cond;
private:
TestSignalAllRunnable(const TestSignalAllRunnable&);
TestSignalAllRunnable operator= (const TestSignalAllRunnable&);
public:
TestSignalAllRunnable(AbstractQueuedSynchronizerTest* parent, TestMutex* mutex, AbstractQueuedSynchronizer::ConditionObject* cond) :
Runnable(), mutex(mutex), parent(parent), cond(cond) {}
virtual ~TestSignalAllRunnable() {}
virtual void run() {
try {
mutex->acquire(1);
cond->await();
mutex->release(1);
}
catch(InterruptedException& e) {
parent->threadUnexpectedException();
}
}
};
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testSignalAll() {
TestMutex mutex;
AbstractQueuedSynchronizer::ConditionObject* c = mutex.newCondition();
TestSignalAllRunnable run1(this, &mutex, c);
Thread t1(&run1);
TestSignalAllRunnable run2(this, &mutex, c);
Thread t2(&run2);
try {
t1.start();
t2.start();
Thread::sleep(SHORT_DELAY_MS);
mutex.acquire(1);
c->signalAll();
mutex.release(1);
t1.join(SHORT_DELAY_MS);
t2.join(SHORT_DELAY_MS);
CPPUNIT_ASSERT(!t1.isAlive());
CPPUNIT_ASSERT(!t2.isAlive());
}
catch (Exception& ex) {
unexpectedException();
}
delete c;
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testToString() {
TestMutex mutex;
std::string us = mutex.toString();
CPPUNIT_ASSERT((int)(us.find("State = 0")) >= 0);
mutex.acquire(1);
std::string ls = mutex.toString();
CPPUNIT_ASSERT((int)(ls.find("State = 1")) >= 0);
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testGetStateWithReleaseShared() {
BooleanLatch l;
CPPUNIT_ASSERT(!l.isSignalled());
l.releaseShared(0);
CPPUNIT_ASSERT(l.isSignalled());
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testReleaseShared() {
BooleanLatch l;
CPPUNIT_ASSERT(!l.isSignalled());
l.releaseShared(0);
CPPUNIT_ASSERT(l.isSignalled());
l.releaseShared(0);
CPPUNIT_ASSERT(l.isSignalled());
}
////////////////////////////////////////////////////////////////////////////////
namespace {
class TestAcquireSharedInterruptiblyRunnable : public Runnable {
private:
BooleanLatch* latch;
AbstractQueuedSynchronizerTest* parent;
private:
TestAcquireSharedInterruptiblyRunnable(const TestAcquireSharedInterruptiblyRunnable&);
TestAcquireSharedInterruptiblyRunnable operator= (const TestAcquireSharedInterruptiblyRunnable&);
public:
TestAcquireSharedInterruptiblyRunnable(AbstractQueuedSynchronizerTest* parent, BooleanLatch* latch) :
Runnable(), latch(latch), parent(parent) {}
virtual ~TestAcquireSharedInterruptiblyRunnable() {}
virtual void run() {
try {
parent->threadAssertFalse(latch->isSignalled());
latch->acquireSharedInterruptibly(0);
parent->threadAssertTrue(latch->isSignalled());
} catch(InterruptedException& e) {
parent->threadUnexpectedException();
}
}
};
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testAcquireSharedInterruptibly() {
BooleanLatch l;
TestAcquireSharedInterruptiblyRunnable run(this, &l);
Thread t(&run);
try {
t.start();
CPPUNIT_ASSERT(!l.isSignalled());
Thread::sleep(SHORT_DELAY_MS);
l.releaseShared(0);
CPPUNIT_ASSERT(l.isSignalled());
t.join();
} catch (InterruptedException& e){
unexpectedException();
}
}
////////////////////////////////////////////////////////////////////////////////
namespace {
class TestAsquireSharedTimedRunnable : public Runnable {
private:
BooleanLatch* latch;
AbstractQueuedSynchronizerTest* parent;
private:
TestAsquireSharedTimedRunnable(const TestAsquireSharedTimedRunnable&);
TestAsquireSharedTimedRunnable operator= (const TestAsquireSharedTimedRunnable&);
public:
TestAsquireSharedTimedRunnable(AbstractQueuedSynchronizerTest* parent, BooleanLatch* latch) :
Runnable(), latch(latch), parent(parent) {}
virtual ~TestAsquireSharedTimedRunnable() {}
virtual void run() {
try {
parent->threadAssertFalse(latch->isSignalled());
parent->threadAssertTrue(latch->tryAcquireSharedNanos(0, AbstractQueuedSynchronizerTest::MEDIUM_DELAY_MS* 1000 * 1000));
parent->threadAssertTrue(latch->isSignalled());
} catch(InterruptedException& e) {
parent->threadUnexpectedException();
}
}
};
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testAsquireSharedTimed() {
BooleanLatch l;
TestAsquireSharedTimedRunnable run(this, &l);
Thread t(&run);
try {
t.start();
CPPUNIT_ASSERT(!l.isSignalled());
Thread::sleep(SHORT_DELAY_MS);
l.releaseShared(0);
CPPUNIT_ASSERT(l.isSignalled());
t.join();
} catch (InterruptedException& e){
unexpectedException();
}
}
////////////////////////////////////////////////////////////////////////////////
namespace {
class TestAcquireSharedInterruptiblyInterruptedExceptionRunnable : public Runnable {
private:
BooleanLatch* latch;
AbstractQueuedSynchronizerTest* parent;
private:
TestAcquireSharedInterruptiblyInterruptedExceptionRunnable(const TestAcquireSharedInterruptiblyInterruptedExceptionRunnable&);
TestAcquireSharedInterruptiblyInterruptedExceptionRunnable operator= (const TestAcquireSharedInterruptiblyInterruptedExceptionRunnable&);
public:
TestAcquireSharedInterruptiblyInterruptedExceptionRunnable(AbstractQueuedSynchronizerTest* parent, BooleanLatch* latch) :
Runnable(), latch(latch), parent(parent) {}
virtual ~TestAcquireSharedInterruptiblyInterruptedExceptionRunnable() {}
virtual void run() {
try {
parent->threadAssertFalse(latch->isSignalled());
latch->acquireSharedInterruptibly(0);
parent->threadShouldThrow();
} catch(InterruptedException& e) {
}
}
};
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testAcquireSharedInterruptiblyInterruptedException() {
BooleanLatch l;
TestAcquireSharedInterruptiblyInterruptedExceptionRunnable run(this, &l);
Thread t(&run);
t.start();
try {
CPPUNIT_ASSERT(!l.isSignalled());
t.interrupt();
t.join();
} catch (InterruptedException& e){
unexpectedException();
}
}
////////////////////////////////////////////////////////////////////////////////
namespace {
class TestAcquireSharedNanosInterruptedExceptionRunnable : public Runnable {
private:
BooleanLatch* latch;
AbstractQueuedSynchronizerTest* parent;
private:
TestAcquireSharedNanosInterruptedExceptionRunnable(const TestAcquireSharedNanosInterruptedExceptionRunnable&);
TestAcquireSharedNanosInterruptedExceptionRunnable operator= (const TestAcquireSharedNanosInterruptedExceptionRunnable&);
public:
TestAcquireSharedNanosInterruptedExceptionRunnable(AbstractQueuedSynchronizerTest* parent, BooleanLatch* latch) :
Runnable(), latch(latch), parent(parent) {}
virtual ~TestAcquireSharedNanosInterruptedExceptionRunnable() {}
virtual void run() {
try {
parent->threadAssertFalse(latch->isSignalled());
latch->tryAcquireSharedNanos(0, AbstractQueuedSynchronizerTest::SMALL_DELAY_MS* 1000 * 1000);
parent->threadShouldThrow();
} catch(InterruptedException& e) {
}
}
};
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testAcquireSharedNanosInterruptedException() {
BooleanLatch l;
TestAcquireSharedNanosInterruptedExceptionRunnable run(this, &l);
Thread t(&run);
t.start();
try {
Thread::sleep(SHORT_DELAY_MS);
CPPUNIT_ASSERT(!l.isSignalled());
t.interrupt();
t.join();
} catch (InterruptedException& e){
unexpectedException();
}
}
////////////////////////////////////////////////////////////////////////////////
namespace {
class TestAcquireSharedNanosTimeoutRunnable : public Runnable {
private:
BooleanLatch* latch;
AbstractQueuedSynchronizerTest* parent;
private:
TestAcquireSharedNanosTimeoutRunnable(const TestAcquireSharedNanosTimeoutRunnable&);
TestAcquireSharedNanosTimeoutRunnable operator= (const TestAcquireSharedNanosTimeoutRunnable&);
public:
TestAcquireSharedNanosTimeoutRunnable(AbstractQueuedSynchronizerTest* parent, BooleanLatch* latch) :
Runnable(), latch(latch), parent(parent) {}
virtual ~TestAcquireSharedNanosTimeoutRunnable() {}
virtual void run() {
try {
parent->threadAssertFalse(latch->isSignalled());
parent->threadAssertFalse(latch->tryAcquireSharedNanos(0, AbstractQueuedSynchronizerTest::SMALL_DELAY_MS* 1000 * 1000));
} catch(InterruptedException& e) {
parent->threadUnexpectedException();
}
}
};
}
////////////////////////////////////////////////////////////////////////////////
void AbstractQueuedSynchronizerTest::testAcquireSharedNanosTimeout() {
BooleanLatch l;
TestAcquireSharedNanosTimeoutRunnable run(this, &l);
Thread t(&run);
t.start();
try {
Thread::sleep( SHORT_DELAY_MS);
CPPUNIT_ASSERT(!l.isSignalled());
t.join();
} catch(InterruptedException& e) {
unexpectedException();
}
}
| 31.971758 | 151 | 0.579384 | novomatic-tech |
06286b2b18cfd53d64bd9681f7984f231baa8655 | 123,585 | cpp | C++ | tools/flang2/flang2exe/mwd.cpp | kammerdienerb/flang | 8cc4a02b94713750f09fe6b756d33daced0b4a74 | [
"Apache-2.0"
] | null | null | null | tools/flang2/flang2exe/mwd.cpp | kammerdienerb/flang | 8cc4a02b94713750f09fe6b756d33daced0b4a74 | [
"Apache-2.0"
] | null | null | null | tools/flang2/flang2exe/mwd.cpp | kammerdienerb/flang | 8cc4a02b94713750f09fe6b756d33daced0b4a74 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2000-2019, NVIDIA CORPORATION. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/** \file
* \brief mw's dump routines
*/
#include "mwd.h"
#include "error.h"
#include "machar.h"
#include "global.h"
#include "symtab.h"
#include "ilm.h"
#include "fih.h"
#include "ili.h"
#include "iliutil.h"
#include "dtypeutl.h"
#include "machreg.h"
#ifdef SOCPTRG
#include "soc.h"
#endif
#include "llutil.h"
#include "symfun.h"
static int putdtypex(DTYPE dtype, int len);
static void _printnme(int n);
static bool g_dout = true;
#if defined(HOST_WIN)
#define vsnprintf _vsnprintf
#endif
#if DEBUG
static FILE *dfile;
static int linelen = 0;
#define BUFSIZE 10000
static char BUF[BUFSIZE];
static int longlines = 1, tight = 0, nexttight = 0;
/* for debug purpuse: test if the current
* function is the one that func specifies */
int
testcurrfunc(const char* func)
{
if(strcmp(SYMNAME(GBL_CURRFUNC), func)==0)
return true;
else
return false;
}
/*
* 'full' is zero for a 'diff' dump, so things like symbol numbers,
* ili numbers, etc., are left off; this makes ili trees and symbol dumps
* that are for all intents and purposes the same look more identical.
* 'full' is 2 for an 'important things' only dump; nmptr, hashlk left off
* 'full' is 1 for full dump, everything
*/
static int full = 1;
void
dumplong(void)
{
longlines = 1;
} /* dumplong */
void
dumpshort(void)
{
longlines = 0;
} /* dumpshort */
void
dumpdiff(void)
{
full = 0;
} /* dumpdiff */
void
dumpddiff(int v)
{
full = v;
} /* dumpddiff */
static void
putit(void)
{
int l = strlen(BUF);
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
if (linelen + l >= 78 && !longlines) {
fprintf(dfile, "\n%s", BUF);
linelen = l;
} else if (linelen > 0 && nexttight) {
fprintf(dfile, "%s", BUF);
linelen += l + 1;
} else if (linelen > 0 && tight) {
fprintf(dfile, " %s", BUF);
linelen += l + 1;
} else if (linelen > 0) {
fprintf(dfile, " %s", BUF);
linelen += l + 2;
} else {
fprintf(dfile, "%s", BUF);
linelen = l;
}
nexttight = 0;
} /* putit */
static void
puttight(void)
{
int l = strlen(BUF);
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
fprintf(dfile, "%s", BUF);
linelen += l;
} /* puttight */
static void
putline(void)
{
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
if (linelen)
fprintf(dfile, "\n");
linelen = 0;
} /* putline */
void
putmwline()
{
putline();
} /* putmwline */
#include <stdarg.h>
static void
puterr(const char *fmt, ...)
{
va_list argptr;
va_start(argptr, fmt);
putline();
strcpy(BUF, "*** ");
vsnprintf(BUF + 4, BUFSIZE - 4, fmt, argptr);
strcat(BUF, " ***");
putit();
putline();
} /* puterr */
static void
appendit(void)
{
int l = strlen(BUF);
if (g_dout)
fprintf(dfile, "%s", BUF);
linelen += l;
nexttight = 0;
} /* appendit */
static void
putint(const char *s, int d)
{
if (g_dout) {
snprintf(BUF, BUFSIZE, "%s:%d", s, d);
putit();
}
} /* putint */
static void
putdouble(const char *s, double d)
{
if (g_dout) {
snprintf(BUF, BUFSIZE, "%s:%lg", s, d);
putit();
}
} /* putdouble */
static void
putbigint(const char *s, ISZ_T d)
{
snprintf(BUF, BUFSIZE, "%s:%" ISZ_PF "d", s, d);
putit();
} /* putbigint */
static void
putINT(const char *s, INT d)
{
snprintf(BUF, BUFSIZE, "%s:%ld", s, (long)d);
putit();
} /* putINT */
static void
putisz(const char *s, ISZ_T d)
{
snprintf(BUF, BUFSIZE, "%s:%" ISZ_PF "d", s, d);
putit();
} /* putisz */
static void
putISZ1(ISZ_T d)
{
snprintf(BUF, BUFSIZE, "%" ISZ_PF "d", d);
putit();
} /* putISZ1 */
static void
putintarray(const char *s, int *x, int size)
{
int i;
if (x != NULL) {
for (i = 0; i < size; ++i) {
if (x[i] != 0) {
snprintf(BUF, BUFSIZE, "%s[%d]:%8d %8x", s, i, x[i], x[i]);
x[i] = 0;
putit();
putline();
}
}
}
} /* putintarray */
static void
put1char(const char *s, char c)
{
snprintf(BUF, BUFSIZE, "%s:%c", s, c);
putit();
} /* put1char */
static void
puthex(const char *s, int d)
{
snprintf(BUF, BUFSIZE, "%s:0x%x", s, d);
putit();
} /* puthex */
static void
putnzhex(const char *s, int d)
{
if (d != 0) {
snprintf(BUF, BUFSIZE, "%s:0x%x", s, d);
putit();
}
} /* putnzhex */
static void
putnvptr(const char *s, void *d)
{
if (d) {
snprintf(BUF, BUFSIZE, "%s:%p", s, d);
putit();
}
} /* putnvptr */
static void
putnzint(const char *s, int d)
{
if (d != 0) {
snprintf(BUF, BUFSIZE, "%s:%d", s, d);
putit();
}
} /* putnzint */
static void
putnzbigint(const char *s, ISZ_T d)
{
if (d != 0) {
snprintf(BUF, BUFSIZE, "%s:%" ISZ_PF "d", s, d);
putit();
}
} /* putnzbigint */
static void
putnzINT(const char *s, INT d)
{
if (d != 0) {
snprintf(BUF, BUFSIZE, "%s:%ld", s, (long)d);
putit();
}
} /* putnzINT */
static void
putnzisz(const char *s, ISZ_T d)
{
if (d != 0) {
snprintf(BUF, BUFSIZE, "%s:%" ISZ_PF "d", s, d);
putit();
}
} /* putnzint */
static void
putnzopc(const char *s, int opc)
{
if (opc != 0) {
if (opc >= 0 && opc < N_ILI) {
snprintf(BUF, BUFSIZE, "%s:%s", s, ilis[opc].name);
} else {
snprintf(BUF, BUFSIZE, "%s:%d", s, opc);
}
putit();
}
} /* putnzopc */
static void
putedge(int d1, int d2)
{
snprintf(BUF, BUFSIZE, "%d-->%d", d1, d2);
putit();
} /* putedge */
static void
put2int(const char *s, int d1, int d2)
{
snprintf(BUF, BUFSIZE, "%s(%d:%d)", s, d1, d2);
putit();
} /* put2int */
static void
put2int1(int d1, int d2)
{
snprintf(BUF, BUFSIZE, "%d:%d", d1, d2);
putit();
} /* put2int1 */
static void
putpint(const char *s, int d)
{
put2int(s, (int)(d & 0xff), (int)(d >> 8));
} /* putpint */
void
putint1(int d)
{
snprintf(BUF, BUFSIZE, "%d", d);
putit();
} /* putint1 */
static void
putint1t(int d)
{
snprintf(BUF, BUFSIZE, "%d", d);
puttight();
} /* putint1t */
static void
putint2(const char *s, int d, const char *s2, int d2)
{
snprintf(BUF, BUFSIZE, " %s:%d,%s:%d", s, d, s2, d2);
putit();
} /* putint2 */
static int
appendint1(int d)
{
int r;
if (!g_dout) {
r = snprintf(BUF, BUFSIZE, "%d", d);
sprintf(BUF, "%s%d", BUF, d);
r = 0;
} else
r = sprintf(BUF, "%d", d);
appendit();
return r;
} /* appendint1 */
static int
appendbigint(ISZ_T d)
{
int r;
if (!g_dout) {
r = snprintf(BUF, BUFSIZE, "%" ISZ_PF "d", d);
sprintf(BUF, ("%s%" ISZ_PF "d"), BUF, d);
r = 0;
} else
r = sprintf(BUF, ("%" ISZ_PF "d"), d);
appendit();
return r;
} /* appendbigint */
static void
appendhex1(int d)
{
snprintf(BUF, BUFSIZE, "0x%x", d);
appendit();
} /* appendhex1 */
static void
putint3star(int d, int star1, const char *star1string, int star2, const char *star2string,
int star3, const char *star3string, int star4, const char *star4string)
{
if (star1 && star2 && star3 && star4) {
snprintf(BUF, BUFSIZE, "%d(%s,%s,%s,%s=%d)", d, star1string, star2string,
star3string, star4string, star4);
} else if (!star1 && star2 && star3 && star4) {
snprintf(BUF, BUFSIZE, "%d(%s,%s,%s=%d)", d, star2string, star3string,
star4string, star4);
} else if (star1 && !star2 && star3 && star4) {
snprintf(BUF, BUFSIZE, "%d(%s,%s,%s=%d)", d, star1string, star3string,
star4string, star4);
} else if (!star1 && !star2 && star3 && star4) {
snprintf(BUF, BUFSIZE, "%d(%s,%s=%d)", d, star3string, star4string, star4);
} else if (star1 && star2 && !star3 && star4) {
snprintf(BUF, BUFSIZE, "%d(%s,%s,%s=%d)", d, star1string, star2string,
star4string, star4);
} else if (!star1 && star2 && !star3 && star4) {
snprintf(BUF, BUFSIZE, "%d(%s,%s=%d)", d, star2string, star4string, star4);
} else if (star1 && !star2 && !star3 && star4) {
snprintf(BUF, BUFSIZE, "%d(%s,%s=%d)", d, star1string, star4string, star4);
} else if (!star1 && !star2 && !star3 && star4) {
snprintf(BUF, BUFSIZE, "%d(%s=%d)", d, star4string, star4);
} else if (star1 && star2 && star3 && !star4) {
snprintf(BUF, BUFSIZE, "%d(%s,%s,%s)", d, star1string, star2string,
star3string);
} else if (!star1 && star2 && star3 && !star4) {
snprintf(BUF, BUFSIZE, "%d(%s,%s)", d, star2string, star3string);
} else if (star1 && !star2 && star3 && !star4) {
snprintf(BUF, BUFSIZE, "%d(%s,%s)", d, star1string, star3string);
} else if (!star1 && !star2 && star3 && !star4) {
snprintf(BUF, BUFSIZE, "%d(%s)", d, star3string);
} else if (star1 && star2 && !star3 && !star4) {
snprintf(BUF, BUFSIZE, "%d(%s,%s)", d, star1string, star2string);
} else if (!star1 && star2 && !star3 && !star4) {
snprintf(BUF, BUFSIZE, "%d(%s)", d, star2string);
} else if (star1 && !star2 && !star3 && !star4) {
snprintf(BUF, BUFSIZE, "%d(%s)", d, star1string);
} else {
snprintf(BUF, BUFSIZE, "%d", d);
}
putit();
} /* putint3star */
static void
putbit(const char *s, int b)
{
/* single space between flags */
if (b) {
int l = strlen(s);
if (linelen + l >= 79 && !longlines) {
fprintf(dfile, "\n%s", s);
linelen = l;
} else if (linelen > 0) {
fprintf(dfile, " %s", s);
linelen += l + 1;
} else {
fprintf(dfile, "%s", s);
linelen = l;
}
}
} /* putbit */
static void
putstring(const char *s, const char *t)
{
snprintf(BUF, BUFSIZE, "%s:%s", s, t);
putit();
} /* putstring */
static void
mputchar(const char *s, char t)
{
snprintf(BUF, BUFSIZE, "%s:%c", s, t);
putit();
} /* mputchar */
static void
putnzchar(const char *s, char t)
{
if (t) {
snprintf(BUF, BUFSIZE, "%s:%c", s, t);
putit();
}
} /* putnzchar */
static void
putnstring(const char *s, const char *t)
{
if (t != NULL) {
snprintf(BUF, BUFSIZE, "%s:%s", s, t);
putit();
}
} /* putstring */
static void
putstringarray(const char *s, char **arr)
{
int i;
if (arr != NULL) {
for (i = 0; arr[i] != NULL; ++i) {
snprintf(BUF, BUFSIZE, "%s[%d]:%s", s, i, arr[i]);
putit();
}
}
} /* putstringarray */
static void
putdefarray(const char *s, char **arr)
{
int i;
if (arr != NULL) {
for (i = 0; arr[i] != NULL; i += 2) {
if (arr[i + 1] == (const char *)1) {
snprintf(BUF, BUFSIZE, "%s[%d] pred:%s", s, i, arr[i]);
} else if (arr[i + 1] == (const char *)0) {
snprintf(BUF, BUFSIZE, "%s[%d] undef:%s", s, i, arr[i]);
} else {
snprintf(BUF, BUFSIZE, "%s[%d] def:%s", s, i, arr[i]);
}
putit();
putline();
}
}
} /* putdefarray */
static void
putstring1(const char *t)
{
snprintf(BUF, BUFSIZE, "%s", t);
putit();
} /* putstring1 */
static void
putstring1t(const char *t)
{
snprintf(BUF, BUFSIZE, "%s", t);
puttight();
nexttight = 0;
} /* putstring1t */
static void
putstring1tt(const char *t)
{
snprintf(BUF, BUFSIZE, "%s", t);
puttight();
nexttight = 1;
} /* putstring1tt */
static int
appendstring1(const char *t)
{
int r;
if (!g_dout) {
strcat(BUF, t);
r = 0;
} else {
r = snprintf(BUF, BUFSIZE, "%s", t);
}
appendit();
return r;
} /* appendstring1 */
static void
putsym(const char *s, SPTR sptr)
{
if (full) {
if (sptr == NOSYM) {
snprintf(BUF, BUFSIZE, "%s:%d=%s", s, sptr, "NOSYM");
} else if (sptr > 0 && sptr < stb.stg_avail) {
snprintf(BUF, BUFSIZE, "%s:%d=%s%s", s, sptr, printname(sptr),
ADDRTKNG(sptr) ? " (&)" : "");
} else {
snprintf(BUF, BUFSIZE, "%s:%d", s, sptr);
}
} else {
if (sptr == NOSYM) {
snprintf(BUF, BUFSIZE, "%s:%s", s, "NOSYM");
} else if (sptr > 0 && sptr < stb.stg_avail) {
snprintf(BUF, BUFSIZE, "%s:%s%s", s, printname(sptr),
ADDRTKNG(sptr) ? " (&)" : "");
} else {
snprintf(BUF, BUFSIZE, "%s:%d", s, sptr);
}
}
putit();
} /* putsym */
static void
putnsym(const char *s, SPTR sptr)
{
if (sptr != 0)
putsym(s, sptr);
} /* putnsym */
static void
putsym1(int sptr)
{
if (full) {
if (sptr == NOSYM) {
snprintf(BUF, BUFSIZE, "%d=%s", sptr, "NOSYM");
} else if (sptr > 0 && sptr < stb.stg_avail) {
snprintf(BUF, BUFSIZE, "%d=%s", sptr, printname(sptr));
} else {
snprintf(BUF, BUFSIZE, "%d", sptr);
}
} else {
if (sptr == NOSYM) {
snprintf(BUF, BUFSIZE, "%s", "NOSYM");
} else if (sptr > 0 && sptr < stb.stg_avail) {
snprintf(BUF, BUFSIZE, "%s", printname(sptr));
} else {
snprintf(BUF, BUFSIZE, "%d", sptr);
}
}
putit();
} /* putsym1 */
static int
appendsym1(int sptr)
{
int r;
if (sptr == NOSYM) {
r = snprintf(BUF, BUFSIZE, "%s", "NOSYM");
} else if (sptr > 0 && sptr < stb.stg_avail) {
r = snprintf(BUF, BUFSIZE, "%s", printname(sptr));
} else {
r = snprintf(BUF, BUFSIZE, "sym%d", sptr);
}
appendit();
return r;
} /* appendsym1 */
static void
putsc(const char *s, int sc)
{
if (full) {
if (sc >= 0 && sc <= SC_MAX) {
snprintf(BUF, BUFSIZE, "%s:%d=%s", s, sc, stb.scnames[sc] + 3);
} else {
snprintf(BUF, BUFSIZE, "%s:%d", s, sc);
}
} else {
if (sc >= 0 && sc <= SC_MAX) {
snprintf(BUF, BUFSIZE, "%s:%s", s, stb.scnames[sc] + 3);
} else {
snprintf(BUF, BUFSIZE, "%s:%d", s, sc);
}
}
putit();
} /* putsc */
static void
putnsc(const char *s, int sc)
{
if (sc != 0)
putsc(s, sc);
} /* putnsc */
static void
putstype(const char *s, int stype)
{
if (full) {
if (stype >= 0 && stype <= ST_MAX) {
snprintf(BUF, BUFSIZE, "%s:%d=%s", s, stype, stb.stypes[stype]);
} else {
snprintf(BUF, BUFSIZE, "%s:%d", s, stype);
}
} else {
if (stype >= 0 && stype <= ST_MAX) {
snprintf(BUF, BUFSIZE, "%s:%s", s, stb.stypes[stype]);
} else {
snprintf(BUF, BUFSIZE, "%s:%d", s, stype);
}
}
putit();
} /* putstype */
static void
putddtype(const char *s, DTYPE d)
{
if (d) {
snprintf(BUF, BUFSIZE, "%s:%d=", s, d);
putit();
putdtypex(d, 80);
}
} /* putddtype */
static void
putmd(const char *s, int md)
{
#ifdef MDG
if (md == 0)
return;
snprintf(BUF, BUFSIZE, "%s:0x%x", s, md);
putit();
if (md & MD_X) {
snprintf(BUF, BUFSIZE, "X");
md &= ~MD_X;
putit();
}
if (md & MD_Y) {
snprintf(BUF, BUFSIZE, "Y");
md &= ~MD_Y;
putit();
}
if (md & MD_DATA) {
snprintf(BUF, BUFSIZE, "data");
md &= ~MD_DATA;
putit();
}
if (md & MD_RO) {
snprintf(BUF, BUFSIZE, "ro");
md &= ~MD_RO;
putit();
}
if (md & MD_TINY) {
snprintf(BUF, BUFSIZE, "tiny");
md &= ~MD_TINY;
putit();
}
if (md & MD_SMALL) {
snprintf(BUF, BUFSIZE, "small");
md &= ~MD_SMALL;
putit();
}
if (md) {
snprintf(BUF, BUFSIZE, "***mdbits:0x%x", md);
putit();
}
#endif /* MDG */
} /* putmd */
static void
putcgmode(const char *s, int cgmode)
{
#ifdef CGMODEG
if (cgmode == 0)
return;
snprintf(BUF, BUFSIZE, "%s:%x", s, cgmode);
putit();
switch (cgmode) {
case 0:
break;
case 1:
snprintf(BUF, BUFSIZE, "gp16");
break;
case 2:
snprintf(BUF, BUFSIZE, "gp32");
break;
default:
snprintf(BUF, BUFSIZE, "other");
break;
}
putit();
#endif /* CGMODEG */
} /* putcgmode */
static void
putxyptr(const char *s, int xyptr)
{
#ifdef XYPTRG
if (xyptr == 0)
return;
snprintf(BUF, BUFSIZE, "%s:%x", s, xyptr);
putit();
switch (xyptr) {
case 0:
break;
case MD_X:
snprintf(BUF, BUFSIZE, "Xptr");
break;
case MD_Y:
snprintf(BUF, BUFSIZE, "Yptr");
break;
}
putit();
#endif /* XYPTRG */
} /* putxyptr */
static void
putnname(const char *s, int off)
{
if (off) {
putstring(s, stb.n_base + off);
}
} /* putnname */
static void
putsymlk(const char *name, int list)
{
int c = 0;
if (list <= NOSYM)
return;
putline();
putstring1(name);
for (; list > NOSYM && c < 200; list = SYMLKG(list), ++c)
putsym1(list);
putline();
} /* putsymlk */
static void
dsymlk(int list)
{
int c = 0;
if (list <= NOSYM)
return;
for (; list > NOSYM && c < 200; list = SYMLKG(list), ++c) {
ds(list);
}
} /* dsymlk */
#ifdef TPLNKG
static void
puttplnk(const char *name, int list)
{
if (list <= NOSYM)
return;
putline();
putstring1(name);
for (; list > NOSYM; list = TPLNKG(list)) {
putsym1(list);
}
} /* puttplnk */
#endif
void
putnme(const char *s, int nme)
{
if (full) {
if (nme < 0 || nme >= nmeb.stg_avail) {
snprintf(BUF, BUFSIZE, "%s:%d=%s", s, nme, "NONE");
putit();
} else {
snprintf(BUF, BUFSIZE, "%s:%d=", s, nme);
putit();
_printnme(nme);
}
} else {
if (nme < 0 || nme >= nmeb.stg_avail) {
snprintf(BUF, BUFSIZE, "%s:%d", s, nme);
putit();
} else {
snprintf(BUF, BUFSIZE, "%s:", s);
putit();
_printnme(nme);
}
}
} /* putnme */
static void
putnnme(const char *s, int nme)
{
if (full) {
if (nme < 0 || nme >= nmeb.stg_avail) {
snprintf(BUF, BUFSIZE, "%s:%d=%s", s, nme, "NONE");
putit();
} else if (nme > 0) {
snprintf(BUF, BUFSIZE, "%s:%d=", s, nme);
putit();
_printnme(nme);
}
} else {
if (nme < 0 || nme >= nmeb.stg_avail) {
snprintf(BUF, BUFSIZE, "%s:%d", s, nme);
putit();
} else if (nme > 0) {
snprintf(BUF, BUFSIZE, "%s:", s);
putit();
_printnme(nme);
}
}
} /* putnnme */
#ifdef DPDSCG
static void
putparam(int dpdsc, int paramct)
{
if (paramct == 0)
return;
putline();
putstring1("Parameters:");
for (; paramct; ++dpdsc, --paramct) {
int sptr = aux.dpdsc_base[dpdsc];
if (sptr == 0) {
putstring1("*");
} else {
putsym1(sptr);
}
}
} /* putparam */
#endif /* DPDSCG */
#define SIZEOF(array) (sizeof(array) / sizeof(char *))
static void
putval(const char *s, int val, const char *values[], int sizeofvalues)
{
if (val < 0 || val >= sizeofvalues) {
snprintf(BUF, BUFSIZE, "%s:%d", s, val);
putit();
} else {
putstring(s, values[val]);
}
} /* putval */
static void
putnval(const char *s, int val, const char *values[], int sizeofvalues)
{
if (val < 0 || val >= sizeofvalues) {
snprintf(BUF, BUFSIZE, "%s:%d", s, val);
putit();
} else if (val > 0) {
putstring(s, values[val]);
}
} /* putnval */
static void
putval1(int val, const char *values[], int sizeofvalues)
{
if (val < 0 || val >= sizeofvalues) {
snprintf(BUF, BUFSIZE, "%d", val);
putit();
} else {
putstring1(values[val]);
}
} /* putval1 */
static void
appendval(int val, const char *values[], int sizeofvalues)
{
if (val < 0 || val >= sizeofvalues) {
snprintf(BUF, BUFSIZE, "/%d", val);
appendit();
} else {
appendstring1(values[val]);
}
} /* appendval */
#ifdef SOCPTRG
void
putsoc(int socptr)
{
int p, q;
if (socptr == 0)
return;
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
if (soc.base == NULL) {
fprintf(dfile, "soc.base not allocated\n");
return;
}
q = 0;
putline();
putstring1("Storage Overlap Chain:");
for (p = socptr; p; p = SOC_NEXT(p)) {
putsym1(SOC_SPTR(p));
if (q == p) {
putstring1(" >>> soc loop");
break;
}
q = p;
}
} /* putsoc */
#endif /* SOCPTRG */
#ifdef CUDAG
static void
putcuda(const char *s, int cu)
{
if (cu) {
strcpy(BUF, s);
strcat(BUF, ":");
if (cu & CUDA_HOST) {
strcat(BUF, "host");
cu &= ~CUDA_HOST;
if (cu)
strcat(BUF, "+");
}
if (cu & CUDA_DEVICE) {
strcat(BUF, "device");
cu &= ~CUDA_DEVICE;
if (cu)
strcat(BUF, "+");
}
if (cu & CUDA_GLOBAL) {
strcat(BUF, "global");
cu &= ~CUDA_GLOBAL;
if (cu)
strcat(BUF, "+");
}
if (cu & CUDA_BUILTIN) {
strcat(BUF, "builtin");
cu &= ~CUDA_BUILTIN;
if (cu)
strcat(BUF, "+");
}
if (cu & CUDA_CONSTRUCTOR) {
strcat(BUF, "constructor");
cu &= ~CUDA_CONSTRUCTOR;
if (cu)
strcat(BUF, "+");
}
#ifdef CUDA_STUB
if (cu & CUDA_STUB) {
strcat(BUF, "stub");
cu &= ~CUDA_STUB;
if (cu)
strcat(BUF, "+");
}
#endif
putit();
}
} /* putcuda */
#endif
static void
check(const char *s, int v)
{
if (v) {
fprintf(dfile, "*** %s: %d %x\n", s, v, v);
}
} /* check */
/* dump one symbol to gbl.dbgfil */
void
dsym(int sptr)
{
SYMTYPE stype;
DTYPE dtype;
const char *np;
#ifdef SOCPTRG
int socptr;
#endif
int i;
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
if (sptr == 0 || sptr >= stb.stg_avail) {
fprintf(dfile, "\nsymbol %d out of %d\n", sptr, stb.stg_avail - 1);
return;
}
BCOPY(stb.stg_base, stb.stg_base + sptr, SYM, 1);
stype = STYPEG(0);
switch (stype) {
case ST_BLOCK:
case ST_CMBLK:
case ST_LABEL:
case ST_BASE:
case ST_UNKNOWN:
dtype = DT_NONE;
break;
default:
dtype = DTYPEG(0);
break;
}
np = printname(sptr);
if (strlen(np) >= 30) {
fprintf(dfile, "\n%s", np);
np = " ";
}
fprintf(dfile, "\n%-30.30s ", np);
if (dtype) {
putdtypex(dtype, 50);
}
fprintf(dfile, "\n");
linelen = 0;
if (full) {
putint("sptr", sptr);
putnzint("dtype", DTYPEG(0));
}
if (full & 1)
putnzint("nmptr", NMPTRG(0));
putnsc("sc", SCG(0));
putstype("stype", STYPEG(0));
putline();
STYPEP(0, ST_UNKNOWN);
DTYPEP(0, DT_NONE);
NMPTRP(0, 0);
SCP(0, SC_NONE);
if (full & 1)
putnsym("hashlk", HASHLKG(0));
putnsym("scope", SCOPEG(SPTR_NULL));
putnsym("symlk", SYMLKG(0));
putline();
HASHLKP(0, SPTR_NULL);
SCOPEP(0, 0);
SYMLKP(0, SPTR_NULL);
switch (stype) {
case ST_ARRAY:
case ST_IDENT:
case ST_STRUCT:
case ST_UNION:
case ST_UNKNOWN:
case ST_VAR:
/* three lines: integers, symbols, bits */
putnzint("address", ADDRESSG(0));
ADDRESSP(0, 0);
#ifdef SDSCG
putnsym("sdsc", SDSCG(0));
SDSCP(0, 0);
#endif
#ifdef ENCLFUNCG
putnsym("enclfunc", ENCLFUNCG(0));
ENCLFUNCP(0, 0);
#endif
#ifdef OMPACCDEVSYMG
putbit("ompaccel", OMPACCDEVSYMG(0));
OMPACCDEVSYMP(0, 0);
#endif
#ifdef OMPACCSHMEMG
putbit("ompaccel-shared", OMPACCSHMEMG(0));
OMPACCSHMEMP(0, 0);
#endif
#ifdef OMPACCSTRUCTG
putbit("ompaccel-host", OMPACCSTRUCTG(0));
OMPACCSTRUCTP(0, 0);
#endif
#ifdef OMPACCDEVSYMG
putbit("ompaccel", OMPACCDEVSYMG(0));
OMPACCDEVSYMP(0, 0);
#endif
#ifdef OMPACCSHMEMG
putbit("ompaccel-shared", OMPACCSHMEMG(0));
OMPACCSHMEMP(0, 0);
#endif
#ifdef OMPACCSTRUCTG
putbit("ompaccel-host", OMPACCSTRUCTG(0));
OMPACCSTRUCTP(0, 0);
#endif
#ifdef OMPACCLITERALG
putbit("ompaccel-literal", OMPACCLITERALG(0));
OMPACCLITERALP(0, 0);
#endif
#ifdef SOCPTRG
socptr = SOCPTRG(0);
putnzint("socptr", SOCPTRG(0));
SOCPTRP(0, 0);
#endif
putline();
{
#ifdef MDG
putmd("mdg", MDG(0));
MDP(0, 0);
#endif
}
putnzint("b3", b3G(0));
b3P(0, 0);
#ifdef ALIASG
putnsym("alias", ALIASG(0));
ALIASP(0, 0);
#endif
#ifdef ALTNAMEG
putnsym("altname", ALTNAMEG(0));
ALTNAMEP(0, 0);
#endif
#ifdef BASESYMG
if (BASEADDRG(0)) {
putnsym("basesym", BASESYMG(0));
BASESYMP(0, 0);
}
#endif
#ifdef CLENG
putnsym("clen", CLENG(0));
CLENP(0, 0);
#endif
putnsym("midnum", MIDNUMG(0));
MIDNUMP(0, 0);
#ifdef IPAINFOG
if (IPANAMEG(0)) {
putnzint("ipainfo", IPAINFOG(0));
if (stb.n_base && IPANAMEG(0) && IPAINFOG(0) > 0 &&
IPAINFOG(0) < stb.namavl) {
putstring("ipaname", stb.n_base + IPAINFOG(0));
}
IPAINFOP(0, 0);
}
#endif
#ifdef ORIGDIMG
putnzint("origdim", ORIGDIMG(0));
ORIGDIMP(0, 0);
#endif
#ifdef ORIGDUMMYG
putnsym("origdummy", ORIGDUMMYG(0));
ORIGDUMMYP(0, 0);
#endif
#ifdef PDALNG
putnzint("pdaln", PDALNG(0));
b4P(0, 0);
#endif
#ifdef PARAMVALG
{
putnzint("paramval", PARAMVALG(0));
PARAMVALP(0, 0);
}
#endif
#ifdef TPLNKG
if (stype == ST_ARRAY) {
putnsym("tplnk", TPLNKG(0));
TPLNKP(0, 0);
}
#endif
#ifdef XYPTRG
{
putxyptr("xyptr", XYPTRG(0));
XYPTRP(0, 0);
}
#endif
#ifdef XREFLKG
{
putnsym("xreflk", XREFLKG(0));
XREFLKP(0, 0);
}
#endif
#ifdef ELFSCNG
putnsym("elfscn", ELFSCNG(0));
ELFSCNP(0, 0);
if (stype != ST_FUNC) {
putnsym("elflkg", ELFLKG(0));
ELFLKP(0, 0);
}
#endif
putline();
putbit("addrtkn", ADDRTKNG(0));
ADDRTKNP(0, 0);
#ifdef ACCINITDATAG
putbit("accinitdata", ACCINITDATAG(0));
ACCINITDATAP(0, 0);
#endif
#ifdef ADJARRG
putbit("adjarr", ADJARRG(0));
ADJARRP(0, 0);
#endif
#ifdef ALLOCG
putbit("alloc", ALLOCG(0));
ALLOCP(0, 0);
#endif
#ifdef ARG1PTRG
putbit("arg1ptr", ARG1PTRG(0));
ARG1PTRP(0, 0);
#endif
putbit("assn", ASSNG(0));
ASSNP(0, 0);
#ifdef ASSUMSHPG
putbit("assumshp", ASSUMSHPG(0));
ASSUMSHPP(0, 0);
#endif
#ifdef ASUMSZG
putbit("asumsz", ASUMSZG(0));
ASUMSZP(0, 0);
#endif
#ifdef AUTOBJG
putbit("autobj", AUTOBJG(0));
AUTOBJP(0, 0);
#endif
#ifdef BASEADDRG
putbit("baseaddr", BASEADDRG(0));
BASEADDRP(0, 0);
#endif
#ifdef CALLEDG
putbit("called", CALLEDG(0));
CALLEDP(0, 0);
#endif
putbit("ccsym", CCSYMG(0));
CCSYMP(0, 0);
#ifdef CLASSG
putbit("class", CLASSG(0));
CLASSP(0, 0);
#endif
#ifdef CONSTANTG
putbit("constant", CONSTANTG(0));
CONSTANTP(0, 0);
#endif
#ifdef CONSTG
putbit("const", CONSTG(0));
CONSTP(0, 0);
#endif
#ifdef COPYPRMSG
putbit("copyprms", COPYPRMSG(0));
COPYPRMSP(0, 0);
#endif
#ifdef DCLDG
putbit("dcld", DCLDG(0));
DCLDP(0, 0);
#endif
putbit("defd", DEFDG(0));
DEFDP(0, 0);
#ifdef DESCARRAYG
putbit("descarray", DESCARRAYG(0));
DESCARRAYP(0, 0);
#endif
#ifdef DEVICEG
putbit("device", DEVICEG(0));
DEVICEP(0, 0);
#endif
#ifdef DEVICECOPYG
putbit("devicecopy", DEVICECOPYG(0));
DEVICECOPYP(0, 0);
#endif
putbit("dinit", DINITG(0));
DINITP(0, 0);
#ifdef DVLG
putbit("dvl", DVLG(0));
DVLP(0, 0);
#endif
#ifdef ESCTYALIASG
putbit("esctyalias", ESCTYALIASG(0));
ESCTYALIASP(0, 0);
#endif
#ifdef FROMINLRG
putbit("frominlr", FROMINLRG(0));
FROMINLRP(0, 0);
#endif
putbit("gscope", GSCOPEG(0));
GSCOPEP(0, 0);
#ifdef HOMEDG
putbit("homed", HOMEDG(0));
HOMEDP(0, 0);
#endif
#ifdef INLING
putbit("inlin", INLING(0));
INLINP(0, 0);
#endif
#ifdef ALWAYSINLING
putbit("alwaysinlin", ALWAYSINLING(0));
ALWAYSINLINP(0, 0);
#endif
#ifdef INLNG
putbit("inln", INLNG(0));
INLNP(0, 0);
#endif
#ifdef INLNARRG
putbit("inlnarr", INLNARRG(0));
INLNARRP(0, 0);
#endif
#ifdef LIBCG
putbit("libc", LIBCG(0));
LIBCP(0, 0);
#endif
#ifdef LIBMG
putbit("libm", LIBMG(0));
LIBMP(0, 0);
#endif
#ifdef LOCLIFETMG
putbit("loclifetm", LOCLIFETMG(0));
LOCLIFETMP(0, 0);
#endif
#ifdef LSCOPEG
putbit("lscope", LSCOPEG(0));
LSCOPEP(0, 0);
#endif
#ifdef LVALG
putbit("lval", LVALG(0));
LVALP(0, 0);
#endif
#ifdef MANAGEDG
putbit("managed", MANAGEDG(0));
MANAGEDP(0, 0);
#endif
putbit("memarg", MEMARGG(0));
MEMARGP(0, 0);
#ifdef MIRROREDG
putbit("mirrored", MIRROREDG(0));
MIRROREDP(0, 0);
#endif
#ifdef ACCCREATEG
putbit("acccreate", ACCCREATEG(0));
ACCCREATEP(0, 0);
#endif
#ifdef ACCCOPYING
putbit("acccopyin", ACCCOPYING(0));
ACCCOPYINP(0, 0);
#endif
#ifdef ACCRESIDENTG
putbit("accresident", ACCRESIDENTG(0));
ACCRESIDENTP(0, 0);
#endif
#ifdef ACCLINKG
putbit("acclink", ACCLINKG(0));
ACCLINKP(0, 0);
#endif
#ifdef MODESETG
if (stype == ST_FUNC) {
putbit("modeset", MODESETG(0));
MODESETP(0, 0);
}
#endif
#ifdef MSCALLG
putbit("mscall", MSCALLG(0));
MSCALLP(0, 0);
#endif
#ifdef CFUNCG
putbit("cfunc", CFUNCG(0));
CFUNCP(0, 0);
#endif
#ifdef NOCONFLICTG
putbit("noconflict", NOCONFLICTG(0));
NOCONFLICTP(0, 0);
#endif
#ifdef NOTEXTERNG
putbit("notextern", NOTEXTERNG(0));
NOTEXTERNP(0, 0);
#endif
#ifdef OPTARGG
putbit("optarg", OPTARGG(0));
OPTARGP(0, 0);
#endif
#ifdef OSXINITG
if (stype == ST_FUNC) {
putbit("osxinit", OSXINITG(0));
OSXINITP(0, 0);
putbit("osxterm", OSXTERMG(0));
OSXTERMP(0, 0);
}
#endif
#ifdef PARAMG
putbit("param", PARAMG(0));
PARAMP(0, 0);
#endif
#ifdef PASSBYVALG
putbit("passbyval", PASSBYVALG(0));
PASSBYVALP(0, 0);
#endif
#ifdef PASSBYREFG
putbit("passbyref", PASSBYREFG(0));
PASSBYREFP(0, 0);
#endif
#ifdef PINNEDG
putbit("pinned", PINNEDG(0));
PINNEDP(0, 0);
#endif
#ifdef POINTERG
putbit("pointer", POINTERG(0));
POINTERP(0, 0);
#endif
#ifdef ALLOCATTRP
putbit("allocattr", ALLOCATTRG(0));
ALLOCATTRP(0, 0);
#endif
#ifdef PROTODCLG
putbit("protodcl", PROTODCLG(0));
PROTODCLP(0, 0);
#endif
#ifdef PTRSAFEG
putbit("ptrsafe", PTRSAFEG(0));
PTRSAFEP(0, 0);
#endif
putbit("qaln", QALNG(0));
QALNP(0, 0);
#ifdef REDUCG
putbit("reduc", REDUCG(0));
REDUCP(0, 0);
#endif
#ifdef REFG
putbit("ref", REFG(0));
REFP(0, 0);
#endif
#ifdef REFDG
putbit("refd", REFDG(0));
REFDP(0, 0);
#endif
#ifdef REFLECTEDG
putbit("reflected", REFLECTEDG(0));
REFLECTEDP(0, 0);
#endif
putbit("regarg", REGARGG(0));
REGARGP(0, 0);
#ifdef RESTRICTG
putbit("restrict", RESTRICTG(0));
RESTRICTP(0, 0);
#endif
#ifdef SAFEG
putbit("safe", SAFEG(0));
SAFEP(0, 0);
#endif
#ifdef SAVEG
putbit("save", SAVEG(0));
SAVEP(0, 0);
#endif
#ifdef SDSCCONTIGG
putbit("sdsccontig", SDSCCONTIGG(0));
SDSCCONTIGP(0, 0);
#endif
#ifdef SDSCS1G
putbit("sdscs1", SDSCS1G(0));
SDSCS1P(0, 0);
#endif
#ifdef SECTG
putbit("sect", SECTG(0));
SECTP(0, 0);
#endif
#ifdef SHAREDG
putbit("shared", SHAREDG(0));
SHAREDP(0, 0);
#endif
#ifdef TEXTUREG
putbit("texture", TEXTUREG(0));
TEXTUREP(0, 0);
#endif
#ifdef INTENTING
putbit("intentin", INTENTING(0));
INTENTINP(0, 0);
#endif
putbit("thread", THREADG(0));
THREADP(0, 0);
#ifdef UNSAFEG
putbit("unsafe", UNSAFEG(0));
UNSAFEP(0, 0);
#endif
#ifdef UPLEVELG
putbit("uplevel", UPLEVELG(0));
UPLEVELP(0, 0);
#endif
#ifdef INTERNREFG
putbit("internref", INTERNREFG(0));
INTERNREFP(0, 0);
#endif
#ifdef VARDSCG
putbit("vardsc", VARDSCG(0));
VARDSCP(0, 0);
#endif
#ifdef VLAG
putbit("vla", VLAG(0));
VLAP(0, 0);
#endif
#ifdef VLAIDXG
putbit("vlaidx", VLAIDXG(0));
VLAIDXP(0, 0);
#endif
putbit("vol", VOLG(0));
VOLP(0, 0);
#ifdef WEAKG
putbit("weak", WEAKG(0));
WEAKP(0, 0);
#endif
#ifdef PARREFG
putbit("parref", PARREFG(0));
PARREFP(0, 0);
#endif
#ifdef PARREFLOADG
putbit("parrefload", PARREFLOADG(0));
PARREFLOADP(0, 0);
#endif
#ifdef OMPTEAMPRIVATEG
putbit("team-private", OMPTEAMPRIVATEG(0));
OMPTEAMPRIVATEP(0, 0);
#endif
/*
putbit( "#", #G(0) ); #P(0,0);
*/
#ifdef SOCPTRG
if (socptr)
putsoc(socptr);
#endif
break;
case ST_BLOCK:
putint("startline", STARTLINEG(0));
STARTLINEP(0, 0);
putint("endline", ENDLINEG(0));
ENDLINEP(0, 0);
#ifdef ENCLFUNCG
putnsym("enclfunc", ENCLFUNCG(0));
ENCLFUNCP(0, 0);
#endif
putnsym("startlab", STARTLABG(0));
STARTLABP(0, 0);
putnsym("endlab", ENDLABG(0));
ENDLABP(0, 0);
putnsym("beginscopelab", BEGINSCOPELABG(0));
BEGINSCOPELABP(0, 0);
putnsym("endscopelab", ENDSCOPELABG(0));
ENDSCOPELABP(0, 0);
#ifdef AUTOBJG
putnzint("autobj", AUTOBJG(0));
AUTOBJP(0, 0);
#endif
#ifdef AINITG
putbit("ainit", AINITG(0));
AINITP(0, 0);
#endif
putbit("ccsym", CCSYMG(0));
CCSYMP(0, 0);
#ifdef FROMINLRG
putbit("frominlr", FROMINLRG(0));
FROMINLRP(0, 0);
#endif
#ifdef REFDG
putbit("refd", REFDG(0));
REFDP(0, 0);
#endif
#ifdef PARUPLEVELG
putint("paruplevel", PARUPLEVELG(0));
PARUPLEVELP(0, 0);
#endif
#ifdef PARSYMSG
putbit("parsyms", PARSYMSG(0));
PARSYMSP(0, 0);
#endif
#ifdef PARSYMSCTG
putbit("parsymsct", PARSYMSCTG(0));
PARSYMSCTP(0, 0);
#endif
break;
case ST_BASE:
break;
case ST_CMBLK:
putint("size", SIZEG(0));
SIZEP(0, 0);
putline();
putsym("cmemf", CMEMFG(0));
CMEMFP(0, 0);
putsym("cmeml", CMEMLG(0));
CMEMLP(0, 0);
#ifdef INMODULEG
putnzint("inmodule", INMODULEG(0));
INMODULEP(0, 0);
#endif
putnsym("midnum", MIDNUMG(0));
MIDNUMP(0, 0);
#ifdef ALTNAMEG
putnsym("altname", ALTNAMEG(0));
ALTNAMEP(0, 0);
#endif
#ifdef PDALNG
putnzint("pdaln", PDALNG(0));
PDALNP(0, 0);
#endif
putline();
#ifdef ACCCREATEG
putbit("acccreate", ACCCREATEG(0));
ACCCREATEP(0, 0);
#endif
#ifdef ACCCOPYING
putbit("acccopyin", ACCCOPYING(0));
ACCCOPYINP(0, 0);
#endif
#ifdef ACCRESIDENTG
putbit("accresident", ACCRESIDENTG(0));
ACCRESIDENTP(0, 0);
#endif
#ifdef ACCLINKG
putbit("acclink", ACCLINKG(0));
ACCLINKP(0, 0);
#endif
putbit("alloc", ALLOCG(0));
ALLOCP(0, 0);
putbit("ccsym", CCSYMG(0));
CCSYMP(0, 0);
#ifdef CONSTANTG
putbit("constant", CONSTANTG(0));
CONSTANTP(0, 0);
#endif
putbit("dcld", DCLDG(0));
DCLDP(0, 0);
putbit("defd", DEFDG(0));
DEFDP(0, 0);
#ifdef DEVICEG
putbit("device", DEVICEG(0));
DEVICEP(0, 0);
#endif
putbit("dinit", DINITG(0));
DINITP(0, 0);
#ifdef FROMINLRG
putbit("frominlr", FROMINLRG(0));
FROMINLRP(0, 0);
#endif
#ifdef FROMMODG
putbit("frommod", FROMMODG(0));
FROMMODP(0, 0);
#endif
#ifdef INLNG
putbit("inln", INLNG(0));
INLNP(0, 0);
#endif
#ifdef MODCMNG
putbit("modcmn", MODCMNG(0));
MODCMNP(0, 0);
#endif
putbit("qaln", QALNG(0));
QALNP(0, 0);
putbit("save", SAVEG(0));
SAVEP(0, 0);
#ifdef THREADG
putbit("thread", THREADG(0));
THREADP(0, 0);
#endif
putbit("vol", VOLG(0));
VOLP(0, 0);
putsymlk("Members:", CMEMFG(sptr));
break;
case ST_CONST:
putnzint("address", ADDRESSG(0));
ADDRESSP(0, 0);
if (DTY(dtype) == TY_PTR) {
putsym("pointee", STGetPointee(0));
CONVAL1P(0, 0);
putnzbigint("offset", ACONOFFG(0));
ACONOFFP(0, 0);
} else {
putint("conval1g", CONVAL1G(0));
CONVAL1P(0, 0);
putbigint("conval2g", CONVAL2G(0));
CONVAL2P(0, 0);
}
putline();
break;
case ST_ENTRY:
putnzint("bihnum", BIHNUMG(0));
BIHNUMP(0, 0);
#ifdef ARGSIZEG
putnzint("argsize", ARGSIZEG(0));
ARGSIZEP(0, 0);
#endif
putint("dpdsc", DPDSCG(0));
DPDSCP(0, 0);
putint("funcline", FUNCLINEG(0));
FUNCLINEP(0, 0);
#ifdef DECLLINEG
putnzint("declline", DECLLINEG(0));
DECLLINEP(0, 0);
#endif
putint("paramct", PARAMCTG(0));
PARAMCTP(0, 0);
#ifdef ALTNAMEG
putnsym("altname", ALTNAMEG(0));
ALTNAMEP(0, 0);
#endif
putline();
#ifdef INMODULEG
putnsym("inmodule", INMODULEG(0));
INMODULEP(0, 0);
#endif
putnsym("gsame", GSAMEG(0));
GSAMEP(0, 0);
putnsym("fval", FVALG(0));
FVALP(0, 0);
#ifdef CUDAG
putcuda("cuda", CUDAG(0));
CUDAP(0, 0);
#endif
#ifdef ACCROUTG
putnzint("accrout", ACCROUTG(0));
ACCROUTP(0, 0);
#endif
#ifdef OMPACCFUNCDEVG
putbit("ompaccel-device", OMPACCFUNCDEVG(0));
OMPACCFUNCDEVP(0, 0);
#endif
#ifdef OMPACCFUNCKERNELG
putbit("ompaccel-kernel", OMPACCFUNCKERNELG(0));
OMPACCFUNCKERNELP(0, 0);
#endif
#ifdef OMPACCFUNCDEVG
putbit("ompaccel-device", OMPACCFUNCDEVG(0));
OMPACCFUNCDEVP(0, 0);
#endif
#ifdef OMPACCFUNCKERNELG
putbit("ompaccel-kernel", OMPACCFUNCKERNELG(0));
OMPACCFUNCKERNELP(0, 0);
#endif
#ifdef IPAINFOG
putnzint("ipainfo", IPAINFOG(0));
if (stb.n_base && IPANAMEG(0) && IPAINFOG(0) > 0 &&
IPAINFOG(0) < stb.namavl) {
putstring("ipaname", stb.n_base + IPAINFOG(0));
}
IPAINFOP(0, 0);
#endif
putline();
putbit("adjarr", ADJARRG(0));
ADJARRP(0, 0);
putbit("aftent", AFTENTG(0));
AFTENTP(0, 0);
#ifdef CALLEDG
putbit("called", CALLEDG(0));
CALLEDP(0, 0);
#endif
putbit("ccsym", CCSYMG(0));
CCSYMP(0, 0);
#ifdef CONTAINEDG
putbit("contained", CONTAINEDG(0));
CONTAINEDP(0, 0);
#endif
#ifdef COPYPRMSG
putbit("copyprms", COPYPRMSG(0));
COPYPRMSP(0, 0);
#endif
putbit("dcld", DCLDG(0));
DCLDP(0, 0);
#ifdef DECORATEG
putbit("decorate", DECORATEG(0));
DECORATEP(0, 0);
#endif
#ifdef FROMINLRG
putbit("frominlr", FROMINLRG(0));
FROMINLRP(0, 0);
#endif
#ifdef MSCALLG
putbit("mscall", MSCALLG(0));
MSCALLP(0, 0);
#endif
#ifdef CFUNCG
putbit("cfunc", CFUNCG(0));
CFUNCP(0, 0);
#endif
#ifdef NOTEXTERNG
putbit("notextern", NOTEXTERNG(0));
NOTEXTERNP(0, 0);
#endif
putbit("pure", PUREG(0));
PUREP(0, 0);
#ifdef ELEMENTALG
putbit("elemental", ELEMENTALG(0));
ELEMENTALP(0, 0);
#endif
#ifdef RECURG
putbit("recur", RECURG(0));
RECURP(0, 0);
#endif
#ifdef STDCALLG
putbit("stdcall", STDCALLG(0));
STDCALLP(0, 0);
#endif
putline();
putparam(DPDSCG(sptr), PARAMCTG(sptr));
break;
case ST_GENERIC:
putnsym("gcmplx", GCMPLXG(0));
GCMPLXP(0, 0);
putnsym("gdble", GDBLEG(0));
GDBLEP(0, 0);
putnsym("gdcmplx", GDCMPLXG(0));
GDCMPLXP(0, 0);
putnsym("gint", GINTG(0));
GINTP(0, 0);
putnsym("gint8", GINT8G(0));
GINT8P(0, 0);
#ifdef GQCMPLXG
putnsym("gqcmplx", GQCMPLXG(0));
GQCMPLXP(0, 0);
#endif
#ifdef GQUADG
putnsym("gquad", GQUADG(0));
GQUADP(0, 0);
#endif
putnsym("greal", GREALG(0));
GREALP(0, 0);
putnsym("gsame", GSAMEG(0));
GSAMEP(0, 0);
putnsym("gsint", GSINTG(0));
GSINTP(0, 0);
putnzint("gndsc", GNDSCG(0));
GNDSCP(0, 0);
putnzint("gncnt", GNCNTG(0));
GNCNTP(0, 0);
putline();
putbit("dcld", DCLDG(0));
DCLDP(0, 0);
break;
case ST_INTRIN:
putddtype("argtyp", ARGTYPG(0));
ARGTYPP(0, 0);
putnzint("arrayf", ARRAYFG(0));
ARRAYFP(0, 0);
putnzint("ilm", ILMG(0));
ILMP(0, 0);
putddtype("inttyp", INTTYPG(0));
INTTYPP(0, 0);
putnname("pnmptr", PNMPTRG(0));
PNMPTRP(0, 0);
putint("paramct", PARAMCTG(0));
PARAMCTP(0, 0);
putline();
putbit("dcld", DCLDG(0));
DCLDP(0, 0);
putbit("expst", EXPSTG(0));
EXPSTP(0, 0);
break;
case ST_LABEL:
putnzint("address", ADDRESSG(0));
ADDRESSP(0, 0);
#ifdef ENCLFUNCG
putnsym("enclfunc", ENCLFUNCG(0));
ENCLFUNCP(0, 0);
#endif
#ifdef FMTPTG
putnsym("fmtpt", FMTPTG(0));
FMTPTP(0, 0);
#endif
putnzint("iliblk", ILIBLKG(0));
ILIBLKP(0, 0);
#ifdef JSCOPEG
putnzint("jscope", JSCOPEG(0));
JSCOPEP(0, 0);
#endif
putint("rfcnt", RFCNTG(0));
RFCNTP(0, 0);
putline();
putbit("ccsym", CCSYMG(0));
CCSYMP(0, 0);
putbit("defd", DEFDG(0));
DEFDP(0, 0);
#ifdef INLING
putbit("inlin", INLING(0));
INLINP(0, 0);
#endif
#ifdef ALWAYSINLING
putbit("alwaysinlin", ALWAYSINLING(0));
ALWAYSINLINP(0, 0);
#endif
#ifdef INLNG
putbit("inln", INLNG(0));
INLNP(0, 0);
#endif
#ifdef LSCOPEG
putbit("lscope", LSCOPEG(0));
LSCOPEP(0, 0);
#endif
putbit("qaln", QALNG(0));
QALNP(0, 0);
#ifdef REFDG
putbit("refd", REFDG(0));
REFDP(0, 0);
#endif
putbit("vol", VOLG(0));
VOLP(0, 0);
putbit("beginscope", BEGINSCOPEG(0));
BEGINSCOPEP(0, 0);
putbit("endscope", ENDSCOPEG(0));
ENDSCOPEP(0, 0);
break;
case ST_MEMBER:
putint("address", ADDRESSG(0));
ADDRESSP(0, 0);
#ifdef BITOFFG
putnzint("bitoff", BITOFFG(0));
BITOFFP(0, 0);
#endif
#ifdef FLDSZG
putnzint("fldsz", FLDSZG(0));
FLDSZP(0, 0);
#endif
#ifdef LDSIZEG
putnzint("ldsize", LDSIZEG(0));
LDSIZEP(0, 0);
#endif
putsym("psmem", PSMEMG(0));
PSMEMP(0, 0);
#ifdef VARIANTG
putsym("variant", VARIANTG(0));
VARIANTP(0, 0);
#endif
#ifdef INDTYPEG
putnzint("indtype", INDTYPEG(0));
INDTYPEP(0, 0);
#endif
#ifdef SDSCG
putnsym("sdsc", SDSCG(0));
SDSCP(0, 0);
#endif
putline();
#ifdef ALLOCATTRG
putbit("allocattr", ALLOCATTRG(0));
ALLOCATTRP(0, 0);
#endif
#ifdef CLASSG
putbit("class", CLASSG(0));
CLASSP(0, 0);
#endif
putbit("ccsym", CCSYMG(0));
CCSYMP(0, 0);
#ifdef DCLDG
putbit("dcld", DCLDG(0));
DCLDP(0, 0);
#endif
#ifdef DESCARRAYG
putbit("descarray", DESCARRAYG(0));
DESCARRAYP(0, 0);
#endif
#ifdef FIELDG
putbit("field", FIELDG(0));
FIELDP(0, 0);
#endif
#ifdef INLING
putbit("inlin", INLING(0));
INLINP(0, 0);
#endif
#ifdef ALWAYSINLING
putbit("alwaysinlin", ALWAYSINLING(0));
ALWAYSINLINP(0, 0);
#endif
#ifdef INLNG
putbit("inln", INLNG(0));
INLNP(0, 0);
#endif
#ifdef MSCALLG
putbit("mscall", MSCALLG(0));
MSCALLP(0, 0);
#endif
#ifdef CFUNCG
putbit("cfunc", CFUNCG(0));
CFUNCP(0, 0);
#endif
#ifdef NOCONFLICTG
putbit("noconflict", NOCONFLICTG(0));
NOCONFLICTP(0, 0);
#endif
#ifdef PLAING
putbit("plain", PLAING(0));
PLAINP(0, 0);
#endif
#ifdef POINTERG
putbit("pointer", POINTERG(0));
POINTERP(0, 0);
#endif
#ifdef PTRSAFEG
putbit("ptrsafe", PTRSAFEG(0));
PTRSAFEP(0, 0);
#endif
#ifdef REFDG
putbit("refd", REFDG(0));
REFDP(0, 0);
#endif
#ifdef SDSCCONTIGG
putbit("sdsccontig", SDSCCONTIGG(0));
SDSCCONTIGP(0, 0);
#endif
#ifdef SDSCS1G
putbit("sdscs1", SDSCS1G(0));
SDSCS1P(0, 0);
#endif
break;
case ST_NML:
putsym("plist", (SPTR) ADDRESSG(0)); // ???
ADDRESSP(0, 0);
putsym("cmemf", CMEMFG(0));
CMEMFP(0, 0);
putsym("cmeml", CMEMLG(0));
CMEMLP(0, 0);
putline();
putbit("dcld", DCLDG(0));
DCLDP(0, 0);
putbit("ref", REFG(0));
REFP(0, 0);
putline();
for (i = CMEMFG(sptr); i; i = NML_NEXT(i)) {
putsym1(NML_SPTR(i));
}
break;
case ST_PARAM:
putint("conval1g", CONVAL1G(0));
CONVAL1P(0, 0);
putint("conval2g", CONVAL2G(0));
CONVAL2P(0, 0);
putline();
putbit("dcld", DCLDG(0));
DCLDP(0, 0);
putbit("ref", REFG(0));
REFP(0, 0);
break;
case ST_PD:
putddtype("argtyp", ARGTYPG(0));
ARGTYPP(0, 0);
putint("paramct", PARAMCTG(0));
PARAMCTP(0, 0);
putnzint("ilm", ILMG(0));
ILMP(0, 0);
putint("pdnum", PDNUMG(0));
PDNUMP(0, 0);
break;
case ST_PLIST:
putint("address", ADDRESSG(0));
ADDRESSP(0, 0);
#ifdef BASESYMG
if (BASEADDRG(0)) {
putnsym("basesym", BASESYMG(0));
BASESYMP(0, 0);
}
#endif
putnzint("deflab", DEFLABG(0));
DEFLABP(0, 0);
putint("pllen", PLLENG(0));
PLLENP(0, 0);
putnzint("swel", SWELG(0));
SWELP(0, 0);
putline();
putbit("addrtkn", ADDRTKNG(0));
ADDRTKNP(0, 0);
#ifdef BASEADDRG
putbit("baseaddr", BASEADDRG(0));
BASEADDRP(0, 0);
#endif
putbit("ccsym", CCSYMG(0));
CCSYMP(0, 0);
putbit("dcld", DCLDG(0));
DCLDP(0, 0);
putbit("dinit", DINITG(0));
DINITP(0, 0);
#ifdef INLING
putbit("inlin", INLING(0));
INLINP(0, 0);
#endif
#ifdef ALWAYSINLING
putbit("alwaysinlin", ALWAYSINLING(0));
ALWAYSINLINP(0, 0);
#endif
#ifdef INLNG
putbit("inln", INLNG(0));
INLNP(0, 0);
#endif
#ifdef LSCOPEG
putbit("lscope", LSCOPEG(0));
LSCOPEP(0, 0);
#endif
putbit("ref", REFG(0));
REFP(0, 0);
break;
case ST_PROC:
#ifdef INMODULEG
putnsym("inmodule", INMODULEG(0));
INMODULEP(0, 0);
#endif
#ifdef ARGSIZEG
putnzint("argsize", ARGSIZEG(0));
ARGSIZEP(0, 0);
#endif
putnzint("address", ADDRESSG(0));
ADDRESSP(0, 0);
putnsym("midnum", MIDNUMG(0));
MIDNUMP(0, 0);
#ifdef IPAINFOG
putnzint("ipainfo", IPAINFOG(0));
if (stb.n_base && IPANAMEG(0) && IPAINFOG(0) > 0 &&
IPAINFOG(0) < stb.namavl) {
putstring("ipaname", stb.n_base + IPAINFOG(0));
}
IPAINFOP(0, 0);
#endif
#ifdef ALTNAMEG
putnsym("altname", ALTNAMEG(0));
ALTNAMEP(0, 0);
#endif
#ifdef ACCROUTG
putnzint("accrout", ACCROUTG(0));
ACCROUTP(0, 0);
#endif
#ifdef ARG1PTRG
putbit("arg1ptr", ARG1PTRG(0));
ARG1PTRP(0, 0);
#endif
#ifdef CUDAG
putcuda("cuda", CUDAG(0));
CUDAP(0, 0);
#endif
putline();
#ifdef CFUNCG
putbit("cfunc", CFUNCG(0));
CFUNCP(0, 0);
#endif
putbit("ccsym", CCSYMG(0));
CCSYMP(0, 0);
#ifdef COPYPRMSG
putbit("copyprms", COPYPRMSG(0));
COPYPRMSP(0, 0);
#endif
#ifdef CONTAINEDG
putbit("contained", CONTAINEDG(0));
CONTAINEDP(0, 0);
#endif
#ifdef DECORATEG
putbit("decorate", DECORATEG(0));
DECORATEP(0, 0);
#endif
#ifdef MSCALLG
putbit("mscall", MSCALLG(0));
MSCALLP(0, 0);
#endif
#ifdef CFUNCG
putbit("cfunc", CFUNCG(0));
CFUNCP(0, 0);
#endif
#ifdef NEEDMODG
putbit("needmod", NEEDMODG(0));
NEEDMODP(0, 0);
#endif
putbit("nopad", NOPADG(0));
NOPADP(0, 0);
putbit("dcld", DCLDG(0));
DCLDP(0, 0);
putbit("func", FUNCG(0));
FUNCP(0, 0);
#ifdef FROMINLRG
putbit("frominlr", FROMINLRG(0));
FROMINLRP(0, 0);
#endif
#ifdef LIBMG
putbit("libm", LIBMG(0));
LIBMP(0, 0);
#endif
putbit("memarg", MEMARGG(0));
MEMARGP(0, 0);
#ifdef PASSBYVALG
putbit("passbyval", PASSBYVALG(0));
PASSBYVALP(0, 0);
#endif
#ifdef PASSBYREFG
putbit("passbyref", PASSBYREFG(0));
PASSBYREFP(0, 0);
#endif
putbit("pure", PUREG(0));
PUREP(0, 0);
putbit("ref", REFG(0));
REFP(0, 0);
#ifdef SDSCSAFEG
putbit("sdscsafe", SDSCSAFEG(0));
SDSCSAFEP(0, 0);
#endif
#ifdef STDCALLG
putbit("stdcall", STDCALLG(0));
STDCALLP(0, 0);
#endif
#ifdef UNIFIEDG
putbit("unified", UNIFIEDG(0));
UNIFIEDP(0, 0);
#endif
putline();
putparam(DPDSCG(sptr), PARAMCTG(sptr));
break;
case ST_STFUNC:
putint("excvlen", EXCVLENG(0));
EXCVLENP(0, 0);
putint("sfdsc", SFDSCG(0));
SFDSCP(0, 0);
putline();
putbit("dcld", DCLDG(0));
DCLDP(0, 0);
break;
case ST_TYPEDEF:
#ifdef ENCLFUNCG
putnsym("enclfunc", ENCLFUNCG(0));
ENCLFUNCP(0, 0);
#endif
#ifdef PDALNG
putnzint("pdaln", PDALNG(0));
PDALNP(0, 0);
#endif
#ifdef DCLDG
putbit("dcld", DCLDG(0));
DCLDP(0, 0);
#endif
#ifdef FROMMODG
putbit("frommod", FROMMODG(0));
FROMMODP(0, 0);
#endif
#ifdef MSCALLG
putbit("mscall", MSCALLG(0));
MSCALLP(0, 0);
#endif
#ifdef CFUNCG
putbit("cfunc", CFUNCG(0));
CFUNCP(0, 0);
#endif
#ifdef CLASSG
putbit("class", CLASSG(0));
CLASSP(0, 0);
#endif
#ifdef PLAING
putbit("plain", PLAING(0));
PLAINP(0, 0);
#endif
break;
case ST_STAG:
#ifdef ENCLFUNCG
putnsym("enclfunc", ENCLFUNCG(0));
ENCLFUNCP(0, 0);
#endif
#ifdef DCLDG
putbit("dcld", DCLDG(0));
DCLDP(0, 0);
#endif
#ifdef INLNG
putbit("inln", INLNG(0));
INLNP(0, 0);
#endif
break;
} /* switch(stype) */
putline();
check("b3", stb.stg_base[0].b3);
check("b4", stb.stg_base[0].b4);
check("f1", stb.stg_base[0].f1);
check("f2", stb.stg_base[0].f2);
check("f3", stb.stg_base[0].f3);
check("f4", stb.stg_base[0].f4);
check("f5", stb.stg_base[0].f5);
check("f6", stb.stg_base[0].f6);
check("f7", stb.stg_base[0].f7);
check("f8", stb.stg_base[0].f8);
check("f9", stb.stg_base[0].f9);
check("f10", stb.stg_base[0].f10);
check("f11", stb.stg_base[0].f11);
check("f12", stb.stg_base[0].f12);
check("f13", stb.stg_base[0].f13);
check("f14", stb.stg_base[0].f14);
check("f15", stb.stg_base[0].f15);
check("f16", stb.stg_base[0].f16);
check("f17", stb.stg_base[0].f17);
check("f18", stb.stg_base[0].f18);
check("f19", stb.stg_base[0].f19);
check("f20", stb.stg_base[0].f20);
check("f21", stb.stg_base[0].f21);
check("f22", stb.stg_base[0].f22);
check("f23", stb.stg_base[0].f23);
check("f24", stb.stg_base[0].f24);
check("f25", stb.stg_base[0].f25);
check("f26", stb.stg_base[0].f26);
check("f27", stb.stg_base[0].f27);
check("f28", stb.stg_base[0].f28);
check("f29", stb.stg_base[0].f29);
check("f30", stb.stg_base[0].f30);
check("f31", stb.stg_base[0].f31);
check("f32", stb.stg_base[0].f32);
check("f33", stb.stg_base[0].f33);
check("f34", stb.stg_base[0].f34);
check("f35", stb.stg_base[0].f35);
check("f36", stb.stg_base[0].f36);
check("f37", stb.stg_base[0].f37);
check("f38", stb.stg_base[0].f38);
check("f39", stb.stg_base[0].f39);
check("f40", stb.stg_base[0].f40);
check("f41", stb.stg_base[0].f41);
check("f42", stb.stg_base[0].f42);
check("f43", stb.stg_base[0].f43);
check("f44", stb.stg_base[0].f44);
check("f45", stb.stg_base[0].f45);
check("f46", stb.stg_base[0].f46);
check("f47", stb.stg_base[0].f47);
check("f48", stb.stg_base[0].f48);
check("f50", stb.stg_base[0].f50);
check("f51", stb.stg_base[0].f51);
check("f52", stb.stg_base[0].f52);
check("f53", stb.stg_base[0].f53);
check("f54", stb.stg_base[0].f54);
check("f55", stb.stg_base[0].f55);
check("f56", stb.stg_base[0].f56);
check("f57", stb.stg_base[0].f57);
check("f58", stb.stg_base[0].f58);
check("f59", stb.stg_base[0].f59);
check("f60", stb.stg_base[0].f60);
check("f61", stb.stg_base[0].f61);
check("f62", stb.stg_base[0].f62);
check("f63", stb.stg_base[0].f63);
check("f64", stb.stg_base[0].f64);
check("f65", stb.stg_base[0].f65);
check("f66", stb.stg_base[0].f66);
check("f67", stb.stg_base[0].f67);
check("f68", stb.stg_base[0].f68);
check("f69", stb.stg_base[0].f69);
check("f70", stb.stg_base[0].f70);
check("f71", stb.stg_base[0].f71);
check("f72", stb.stg_base[0].f72);
check("f73", stb.stg_base[0].f73);
check("f74", stb.stg_base[0].f74);
check("f75", stb.stg_base[0].f75);
check("f76", stb.stg_base[0].f76);
check("f77", stb.stg_base[0].f77);
check("f78", stb.stg_base[0].f78);
check("f79", stb.stg_base[0].f79);
check("f80", stb.stg_base[0].f80);
check("f81", stb.stg_base[0].f81);
check("f82", stb.stg_base[0].f82);
check("f83", stb.stg_base[0].f83);
check("f84", stb.stg_base[0].f84);
check("f85", stb.stg_base[0].f85);
check("f86", stb.stg_base[0].f86);
check("f87", stb.stg_base[0].f87);
check("f88", stb.stg_base[0].f88);
check("f89", stb.stg_base[0].f89);
check("f90", stb.stg_base[0].f90);
check("f91", stb.stg_base[0].f91);
check("f92", stb.stg_base[0].f92);
check("f93", stb.stg_base[0].f93);
check("f94", stb.stg_base[0].f94);
check("f95", stb.stg_base[0].f95);
check("f96", stb.stg_base[0].f96);
check("f110", stb.stg_base[0].f110);
check("f111", stb.stg_base[0].f111);
check("w8", stb.stg_base[0].w8);
check("w9", stb.stg_base[0].w9);
check("w10", stb.stg_base[0].w10);
check("w11", stb.stg_base[0].w11);
check("w12", stb.stg_base[0].w12);
check("w13", stb.stg_base[0].w13);
check("w14", stb.stg_base[0].w14);
check("w15", stb.stg_base[0].w15);
check("w16", stb.stg_base[0].w16);
check("w17", stb.stg_base[0].w17);
check("w18", stb.stg_base[0].w18);
check("w20", stb.stg_base[0].w20);
} /* dsym */
void
dsyms(int l, int u)
{
int i;
if (l <= 0)
l = stb.firstusym;
if (u <= 0)
u = stb.stg_avail - 1;
if (u >= stb.stg_avail)
u = stb.stg_avail - 1;
for (i = l; i <= u; ++i) {
dsym(i);
}
fprintf(dfile, "\n");
} /* dsyms */
void
ds(int sptr)
{
dsym(sptr);
} /* ds */
void
dsa(void)
{
dsyms(0, 0);
} /* dsa */
void
dss(int l, int u)
{
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
fprintf(dfile, "\n********** SYMBOL TABLE **********\n");
dsyms(l, u);
} /* dss */
void
dgbl(void)
{
GBL mbl;
int *ff;
int i, mblsize;
memcpy(&mbl, &gbl, sizeof(gbl));
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
putsym("gbl.currsub", mbl.currsub);
mbl.currsub = SPTR_NULL;
putnstring("gbl.datetime", mbl.datetime);
memset(mbl.datetime, 0, sizeof(mbl.datetime));
putline();
putnzint("gbl.maxsev", mbl.maxsev);
mbl.maxsev = 0;
putnzint("gbl.findex", mbl.findex);
mbl.findex = 0;
putsymlk("gbl.entries=", mbl.entries);
mbl.entries = SPTR_NULL;
putsymlk("gbl.cmblks=", mbl.cmblks);
mbl.cmblks = SPTR_NULL;
putsymlk("gbl.externs=", mbl.externs);
mbl.externs = SPTR_NULL;
putsymlk("gbl.consts=", mbl.consts);
mbl.consts = SPTR_NULL;
putsymlk("gbl.locals=", mbl.locals);
mbl.locals = SPTR_NULL;
putsymlk("gbl.statics=", mbl.statics);
mbl.statics = SPTR_NULL;
putsymlk("gbl.bssvars=", mbl.bssvars);
mbl.bssvars = SPTR_NULL;
putsymlk("gbl.locals=", mbl.locals);
mbl.locals = SPTR_NULL;
putsymlk("gbl.basevars=", mbl.basevars);
mbl.basevars = SPTR_NULL;
putsymlk("gbl.asgnlbls=", mbl.asgnlbls);
mbl.asgnlbls = SPTR_NULL;
putsymlk("gbl.autobj=", mbl.autobj);
mbl.autobj = 0;
putsymlk("gbl.typedescs=", mbl.typedescs);
mbl.typedescs = SPTR_NULL;
putline();
putnsym("gbl.outersub", mbl.outersub);
mbl.outersub = SPTR_NULL;
putline();
putnzint("gbl.vfrets", mbl.vfrets);
mbl.vfrets = 0;
putnzint("gbl.func_count", mbl.func_count);
mbl.func_count = 0;
putnzint("gbl.rutype=", mbl.rutype);
mbl.rutype = (RUTYPE)0; // no 0 value defined
putnzint("gbl.funcline=", mbl.funcline);
mbl.funcline = 0;
putnzint("gbl.threadprivate=", mbl.threadprivate);
mbl.threadprivate = SPTR_NULL;
putnzint("gbl.nofperror=", mbl.nofperror);
mbl.nofperror = 0;
putnzint("gbl.fperror_status=", mbl.fperror_status);
mbl.fperror_status = 0;
putnzint("gbl.entbih", mbl.entbih);
mbl.entbih = 0;
putnzint("gbl.lineno", mbl.lineno);
mbl.lineno = 0;
mbl.multiversion = 0;
mbl.multi_func_count = 0;
mbl.numversions = 0;
putnzint("gbl.pgfi_avail", mbl.pgfi_avail);
mbl.pgfi_avail = 0;
putnzint("gbl.ec_avail", mbl.ec_avail);
mbl.ec_avail = 0;
putnzint("gbl.cuda_constructor", mbl.cuda_constructor);
mbl.cuda_constructor = 0;
putnzint("gbl.cudaemu", mbl.cudaemu);
mbl.cudaemu = 0;
putnzint("gbl.ftn_true", mbl.ftn_true);
mbl.ftn_true = 0;
putnzint("gbl.in_include", mbl.in_include);
mbl.in_include = 0;
putnzint("gbl.denorm", mbl.denorm);
mbl.denorm = 0;
putnzint("gbl.nowarn", mbl.nowarn);
mbl.nowarn = 0;
putnzint("gbl.internal", mbl.internal);
mbl.internal = 0;
putnzisz("gbl.caddr", mbl.caddr);
mbl.caddr = 0;
putnzisz("gbl.locaddr", mbl.locaddr);
mbl.locaddr = 0;
putnzisz("gbl.saddr", mbl.saddr);
mbl.saddr = 0;
putnzisz("gbl.bss_addr", mbl.bss_addr);
mbl.bss_addr = 0;
putnzisz("gbl.paddr", mbl.paddr);
mbl.paddr = 0;
putline();
putnsym("gbl.prvt_sym_sz", (SPTR) mbl.prvt_sym_sz); // ???
mbl.prvt_sym_sz = 0;
putnsym("gbl.stk_sym_sz", (SPTR) mbl.stk_sym_sz); // ???
mbl.stk_sym_sz = 0;
putline();
putnstring("gbl.src_file", mbl.src_file);
mbl.src_file = NULL;
putnstring("gbl.file_name", mbl.file_name);
mbl.file_name = NULL;
putnstring("gbl.curr_file", mbl.curr_file);
mbl.curr_file = NULL;
putnstring("gbl.module", mbl.module);
mbl.module = NULL;
mbl.srcfil = NULL;
mbl.cppfil = NULL;
mbl.dbgfil = NULL;
mbl.ilmfil = NULL;
mbl.objfil = NULL;
mbl.asmfil = NULL;
putline();
ff = (int *)(&mbl);
mblsize = sizeof(mbl) / sizeof(int);
for (i = 0; i < mblsize; ++i) {
if (ff[i] != 0) {
fprintf(dfile, "*** gbl[%d] = %d 0x%x\n", i, ff[i], ff[i]);
}
}
} /* dgbl */
void
dflg(void)
{
FLG mlg;
int *ff;
int i, mlgsize;
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
memcpy(&mlg, &flg, sizeof(flg));
putnzint("flg.asmcode", mlg.asmcode);
mlg.asmcode = 0;
putnzint("flg.list", mlg.list);
mlg.list = 0;
putnzint("flg.object", mlg.object);
mlg.object = 0;
putnzint("flg.xref", mlg.xref);
mlg.xref = 0;
putnzint("flg.code", mlg.code);
mlg.code = 0;
putnzint("flg.include", mlg.include);
mlg.include = 0;
putnzint("flg.debug", mlg.debug);
mlg.debug = 0;
putnzint("flg.opt", mlg.opt);
mlg.opt = 0;
putnzint("flg.depchk", mlg.depchk);
mlg.depchk = 0;
putnzint("flg.depwarn", mlg.depwarn);
mlg.depwarn = 0;
putnzint("flg.dclchk", mlg.dclchk);
mlg.dclchk = 0;
putnzint("flg.locchk", mlg.locchk);
mlg.locchk = 0;
putnzint("flg.onetrip", mlg.onetrip);
mlg.onetrip = 0;
putnzint("flg.save", mlg.save);
mlg.save = 0;
putnzint("flg.inform", mlg.inform);
mlg.inform = 0;
putnzINT("flg.xoff", mlg.xoff);
mlg.xoff = 0;
putnzINT("flg.xon", mlg.xon);
mlg.xon = 0;
putnzint("flg.ucase", mlg.ucase);
mlg.ucase = 0;
putnzint("flg.dlines", mlg.dlines);
mlg.dlines = 0;
putnzint("flg.extend_source", mlg.extend_source);
mlg.extend_source = 0;
putnzint("flg.i4", mlg.i4);
mlg.i4 = 0;
putnzint("flg.line", mlg.line);
mlg.line = 0;
putnzint("flg.symbol", mlg.symbol);
mlg.symbol = 0;
putnzint("flg.profile", mlg.profile);
mlg.profile = 0;
putnzint("flg.standard", mlg.standard);
mlg.profile = 0;
putnzint("flg.dalign", mlg.dalign);
mlg.dalign = 0;
putnzint("flg.astype", mlg.astype);
mlg.astype = 0;
putnzint("flg.recursive", mlg.recursive);
mlg.recursive = 0;
putnzint("flg.ieee", mlg.ieee);
mlg.ieee = 0;
putnzint("flg.inliner", mlg.inliner);
mlg.inliner = 0;
putnzint("flg.autoinline", mlg.autoinline);
mlg.autoinline = 0;
putnzint("flg.vect", mlg.vect);
mlg.vect = 0;
putnzint("flg.endian", mlg.endian);
mlg.endian = 0;
putnzint("flg.terse", mlg.terse);
mlg.terse = 0;
putnzint("flg.dollar", mlg.dollar);
mlg.dollar = 0;
putnzint("flg.quad", mlg.quad);
mlg.quad = 0;
putnzint("flg.anno", mlg.anno);
mlg.anno = 0;
putnzint("flg.qa", mlg.qa);
mlg.qa = 0;
putnzint("flg.es", mlg.es);
mlg.es = 0;
putnzint("flg.p", mlg.p);
mlg.p = 0;
putnzint("flg.smp", mlg.smp);
mlg.smp = 0;
putnzint("flg.errorlimit", mlg.errorlimit);
mlg.errorlimit = 0;
putnzint("flg.trans_inv", mlg.trans_inv);
mlg.trans_inv = 0;
putnzint("flg.tpcount", mlg.tpcount);
mlg.tpcount = 0;
if (mlg.stdinc == (char *)0) {
putint("flg.stdinc", 0);
mlg.stdinc = NULL;
} else if (mlg.stdinc == (char *)1) {
putint("flg.stdinc", 1);
mlg.stdinc = NULL;
} else {
putline();
putstring("flg.stdinc", mlg.stdinc);
mlg.stdinc = NULL;
}
putline();
putdefarray("flg.def", mlg.def);
mlg.def = NULL;
putstringarray("flg.idir", mlg.idir);
mlg.idir = NULL;
putline();
putintarray("flg.tpvalue", mlg.tpvalue, sizeof(mlg.tpvalue) / sizeof(int));
putintarray("flg.dbg", mlg.dbg, sizeof(mlg.dbg) / sizeof(int));
putintarray("flg.x", mlg.x, sizeof(mlg.x) / sizeof(int));
putline();
ff = (int *)(&mlg);
mlgsize = sizeof(mlg) / sizeof(int);
for (i = 0; i < mlgsize; ++i) {
if (ff[i] != 0) {
fprintf(dfile, "*** flg[%d] = %d %x\n", i, ff[i], ff[i]);
}
}
} /* dflg */
static bool
simpledtype(DTYPE dtype)
{
if (dtype < DT_NONE || ((int)dtype) >= stb.dt.stg_avail)
return false;
if (DTY(dtype) < TY_NONE || DTY(dtype) > TY_MAX)
return false;
if (dlen(DTY(dtype)) == 1)
return true;
if (DTY(dtype) == TY_PTR)
return true;
return false;
} /* simpledtype */
static int
putenumlist(int member, int len)
{
int r = 0;
if (len < 0)
return 0;
if (SYMLKG(member) > NOSYM) {
r += putenumlist(SYMLKG(member), len);
r += appendstring1(",");
}
if (r >= len)
return r;
r += appendsym1(member);
return r;
} /* putenumlist */
int
putdty(TY_KIND dty)
{
int r;
switch (dty) {
case TY_NONE:
r = appendstring1("none");
break;
case TY_WORD:
r = appendstring1("word");
break;
case TY_DWORD:
r = appendstring1("dword");
break;
case TY_HOLL:
r = appendstring1("hollerith");
break;
case TY_BINT:
r = appendstring1("int*1");
break;
case TY_UBINT:
r = appendstring1("uint*1");
break;
case TY_SINT:
r = appendstring1("short int");
break;
case TY_USINT:
r = appendstring1("unsigned short");
break;
case TY_INT:
r = appendstring1("int");
break;
case TY_UINT:
r = appendstring1("unsigned int");
break;
case TY_INT8:
r = appendstring1("int*8");
break;
case TY_UINT8:
r = appendstring1("unsigned int*8");
break;
case TY_INT128:
r = appendstring1("int128");
break;
case TY_UINT128:
r = appendstring1("uint128");
break;
case TY_128:
r = appendstring1("ty128");
break;
case TY_256:
r = appendstring1("ty256");
break;
case TY_512:
r = appendstring1("ty512");
break;
case TY_REAL:
r = appendstring1("real");
break;
case TY_FLOAT128:
r = appendstring1("float128");
break;
case TY_DBLE:
r = appendstring1("double");
break;
case TY_QUAD:
r = appendstring1("quad");
break;
case TY_CMPLX:
r = appendstring1("complex");
break;
case TY_DCMPLX:
r = appendstring1("double complex");
break;
case TY_CMPLX128:
r = appendstring1("cmplx128");
break;
case TY_BLOG:
r = appendstring1("byte logical");
break;
case TY_SLOG:
r = appendstring1("short logical");
break;
case TY_LOG:
r = appendstring1("logical");
break;
case TY_LOG8:
r = appendstring1("logical*8");
break;
case TY_CHAR:
r = appendstring1("character");
break;
case TY_NCHAR:
r = appendstring1("ncharacter");
break;
case TY_PTR:
r = appendstring1("pointer");
break;
case TY_ARRAY:
r = appendstring1("array");
break;
case TY_STRUCT:
r = appendstring1("struct");
break;
case TY_UNION:
r = appendstring1("union");
break;
case TY_NUMERIC:
r = appendstring1("numeric");
break;
case TY_ANY:
r = appendstring1("any");
break;
case TY_PROC:
r = appendstring1("proc");
break;
case TY_VECT:
r = appendstring1("vect");
break;
case TY_PFUNC:
r = appendstring1("prototype func");
break;
case TY_PARAM:
r = appendstring1("parameter");
break;
default:
// Don't use a case label for TY_FLOAT, because it might alias TY_REAL.
if (dty == TY_FLOAT) {
r = appendstring1("float");
break;
}
r = appendstring1("dty:");
r += appendint1(dty);
r = 0;
break;
}
return r;
} /* putdty */
void
_putdtype(DTYPE dtype, int structdepth)
{
TY_KIND dty;
ADSC *ad;
int numdim;
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
if (dtype >= stb.dt.stg_avail) {
fprintf(dfile, "\ndtype %d out of %d\n", dtype, stb.dt.stg_avail - 1);
return;
}
dty = DTY(dtype);
switch (dty) {
default:
putdty(dty);
break;
case TY_CHAR:
appendstring1("char*");
appendint1(DTyCharLength(dtype));
break;
case TY_ARRAY:
_putdtype(DTySeqTyElement(dtype), structdepth);
ad = AD_DPTR(dtype);
numdim = AD_NUMDIM(ad);
appendstring1("(");
if (numdim >= 1 && numdim <= 7) {
int i;
for (i = 0; i < numdim; ++i) {
if (i)
appendstring1(",");
appendsym1(AD_LWBD(ad, i));
appendstring1(":");
appendsym1(AD_UPBD(ad, i));
}
}
appendstring1(")");
break;
case TY_PTR:
if (simpledtype(DTySeqTyElement(dtype))) {
appendstring1("*");
_putdtype(DTySeqTyElement(dtype), structdepth);
} else {
appendstring1("*(");
_putdtype(DTySeqTyElement(dtype), structdepth);
appendstring1(")");
}
break;
case TY_PARAM:
appendstring1("(");
_putdtype(DTyArgType(dtype), structdepth);
if (DTyArgSym(dtype)) {
appendstring1(" ");
appendsym1(DTyArgSym(dtype));
}
if (DTyArgNext(dtype)) {
appendstring1(", next=");
appendint1(DTyArgNext(dtype));
}
appendstring1(")");
break;
case TY_STRUCT:
case TY_UNION:
if (dty == TY_STRUCT)
appendstring1("struct");
if (dty == TY_UNION)
appendstring1("union");
DTySet(dtype, -dty);
if (DTyAlgTyTag(dtype)) {
appendstring1(" ");
appendsym1(DTyAlgTyTag(dtype));
}
if (DTyAlgTyTag(dtype) == SPTR_NULL || structdepth == 0) {
appendstring1("{");
if (DTyAlgTyMember(dtype)) {
int member;
for (member = DTyAlgTyMember(dtype); member > NOSYM && member < stb.stg_avail;) {
_putdtype(DTYPEG(member), structdepth + 1);
appendstring1(" ");
appendsym1(member);
member = SYMLKG(member);
appendstring1(";");
}
}
appendstring1("}");
}
DTySet(dtype, dty);
break;
case -TY_STRUCT:
case -TY_UNION:
if (dty == -TY_STRUCT)
appendstring1("struct");
if (dty == -TY_UNION)
appendstring1("union");
if (DTyAlgTyTagNeg(dtype)) {
appendstring1(" ");
appendsym1(DTyAlgTyTagNeg(dtype));
} else {
appendstring1(" ");
appendint1(dtype);
}
break;
}
} /* _putdtype */
void
putdtype(DTYPE dtype)
{
_putdtype(dtype, 0);
} /* putdtype */
static int
putdtypex(DTYPE dtype, int len)
{
TY_KIND dty;
int r = 0;
ADSC *ad;
int numdim;
if (len < 0)
return 0;
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
if (dtype >= stb.dt.stg_avail) {
fprintf(dfile, "\ndtype %d out of %d\n", dtype, stb.dt.stg_avail - 1);
return 0;
}
dty = DTY(dtype);
switch (dty) {
default:
r += putdty(dty);
break;
case TY_CHAR:
r += appendstring1("char*");
r += appendint1(DTyCharLength(dtype));
break;
case TY_ARRAY:
r += putdtypex(DTySeqTyElement(dtype), len - r);
ad = AD_DPTR(dtype);
numdim = AD_NUMDIM(ad);
r += appendstring1("(");
if (numdim >= 1 && numdim <= 7) {
int i;
for (i = 0; i < numdim && r < len; ++i) {
if (i)
r += appendstring1(",");
r += appendsym1(AD_LWBD(ad, i));
r += appendstring1(":");
r += appendsym1(AD_UPBD(ad, i));
}
}
r += appendstring1(")");
break;
case TY_PTR:
if (simpledtype(DTySeqTyElement(dtype))) {
r += appendstring1("*");
r += putdtypex(DTySeqTyElement(dtype), len - 4);
} else {
r += appendstring1("*(");
r += putdtypex(DTySeqTyElement(dtype), len - 4);
r += appendstring1(")");
}
break;
case TY_PARAM:
r += appendstring1("(");
r += putdtypex(DTyArgType(dtype), len - 4);
if (DTyArgSym(dtype)) {
r += appendstring1(" ");
r += appendsym1(DTyArgSym(dtype));
}
if (DTyArgNext(dtype)) {
r += appendstring1(", next=");
r += appendint1(DTyArgNext(dtype));
}
r += appendstring1(")");
break;
case TY_STRUCT:
case TY_UNION:
if (dty == TY_STRUCT)
r += appendstring1("struct");
if (dty == TY_UNION)
r += appendstring1("union");
DTySet(dtype, -dty);
if (DTyAlgTyTag(dtype)) {
r += appendstring1(" ");
r += appendsym1(DTyAlgTyTag(dtype));
}
r += appendstring1("{");
if (DTyAlgTyMember(dtype)) {
int member;
for (member = DTyAlgTyMember(dtype);
member > NOSYM && member < stb.stg_avail && r < len;) {
r += putdtypex(DTYPEG(member), len - 4);
r += appendstring1(" ");
r += appendsym1(member);
member = SYMLKG(member);
r += appendstring1(";");
}
}
r += appendstring1("}");
DTySet(dtype, dty);
break;
case -TY_STRUCT:
case -TY_UNION:
if (dty == -TY_STRUCT)
r += appendstring1("struct");
if (dty == -TY_UNION)
r += appendstring1("union");
if (DTyAlgTyTagNeg(dtype)) {
r += appendstring1(" ");
r += appendsym1(DTyAlgTyTagNeg(dtype));
} else {
r += appendstring1(" ");
r += appendint1(dtype);
}
break;
}
return r;
} /* putdtypex */
void
dumpdtype(DTYPE dtype)
{
ADSC *ad;
int numdim;
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
fprintf(dfile, "\n");
putint("dtype", dtype);
if (dtype <= 0 || dtype >= stb.dt.stg_avail) {
fprintf(dfile, "\ndtype %d out of %d\n", dtype, stb.dt.stg_avail - 1);
return;
}
appendstring1(" ");
putdty(DTY(dtype));
switch (DTY(dtype)) {
case TY_ARRAY:
putint("dtype", DTySeqTyElement(dtype));
ad = AD_DPTR(dtype);
numdim = AD_NUMDIM(ad);
putint("numdim", numdim);
putnzint("scheck", AD_SCHECK(ad));
putnsym("zbase", (SPTR) AD_ZBASE(ad)); // ???
putnsym("numelm", AD_NUMELM(ad));
putnsym("sdsc", AD_SDSC(ad));
if (numdim >= 1 && numdim <= 7) {
int i;
for (i = 0; i < numdim; ++i) {
putline();
putint("dim", i);
putint("mlpyr", AD_MLPYR(ad, i));
putint("lwbd", AD_LWBD(ad, i));
putint("upbd", AD_UPBD(ad, i));
}
}
break;
case TY_CHAR:
putint("len", DTyCharLength(dtype));
break;
case TY_PARAM:
putint("dtype", DTyArgType(dtype));
putnsym("sptr", DTyArgSym(dtype));
putint("next", DTyArgNext(dtype));
break;
case TY_PTR:
putint("dtype", DTySeqTyElement(dtype));
break;
case TY_STRUCT:
case TY_UNION:
putsym("member", DTyAlgTyMember(dtype));
putint("size", DTyAlgTySize(dtype));
putnsym("tag", DTyAlgTyTag(dtype));
putint("align", DTyAlgTyAlign(dtype));
break;
case TY_VECT:
fprintf(dfile, "<%lu x ", DTyVecLength(dtype));
putdtype(DTySeqTyElement(dtype));
fputc('>', dfile);
default:
/* simple datatypes, just the one line of info */
putline();
return;
}
putline();
putdtype(dtype);
putline();
} /* dumpdtype */
void
ddtype(DTYPE dtype)
{
dumpdtype(dtype);
} /* ddtype */
void
dumpdtypes(void)
{
DTYPE dtype;
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
fprintf(dfile, "\n********** DATATYPE TABLE **********\n");
for (dtype = (DTYPE)1; ((int)dtype) < stb.dt.stg_avail; dtype += dlen(DTY(dtype))) {
dumpdtype(dtype);
}
fprintf(dfile, "\n");
} /* dumpdtypes */
void
dumpnewdtypes(int olddtavail)
{
DTYPE dtype;
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
fprintf(dfile, "\n********** DATATYPE TABLE **********\n");
for (dtype = (DTYPE)olddtavail; ((int)dtype) < stb.dt.stg_avail; dtype += dlen(DTY(dtype))) {
dumpdtype(dtype);
}
fprintf(dfile, "\n");
} /* dumpnewdtypes */
void
ddtypes(void)
{
dumpdtypes();
} /* ddtypes */
static char prefix[1500];
static char *
smsz(int m)
{
const char *msz = NULL;
static char B[15];
switch (m) {
case MSZ_SBYTE:
msz = "sb";
break;
case MSZ_SHWORD:
msz = "sh";
break;
case MSZ_WORD:
msz = "wd";
break;
case MSZ_SLWORD:
msz = "sl";
break;
case MSZ_BYTE:
msz = "bt";
break;
case MSZ_UHWORD:
msz = "uh";
break;
case MSZ_PTR:
msz = "pt";
break;
case MSZ_ULWORD:
msz = "ul";
break;
case MSZ_F4:
msz = "fl";
break;
case MSZ_F8:
msz = "db";
break;
#ifdef MSZ_I8
case MSZ_I8:
msz = "i8";
break;
#endif
#ifdef MSZ_F10
case MSZ_F10:
msz = "ep";
break;
#endif
default:
break;
}
if (msz ) {
snprintf(B, 15, "%s", msz);
} else {
snprintf(B, 15, "%d", m);
}
return B;
} /* smsz */
char* scond(int);
static void
putstc(ILI_OP opc, int opnum, int opnd)
{
switch (ilstckind(opc, opnum)) {
case 1:
putstring("cond", scond(opnd));
break;
case 2:
putstring("msz", smsz(opnd));
break;
default:
putint("stc", opnd);
break;
}
} /* putstc */
#define OT_UNARY 1
#define OT_BINARY 2
#define OT_LEAF 3
static int
optype(int opc)
{
switch (opc) {
case IL_INEG:
case IL_UINEG:
case IL_KNEG:
case IL_UKNEG:
case IL_SCMPLXNEG:
case IL_DCMPLXNEG:
case IL_FNEG:
case IL_DNEG:
return OT_UNARY;
case IL_LD:
case IL_LDKR:
case IL_LDSP:
case IL_LDDP:
case IL_LDA:
case IL_ICON:
case IL_KCON:
case IL_DCON:
case IL_FCON:
case IL_ACON:
return OT_LEAF;
}
return OT_BINARY;
} /* optype */
static void _printili(int i);
static void
pnme(int n, int ili)
{
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
if (n < 0 || n >= nmeb.stg_avail) {
fprintf(dfile, "nme:%d/%d", n, nmeb.stg_avail);
return;
}
switch (NME_TYPE(n)) {
case NT_VAR:
appendstring1(printname(NME_SYM(n)));
break;
case NT_MEM:
if (NME_NM(n)) {
if (NME_TYPE(NME_NM(n)) == NT_IND)
appendstring1("(");
pnme(NME_NM(n), ili);
if (NME_TYPE(NME_NM(n)) == NT_IND)
appendstring1(")");
} else {
appendstring1("Unknown");
}
if (NME_SYM(n) == 0) {
appendstring1(".real");
} else if (NME_SYM(n) == 1) {
appendstring1(".imag");
} else {
appendstring1(".");
appendstring1(printname(NME_SYM(n)));
}
break;
case NT_ARR:
if (NME_TYPE(NME_NM(n)) == NT_IND)
appendstring1("(");
pnme(NME_NM(n), ili);
if (NME_TYPE(NME_NM(n)) == NT_IND)
appendstring1(")");
if (NME_SYM(n) == NME_NULL) {
appendstring1("[]");
} else if (NME_SYM(n) == 0) {
appendstring1("[");
appendint1(NME_CNST(n));
appendstring1("]");
} else {
appendstring1("[?]");
}
break;
case NT_IND:
appendstring1("*(");
pnme(NME_NM(n), ili);
if (NME_SYM(n) == NME_NULL) {
} else if (NME_SYM(n) == 0) {
if (NME_CNST(n)) {
appendstring1("+");
appendint1(NME_CNST(n));
}
} else {
appendstring1("<");
_printili(ili);
appendstring1(">");
}
appendstring1(")");
break;
case NT_SAFE:
appendstring1("safe(");
pnme(NME_NM(n), ili);
appendstring1(")");
break;
case NT_UNK:
if (NME_SYM(n) == 0) {
appendstring1("unknown");
} else if (NME_SYM(n) == 1) {
appendstring1("volatile");
} else {
appendstring1("unknown:");
appendint1(NME_SYM(n));
}
break;
default:
appendstring1("nme(");
appendint1(n);
appendstring1(":");
appendint1(NME_TYPE(n));
appendstring1(")");
break;
}
} /* pnme */
static void
appendtarget(int sptr)
{
if (sptr > 0 && sptr < stb.stg_avail) {
appendstring1("[bih");
appendint1(ILIBLKG(sptr));
appendstring1("]");
}
} /* appendtarget */
static void
_put_device_type(int d)
{
static const char *names[] = {"*", "host", "nvidia", "?",
"?", "opencl", NULL};
int dd = 1, i, any = 0;
if (!d)
return;
appendstring1(" device_type(");
for (i = 0; names[i]; ++i) {
if (d & dd) {
if (any)
appendstring1(",");
appendstring1(names[i]);
++any;
}
dd <<= 1;
}
if (!any)
appendhex1(d);
appendstring1(")");
} /* _put_device_type */
static void
_printili(int i)
{
int n, k, j, noprs;
ILI_OP opc;
int o, typ;
const char *opval;
static const char *ccval[] = {"??", "==", "!=", "<", ">=", "<=", ">",
"!==", "!!=", "!<", "!>=", "!<=", "!>"};
static const char *ccvalzero[] = {"??", "==0", "!=0", "<0", ">=0",
"<=0", ">0", "!==0", "!!=0", "!<0",
"!>=0", "!<=0", "!>0"};
#define NONE 0
#define UNOP 1
#define postUNOP 2
#define BINOP 3
#define INTRINSIC 4
#define MVREG 5
#define DFREG 6
#define PSCOMM 7
#define ENC_N_OP 8
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
if (g_dout && (i <= 0 || i >= ilib.stg_size)) {
fprintf(dfile, "ili %d out of %d", i, ilib.stg_size - 1);
return;
}
opc = ILI_OPC(i);
if (opc <= 0 || opc >= N_ILI) {
appendstring1("illegalopc(");
appendint1(opc);
appendstring1(")");
return;
}
noprs = ilis[opc].oprs;
typ = NONE;
switch (opc) {
case IL_IADD:
case IL_KADD:
case IL_UKADD:
case IL_FADD:
case IL_DADD:
case IL_UIADD:
case IL_AADD:
opval = "+";
typ = BINOP;
break;
case IL_ISUB:
case IL_KSUB:
case IL_UKSUB:
case IL_FSUB:
case IL_DSUB:
case IL_UISUB:
case IL_ASUB:
opval = "-";
typ = BINOP;
break;
case IL_IMUL:
case IL_KMUL:
case IL_UKMUL:
case IL_FMUL:
case IL_DMUL:
case IL_UIMUL:
opval = "*";
typ = BINOP;
break;
case IL_DDIV:
case IL_KDIV:
case IL_UKDIV:
case IL_FDIV:
case IL_IDIV:
opval = "/";
typ = BINOP;
break;
case IL_KAND:
case IL_AND:
opval = "&";
typ = BINOP;
break;
case IL_KOR:
case IL_OR:
opval = "|";
typ = BINOP;
break;
case IL_KXOR:
case IL_XOR:
opval = "^";
typ = BINOP;
break;
case IL_KMOD:
case IL_KUMOD:
case IL_MOD:
case IL_UIMOD:
opval = "%";
typ = BINOP;
break;
case IL_LSHIFT:
case IL_ULSHIFT:
opval = "<<";
typ = BINOP;
break;
case IL_RSHIFT:
case IL_URSHIFT:
opval = ">>";
typ = BINOP;
break;
case IL_ARSHIFT:
case IL_KARSHIFT:
opval = "a>>";
typ = BINOP;
break;
case IL_KCMP:
case IL_UKCMP:
case IL_ICMP:
case IL_FCMP:
case IL_SCMPLXCMP:
case IL_DCMPLXCMP:
case IL_DCMP:
case IL_ACMP:
case IL_UICMP:
opval = ccval[ILI_OPND(i, 3)];
typ = BINOP;
break;
case IL_INEG:
case IL_KNEG:
case IL_UKNEG:
case IL_DNEG:
case IL_UINEG:
case IL_FNEG:
case IL_SCMPLXNEG:
case IL_DCMPLXNEG:
opval = "-";
typ = UNOP;
break;
case IL_NOT:
case IL_UNOT:
case IL_KNOT:
case IL_UKNOT:
opval = "!";
typ = UNOP;
break;
case IL_ICMPZ:
case IL_KCMPZ:
case IL_UKCMPZ:
case IL_FCMPZ:
case IL_DCMPZ:
case IL_ACMPZ:
case IL_UICMPZ:
opval = ccvalzero[ILI_OPND(i, 2)];
typ = postUNOP;
break;
case IL_FMAX:
case IL_DMAX:
case IL_KMAX:
case IL_UKMAX:
case IL_IMAX:
n = 2;
opval = "max";
typ = INTRINSIC;
break;
case IL_FMIN:
case IL_DMIN:
case IL_KMIN:
case IL_UKMIN:
case IL_IMIN:
n = 2;
opval = "min";
typ = INTRINSIC;
break;
case IL_DBLE:
n = 1;
opval = "dble";
typ = INTRINSIC;
break;
case IL_SNGL:
n = 1;
opval = "sngl";
typ = INTRINSIC;
break;
case IL_FIX:
case IL_FIXK:
case IL_FIXUK:
n = 1;
opval = "fix";
typ = INTRINSIC;
break;
case IL_DFIXK:
case IL_DFIXUK:
n = 1;
opval = "dfix";
typ = INTRINSIC;
break;
case IL_UFIX:
n = 1;
opval = "fix";
typ = INTRINSIC;
break;
case IL_DFIX:
case IL_DFIXU:
n = 1;
opval = "dfix";
typ = INTRINSIC;
break;
case IL_FLOAT:
case IL_FLOATU:
n = 1;
opval = "float";
typ = INTRINSIC;
break;
case IL_DFLOAT:
case IL_DFLOATU:
n = 1;
opval = "dfloat";
typ = INTRINSIC;
break;
case IL_DNEWT:
case IL_FNEWT:
n = 1;
opval = "recip";
typ = INTRINSIC;
break;
case IL_DABS:
n = 1;
opval = "abs";
typ = INTRINSIC;
break;
case IL_FABS:
n = 1;
opval = "abs";
typ = INTRINSIC;
break;
case IL_KABS:
n = 1;
opval = "abs";
typ = INTRINSIC;
break;
case IL_IABS:
n = 1;
opval = "abs";
typ = INTRINSIC;
break;
case IL_FSQRT:
n = 1;
opval = "sqrt";
typ = INTRINSIC;
break;
case IL_DSQRT:
n = 1;
opval = "dsqrt";
typ = INTRINSIC;
break;
case IL_KCJMP:
case IL_UKCJMP:
case IL_ICJMP:
case IL_FCJMP:
case IL_DCJMP:
case IL_ACJMP:
case IL_UICJMP:
_printili(ILI_OPND(i, 1));
appendstring1(" ");
appendstring1(ccval[ILI_OPND(i, 3)]);
appendstring1(" ");
_printili(ILI_OPND(i, 2));
appendstring1(" goto ");
if (full) {
appendint1(ILI_OPND(i, 4));
appendstring1("=");
}
appendsym1(ILI_OPND(i, 4));
appendtarget(ILI_OPND(i, 4));
break;
case IL_KCJMPZ:
case IL_UKCJMPZ:
case IL_ICJMPZ:
case IL_FCJMPZ:
case IL_DCJMPZ:
case IL_ACJMPZ:
case IL_UICJMPZ:
_printili(ILI_OPND(i, 1));
appendstring1(" ");
appendstring1(ccval[ILI_OPND(i, 2)]);
appendstring1(" 0 ");
appendstring1(" goto ");
if (full) {
appendint1(ILI_OPND(i, 3));
appendstring1("=");
}
appendsym1(ILI_OPND(i, 3));
appendtarget(ILI_OPND(i, 3));
break;
case IL_JMP:
appendstring1("goto ");
if (full) {
appendint1(ILI_OPND(i, 1));
appendstring1("=");
}
appendsym1(ILI_OPND(i, 1));
appendtarget(ILI_OPND(i, 1));
break;
case IL_DFRKR:
case IL_DFRIR:
case IL_DFRSP:
case IL_DFRDP:
case IL_DFRCS:
case IL_DFRCD:
case IL_DFRAR:
_printili(ILI_OPND(i, 1));
break;
case IL_QJSR:
case IL_JSR:
appendstring1(printname(ILI_OPND(i, 1)));
appendstring1("(");
j = ILI_OPND(i, 2);
k = 0;
while (ILI_OPC(j) != 0) {
if (k)
appendstring1(", ");
switch (ILI_OPC(j)) {
case IL_DAKR:
case IL_DAAR:
case IL_DADP:
#ifdef IL_DA128
case IL_DA128:
#endif
#ifdef IL_DA256
case IL_DA256:
#endif
case IL_DASP:
case IL_DAIR:
_printili(ILI_OPND(j, 1));
j = ILI_OPND(j, 3);
break;
case IL_ARGKR:
case IL_ARGIR:
case IL_ARGSP:
case IL_ARGDP:
case IL_ARGAR:
_printili(ILI_OPND(j, 1));
j = ILI_OPND(j, 2);
break;
#ifdef IL_ARGRSRV
case IL_ARGRSRV:
appendstring1("rsrv(");
appendint1(ILI_OPND(j, 1));
appendstring1(")");
j = ILI_OPND(j, 2);
break;
#endif
default:
goto done;
}
++k;
}
done:
appendstring1(")");
break;
case IL_MVKR:
opval = "MVKR";
appendstring1(opval);
appendstring1("(");
appendint1(KR_MSH(ILI_OPND(i, 2)));
appendstring1(",");
appendint1(KR_LSH(ILI_OPND(i, 2)));
appendstring1(")");
_printili(ILI_OPND(i, 1));
break;
case IL_MVIR:
opval = "MVIR";
typ = MVREG;
break;
case IL_MVSP:
opval = "MVSP";
typ = MVREG;
break;
case IL_MVDP:
opval = "MVDP";
typ = MVREG;
break;
case IL_MVAR:
opval = "MVAR";
typ = MVREG;
break;
case IL_KRDF:
opval = "KRDF";
appendstring1(opval);
appendstring1("(");
appendint1(KR_MSH(ILI_OPND(i, 1)));
appendstring1(",");
appendint1(KR_LSH(ILI_OPND(i, 1)));
appendstring1(")");
break;
case IL_IRDF:
opval = "IRDF";
typ = DFREG;
break;
case IL_SPDF:
opval = "SPDF";
typ = DFREG;
break;
case IL_DPDF:
opval = "DPDF";
typ = DFREG;
break;
case IL_ARDF:
opval = "ARDF";
typ = DFREG;
break;
case IL_IAMV:
case IL_AIMV:
case IL_KAMV:
case IL_AKMV:
_printili(ILI_OPND(i, 1));
break;
case IL_KIMV:
appendstring1("_K2I(");
_printili(ILI_OPND(i, 1));
appendstring1(")");
break;
case IL_IKMV:
appendstring1("_I2K(");
_printili(ILI_OPND(i, 1));
appendstring1(")");
break;
case IL_UIKMV:
appendstring1("_UI2K(");
_printili(ILI_OPND(i, 1));
appendstring1(")");
break;
case IL_CSE:
case IL_CSEKR:
case IL_CSEIR:
case IL_CSESP:
case IL_CSEDP:
case IL_CSEAR:
case IL_CSECS:
case IL_CSECD:
#ifdef LONG_DOUBLE_FLOAT128
case IL_FLOAT128CSE:
#endif
appendstring1("#<");
_printili(ILI_OPND(i, 1));
appendstring1(">#");
break;
case IL_FREEKR:
opval = "FREEKR";
typ = PSCOMM;
break;
case IL_FREEDP:
opval = "FREEDP";
typ = PSCOMM;
break;
case IL_FREECS:
opval = "FREECS";
typ = PSCOMM;
break;
case IL_FREECD:
opval = "FREECD";
typ = PSCOMM;
break;
case IL_FREESP:
opval = "FREESP";
typ = PSCOMM;
break;
case IL_FREEAR:
opval = "FREEAR";
typ = PSCOMM;
break;
case IL_FREEIR:
opval = "FREEIR";
typ = PSCOMM;
break;
#ifdef LONG_DOUBLE_FLOAT128
case IL_FLOAT128FREE:
opval = "FLOAT128FREE";
typ = PSCOMM;
break;
#endif
case IL_KCON:
case IL_ICON:
case IL_FCON:
case IL_DCON:
appendstring1(printname(ILI_OPND(i, 1)));
break;
case IL_ACON:
j = ILI_OPND(i, 1);
appendstring1("&");
if (ACONOFFG(j)) {
appendstring1("(");
}
if (CONVAL1G(j)) {
appendstring1(printname(CONVAL1G(j)));
if (CONVAL1G(j) > NOSYM && CONVAL1G(j) < stb.stg_avail &&
SCG(CONVAL1G(j)) == SC_PRIVATE)
appendstring1("'");
} else {
appendint1(CONVAL1G(j));
}
if (ACONOFFG(j) > 0) {
appendstring1("+");
appendbigint(ACONOFFG(j));
appendstring1(")");
} else if (ACONOFFG(j) < 0) {
appendstring1("-");
appendbigint(-ACONOFFG(j));
appendstring1(")");
}
break;
case IL_LD:
case IL_LDSP:
case IL_LDDP:
case IL_LDKR:
case IL_LDA:
_printnme(ILI_OPND(i, 2));
if (DBGBIT(10, 4096)) {
appendstring1("<*");
_printili(ILI_OPND(i, 1));
appendstring1("*>");
}
break;
case IL_STKR:
case IL_ST:
case IL_STDP:
case IL_STSP:
case IL_SSTS_SCALAR:
case IL_DSTS_SCALAR:
case IL_STA:
_printnme(ILI_OPND(i, 3));
if (DBGBIT(10, 4096)) {
appendstring1("<*");
_printili(ILI_OPND(i, 2));
appendstring1("*>");
}
appendstring1(" = ");
_printili(ILI_OPND(i, 1));
appendstring1(";");
break;
case IL_LABEL: {
int label = ILI_OPND(i, 1);
appendstring1("label ");
appendsym1(label);
if (BEGINSCOPEG(label)) {
appendstring1(" beginscope(");
appendsym1(ENCLFUNCG(label));
appendstring1(")");
}
if (ENDSCOPEG(label)) {
appendstring1(" endscope(");
appendsym1(ENCLFUNCG(label));
appendstring1(")");
}
break;
}
case IL_NULL:
if (noprs == 1 && ILI_OPND(i, 1) == 0) {
/* expected case, print nothing else */
appendstring1("NULL");
break;
}
/* fall through */
default:
appendstring1(ilis[opc].name);
if (noprs) {
int j;
appendstring1("(");
for (j = 1; j <= noprs; ++j) {
if (j > 1)
appendstring1(",");
switch (IL_OPRFLAG(opc, j)) {
#ifdef ILIO_NULL
case ILIO_NULL:
appendstring1("null=");
appendint1(ILI_OPND(i, j));
break;
#endif
#ifdef ILIO_SYM
case ILIO_SYM:
if (full) {
appendint1(ILI_OPND(i, j));
appendstring1("=");
}
appendsym1(ILI_OPND(i, j));
break;
#endif
#ifdef ILIO_OFF
case ILIO_OFF:
appendstring1("off=");
appendint1(ILI_OPND(i, j));
break;
#endif
#ifdef ILIO_NME
case ILIO_NME:
appendstring1("nme=");
if (full) {
appendint1(ILI_OPND(i, j));
appendstring1("=");
}
_printnme(ILI_OPND(i, j));
break;
#endif
#ifdef ILIO_IR
case ILIO_IR:
appendstring1("ir=");
appendint1(ILI_OPND(i, j));
break;
#endif
#ifdef ILIO_SP
case ILIO_SP:
appendstring1("sp=");
appendint1(ILI_OPND(i, j));
break;
#endif
#ifdef ILIO_DR
case ILIO_DR:
appendstring1("dr=");
appendint1(ILI_OPND(i, j));
break;
#endif
#ifdef ILIO_AR
case ILIO_AR:
appendstring1("ar=");
appendint1(ILI_OPND(i, j));
break;
#endif
#ifdef ILIO_KR
case ILIO_KR:
appendstring1("kr=");
appendint1(ILI_OPND(i, j));
break;
#endif
#ifdef ILIO_XMM
case ILIO_XMM:
/*
bits 0:23 of the operand represent the virtual register
number, and the value of the top byte is 1 for 'ymm'
register, otherwise for 'xmm' register.
*/
if (ILI_OPND(i, j) >> 24 == 1)
appendstring1("ymm=");
else
appendstring1("xmm=");
appendint1(ILI_OPND(i, j) & 0xFFFFFF);
break;
#endif
#ifdef ILIO_LNK
case ILIO_LNK:
#endif
#ifdef ILIO_IRLNK
case ILIO_IRLNK:
#endif
#ifdef ILIO_SPLNK
case ILIO_SPLNK:
#endif
#ifdef ILIO_DPLNK
case ILIO_DPLNK:
#endif
#ifdef ILIO_ARLNK
case ILIO_ARLNK:
#endif
#ifdef ILIO_KRLNK
case ILIO_KRLNK:
#endif
#ifdef ILIO_CSLNK
case ILIO_CSLNK:
#endif
#ifdef ILIO_CDLNK
case ILIO_CDLNK:
#endif
#ifdef ILIO_QPLNK
case ILIO_QPLNK:
#endif
#ifdef ILIO_CQLNK
case ILIO_CQLNK:
#endif
#ifdef ILIO_128LNK
case ILIO_128LNK:
#endif
#ifdef ILIO_256LNK
case ILIO_256LNK:
#endif
#ifdef ILIO_512LNK
case ILIO_512LNK:
#endif
#ifdef ILIO_X87LNK
case ILIO_X87LNK:
#endif
#ifdef ILIO_DOUBLEDOUBLELNK
case ILIO_DOUBLEDOUBLELNK:
#endif
_printili(ILI_OPND(i, j));
break;
default:
appendstring1("op=");
appendint1(ILI_OPND(i, j));
break;
}
}
appendstring1(")");
}
break;
}
switch (typ) {
case BINOP:
o = optype(ILI_OPC(ILI_OPND(i, 1)));
if (o != OT_UNARY && o != OT_LEAF) {
appendstring1("(");
_printili(ILI_OPND(i, 1));
appendstring1(")");
} else {
_printili(ILI_OPND(i, 1));
}
appendstring1(opval);
o = optype(ILI_OPC(ILI_OPND(i, 2)));
if (o != OT_UNARY && o != OT_LEAF) {
appendstring1("(");
_printili(ILI_OPND(i, 2));
appendstring1(")");
} else {
_printili(ILI_OPND(i, 2));
}
break;
case UNOP:
appendstring1(opval);
o = optype(ILI_OPC(ILI_OPND(i, 1)));
if (o != OT_UNARY && o != OT_LEAF) {
appendstring1("(");
_printili(ILI_OPND(i, 1));
appendstring1(")");
} else {
_printili(ILI_OPND(i, 1));
}
break;
case postUNOP:
o = optype(ILI_OPC(ILI_OPND(i, 1)));
if (o != OT_UNARY && o != OT_LEAF) {
appendstring1("(");
_printili(ILI_OPND(i, 1));
appendstring1(")");
} else {
_printili(ILI_OPND(i, 1));
}
appendstring1(opval);
break;
case INTRINSIC:
appendstring1(opval);
appendstring1("(");
for (j = 1; j <= n; ++j) {
_printili(ILI_OPND(i, j));
if (j != n)
appendstring1(",");
}
appendstring1(")");
break;
case MVREG:
appendstring1(opval);
appendstring1(".");
appendint1(ILI_OPND(i, 2));
appendstring1("=");
_printili(ILI_OPND(i, 1));
break;
case DFREG:
appendstring1(opval);
appendstring1("(");
appendint1(ILI_OPND(i, 1));
appendstring1(")");
break;
case PSCOMM:
appendstring1(opval);
appendstring1(" = ");
_printili(ILI_OPND(i, 1));
appendstring1(";");
break;
case ENC_N_OP:
appendstring1(opval);
appendstring1("#0x");
appendhex1(ILI_OPND(i, n + 1));
appendstring1("(");
for (j = 1; j <= n; ++j) {
_printili(ILI_OPND(i, j));
if (j != n)
appendstring1(",");
}
appendstring1(")");
break;
default:
break;
}
} /* _printili */
/*
* call _printili with linelen = 0, so no prefix blanks are added
*/
void
printili(int i)
{
linelen = 0;
_printili(i);
linelen = 0;
} /* printili */
/**
* call _printilt with linelen = 0, so no prefix blanks are added
*/
void
printilt(int i)
{
linelen = 0;
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
snprintf(BUF, BUFSIZE, "ilt:%-4d", i);
putit();
if (iltb.stg_base && i > 0 && i < iltb.stg_size && ILT_ILIP(i)) {
snprintf(BUF, BUFSIZE, "lineno:%-4d ili:%-4d ", ILT_LINENO(i),
ILT_ILIP(i));
putit();
_printili(ILT_ILIP(i));
}
putline();
linelen = 0;
} /* printilt */
void
putili(const char *name, int ilix)
{
if (ilix <= 0)
return;
if (full) {
snprintf(BUF, BUFSIZE, "%s:%d=", name, ilix);
} else {
snprintf(BUF, BUFSIZE, "%s=", name);
}
putit();
_printili(ilix);
} /* putili */
void
printblock(int block)
{
int ilt;
if (bihb.stg_base == NULL) {
fprintf(dfile, "bihb.stg_base not allocated\n");
return;
}
db(block);
for (ilt = BIH_ILTFIRST(block); ilt; ilt = ILT_NEXT(ilt)) {
if (full) {
snprintf(BUF, BUFSIZE, "ilt:%d", ilt);
putit();
}
if (ilt >= 0 && ilt < iltb.stg_size) {
putint("lineno", ILT_LINENO(ilt));
putili("ili", ILT_ILIP(ilt));
putline();
}
}
} /* printblock */
void
printblockline(int block)
{
int ilt;
if (bihb.stg_base == NULL) {
fprintf(dfile, "bihb.stg_base not allocated\n");
return;
}
db(block);
for (ilt = BIH_ILTFIRST(block); ilt; ilt = ILT_NEXT(ilt)) {
if (full) {
snprintf(BUF, BUFSIZE, "ilt:%d", ilt);
putit();
}
if (ilt >= 0 && ilt < iltb.stg_size) {
putint("lineno", ILT_LINENO(ilt));
putint("findex", ILT_FINDEX(ilt));
putili("ili", ILT_ILIP(ilt));
putline();
}
}
} /* printblockline */
void
printblocks(void)
{
int block;
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
if (bihb.stg_base == NULL) {
fprintf(dfile, "bihb.stg_base not allocated\n");
return;
}
if (full) {
fprintf(dfile, "func_count=%d, curr_func=%d=%s\n", gbl.func_count,
GBL_CURRFUNC, GBL_CURRFUNC > 0 ? SYMNAME(GBL_CURRFUNC) : "");
} else {
fprintf(dfile, "func_count=%d, curr_func=%s\n", gbl.func_count,
GBL_CURRFUNC > 0 ? SYMNAME(GBL_CURRFUNC) : "");
}
#ifdef CUDAG
if (GBL_CURRFUNC > 0)
putcuda("cuda", CUDAG(GBL_CURRFUNC));
fprintf(dfile, "\n");
#endif
block = BIHNUMG(GBL_CURRFUNC);
for (; block; block = BIH_NEXT(block)) {
printblock(block);
if (BIH_LAST(block))
break;
fprintf(dfile, "\n");
}
} /* printblocks */
void
printblockt(int firstblock, int lastblock)
{
int block, limit = 1000, b;
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
if (bihb.stg_base == NULL) {
fprintf(dfile, "bihb.stg_base not allocated\n");
return;
}
fprintf(dfile, "func_count=%d, curr_func=%d=%s, blocks=%d:%d\n",
gbl.func_count, GBL_CURRFUNC,
GBL_CURRFUNC > 0 ? SYMNAME(GBL_CURRFUNC) : "", firstblock, lastblock);
block = BIHNUMG(GBL_CURRFUNC);
for (; block; block = BIH_NEXT(block)) {
if (block == firstblock)
break;
}
if (block != firstblock) {
fprintf(dfile, "block:%d not found\n", firstblock);
for (b = 0, block = firstblock; block && b < limit;
block = BIH_NEXT(block), ++b) {
printblock(block);
if (BIH_LAST(block) || block == lastblock)
break;
fprintf(dfile, "\n");
}
if (block != lastblock)
fprintf(dfile, "block:%d not found\n", lastblock);
} else {
for (b = 0; block && b < limit; block = BIH_NEXT(block), ++b) {
printblock(block);
if (BIH_LAST(block) || block == lastblock)
break;
fprintf(dfile, "\n");
}
if (block != lastblock)
fprintf(dfile, "block:%d not found\n", lastblock);
}
} /* printblockt */
void
printblocktt(int firstblock, int lastblock)
{
int block;
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
if (bihb.stg_base == NULL) {
fprintf(dfile, "bihb.stg_base not allocated\n");
return;
}
fprintf(dfile, "func_count=%d, curr_func=%d=%s, blocks=%d:%d\n",
gbl.func_count, GBL_CURRFUNC,
GBL_CURRFUNC > 0 ? SYMNAME(GBL_CURRFUNC) : "", firstblock, lastblock);
for (block = firstblock; block; block = BIH_NEXT(block)) {
printblock(block);
if (BIH_LAST(block) || block == lastblock)
break;
fprintf(dfile, "\n");
}
if (block != lastblock) {
fprintf(dfile, "block:%d not found\n", lastblock);
}
} /* printblocktt */
void
printblocksline(void)
{
int block;
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
if (bihb.stg_base == NULL) {
fprintf(dfile, "bihb.stg_base not allocated\n");
return;
}
fprintf(dfile, "func_count=%d, curr_func=%d=%s\n", gbl.func_count,
GBL_CURRFUNC, GBL_CURRFUNC > 0 ? SYMNAME(GBL_CURRFUNC) : "");
block = BIHNUMG(GBL_CURRFUNC);
for (; block; block = BIH_NEXT(block)) {
printblockline(block);
if (BIH_LAST(block))
break;
fprintf(dfile, "\n");
}
} /* printblocksline */
void
dili(int ilix)
{
ILI_OP opc;
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
if (full)
putint("ili", ilix);
if (ilix <= 0 || ilix >= ilib.stg_size) {
putstring1("out of bounds");
putline();
return;
}
opc = ILI_OPC(ilix);
if (opc <= 0 || opc >= N_ILI) {
putint("illegalopc", opc);
} else {
int noprs, j;
static const char *iltypes[] = {"(null)", "(arth)", "(branch)", "(cons)",
"(define)", "(load)", "(move)", "(other)",
"(proc)", "(store)"};
putstring("opc", IL_NAME(opc));
putval1(IL_TYPE(opc), iltypes, SIZEOF(iltypes));
noprs = IL_OPRS(opc);
for (j = 1; j <= noprs; ++j) {
int opnd;
opnd = ILI_OPND(ilix, j);
switch (IL_OPRFLAG(opc, j)) {
case ILIO_SYM:
putsym("sym", (SPTR)opnd);
if (opc == IL_ACON) {
putnsym("base", SymConval1((SPTR)opnd));
putnzbigint("offset", ACONOFFG(opnd));
}
break;
case ILIO_OFF:
putsym("sym", (SPTR)opnd);
break;
case ILIO_NME:
putnme("nme", opnd);
break;
case ILIO_STC:
putstc(opc, j, opnd);
break;
case ILIO_LNK:
if (full) {
putint("lnk", opnd);
} else {
putstring1("lnk");
}
break;
case ILIO_IRLNK:
if (full) {
putint("irlnk", opnd);
} else {
putstring1("irlnk");
}
break;
case ILIO_KRLNK:
if (full) {
putint("krlnk", opnd);
} else {
putstring1("krlnk");
}
break;
case ILIO_ARLNK:
if (full) {
putint("arlnk", opnd);
} else {
putstring1("arlnk");
}
break;
case ILIO_SPLNK:
if (full) {
putint("splnk", opnd);
} else {
putstring1("splnk");
}
break;
case ILIO_DPLNK:
if (full) {
putint("dplnk", opnd);
} else {
putstring1("dplnk");
}
break;
#ifdef ILIO_CSLNK
case ILIO_CSLNK:
if (full) {
putint("cslnk", opnd);
} else {
putstring1("cslnk");
}
break;
case ILIO_QPLNK:
if (full) {
putint("qplnk", opnd);
} else {
putstring1("qplnk");
}
break;
case ILIO_CDLNK:
if (full) {
putint("cdlnk", opnd);
} else {
putstring1("cdlnk");
}
break;
case ILIO_CQLNK:
if (full) {
putint("cqlnk", opnd);
} else {
putstring1("cqlnk");
}
break;
case ILIO_128LNK:
if (full) {
putint("128lnk", opnd);
} else {
putstring1("128lnk");
}
break;
case ILIO_256LNK:
if (full) {
putint("256lnk", opnd);
} else {
putstring1("256lnk");
}
break;
case ILIO_512LNK:
if (full) {
putint("512lnk", opnd);
} else {
putstring1("512lnk");
}
break;
#ifdef LONG_DOUBLE_FLOAT128
case ILIO_FLOAT128LNK:
if (full) {
putint("float128lnk", opnd);
} else {
putstring1("float128lnk");
}
break;
#endif
#endif /* ILIO_CSLNK */
#ifdef ILIO_PPLNK
case ILIO_PPLNK:
if (full) {
putint("pplnk", opnd);
} else {
putstring1("pplnk");
}
break;
#endif
case ILIO_IR:
putint("ir", opnd);
break;
#ifdef ILIO_KR
case ILIO_KR:
putpint("kr", opnd);
break;
#endif
case ILIO_AR:
putint("ar", opnd);
break;
case ILIO_SP:
putint("sp", opnd);
break;
case ILIO_DP:
putint("dp", opnd);
break;
default:
put2int("Unknown", IL_OPRFLAG(opc, j), opnd);
break;
}
}
}
if (full) {
putnzint("alt", ILI_ALT(ilix));
} else {
if (ILI_ALT(ilix)) {
putstring1("alt");
}
}
putnzint("count/rat/repl", ILI_COUNT(ilix));
if (full)
putnzint("hshlnk", ILI_HSHLNK(ilix));
putnzint("visit", ILI_VISIT(ilix));
if (full)
putnzint("vlist", ILI_VLIST(ilix));
putline();
} /* dili */
static void
dilitreex(int ilix, int l, int notlast)
{
ILI_OP opc;
int noprs, j, jj, nlinks;
int nshift = 0;
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
fprintf(dfile, "%s", prefix);
dili(ilix);
if (ilix <= 0 || ilix >= ilib.stg_size)
return;
if (l) {
if (notlast) {
strcpy(prefix + l - 4, "| ");
} else {
strcpy(prefix + l - 4, " ");
}
}
opc = ILI_OPC(ilix);
if (opc >= 0 && opc < N_ILI) {
noprs = IL_OPRS(opc);
} else {
noprs = 0;
}
nlinks = 0;
for (j = 1; j <= noprs; ++j) {
if (IL_ISLINK(opc, j)) {
++nlinks;
}
}
if (ILI_ALT(ilix))
++nlinks;
switch (opc) {
case IL_CSEIR:
case IL_CSESP:
case IL_CSEDP:
case IL_CSECS:
case IL_CSECD:
case IL_CSEAR:
case IL_CSEKR:
case IL_CSE:
#ifdef LONG_DOUBLE_FLOAT128
case IL_FLOAT128CSE:
#endif
/* don't recurse unless we're at the top level */
if (l > 4)
nlinks = 0;
break;
case IL_ACCCOPY:
case IL_ACCCOPYIN:
case IL_ACCCOPYOUT:
case IL_ACCLOCAL:
case IL_ACCCREATE:
case IL_ACCDELETE:
case IL_ACCPRESENT:
case IL_ACCPCOPY:
case IL_ACCPCOPYIN:
case IL_ACCPCOPYOUT:
case IL_ACCPCREATE:
case IL_ACCPNOT:
case IL_ACCTRIPLE:
nshift = 1;
break;
default :
break;
}
if (nlinks) {
for (jj = 1; jj <= noprs; ++jj) {
j = jj;
if (nshift) {
j += nshift;
if (j > noprs)
j -= noprs;
}
if (IL_ISLINK(opc, j)) {
int opnd;
opnd = ILI_OPND(ilix, j);
if (ILI_OPC(opnd) != IL_NULL) {
strcpy(prefix + l, "+-- ");
dilitreex(opnd, l + 4, --nlinks);
}
prefix[l] = '\0';
}
}
if (ILI_ALT(ilix) && ILI_ALT(ilix) != ilix &&
ILI_OPC(ILI_ALT(ilix)) != IL_NULL) {
int opnd;
opnd = ILI_ALT(ilix);
strcpy(prefix + l, "+-- ");
dilitreex(opnd, l + 4, --nlinks);
prefix[l] = '\0';
}
}
} /* dilitreex */
void
dilitre(int ilix)
{
prefix[0] = ' ';
prefix[1] = ' ';
prefix[2] = ' ';
prefix[3] = ' ';
prefix[4] = '\0';
dilitreex(ilix, 4, 0);
prefix[0] = '\0';
} /* dilitre */
void
dilt(int ilt)
{
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
if (iltb.stg_base == NULL) {
fprintf(dfile, "iltb.stg_base not allocated\n");
return;
}
if (full) {
putint("ilt", ilt);
} else {
putstring1("ilt:");
}
if (ilt <= 0 || ilt >= iltb.stg_size) {
fprintf(dfile, "\nilt %d out of %d\n", ilt, iltb.stg_size - 1);
return;
}
if (full) {
putnzint("ilip", ILT_ILIP(ilt));
putnzint("prev", ILT_PREV(ilt));
putnzint("next", ILT_NEXT(ilt));
#ifdef ILT_GUARD
putnzint("guard", ILT_GUARD(ilt));
#endif
}
putnzint("lineno", ILT_LINENO(ilt));
putnzint("findex", ILT_FINDEX(ilt));
#ifdef ILT_EXSDSCUNSAFE
putbit("sdscunsafe", ILT_EXSDSCUNSAFE(ilt));
#endif
putbit("st", ILT_ST(ilt));
putbit("br", ILT_BR(ilt));
putbit("can_throw", ILT_CAN_THROW(ilt));
putbit("dbgline", ILT_DBGLINE(ilt));
putbit("delete", ILT_DELETE(ilt));
putbit("ex", ILT_EX(ilt));
putbit("free", ILT_FREE(ilt));
putbit("ignore", ILT_IGNORE(ilt));
putbit("split", ILT_SPLIT(ilt));
putbit("cplx", ILT_CPLX(ilt));
putbit("keep", ILT_KEEP(ilt));
putbit("mcache", ILT_MCACHE(ilt));
putbit("nodel", ILT_NODEL(ilt));
#ifdef ILT_DELEBB
putbit("delebb", ILT_DELEBB(ilt));
#endif
#ifdef ILT_EQASRT
putbit("eqasrt", ILT_EQASRT(ilt));
#endif
#ifdef ILT_PREDC
putbit("predc", ILT_PREDC(ilt));
#endif
putline();
} /* dilt */
void
dumpilt(int ilt)
{
dilt(ilt);
if (ilt >= 0 && ilt < iltb.stg_size)
dilitre(ILT_ILIP(ilt));
} /* dumpilt */
void
dumpilts()
{
int bihx, iltx;
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
if (bihb.stg_base == NULL) {
fprintf(dfile, "bihb.stg_base not allocated\n");
return;
}
bihx = BIHNUMG(gbl.currsub);
for (; bihx; bihx = BIH_NEXT(bihx)) {
db(bihx);
for (iltx = BIH_ILTFIRST(bihx); iltx; iltx = ILT_NEXT(iltx)) {
dilt(iltx);
}
if (BIH_LAST(bihx))
break;
fprintf(dfile, "\n");
}
} /* dumpilts */
void
db(int block)
{
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
if (bihb.stg_base == NULL) {
fprintf(dfile, "bihb.stg_base not allocated\n");
return;
}
if (full) {
putint("block", block);
} else {
putstring1("block:");
}
if (block <= 0 || block >= bihb.stg_size) {
fprintf(dfile, "\nblock %d out of %d\n", block, bihb.stg_size - 1);
return;
}
putnzint("lineno", BIH_LINENO(block));
if (full)
putnzint("iltfirst", BIH_ILTFIRST(block));
if (full)
putnzint("iltlast", BIH_ILTLAST(block));
if (full)
putnzint("prev", BIH_PREV(block));
if (full)
putnzint("next", BIH_NEXT(block));
putnsym("label", BIH_LABEL(block));
if (BIH_LABEL(block)) {
putnzint("rfcnt", RFCNTG(BIH_LABEL(block)));
putbit("vol", VOLG(BIH_LABEL(block)));
}
putnzint("assn", BIH_ASSN(block));
putnzint("rgset", BIH_RGSET(block));
#ifdef BIH_ASM
putbit("asm", BIH_ASM(block));
#endif
putbit("rd", BIH_RD(block));
putbit("ft", BIH_FT(block));
putbit("en", BIH_EN(block));
putbit("ex", BIH_EX(block));
#ifdef BIH_EXSDSCUNSAFE
putbit("sdscunsafe", BIH_EXSDSCUNSAFE(block));
#endif
putbit("last", BIH_LAST(block));
putbit("xt", BIH_XT(block));
putbit("pl", BIH_PL(block));
putbit("ztrp", BIH_ZTRP(block));
putbit("guardee", BIH_GUARDEE(block));
putbit("guarder", BIH_GUARDER(block));
putbit("smove", BIH_SMOVE(block));
putbit("nobla", BIH_NOBLA(block));
putbit("nomerge", BIH_NOMERGE(block));
putbit("qjsr", BIH_QJSR(block));
putbit("head", BIH_HEAD(block));
putbit("tail", BIH_TAIL(block));
putbit("innermost", BIH_INNERMOST(block));
putbit("mexits", BIH_MEXITS(block));
putbit("ozcr", BIH_OZCR(block));
putbit("par", BIH_PAR(block));
putbit("cs", BIH_CS(block));
putbit("streg", BIH_STREG(block));
putbit("vpar", BIH_VPAR(block));
putbit("enlab", BIH_ENLAB(block));
putbit("mark", BIH_MARK(block));
putbit("mark2", BIH_MARK2(block));
putbit("mark3", BIH_MARK3(block));
putbit("parloop", BIH_PARLOOP(block));
putbit("parsect", BIH_PARSECT(block));
putbit("resid", BIH_RESID(block));
putbit("ujres", BIH_UJRES(block));
putbit("simd", BIH_SIMD(block));
putbit("ldvol", BIH_LDVOL(block));
putbit("stvol", BIH_STVOL(block));
putbit("task", BIH_TASK(block));
putbit("paraln", BIH_PARALN(block));
putbit("invif", BIH_INVIF(block));
putbit("noinvif", BIH_NOINVIF(block));
putbit("combst", BIH_COMBST(block));
putbit("deletable", BIH_DELETABLE(block));
putbit("vcand", BIH_VCAND(block));
putbit("accel", BIH_ACCEL(block));
putbit("endaccel", BIH_ENDACCEL(block));
putbit("accdata", BIH_ACCDATA(block));
putbit("endaccdata", BIH_ENDACCDATA(block));
putbit("kernel", BIH_KERNEL(block));
putbit("endkernel", BIH_ENDKERNEL(block));
putbit("midiom", BIH_MIDIOM(block));
putbit("nodepchk", BIH_NODEPCHK(block));
putbit("doconc", BIH_DOCONC(block));
putline();
#ifdef BIH_FINDEX
if (BIH_FINDEX(block) || BIH_FTAG(block)) {
putint("findex", BIH_FINDEX(block));
putint("ftag", BIH_FTAG(block));
/* The casting from double to int may cause an overflow in int.
* Just take a short-cut here for the ease of debugging. Will need
* to create a new function to accommodate the non-int types.
*/
if (BIH_BLKCNT(block) != -1.0)
putdouble("blkCnt", BIH_BLKCNT(block));
if (BIH_FINDEX(block) > 0 && BIH_FINDEX(block) < fihb.stg_avail) {
if (FIH_DIRNAME(BIH_FINDEX(block))) {
putstring1(FIH_DIRNAME(BIH_FINDEX(block)));
putstring1t("/");
putstring1t(FIH_FILENAME(BIH_FINDEX(block)));
} else {
putstring1(FIH_FILENAME(BIH_FINDEX(block)));
}
if (FIH_FUNCNAME(BIH_FINDEX(block)) != NULL) {
putstring1(FIH_FUNCNAME(BIH_FINDEX(block)));
}
} else if (BIH_FINDEX(block) < 0 || BIH_FINDEX(block) >= fihb.stg_avail) {
puterr("bad findex value");
}
putline();
}
#endif
} /* db */
void
dumpblock(int block)
{
int ilt;
if (bihb.stg_base == NULL) {
fprintf(dfile, "bihb.stg_base not allocated\n");
return;
}
db(block);
for (ilt = BIH_ILTFIRST(block); ilt; ilt = ILT_NEXT(ilt)) {
dilt(ilt);
if (ilt >= 0 && ilt < iltb.stg_size)
dilitre(ILT_ILIP(ilt));
}
} /* dumpblock */
void
dumptblock(const char *title, int block)
{
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
fprintf(dfile, "\n********** dump block %d %s **********\n", block, title);
dumpblock(block);
} /* dumptblock */
void
dbih(void)
{
int block;
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
if (bihb.stg_base == NULL) {
fprintf(dfile, "bihb.stg_base not allocated\n");
return;
}
block = BIHNUMG(gbl.currsub);
for (; block; block = BIH_NEXT(block)) {
dumpblock(block);
if (BIH_LAST(block))
break;
fprintf(dfile, "\n");
}
} /* dbih */
void
dbihonly(void)
{
int block;
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
if (bihb.stg_base == NULL) {
fprintf(dfile, "bihb.stg_base not allocated\n");
return;
}
block = BIHNUMG(gbl.currsub);
for (; block; block = BIH_NEXT(block)) {
db(block);
if (BIH_LAST(block))
break;
fprintf(dfile, "\n");
}
} /* dbihonly */
void
dumpblocksonly(void)
{
dbihonly();
} /* dumpblocksonly */
void
dumpblocks(const char *title)
{
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
fprintf(dfile, "\n********** BLOCK INFORMATION HEADER TABLE **********\n");
fprintf(dfile, "%s called\n", title);
dbih();
fprintf(dfile, "%s done\n**********\n\n", title);
} /* dumpblocks */
#ifdef FIH_FULLNAME
void
dfih(int f)
{
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
if (fihb.stg_base == NULL) {
fprintf(dfile, "fihb.stg_base not allocated\n");
return;
}
if (full) {
putint("fih", f);
} else {
putstring1("fih:");
}
if (f <= 0 || f >= fihb.stg_size) {
fprintf(dfile, "\nfile %d out of %d\n", f, fihb.stg_size - 1);
return;
}
putstring("fullname", FIH_FULLNAME(f));
if (FIH_FUNCNAME(f) != NULL && FIH_FUNCNAME(f)[0] != '\0') {
putstring("funcname", FIH_FUNCNAME(f));
}
putint("functag", FIH_FUNCTAG(f));
putint("srcline", FIH_SRCLINE(f));
putnzint("level", FIH_LEVEL(f));
putnzint("parent", FIH_PARENT(f));
putnzint("lineno", FIH_LINENO(f));
putnzint("next", FIH_NEXT(f));
putnzint("child", FIH_CHILD(f));
putbit("included", FIH_INC(f));
putbit("inlined", FIH_INL(f));
putbit("ipainlined", FIH_IPAINL(f));
putbit("ccff", FIH_FLAGS(f) & FIH_CCFF);
putbit("ccffinfo", (FIH_CCFFINFO(f) != NULL));
putline();
} /* dfih */
void
dumpfile(int f)
{
dfih(f);
} /* dumpfile */
void
dumpfiles(void)
{
int f;
for (f = 1; f < fihb.stg_avail; ++f) {
dfih(f);
}
} /* dumpfiles */
#endif
#ifdef NME_PTE
void
putptelist(int pte)
{
for (; pte > 0; pte = (PTE_NEXT(pte) == pte ? -1 : PTE_NEXT(pte))) {
switch (PTE_TYPE(pte)) {
case PT_UNK:
putstring1("unk");
break;
case PT_PSYM:
putsym("psym", PTE_SPTR(pte));
break;
case PT_ISYM:
putsym("isym", PTE_SPTR(pte));
break;
case PT_ANON:
putint("anon", PTE_VAL(pte));
break;
case PT_GDYN:
putint("gdyn", PTE_VAL(pte));
break;
case PT_LDYN:
putint("ldyn", PTE_VAL(pte));
break;
case PT_NLOC:
putstring1("nonlocal");
break;
default:
put2int("???", PTE_TYPE(pte), PTE_VAL(pte));
break;
}
}
} /* putptelist */
#endif
static void
_printnme(int n)
{
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
if (n < 0 || n >= nmeb.stg_avail) {
putint("nme", n);
return;
}
switch (NME_TYPE(n)) {
case NT_VAR:
appendstring1(printname(NME_SYM(n)));
if (NME_SYM(n) > NOSYM && NME_SYM(n) < stb.stg_avail &&
SCG(NME_SYM(n)) == SC_PRIVATE)
appendstring1("'");
break;
case NT_MEM:
if (NME_NM(n)) {
_printnme(NME_NM(n));
} else {
appendstring1("Unknown");
}
if (NME_SYM(n) == 0) {
appendstring1(".real");
} else if (NME_SYM(n) == 1) {
appendstring1(".imag");
} else {
appendstring1(".");
appendstring1(printname(NME_SYM(n)));
}
break;
case NT_ARR:
if (NME_NM(n)) {
_printnme(NME_NM(n));
} else {
appendstring1("Unknown");
}
if (NME_SYM(n) == 0) {
appendstring1("[");
appendint1(NME_CNST(n));
appendstring1("]");
} else if (NME_SUB(n) != 0) {
appendstring1("[");
_printili(NME_SUB(n));
appendstring1("]");
} else {
appendstring1("[?]");
}
break;
case NT_IND:
appendstring1("*(");
if (NME_NM(n)) {
_printnme(NME_NM(n));
} else {
appendstring1("Unknown");
}
if (NME_SYM(n) == NME_NULL) {
} else if (NME_SYM(n) == 0) {
if (NME_CNST(n)) {
appendstring1("+");
appendint1(NME_CNST(n));
}
} else {
appendstring1("+?");
}
appendstring1(")");
if (NME_SUB(n) != 0) {
appendstring1("[");
_printili(NME_SUB(n));
appendstring1("]");
}
break;
case NT_UNK:
if (NME_SYM(n) == 0) {
appendstring1("unknown");
} else if (NME_SYM(n) == 1) {
appendstring1("volatile");
} else {
appendstring1("unknown:");
appendint1(NME_SYM(n));
}
break;
default:
appendstring1("nme(");
appendint1(n);
appendstring1(":");
appendint1(NME_TYPE(n));
appendstring1(")");
break;
}
} /* _printnme */
void
pprintnme(int n)
{
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
putstring1("");
_printnme(n);
} /* pprintnme */
void
printnme(int n)
{
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
linelen = 0;
_printnme(n);
} /* printnme */
static const char *nmetypes[] = {"unknown ", "indirect", "variable",
"member ", "element ", "safe "};
void
_dumpnme(int n, bool dumpdefsuses)
{
int store, pte;
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
if (n <= 0 || n >= nmeb.stg_avail) {
fprintf(dfile, "\nNME %d out of %d\n", n, nmeb.stg_avail - 1);
return;
}
if (nmeb.stg_base == NULL) {
fprintf(dfile, "nmeb.stg_base not allocated\n");
return;
}
if (full) {
putint("nme", n);
} else {
putstring1("nme");
}
putval1(NME_TYPE(n), nmetypes, SIZEOF(nmetypes));
switch (NME_TYPE(n)) {
case NT_VAR:
putsym("var", NME_SYM(n));
break;
case NT_MEM:
pprintnme(n);
if (NME_SYM(n) == 0) {
putstring1(".real");
} else if (NME_SYM(n) == 1) {
putstring1(".imag");
break;
} else {
putsym("member", NME_SYM(n));
}
break;
case NT_ARR:
case NT_IND:
pprintnme(n);
if (NME_SYM(n) == NME_NULL) {
putint("sym", -1);
} else if (NME_SYM(n) == 0) {
} else {
if (NME_SYM(n) > 0 && NME_SYM(n) < stb.stg_avail) {
putsym("sym", NME_SYM(n));
} else {
putnzint("sym", NME_SYM(n));
}
}
break;
case NT_UNK:
pprintnme(n);
break;
default:
if (NME_SYM(n) > 0 && NME_SYM(n) < stb.stg_avail) {
putsym("sym", NME_SYM(n));
} else {
putnzint("sym", NME_SYM(n));
}
break;
}
putnzint("nm", NME_NM(n));
#ifdef NME_BASE
putnzint("base", NME_BASE(n));
#endif
putnzint("cnst", NME_CNST(n));
putnzint("cnt", NME_CNT(n));
if (full & 1)
putnzint("hashlink", NME_HSHLNK(n));
putnzint("inlarr", NME_INLARR(n));
putnzint("rat/rfptr", NME_RAT(n));
putnzint("stl", NME_STL(n));
putnzint("sub", NME_SUB(n));
putnzint("mask", NME_MASK(n));
#ifdef NME_PTE
pte = NME_PTE(n);
if (dumpdefsuses && pte) {
putline();
putstring1("pointer targets:");
putptelist(pte);
}
#endif
} /* _dumpnme */
void
dumpnnme(int n)
{
linelen = 0;
_dumpnme(n, false);
putline();
} /* dumpnme */
void
dumpnme(int n)
{
linelen = 0;
_dumpnme(n, true);
putline();
} /* dumpnme */
void
dumpnmes(void)
{
int n;
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
if (nmeb.stg_base == NULL) {
fprintf(dfile, "nmeb.stg_base not allocated\n");
return;
}
fprintf(dfile, "\n********** NME TABLE **********\n");
for (n = 1; n < nmeb.stg_avail; ++n) {
fprintf(dfile, "\n");
dumpnme(n);
}
fprintf(dfile, "\n");
} /* dumpnmes */
#endif
char *
printname(int sptr)
{
extern void cprintf(char *s, const char *format, INT *val);
static char b[200];
double dd;
union {
float ff;
ISZ_T ww;
} xx;
if (sptr <= 0 || sptr >= stb.stg_avail) {
snprintf(b, 200, "symbol %d out of %d", sptr, stb.stg_avail - 1);
return b;
}
if (STYPEG(sptr) == ST_CONST) {
INT num[2], cons1, cons2;
int pointee;
char *bb, *ee;
switch (DTY(DTYPEG(sptr))) {
case TY_INT8:
case TY_UINT8:
num[0] = CONVAL1G(sptr);
num[1] = CONVAL2G(sptr);
ui64toax(num, b, 22, 0, 10);
break;
case TY_INT:
snprintf(b, 200, "%10d", CONVAL2G(sptr));
break;
case TY_FLOAT:
xx.ww = CONVAL2G(sptr);
if ((xx.ww & 0x7f800000) == 0x7f800000) {
/* Infinity or NaN */
snprintf(b, 200, ("(float)(0x%8.8" ISZ_PF "x)"), xx.ww);
} else {
dd = xx.ff;
snprintf(b, 200, "%.8ef", dd);
}
break;
case TY_DBLE:
num[0] = CONVAL1G(sptr);
num[1] = CONVAL2G(sptr);
if ((num[0] & 0x7ff00000) == 0x7ff00000) {
/* Infinity or NaN */
snprintf(b, 200, "(double)(0x%8.8x%8.8xLL)", num[0], num[1]);
} else {
cprintf(b, "%.17le", num);
}
break;
case TY_CMPLX:
xx.ww = CONVAL1G(sptr);
if ((xx.ww & 0x7f800000) == 0x7f800000) {
/* Infinity or NaN */
int len;
len = snprintf(b, 200, ("(0x%8.8" ISZ_PF "x, "), xx.ww);
bb = b + len;
} else {
b[0] = '(';
sprintf(&b[1], "%17.10e", xx.ff);
b[18] = ',';
b[19] = ' ';
bb = &b[20];
}
xx.ww = CONVAL2G(sptr);
if ((xx.ww & 0x7f800000) == 0x7f800000) {
snprintf(bb, 200, ("(0x%8.8" ISZ_PF "x, "), xx.ww);
} else {
sprintf(bb, "%17.10e", xx.ff);
bb += 17;
*bb++ = ')';
*bb = '\0';
}
break;
case TY_DCMPLX:
cons1 = CONVAL1G(sptr);
cons2 = CONVAL2G(sptr);
num[0] = CONVAL1G(cons1);
num[1] = CONVAL2G(cons1);
if ((num[0] & 0x7ff00000) == 0x7ff00000) {
/* Infinity or NaN */
int len;
len = snprintf(b, 200, "(0x%8.8x%8.8xLL, ", num[0], num[1]);
bb = b + len;
} else {
b[0] = '(';
cprintf(&b[1], "%24.17le", num);
b[25] = ',';
b[26] = ' ';
bb = &b[27];
}
num[0] = CONVAL1G(cons2);
num[1] = CONVAL2G(cons2);
if ((num[0] & 0x7ff00000) == 0x7ff00000) {
/* Infinity or NaN */
snprintf(bb, 200, "0x%8.8x%8.8xLL", num[0], num[1]);
} else {
cprintf(bb, "%24.17le", num);
bb += 24;
*bb++ = ')';
*bb = '\0';
}
break;
case TY_QUAD:
num[0] = CONVAL1G(sptr);
num[1] = CONVAL2G(sptr);
cprintf(b, "%.17le", num);
break;
case TY_PTR:
pointee = CONVAL1G(sptr);
if (pointee > 0 && pointee < stb.stg_avail && STYPEG(pointee) != ST_CONST
) {
if (ACONOFFG(sptr) == 0) {
snprintf(b, 200, "*%s", SYMNAME(pointee));
} else {
snprintf(b, 200, "*%s+%" ISZ_PF "d", SYMNAME(pointee),
ACONOFFG(sptr));
}
} else {
if (ACONOFFG(sptr) == 0) {
snprintf(b, 200, "*(sym %d)", pointee);
} else {
snprintf(b, 200, "*(sym %d)+%" ISZ_PF "d", pointee, ACONOFFG(sptr));
}
}
break;
case TY_WORD:
snprintf(b, 200, "%10" ISZ_PF "d", ACONOFFG(sptr));
break;
case TY_CHAR:
return stb.n_base + CONVAL1G(sptr);
case TY_BLOG:
case TY_SLOG:
case TY_LOG:
snprintf(b, 200, "%10d", CONVAL2G(sptr));
break;
case TY_LOG8:
num[0] = CONVAL1G(sptr);
num[1] = CONVAL2G(sptr);
ui64toax(num, b, 22, 0, 10);
break;
default:
snprintf(b, 200, "unknown constant %d dty %d", sptr,
DTY(DTYPEG(sptr)));
break;
}
for (bb = b; *bb == ' '; ++bb)
;
for (ee = bb; *ee; ++ee)
; /* go to end of string */
for (; ee > bb && *(ee - 1) == ' '; --ee)
*ee = '\0';
return bb;
}
/* default case */
if (strncmp(SYMNAME(sptr), "..inline", 8) == 0) {
/* append symbol number to distinguish */
snprintf(b, 200, "%s_%d", SYMNAME(sptr), sptr);
return b;
}
return SYMNAME(sptr);
} /* printname */
#if DEBUG
/*
* dump the DVL structure
*/
void
dumpdvl(int d)
{
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
if (aux.dvl_base == NULL) {
fprintf(dfile, "aux.dvl_base not allocated\n");
return;
}
if (d < 0 || d >= aux.dvl_avl) {
fprintf(dfile, "\ndvl %d out of %d\n", d, aux.dvl_avl - 1);
return;
}
putint("dvl", d);
putsym("sym", (SPTR) DVL_SPTR(d)); // ???
putINT("conval", DVL_CONVAL(d));
putline();
} /* dumpdvl */
void
dumpdvls()
{
int d;
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
if (aux.dvl_base == NULL) {
fprintf(dfile, "aux.dvl_base not allocated\n");
return;
}
for (d = 0; d < aux.dvl_avl; ++d) {
fprintf(dfile, "\n");
dumpdvl(d);
}
} /* dumpdvls */
/*
* dump variables which are kept on the stack
*/
void
stackvars()
{
int sptr;
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
fprintf(dfile, "Local variables:\n");
for (sptr = gbl.locals; sptr > NOSYM; sptr = SYMLKG(sptr)) {
dsym(sptr);
}
} /* stackvars */
/*
* diagnose what stack locations are used
*/
void
stackcheck()
{
long maxstack, minstack, i, j, addr, size, totused, totfree;
int sptr, lastclash;
int *stack, *stackmem;
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
minstack = 0;
maxstack = -1;
for (sptr = gbl.locals; sptr > NOSYM; sptr = SYMLKG(sptr)) {
size = size_of(DTYPEG(sptr));
if (ADDRESSG(sptr) - size < minstack)
minstack = ADDRESSG(sptr) - size;
if (ADDRESSG(sptr) + size > maxstack)
maxstack = ADDRESSG(sptr) + size;
}
fprintf(dfile, "Stack for subprogram %d:%s\n%8ld:%-8ld\n", gbl.func_count,
SYMNAME(gbl.currsub), minstack, maxstack);
stackmem = (int *)malloc((maxstack - minstack + 1) * sizeof(int));
stack = stackmem - minstack; /* minstack is <= 0 */
for (i = minstack; i <= maxstack; ++i)
stack[i] = 0;
for (sptr = gbl.locals; sptr > NOSYM; sptr = SYMLKG(sptr)) {
addr = ADDRESSG(sptr);
size = size_of(DTYPEG(sptr));
lastclash = 0;
for (i = addr; i < addr + size; ++i) {
if (stack[i] != 0) {
if (stack[i] != lastclash)
fprintf(dfile, "sptr %d:%s and %d:%s clash at memory %ld\n", sptr,
SYMNAME(sptr), stack[i], SYMNAME(stack[i]), i);
lastclash = stack[i];
}
stack[i] = sptr;
}
}
sptr = -1;
totfree = 0;
totused = 0;
for (i = minstack; i <= maxstack; ++i) {
if (stack[i] == 0)
++totfree;
else
++totused;
if (stack[i] != sptr) {
sptr = stack[i];
for (j = i; j < maxstack && stack[j + 1] == sptr; ++j)
;
if (sptr == 0) {
fprintf(dfile, "%8ld:%-8ld ---free (%ld)\n", i, j, j - i + 1);
} else {
size = size_of(DTYPEG(sptr));
fprintf(dfile, "%8ld:%-8ld %8ld(%%rsp) %5d:%s (%ld) ", i, j,
i + 8 - minstack, sptr, SYMNAME(sptr), size);
putdtypex(DTYPEG(sptr), 1000);
fprintf(dfile, "\n");
}
}
}
fprintf(dfile, "%8ld used\n%8ld free\n", totused, totfree);
free(stackmem);
} /* stackcheck */
#endif /* DEBUG */
| 21.91612 | 95 | 0.568653 | kammerdienerb |
06311e251ef6551dd4c1494ace2781442008794a | 9,775 | cpp | C++ | src/node_server_actions_1.cpp | srinivasyadav18/octotiger | 4d93c50fe345a081b7985ecb4cb698d16c121565 | [
"BSL-1.0"
] | 35 | 2016-11-17T22:35:11.000Z | 2022-01-24T19:07:36.000Z | src/node_server_actions_1.cpp | srinivasyadav18/octotiger | 4d93c50fe345a081b7985ecb4cb698d16c121565 | [
"BSL-1.0"
] | 123 | 2016-11-17T21:29:25.000Z | 2022-03-03T21:40:04.000Z | src/node_server_actions_1.cpp | srinivasyadav18/octotiger | 4d93c50fe345a081b7985ecb4cb698d16c121565 | [
"BSL-1.0"
] | 10 | 2018-11-28T18:17:42.000Z | 2022-01-25T12:52:37.000Z | // Copyright (c) 2019 AUTHORS
//
// 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 "octotiger/config.hpp"
#include "octotiger/container_device.hpp"
#include "octotiger/defs.hpp"
#include "octotiger/diagnostics.hpp"
#include "octotiger/future.hpp"
#include "octotiger/node_client.hpp"
#include "octotiger/node_registry.hpp"
#include "octotiger/node_server.hpp"
#include "octotiger/options.hpp"
#include "octotiger/profiler.hpp"
#include "octotiger/taylor.hpp"
#include <hpx/include/lcos.hpp>
#include <hpx/include/run_as.hpp>
#include <hpx/collectives/broadcast.hpp>
#include <boost/iostreams/stream.hpp>
#include <algorithm>
#include <array>
#include <chrono>
#include <fstream>
#include <vector>
using amr_error_action_type = node_server::amr_error_action;
HPX_REGISTER_ACTION(amr_error_action_type);
future<std::pair<real, real>> node_client::amr_error() const {
return hpx::async<typename node_server::amr_error_action>(get_unmanaged_gid());
}
std::pair<real, real> node_server::amr_error() {
std::vector<hpx::future<std::pair<real, real>>> kfuts;
auto sum = std::make_pair(0.0, 0.0);
if (is_refined) {
for (int i = 0; i < NCHILD; i++) {
kfuts.push_back(children[i].amr_error());
}
hpx::wait_all(kfuts);
for (int i = 0; i < NCHILD; i++) {
auto tmp = kfuts[i].get();
sum.first += tmp.first;
sum.second += tmp.second;
}
} else {
sum = grid_ptr->amr_error();
}
return sum;
}
using regrid_gather_action_type = node_server::regrid_gather_action;
HPX_REGISTER_ACTION(regrid_gather_action_type);
future<node_count_type> node_client::regrid_gather(bool rb) const {
return hpx::async<typename node_server::regrid_gather_action>(get_unmanaged_gid(), rb);
}
node_count_type node_server::regrid_gather(bool rebalance_only) {
node_registry::delete_(my_location);
node_count_type count;
count.total = 1;
count.leaf = is_refined ? 0 : 1;
std::vector<hpx::future<void>> kfuts;
if (is_refined) {
if (!rebalance_only) {
/* Turning refinement off */
if (refinement_flag == 0) {
for (int i = 0; i < NCHILD; i++) {
kfuts.push_back(children[i].kill());
}
std::fill_n(children.begin(), NCHILD, node_client());
is_refined = false;
}
}
if (is_refined) {
std::array<future<node_count_type>, NCHILD> futs;
integer index = 0;
for (auto &child : children) {
futs[index++] = child.regrid_gather(rebalance_only);
}
auto futi = futs.begin();
for (auto const &ci : geo::octant::full_set()) {
const auto child_cnt = futi->get();
++futi;
child_descendant_count[ci] = child_cnt.total;
count.leaf += child_cnt.leaf;
count.total += child_cnt.total;
}
} else {
count.leaf = 1;
for (auto const &ci : geo::octant::full_set()) {
child_descendant_count[ci] = 0;
}
}
} else if (!rebalance_only) {
if (refinement_flag != 0) {
refinement_flag = 0;
count.total += NCHILD;
count.leaf += NCHILD - 1;
/* Turning refinement on*/
is_refined = true;
for (auto &ci : geo::octant::full_set()) {
child_descendant_count[ci] = 1;
}
}
}
grid_ptr->set_leaf(!is_refined);
hpx::wait_all(kfuts);
return count;
}
future<hpx::id_type> node_server::create_child(hpx::id_type const &locality, integer ci) {
return hpx::async(hpx::util::annotated_function([ci, this](hpx::id_type const locality) {
return hpx::new_<node_server>(locality, my_location.get_child(ci), me, current_time, rotational_time, step_num, hcycle, rcycle, gcycle).then([this, ci](future<hpx::id_type> &&child_idf) {
hpx::id_type child_id = child_idf.get();
node_client child = child_id;
{
std::array<integer, NDIM> lb = {2 * H_BW, 2 * H_BW, 2 * H_BW};
std::array<integer, NDIM> ub;
lb[XDIM] += (1 & (ci >> 0)) * (INX);
lb[YDIM] += (1 & (ci >> 1)) * (INX);
lb[ZDIM] += (1 & (ci >> 2)) * (INX);
for (integer d = 0; d != NDIM; ++d) {
ub[d] = lb[d] + (INX);
}
std::vector<real> outflows(opts().n_fields, ZERO);
if (ci == 0) {
outflows = grid_ptr->get_outflows_raw();
}
if (current_time > ZERO || opts().restart_filename != "") {
std::vector<real> prolong;
{
std::unique_lock < hpx::lcos::local::spinlock > lk(prolong_mtx);
prolong = grid_ptr->get_prolong(lb, ub);
}
GET(child.set_grid(std::move(prolong), std::move(outflows)));
}
}
if (opts().radiation) {
std::array<integer, NDIM> lb = {2 * R_BW, 2 * R_BW, 2 * R_BW};
std::array<integer, NDIM> ub;
lb[XDIM] += (1 & (ci >> 0)) * (INX);
lb[YDIM] += (1 & (ci >> 1)) * (INX);
lb[ZDIM] += (1 & (ci >> 2)) * (INX);
for (integer d = 0; d != NDIM; ++d) {
ub[d] = lb[d] + (INX);
}
/* std::vector<real> outflows(NF, ZERO);
if (ci == 0) {
outflows = grid_ptr->get_outflows();
}*/
if (current_time > ZERO) {
std::vector<real> prolong;
{
std::unique_lock < hpx::lcos::local::spinlock > lk(prolong_mtx);
prolong = rad_grid_ptr->get_prolong(lb, ub);
}
child.set_rad_grid(std::move(prolong)/*, std::move(outflows)*/).get();
}
}
return child_id;
});}, "node_server::create_child::lambda"), locality);
}
using regrid_scatter_action_type = node_server::regrid_scatter_action;
HPX_REGISTER_ACTION(regrid_scatter_action_type);
future<void> node_client::regrid_scatter(integer a, integer b) const {
return hpx::async<typename node_server::regrid_scatter_action>(get_unmanaged_gid(), a, b);
}
void node_server::regrid_scatter(integer a_, integer total) {
position = a_;
refinement_flag = 0;
std::array<future<void>, geo::octant::count()> futs;
if (is_refined) {
integer a = a_;
++a;
integer index = 0;
for (auto &ci : geo::octant::full_set()) {
const integer loc_index = a * options::all_localities.size() / total;
const auto child_loc = options::all_localities[loc_index];
if (children[ci].empty()) {
futs[index++] = create_child(child_loc, ci).then([this, ci, a, total](future<hpx::id_type> &&child) {
children[ci] = GET(child);
GET(children[ci].regrid_scatter(a, total));
});
} else {
const hpx::id_type id = children[ci].get_gid();
integer current_child_id = hpx::naming::get_locality_id_from_gid(id.get_gid());
auto current_child_loc = options::all_localities[current_child_id];
if (child_loc != current_child_loc) {
futs[index++] = children[ci].copy_to_locality(child_loc).then([this, ci, a, total](future<hpx::id_type> &&child) {
children[ci] = GET(child);
GET(children[ci].regrid_scatter(a, total));
});
} else {
futs[index++] = children[ci].regrid_scatter(a, total);
}
}
a += child_descendant_count[ci];
}
}
if (is_refined) {
for (auto &f : futs) {
GET(f);
}
}
clear_family();
}
node_count_type node_server::regrid(const hpx::id_type &root_gid, real omega, real new_floor, bool rb, bool grav_energy_comp) {
timings::scope ts(timings_, timings::time_regrid);
hpx::util::high_resolution_timer timer;
assert(grid_ptr != nullptr);
print("-----------------------------------------------\n");
if (!rb) {
print("checking for refinement\n");
check_for_refinement(omega, new_floor);
} else {
node_registry::clear();
}
print("regridding\n");
real tstart = timer.elapsed();
auto a = regrid_gather(rb);
real tstop = timer.elapsed();
print("Regridded tree in %f seconds\n", real(tstop - tstart));
print("rebalancing %i nodes with %i leaves\n", int(a.total), int(a.leaf));
tstart = timer.elapsed();
regrid_scatter(0, a.total);
tstop = timer.elapsed();
print("Rebalanced tree in %f seconds\n", real(tstop - tstart));
assert(grid_ptr != nullptr);
tstart = timer.elapsed();
print("forming tree connections\n");
a.amr_bnd = form_tree(hpx::unmanaged(root_gid));
print("%i amr boundaries\n", a.amr_bnd);
tstop = timer.elapsed();
print("Formed tree in %f seconds\n", real(tstop - tstart));
print("solving gravity\n");
solve_gravity(grav_energy_comp, false);
double elapsed = timer.elapsed();
print("regrid done in %f seconds\n---------------------------------------\n", elapsed);
return a;
}
using set_aunt_action_type = node_server::set_aunt_action;
HPX_REGISTER_ACTION(set_aunt_action_type);
future<void> node_client::set_aunt(const hpx::id_type &aunt, const geo::face &f) const {
return hpx::async<typename node_server::set_aunt_action>(get_unmanaged_gid(), aunt, f);
}
void node_server::set_aunt(const hpx::id_type &aunt, const geo::face &face) {
if (aunts[face].get_gid() != hpx::invalid_id) {
print("AUNT ALREADY SET\n");
abort();
}
aunts[face] = aunt;
}
using set_grid_action_type = node_server::set_grid_action;
HPX_REGISTER_ACTION(set_grid_action_type);
future<void> node_client::set_grid(std::vector<real> &&g, std::vector<real> &&o) const {
return hpx::async<typename node_server::set_grid_action>(get_unmanaged_gid(), std::move(g), std::move(o));
}
void node_server::set_grid(const std::vector<real> &data, std::vector<real> &&outflows) {
grid_ptr->set_prolong(data, std::move(outflows));
}
using solve_gravity_action_type = node_server::solve_gravity_action;
HPX_REGISTER_ACTION(solve_gravity_action_type);
future<void> node_client::solve_gravity(bool ene, bool aonly) const {
return hpx::async<typename node_server::solve_gravity_action>(get_unmanaged_gid(), ene, aonly);
}
void node_server::solve_gravity(bool ene, bool aonly) {
if (!opts().gravity) {
return;
}
std::array<future<void>, NCHILD> child_futs;
if (is_refined) {
integer index = 0;
;
for (auto &child : children) {
child_futs[index++] = child.solve_gravity(ene, aonly);
}
}
compute_fmm(RHO, ene, aonly);
if (is_refined) {
// wait_all_and_propagate_exceptions(child_futs);
for (auto &f : child_futs) {
GET(f);
}
}
}
| 31.230032 | 189 | 0.668951 | srinivasyadav18 |
0632117eadb9df1777de7677ec3db36e22dfec98 | 2,811 | hpp | C++ | graphics/source/geometry/curve.hpp | HrvojeFER/irg-lab | 53f27430d39fa099dd605cfd632e38b55a392699 | [
"MIT"
] | null | null | null | graphics/source/geometry/curve.hpp | HrvojeFER/irg-lab | 53f27430d39fa099dd605cfd632e38b55a392699 | [
"MIT"
] | null | null | null | graphics/source/geometry/curve.hpp | HrvojeFER/irg-lab | 53f27430d39fa099dd605cfd632e38b55a392699 | [
"MIT"
] | null | null | null | #ifndef IRGLAB_CURVE_HPP
#define IRGLAB_CURVE_HPP
#include "external/external.hpp"
#include "primitive/primitive.hpp"
namespace il
{
// Type traits
[[nodiscard, maybe_unused]] constexpr bool is_curve_description_supported(
small_natural_number dimension_count)
{
return is_vector_size_supported(dimension_count);
}
// Base
template<small_natural_number DimensionCount>
class [[maybe_unused]] curve
{
// Traits and types
public:
[[maybe_unused]] static constexpr small_natural_number dimension_count = DimensionCount;
using control_point [[maybe_unused]] = cartesian_coordinates<dimension_count>;
// Constructors and related methods
// Only std::initializer_list constructor because I want to discourage the use of curves with
// a lot of control points because that would greatly affect performance.
template<
#pragma clang diagnostic push
#pragma ide diagnostic ignored "UnusedLocalVariable"
typename Dummy = void, std::enable_if_t<
std::is_same_v<Dummy, void> && is_curve_description_supported(dimension_count), int> = 0>
#pragma clang diagnostic pop
[[nodiscard, maybe_unused]] explicit curve(std::initializer_list<control_point> control_points) :
_control_points{control_points}
{ }
// Non-modifiers
[[nodiscard, maybe_unused]] cartesian_coordinates<dimension_count> operator()(
const rational_number parameter)
{
cartesian_coordinates<dimension_count> result{ };
for (natural_number i = 0 ; i < _control_points.size() ; ++i)
result += _control_points[i] * _get_bernstein_polynomial_result(
i, _control_points.size() - 1, parameter);
return result;
}
// Implementation details
private:
[[nodiscard]] static rational_number _get_bernstein_polynomial_result(
const natural_number index,
const natural_number control_point_count,
const rational_number parameter)
{
return static_cast<rational_number>(
number_of_combinations(control_point_count, index) *
glm::pow(parameter, index) *
glm::pow(1 - parameter, control_point_count - index));
}
// Data
std::vector<control_point> _control_points;
};
}
// Dimensional aliases
namespace il::d2
{
using curve [[maybe_unused]] = il::curve<dimension_count>;
}
namespace il::d3
{
using curve [[maybe_unused]] = il::curve<dimension_count>;
}
#endif
| 28.11 | 114 | 0.622554 | HrvojeFER |
06352ea040e35c97c36f7dbbbd6831e090340c34 | 3,068 | cpp | C++ | wpilibcExamples/src/main/cpp/templates/sample/cpp/Robot.cpp | balupillai/allwpilib | 6992f5421f8222e1edf872a8788d88016ba46f2b | [
"BSD-3-Clause"
] | 1 | 2021-10-10T06:52:41.000Z | 2021-10-10T06:52:41.000Z | wpilibcExamples/src/main/cpp/templates/sample/cpp/Robot.cpp | balupillai/allwpilib | 6992f5421f8222e1edf872a8788d88016ba46f2b | [
"BSD-3-Clause"
] | null | null | null | wpilibcExamples/src/main/cpp/templates/sample/cpp/Robot.cpp | balupillai/allwpilib | 6992f5421f8222e1edf872a8788d88016ba46f2b | [
"BSD-3-Clause"
] | null | null | null | /*----------------------------------------------------------------------------*/
/* Copyright (c) 2017-2018 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
#include "Robot.h"
#include <iostream>
#include <frc/Timer.h>
#include <frc/smartdashboard/SmartDashboard.h>
Robot::Robot() {
// Note SmartDashboard is not initialized here, wait until RobotInit() to make
// SmartDashboard calls
m_robotDrive.SetExpiration(0.1);
}
void Robot::RobotInit() {
m_chooser.SetDefaultOption(kAutoNameDefault, kAutoNameDefault);
m_chooser.AddOption(kAutoNameCustom, kAutoNameCustom);
frc::SmartDashboard::PutData("Auto Modes", &m_chooser);
}
/**
* This autonomous (along with the chooser code above) shows how to select
* between different autonomous modes using the dashboard. The sendable chooser
* code works with the Java SmartDashboard. If you prefer the LabVIEW Dashboard,
* remove all of the chooser code and uncomment the GetString line to get the
* auto name from the text box below the Gyro.
*
* You can add additional auto modes by adding additional comparisons to the
* if-else structure below with additional strings. If using the SendableChooser
* make sure to add them to the chooser code above as well.
*/
void Robot::Autonomous() {
std::string autoSelected = m_chooser.GetSelected();
// std::string autoSelected = frc::SmartDashboard::GetString(
// "Auto Selector", kAutoNameDefault);
std::cout << "Auto selected: " << autoSelected << std::endl;
// MotorSafety improves safety when motors are updated in loops but is
// disabled here because motor updates are not looped in this autonomous mode.
m_robotDrive.SetSafetyEnabled(false);
if (autoSelected == kAutoNameCustom) {
// Custom Auto goes here
std::cout << "Running custom Autonomous" << std::endl;
// Spin at half speed for two seconds
m_robotDrive.ArcadeDrive(0.0, 0.5);
frc::Wait(2.0);
// Stop robot
m_robotDrive.ArcadeDrive(0.0, 0.0);
} else {
// Default Auto goes here
std::cout << "Running default Autonomous" << std::endl;
// Drive forwards at half speed for two seconds
m_robotDrive.ArcadeDrive(-0.5, 0.0);
frc::Wait(2.0);
// Stop robot
m_robotDrive.ArcadeDrive(0.0, 0.0);
}
}
/**
* Runs the motors with arcade steering.
*/
void Robot::OperatorControl() {
m_robotDrive.SetSafetyEnabled(true);
while (IsOperatorControl() && IsEnabled()) {
// Drive with arcade style (use right stick)
m_robotDrive.ArcadeDrive(-m_stick.GetY(), m_stick.GetX());
// The motors will be updated every 5ms
frc::Wait(0.005);
}
}
/**
* Runs during test mode
*/
void Robot::Test() {}
#ifndef RUNNING_FRC_TESTS
int main() { return frc::StartRobot<Robot>(); }
#endif
| 32.989247 | 80 | 0.650587 | balupillai |
0638e398efc5a165f675d66a600f7203bbdcafee | 1,304 | cpp | C++ | cppcheck/data/c_files/82.cpp | awsm-research/LineVul | 246baf18c1932094564a10c9b81efb21914b2978 | [
"MIT"
] | 2 | 2022-03-23T12:16:20.000Z | 2022-03-31T06:19:40.000Z | cppcheck/data/c_files/82.cpp | awsm-research/LineVul | 246baf18c1932094564a10c9b81efb21914b2978 | [
"MIT"
] | null | null | null | cppcheck/data/c_files/82.cpp | awsm-research/LineVul | 246baf18c1932094564a10c9b81efb21914b2978 | [
"MIT"
] | null | null | null | status_t SampleTable::setTimeToSampleParams(
off64_t data_offset, size_t data_size) {
if (!mTimeToSample.empty() || data_size < 8) {
return ERROR_MALFORMED;
}
uint8_t header[8];
if (mDataSource->readAt(
data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) {
return ERROR_IO;
}
if (U32_AT(header) != 0) {
// Expected version = 0, flags = 0.
return ERROR_MALFORMED;
}
mTimeToSampleCount = U32_AT(&header[4]);
if ((uint64_t)mTimeToSampleCount >
(uint64_t)UINT32_MAX / (2 * sizeof(uint32_t))) {
// Choose this bound because
// 1) 2 * sizeof(uint32_t) is the amount of memory needed for one
// time-to-sample entry in the time-to-sample table.
// 2) mTimeToSampleCount is the number of entries of the time-to-sample
// table.
// 3) We hope that the table size does not exceed UINT32_MAX.
ALOGE(" Error: Time-to-sample table size too large.");
return ERROR_OUT_OF_RANGE;
}
// Note: At this point, we know that mTimeToSampleCount * 2 will not
// overflow because of the above condition.
if (!mDataSource->getVector(data_offset + 8, &mTimeToSample,
mTimeToSampleCount * 2)) {
ALOGE(" Error: Incomplete data read for time-to-sample table.");
return ERROR_IO;
}
for (size_t i = 0; i < mTimeToSample.size(); ++i) {
mTimeToSample.editItemAt(i) = ntohl(mTimeToSample[i]);
}
return OK;
}
| 28.347826 | 71 | 0.721626 | awsm-research |
063c6beca76fd6308e9eabe47e48eaa887948f89 | 6,980 | cpp | C++ | apps/enumeration/numericalSemigroups/hivert.cpp | ruairidhm98/YewPar | dfcc204a308232ceca3223252f3a1b4a2f6f42f6 | [
"MIT"
] | null | null | null | apps/enumeration/numericalSemigroups/hivert.cpp | ruairidhm98/YewPar | dfcc204a308232ceca3223252f3a1b4a2f6f42f6 | [
"MIT"
] | null | null | null | apps/enumeration/numericalSemigroups/hivert.cpp | ruairidhm98/YewPar | dfcc204a308232ceca3223252f3a1b4a2f6f42f6 | [
"MIT"
] | null | null | null | /* Original Numerical Semigroups Code by Florent Hivert: https://www.lri.fr/~hivert/
Link: https://github.com/hivert/NumericMonoid/blob/master/src/Cilk++/monoid.hpp
*/
#include <hpx/hpx_init.hpp>
#include <hpx/include/iostreams.hpp>
#include <vector>
#include <chrono>
#include "YewPar.hpp"
#include "skeletons/Seq.hpp"
#include "skeletons/DepthBounded.hpp"
#include "skeletons/StackStealing.hpp"
#include "skeletons/Budget.hpp"
#include "monoid.hpp"
// Numerical Semigroups don't have a space
struct Empty {};
struct NodeGen : YewPar::NodeGenerator<Monoid, Empty> {
Monoid group;
generator_iter<CHILDREN> it;
NodeGen(const Empty &, const Monoid & s) : group(s), it(generator_iter<CHILDREN>(s)){
this->numChildren = it.count(group);
it.move_next(group); // Original code skips begin
}
Monoid next() override {
auto res = remove_generator(group, it.get_gen());
it.move_next(group);
return res;
}
};
int hpx_main(boost::program_options::variables_map & opts) {
auto spawnDepth = opts["spawn-depth"].as<unsigned>();
auto maxDepth = opts["genus"].as<unsigned>();
auto skeleton = opts["skeleton"].as<std::string>();
//auto stealAll = opts["stealall"].as<bool>();
Monoid root;
init_full_N(root);
auto start_time = std::chrono::steady_clock::now();
std::vector<std::uint64_t> counts;
if (skeleton == "depthbounded") {
YewPar::Skeletons::API::Params<> searchParameters;
searchParameters.maxDepth = maxDepth;
searchParameters.spawnDepth = spawnDepth;
counts = YewPar::Skeletons::DepthBounded<NodeGen,
YewPar::Skeletons::API::CountNodes,
YewPar::Skeletons::API::DepthLimited>
::search(Empty(), root, searchParameters);
} else if (skeleton == "stacksteal"){
YewPar::Skeletons::API::Params<> searchParameters;
searchParameters.maxDepth = maxDepth;
searchParameters.stealAll = static_cast<bool>(opts.count("chunked"));
// EXTENSION
if (opts.count("nodes")) {
counts = YewPar::Skeletons::StackStealing<NodeGen,
YewPar::Skeletons::API::CountNodes,
YewPar::Skeletons::API::NodeCounts,
YewPar::Skeletons::API::DepthLimited>
::search(Empty(), root, searchParameters);
} else if (opts.count("backtracks")) {
counts = YewPar::Skeletons::StackStealing<NodeGen,
YewPar::Skeletons::API::CountNodes,
YewPar::Skeletons::API::Backtracks,
YewPar::Skeletons::API::DepthLimited>
::search(Empty(), root, searchParameters);
} else if (opts.count("regularity")) {
counts = YewPar::Skeletons::StackStealing<NodeGen,
YewPar::Skeletons::API::CountNodes,
YewPar::Skeletons::API::Regularity,
YewPar::Skeletons::API::DepthLimited>
::search(Empty(), root, searchParameters);
} else {
counts = YewPar::Skeletons::StackStealing<NodeGen,
YewPar::Skeletons::API::CountNodes,
YewPar::Skeletons::API::DepthLimited>
::search(Empty(), root, searchParameters);
}
// END EXTENSION
} else if (skeleton == "budget"){
YewPar::Skeletons::API::Params<> searchParameters;
searchParameters.backtrackBudget = opts["backtrack-budget"].as<unsigned>();
searchParameters.maxDepth = maxDepth;
// EXTENSION
if (opts.count("nodes")) {
counts = YewPar::Skeletons::Budget<NodeGen,
YewPar::Skeletons::API::CountNodes,
YewPar::Skeletons::API::NodeCounts,
YewPar::Skeletons::API::DepthLimited>
::search(Empty(), root, searchParameters);
} else if (opts.count("backtracks")) {
counts = YewPar::Skeletons::Budget<NodeGen,
YewPar::Skeletons::API::CountNodes,
YewPar::Skeletons::API::Backtracks,
YewPar::Skeletons::API::DepthLimited>
::search(Empty(), root, searchParameters);
} else if (opts.count("regularity")) {
counts = YewPar::Skeletons::Budget<NodeGen,
YewPar::Skeletons::API::CountNodes,
YewPar::Skeletons::API::Regularity,
YewPar::Skeletons::API::DepthLimited>
::search(Empty(), root, searchParameters);
} else {
counts = YewPar::Skeletons::Budget<NodeGen,
YewPar::Skeletons::API::CountNodes,
YewPar::Skeletons::API::DepthLimited>
::search(Empty(), root, searchParameters);
}
// END EXTENSION
} else {
hpx::cout << "Invalid skeleton type: " << skeleton << hpx::endl;
return hpx::finalize();
}
auto overall_time = std::chrono::duration_cast<std::chrono::milliseconds>
(std::chrono::steady_clock::now() - start_time);
hpx::cout << "Results Table: " << hpx::endl;
for (auto i = 0; i <= maxDepth; ++i) {
hpx::cout << i << ": " << counts[i] << hpx::endl;
}
hpx::cout << "=====" << hpx::endl;
hpx::cout << "cpu = " << overall_time.count() << hpx::endl;
return hpx::finalize();
}
int main(int argc, char* argv[]) {
boost::program_options::options_description
desc_commandline("Usage: " HPX_APPLICATION_STRING " [options]");
desc_commandline.add_options()
( "skeleton",
boost::program_options::value<std::string>()->default_value("seq"),
"Which skeleton to use: seq, depthbound, stacksteal, or budget"
)
( "spawn-depth,d",
boost::program_options::value<unsigned>()->default_value(0),
"Depth in the tree to spawn until (for parallel skeletons only)"
)
( "genus,g",
boost::program_options::value<unsigned>()->default_value(0),
"Depth in the tree to count until"
)
( "backtrack-budget,b",
boost::program_options::value<unsigned>()->default_value(500),
"Number of backtracks before spawning work"
)
( "verbose,v",
boost::program_options::value<bool>()->default_value(false),
"Enable verbose output"
)
("chunked", "Use chunking with stack stealing")
// EXTENSION
("backtracks", "Collect the backtracks metric")
("nodes", "Collect the backtracks metric")
("regularity", "Collect the backtracks metric");
// END EXTENSION
YewPar::registerPerformanceCounters();
return hpx::init(desc_commandline, argc, argv);
}
| 40.581395 | 87 | 0.571777 | ruairidhm98 |
063dc7485b02ff563021ac01662259de76748e96 | 3,180 | cpp | C++ | mcommon/ui/ui_manager.cpp | cmaughan/mgfx | 488453333f23b38b22ba06b984615a8069dadcbf | [
"MIT"
] | 36 | 2017-03-27T16:57:47.000Z | 2022-01-12T04:17:55.000Z | mcommon/ui/ui_manager.cpp | cmaughan/mgfx | 488453333f23b38b22ba06b984615a8069dadcbf | [
"MIT"
] | 5 | 2017-03-04T12:13:54.000Z | 2017-03-26T21:55:08.000Z | mcommon/ui/ui_manager.cpp | cmaughan/mgfx | 488453333f23b38b22ba06b984615a8069dadcbf | [
"MIT"
] | 7 | 2017-03-04T11:01:44.000Z | 2018-08-28T09:25:47.000Z | #include "mcommon.h"
#include "ui_manager.h"
// Statics
uint64_t UIMessage::CurrentID = 1;
namespace
{
uint64_t InvalidMessageID = 0;
}
void UIMessage::Log()
{
/* uint32_t level = easyloggingERROR;
if (m_type & MessageType::Warning)
{
level = WARNING;
}
*/
std::ostringstream str;
try
{
if (!m_file.empty())
{
str << m_file.string();
}
}
catch (fs::filesystem_error&)
{
// Ignore file errors
}
if (m_line != -1)
{
str << "(" << m_line;
if (m_columnRange.start != -1)
{
str << "," << m_columnRange.start;
if (m_columnRange.end != -1)
{
str << "-" << m_columnRange.end;
}
}
str << "): ";
}
else
{
// Just a file, no line
if (!m_file.empty())
{
str << ": ";
}
}
str << m_message;
LOG(INFO) << str.str();
}
UIManager::UIManager()
{
}
UIManager& UIManager::Instance()
{
static UIManager manager;
return manager;
}
uint64_t UIManager::AddMessage(uint32_t type, const std::string& message, const fs::path& file, int32_t line, const ColumnRange& column)
{
auto spMessage = std::make_shared<UIMessage>(type, message, file, line, column);
spMessage->Log();
if (type & MessageType::Task ||
!file.empty())
{
m_taskMessages[spMessage->m_id] = spMessage;
}
if (!file.empty())
{
m_fileMessages[spMessage->m_file].push_back(spMessage->m_id);
}
if (type & MessageType::System)
{
SDL_MessageBoxButtonData button;
button.flags = SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT;
button.buttonid = 0;
button.text = "OK";
SDL_MessageBoxData mbData;
mbData.buttons = &button;
mbData.colorScheme = nullptr;
if (type & MessageType::Error)
{
mbData.flags = SDL_MessageBoxFlags::SDL_MESSAGEBOX_ERROR;
mbData.title = "Error";
}
else if (type & MessageType::Warning)
{
mbData.flags = SDL_MessageBoxFlags::SDL_MESSAGEBOX_WARNING;
mbData.title = "Warning";
}
else if (type & MessageType::Info)
{
mbData.flags = SDL_MessageBoxFlags::SDL_MESSAGEBOX_INFORMATION;
mbData.title = "Information";
}
mbData.message = spMessage->m_message.c_str();
mbData.numbuttons = 1;
mbData.window = nullptr;
int buttonID = 0;
SDL_ShowMessageBox(&mbData, &buttonID);
}
return spMessage->m_id;
}
// Remove a message for a given ID
void UIManager::RemoveMessage(uint64_t id)
{
auto itrFound = m_taskMessages.find(id);
if (itrFound != m_taskMessages.end())
{
if (!itrFound->second->m_file.empty())
{
m_fileMessages.erase(itrFound->second->m_file);
}
}
}
// Remove all messages associated with a file
void UIManager::ClearFileMessages(fs::path path)
{
while(!m_fileMessages[path].empty())
{
RemoveMessage(m_fileMessages[path][0]);
}
}
| 22.553191 | 136 | 0.555031 | cmaughan |
064065e6ba627b73355756f7706d3276ca4312ff | 2,602 | hpp | C++ | Simulator/includes/BitMaskEnums.hpp | lilggamegenius/M68KSimulator | af22bde681c11b0a8ee6fa4692be969566037926 | [
"MIT"
] | null | null | null | Simulator/includes/BitMaskEnums.hpp | lilggamegenius/M68KSimulator | af22bde681c11b0a8ee6fa4692be969566037926 | [
"MIT"
] | null | null | null | Simulator/includes/BitMaskEnums.hpp | lilggamegenius/M68KSimulator | af22bde681c11b0a8ee6fa4692be969566037926 | [
"MIT"
] | null | null | null | //
// Created by ggonz on 11/22/2021.
//
#pragma once
namespace M68K::Opcodes{
template<typename Enum>
struct EnableBitMaskOperators {
static const bool enable = false;
};
template<typename Enum>
typename std::enable_if<EnableBitMaskOperators<Enum>::enable, Enum>::type
operator|(Enum lhs, Enum rhs) {
using underlying = typename std::underlying_type<Enum>::type;
return static_cast<Enum> (
static_cast<underlying>(lhs) |
static_cast<underlying>(rhs)
);
}
template<typename Enum>
typename std::enable_if<EnableBitMaskOperators<Enum>::enable, Enum>::type
operator&(Enum lhs, Enum rhs) {
using underlying = typename std::underlying_type<Enum>::type;
return static_cast<Enum> (
static_cast<underlying>(lhs) &
static_cast<underlying>(rhs)
);
}
template<typename Enum>
typename std::enable_if<EnableBitMaskOperators<Enum>::enable, Enum>::type
operator^(Enum lhs, Enum rhs) {
using underlying = typename std::underlying_type<Enum>::type;
return static_cast<Enum> (
static_cast<underlying>(lhs) ^
static_cast<underlying>(rhs)
);
}
template<typename Enum>
typename std::enable_if<EnableBitMaskOperators<Enum>::enable, Enum>::type
operator~(Enum rhs) {
using underlying = typename std::underlying_type<Enum>::type;
return static_cast<Enum> (
~static_cast<underlying>(rhs)
);
}
template<typename Enum>
typename std::enable_if<EnableBitMaskOperators<Enum>::enable, Enum>::type &
operator|=(Enum &lhs, Enum rhs) {
using underlying = typename std::underlying_type<Enum>::type;
lhs = static_cast<Enum> (
static_cast<underlying>(lhs) |
static_cast<underlying>(rhs)
);
return lhs;
}
template<typename Enum>
typename std::enable_if<EnableBitMaskOperators<Enum>::enable, Enum>::type &
operator&=(Enum &lhs, Enum rhs) {
using underlying = typename std::underlying_type<Enum>::type;
lhs = static_cast<Enum> (
static_cast<underlying>(lhs) &
static_cast<underlying>(rhs)
);
return lhs;
}
template<typename Enum>
typename std::enable_if<EnableBitMaskOperators<Enum>::enable, Enum>::type &
operator^=(Enum &lhs, Enum rhs) {
using underlying = typename std::underlying_type<Enum>::type;
lhs = static_cast<Enum> (
static_cast<underlying>(lhs) ^
static_cast<underlying>(rhs)
);
return lhs;
}
constexpr int bit(int index) {
if (index == 0) return 0;
return 1 << (index - 1);
}
#define ENABLE_BITMASK_OPERATORS(x) \
template<> \
struct EnableBitMaskOperators<x> \
{ \
static const bool enable = true; \
};
} | 26.02 | 76 | 0.691391 | lilggamegenius |