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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1aa1ca3764f44acc65714469fd96138ceacc60c5
| 1,534
|
cpp
|
C++
|
MPAGSCipher/CaesarCipher.cpp
|
MPAGS-CPP-2019/mpags-day-3-rrStein
|
e4ff5e2023dbb8e4a7981b25c7d11811ead13c0c
|
[
"MIT"
] | null | null | null |
MPAGSCipher/CaesarCipher.cpp
|
MPAGS-CPP-2019/mpags-day-3-rrStein
|
e4ff5e2023dbb8e4a7981b25c7d11811ead13c0c
|
[
"MIT"
] | null | null | null |
MPAGSCipher/CaesarCipher.cpp
|
MPAGS-CPP-2019/mpags-day-3-rrStein
|
e4ff5e2023dbb8e4a7981b25c7d11811ead13c0c
|
[
"MIT"
] | null | null | null |
#include "CaesarCipher.hpp"
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
// #include "RunCaesarCipher.hpp"
// #include "RunCaesarCipher.cpp"
CaesarCipher::CaesarCipher(const std::string &caesar_key)
: caesar_key_{std::stoul(caesar_key)} {}
CaesarCipher::CaesarCipher(const size_t &caesar_key)
: caesar_key_{caesar_key} {}
std::string CaesarCipher::applyCipher(const std::string &inputText,
const bool encrypt) const
// : inputText_{inputText}, encrypt_{encrypt}
{
const size_t truncatedKey{caesar_key_ % alphabetSize_};
std::string outputText{""};
// Loop over the input text
char processedChar{'x'};
for (const auto &origChar : inputText) {
// For each character in the input text, find the corresponding position in
// the alphabet by using an indexed loop over the alphabet container
for (size_t i{0}; i < alphabetSize_; ++i) {
if (origChar == alphabet_[i]) {
// Apply the appropriate shift (depending on whether we're encrypting
// or decrypting) and determine the new character
// Can then break out of the loop over the alphabet
if (encrypt) {
processedChar = alphabet_[(i + truncatedKey) % alphabetSize_];
} else {
processedChar =
alphabet_[(i + alphabetSize_ - truncatedKey) % alphabetSize_];
}
break;
}
}
// Add the new character to the output text
outputText += processedChar;
}
return outputText;
}
| 30.68
| 79
| 0.656454
|
MPAGS-CPP-2019
|
1aaa3c3ebc0ac201b16987d8482409b46de800bb
| 2,512
|
hpp
|
C++
|
include/graphplan/Action.hpp
|
aldukeman/graphplan
|
33b575a75aa25243e0a3bc658a7932e75a1ef2ef
|
[
"MIT"
] | null | null | null |
include/graphplan/Action.hpp
|
aldukeman/graphplan
|
33b575a75aa25243e0a3bc658a7932e75a1ef2ef
|
[
"MIT"
] | 1
|
2016-01-13T20:42:26.000Z
|
2022-03-10T02:14:49.000Z
|
include/graphplan/Action.hpp
|
aldukeman/graphplan
|
33b575a75aa25243e0a3bc658a7932e75a1ef2ef
|
[
"MIT"
] | 1
|
2019-08-24T10:25:44.000Z
|
2019-08-24T10:25:44.000Z
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 Anton Dukeman
*
* 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.
*/
/**
* @file Action.hpp
* @author Anton Dukeman <anton.dukeman@gmail.com>
*
* An Action in Graphplan
*/
#ifndef _GRAPHPLAN_ACTION_H_
#define _GRAPHPLAN_ACTION_H_
#include <string>
#include <set>
#include "graphplan/Proposition.hpp"
namespace graphplan
{
class Action
{
public:
/// Constructor
Action(const std::string& n = "");
/// equality operator
bool operator==(const Action& a) const;
/// less than operator
bool operator<(const Action& a) const;
/// add delete
void add_effect(const Proposition& p);
/// add precondition
void add_precondition(const Proposition& p);
/// get proposition name
const std::string& get_name() const;
/// get adds
const std::set<Proposition>& get_effects() const;
/// get preconditions
const std::set<Proposition>& get_preconditions() const;
/// check if this is a maintenance action
bool is_maintenance_action() const;
/// get string version
std::string to_string() const;
/// set action name
void set_name(const std::string& n);
protected:
/// name of the proposition
std::string name_;
/// added propositions
std::set<Proposition> effects_;
/// required propositions
std::set<Proposition> preconditions_;
}; // class Action
} // namespace graphplan
#endif // _GRAPHPLAN_ACTION_H_
| 27.604396
| 80
| 0.705414
|
aldukeman
|
1aad3a3ec328941ebf17269947721d86450d3671
| 1,836
|
cpp
|
C++
|
test/stc/test-vcs.cpp
|
antonvw/wxExtension
|
d5523346cf0b1dbd45fd20dc33bf8d679299676c
|
[
"MIT"
] | 9
|
2016-01-10T20:59:02.000Z
|
2019-01-09T14:18:13.000Z
|
test/stc/test-vcs.cpp
|
antonvw/wxExtension
|
d5523346cf0b1dbd45fd20dc33bf8d679299676c
|
[
"MIT"
] | 31
|
2015-01-30T17:46:17.000Z
|
2017-03-04T17:33:50.000Z
|
test/stc/test-vcs.cpp
|
antonvw/wxExtension
|
d5523346cf0b1dbd45fd20dc33bf8d679299676c
|
[
"MIT"
] | 2
|
2015-04-05T08:45:22.000Z
|
2018-08-24T06:43:24.000Z
|
////////////////////////////////////////////////////////////////////////////////
// Name: test-vcs.cpp
// Purpose: Implementation for wex unit testing
// Author: Anton van Wezenbeek
// Copyright: (c) 2021 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////
#include <wex/core/config.h>
#include <wex/stc/vcs.h>
#include <wex/ui/menu.h>
#include "../test.h"
#include <vector>
TEST_SUITE_BEGIN("wex::vcs");
TEST_CASE("wex::vcs")
{
wex::path file(wex::test::get_path("test.h"));
file.make_absolute();
SUBCASE("statics")
{
REQUIRE(wex::vcs::load_document());
REQUIRE(wex::vcs::dir_exists(file));
REQUIRE(!wex::vcs::empty());
REQUIRE(wex::vcs::size() > 0);
}
SUBCASE("others")
{
// In wex::app the vcs is loaded, so current vcs is known,
// using this constructor results in command id 3, being add.
wex::vcs vcs(std::vector<wex::path>{file}, 3);
REQUIRE(vcs.config_dialog(wex::data::window().button(wxAPPLY | wxCANCEL)));
#ifndef __WXMSW__
REQUIRE(vcs.execute());
REQUIRE(vcs.execute("status"));
REQUIRE(!vcs.execute("xxx"));
REQUIRE(vcs.show_dialog(wex::data::window().button(wxAPPLY | wxCANCEL)));
REQUIRE(vcs.request(wex::data::window().button(wxAPPLY | wxCANCEL)));
REQUIRE(vcs.entry().build_menu(100, new wex::menu("test", 0)) > 0);
REQUIRE(vcs.entry().get_command().get_command() == "add");
REQUIRE(!vcs.get_branch().empty());
REQUIRE(vcs.toplevel().string().find("wex") != std::string::npos);
REQUIRE(vcs.name() == "Auto");
REQUIRE(!vcs.entry().get_command().is_open());
wex::config(_("vcs.Base folder"))
.set(std::list<std::string>{wxGetCwd().ToStdString()});
REQUIRE(vcs.set_entry_from_base());
REQUIRE(vcs.use());
#endif
}
}
TEST_SUITE_END();
| 27
| 80
| 0.582244
|
antonvw
|
1ab07d703b2db70916abe6b16f78f7bd63606c4b
| 2,219
|
cpp
|
C++
|
contract/lite-client/tddb/td/db/utils/FileSyncState.cpp
|
TONCommunity/ton-sync-payments-channel
|
2e5cd4902406923fdba32b8309ab8c40db3ae5bc
|
[
"MIT"
] | 5
|
2019-10-15T18:26:06.000Z
|
2020-05-09T14:09:49.000Z
|
contract/lite-client/tddb/td/db/utils/FileSyncState.cpp
|
TONCommunity/ton-sync-payments-channel
|
2e5cd4902406923fdba32b8309ab8c40db3ae5bc
|
[
"MIT"
] | null | null | null |
contract/lite-client/tddb/td/db/utils/FileSyncState.cpp
|
TONCommunity/ton-sync-payments-channel
|
2e5cd4902406923fdba32b8309ab8c40db3ae5bc
|
[
"MIT"
] | 2
|
2020-07-24T16:09:02.000Z
|
2021-08-18T17:08:28.000Z
|
/*
This file is part of TON Blockchain Library.
TON Blockchain 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 of the License, or
(at your option) any later version.
TON Blockchain 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 TON Blockchain Library. If not, see <http://www.gnu.org/licenses/>.
Copyright 2017-2019 Telegram Systems LLP
*/
#include "FileSyncState.h"
namespace td {
std::pair<FileSyncState::Reader, FileSyncState::Writer> FileSyncState::create() {
auto self = std::make_shared<Self>();
return {Reader(self), Writer(self)};
}
FileSyncState::Reader::Reader(std::shared_ptr<Self> self) : self(std::move(self)) {
}
bool FileSyncState::Reader::set_requested_sync_size(size_t size) const {
if (self->requested_synced_size.load(std::memory_order_relaxed) == size) {
return false;
}
self->requested_synced_size.store(size, std::memory_order_release);
return true;
}
size_t FileSyncState::Reader::synced_size() const {
return self->synced_size;
}
size_t FileSyncState::Reader::flushed_size() const {
return self->flushed_size;
}
FileSyncState::Writer::Writer(std::shared_ptr<Self> self) : self(std::move(self)) {
}
size_t FileSyncState::Writer::get_requested_synced_size() {
return self->requested_synced_size.load(std::memory_order_acquire);
}
bool FileSyncState::Writer::set_synced_size(size_t size) {
if (self->synced_size.load(std::memory_order_relaxed) == size) {
return false;
}
self->synced_size.store(size, std::memory_order_release);
return true;
}
bool FileSyncState::Writer::set_flushed_size(size_t size) {
if (self->flushed_size.load(std::memory_order_relaxed) == size) {
return false;
}
self->flushed_size.store(size, std::memory_order_release);
return true;
}
} // namespace td
| 32.632353
| 83
| 0.741325
|
TONCommunity
|
1ab2a2b907d33254514ee46febe49a69ed08a539
| 3,229
|
cpp
|
C++
|
Source/Core/BuildCommon/BakeModel.cpp
|
schuttejoe/ShootyEngine
|
56a7fab5a479ec93d7f641bb64b8170f3b0d3095
|
[
"MIT"
] | 81
|
2018-07-31T17:13:47.000Z
|
2022-03-03T09:24:22.000Z
|
Source/Core/BuildCommon/BakeModel.cpp
|
schuttejoe/ShootyEngine
|
56a7fab5a479ec93d7f641bb64b8170f3b0d3095
|
[
"MIT"
] | 2
|
2018-10-15T04:39:43.000Z
|
2019-12-05T03:46:50.000Z
|
Source/Core/BuildCommon/BakeModel.cpp
|
schuttejoe/ShootyEngine
|
56a7fab5a479ec93d7f641bb64b8170f3b0d3095
|
[
"MIT"
] | 9
|
2018-10-11T06:32:12.000Z
|
2020-10-01T03:46:37.000Z
|
//=================================================================================================================================
// Joe Schutte
//=================================================================================================================================
#include "BuildCommon/BakeModel.h"
#include "BuildCore/BuildContext.h"
#include "SceneLib/ModelResource.h"
namespace Selas
{
//=============================================================================================================================
Error BakeModel(BuildProcessorContext* context, cpointer name, const BuiltModel& model)
{
ModelResourceData data;
data.aaBox = model.aaBox;
data.totalVertexCount = (uint32)model.positions.Count();
data.totalCurveVertexCount = (uint32)model.curveVertices.Count();
data.curveModelName = model.curveModelNameHash;
data.pad = 0;
data.indexSize = model.indices.DataSize();
data.faceIndexSize = model.faceIndexCounts.DataSize();
data.positionSize = model.positions.DataSize();
data.normalsSize = model.normals.DataSize();
data.tangentsSize = model.tangents.DataSize();
data.uvsSize = model.uvs.DataSize();
data.curveIndexSize = model.curveIndices.DataSize();
data.curveVertexSize = model.curveVertices.DataSize();
data.cameras.Append(model.cameras);
data.textureResourceNames.Append(model.textures);
data.materials.Append(model.materials);
data.materialHashes.Append(model.materialHashes);
data.meshes.Append(model.meshes);
data.curves.Append(model.curves);
context->CreateOutput(ModelResource::kDataType, ModelResource::kDataVersion, name, data);
ModelGeometryData geometry;
geometry.indexSize = model.indices.DataSize();
geometry.faceIndexSize = model.faceIndexCounts.DataSize();
geometry.positionSize = model.positions.DataSize();
geometry.normalsSize = model.normals.DataSize();
geometry.tangentsSize = model.tangents.DataSize();
geometry.uvsSize = model.uvs.DataSize();
geometry.curveIndexSize = model.curveIndices.DataSize();
geometry.curveVertexSize = model.curveVertices.DataSize();
geometry.indices = (uint32*)model.indices.DataPointer();
geometry.faceIndexCounts = (uint32*)model.faceIndexCounts.DataPointer();
geometry.positions = (float3*)model.positions.DataPointer();
geometry.normals = (float3*)model.normals.DataPointer();
geometry.tangents = (float4*)model.tangents.DataPointer();
geometry.uvs = (float2*)model.uvs.DataPointer();
geometry.curveIndices = (uint32*)model.curveIndices.DataPointer();
geometry.curveVertices = (float4*)model.curveVertices.DataPointer();
context->CreateOutput(ModelResource::kGeometryDataType, ModelResource::kDataVersion, name, geometry);
return Success_;
}
}
| 52.934426
| 131
| 0.557138
|
schuttejoe
|
1ab3c6a1df288059f40f05ae58d6ee12e894cd73
| 1,037
|
cpp
|
C++
|
tests/fixture/test_assert.cpp
|
sugawaray/filemanager
|
3dcb908d4c1e0c36de0c60e1b2e1291eec986cb1
|
[
"MIT"
] | null | null | null |
tests/fixture/test_assert.cpp
|
sugawaray/filemanager
|
3dcb908d4c1e0c36de0c60e1b2e1291eec986cb1
|
[
"MIT"
] | null | null | null |
tests/fixture/test_assert.cpp
|
sugawaray/filemanager
|
3dcb908d4c1e0c36de0c60e1b2e1291eec986cb1
|
[
"MIT"
] | null | null | null |
#include <sstream>
#include "assert.h"
#include "test_assert.h"
using std::cerr;
using std::endl;
using std::ostringstream;
using test::fixture::Assert;
START_TEST(should_not_output_when_true)
{
ostringstream os;
Assert(true, 1, 2, os);
if (os.str() != "")
cerr << "should_not_output_when_true" << endl;
}
END_TEST
START_TEST(should_output_when_false_with_2_params)
{
ostringstream os;
Assert(false, 1, 2, os);
ostringstream expected;
expected << 1 << ":" << 2 << endl;
if (os.str() != expected.str()) {
cerr << os.str();
cerr << "should_output_when_false_with_2_params" << endl;
}
}
END_TEST
namespace test {
namespace fixture {
TCase* create_assert_tcase()
{
TCase* tcase(tcase_create("assert"));
tcase_add_test(tcase, should_not_output_when_true);
tcase_add_test(tcase, should_output_when_false_with_2_params);
return tcase;
}
Suite* create_assert_fixture_suite()
{
Suite* suite(suite_create("test::fixture::Assert"));
suite_add_tcase(suite, create_assert_tcase());
return suite;
}
} // fixture
} // test
| 19.942308
| 63
| 0.724204
|
sugawaray
|
1ab59718d64e2d57fadb5d3a4edd505beb48fc2b
| 1,071
|
cpp
|
C++
|
third_party/txt/tests/UnicodeUtilsTest.cpp
|
onix39/engine
|
ec66a45a3a7d5b9dfc2e0feab8965db7a91027cc
|
[
"BSD-3-Clause"
] | 5,823
|
2015-09-20T02:43:18.000Z
|
2022-03-31T23:38:55.000Z
|
third_party/txt/tests/UnicodeUtilsTest.cpp
|
shoryukenn/engine
|
0dc86cda19d55aba8b719231c11306eeaca4b798
|
[
"BSD-3-Clause"
] | 20,081
|
2015-09-19T16:07:59.000Z
|
2022-03-31T23:33:26.000Z
|
third_party/txt/tests/UnicodeUtilsTest.cpp
|
shoryukenn/engine
|
0dc86cda19d55aba8b719231c11306eeaca4b798
|
[
"BSD-3-Clause"
] | 5,383
|
2015-09-24T22:49:53.000Z
|
2022-03-31T14:33:51.000Z
|
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <gtest/gtest.h>
#include "UnicodeUtils.h"
namespace minikin {
TEST(UnicodeUtils, parse) {
const size_t BUF_SIZE = 256;
uint16_t buf[BUF_SIZE];
size_t offset;
size_t size;
ParseUnicode(buf, BUF_SIZE, "U+000D U+1F431 | 'a'", &size, &offset);
EXPECT_EQ(size, 4u);
EXPECT_EQ(offset, 3u);
EXPECT_EQ(buf[0], 0x000D);
EXPECT_EQ(buf[1], 0xD83D);
EXPECT_EQ(buf[2], 0xDC31);
EXPECT_EQ(buf[3], 'a');
}
} // namespace minikin
| 28.184211
| 75
| 0.708683
|
onix39
|
1ab88a18dd8f74b863bbd45e262d092e29d0acfa
| 432
|
cpp
|
C++
|
WindowsServiceCppTemplate/ServiceControlManager.cpp
|
AinoMegumi/WindowsServiceCppTemplate
|
fd123fe43c13356308b3d27a7a5692078979426d
|
[
"MIT"
] | 1
|
2021-07-06T14:31:15.000Z
|
2021-07-06T14:31:15.000Z
|
WindowsServiceCppTemplate/ServiceControlManager.cpp
|
AinoMegumi/WindowsServiceCppTemplate
|
fd123fe43c13356308b3d27a7a5692078979426d
|
[
"MIT"
] | null | null | null |
WindowsServiceCppTemplate/ServiceControlManager.cpp
|
AinoMegumi/WindowsServiceCppTemplate
|
fd123fe43c13356308b3d27a7a5692078979426d
|
[
"MIT"
] | null | null | null |
#include "ServiceControlManager.h"
#include "GetErrorMessage.h"
#include <stdexcept>
ServiceControlManager::ServiceControlManager()
: SCM(OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS)) {
if (this->SCM == nullptr) {
throw std::runtime_error(
"Failed In OpenSCManager Function\n"
+ GetErrorMessageA()
);
}
}
ServiceControlManager::operator const SC_HANDLE& () const noexcept { return this->SCM; }
| 25.411765
| 89
| 0.710648
|
AinoMegumi
|
1ab92d52afb6aff23e6b6df1dcee0273b674a834
| 4,415
|
cpp
|
C++
|
src/args/Arg.cpp
|
GAStudyGroup/VRP
|
54ec7ff3f0a4247d3effe609cf916fc235a08664
|
[
"MIT"
] | 8
|
2018-11-28T15:13:26.000Z
|
2021-10-08T18:34:28.000Z
|
sources/Arg.cpp
|
Arch23/Cpp-Argument-Parser
|
03787751e725db8820b02b702e65b31537dc73d2
|
[
"MIT"
] | 4
|
2018-03-28T19:26:27.000Z
|
2018-04-07T03:02:15.000Z
|
sources/Arg.cpp
|
Arch23/Cpp-Argument-Parser
|
03787751e725db8820b02b702e65b31537dc73d2
|
[
"MIT"
] | 2
|
2019-12-12T09:36:48.000Z
|
2020-04-23T08:26:22.000Z
|
#include "Arg.hpp"
#include <sstream>
using std::istringstream;
#include <set>
using std::set;
#include <algorithm>
using std::any_of;
#include <iostream>
using std::cout;
using std::endl;
Arg::Arg(int argc, char **argv):argc(argc),argv(argv){
programName = "Default Name";
helpSetted = false;
}
void Arg::newArgument(string arg, bool required, string description){
vector<string> argV{split(arg,'|')};
arguments.push_back(Argument(argV, required, description));
}
void Arg::validateArguments(){
//programmer error, name or alias repeated
nameConflict();
processInput();
if(helpSetted && isSet("help")){
throw std::runtime_error(help());
}else{
processRequired();
}
}
void Arg::processRequired(){
bool error{false};
string errorMsg{""};
for(Argument a : arguments){
if(a.getRequired() && a.getOption().empty()){
if(error){
errorMsg += "\n";
}
error = true;
errorMsg += "Required argument: "+a.getArg()[0];
}
}
throwException(errorMsg);
}
void Arg::processInput(){
vector<string> argVector;
bool error{false};
string errorMsg{""};
for(int i=1;i<argc;i++){
string arg = argv[i];
if(arg[0] == '-'){
arg.erase(0,1);
argVector.push_back(arg);
}else{
argVector.back() += " ";
argVector.back() += arg;
}
}
for(string arg : argVector){
vector<string> argSplited = split(arg);
Argument *a = getArgument(argSplited[0]);
if(a==nullptr){
if(error){
errorMsg += "\n";
}
error = true;
errorMsg += "Unexpected argument: "+argSplited[0];
}else{
string option{""};
for(unsigned i=1;i<argSplited.size();i++){
option += argSplited[i];
if((++i)<argSplited.size()){
option += " ";
}
}
a->setOption(option);
a->setArg(true);
}
}
throwException(errorMsg);
}
void Arg::throwException(string errorMsg){
if(!errorMsg.empty()){
if(helpSetted){
errorMsg += "\nUse -help or -h to display program options.";
}
throw std::runtime_error(errorMsg);
}
}
string Arg::help(){
string tmp{};
tmp += programName+"\n\n";
tmp += "Options:\n";
for(Argument a : arguments){
tmp += a.to_string();
tmp += "\n\n";
}
return(tmp);
}
Arg::Argument* Arg::getArgument(string arg){
vector<string> argV = split(arg,'|');
for(string s : argV){
for(Argument &a : arguments){
for(string name : a.getArg()){
if(name == s){
return(&a);
}
}
}
}
return(nullptr);
}
bool Arg::isSet(string arg){
Argument *a = getArgument(arg);
if(a!=nullptr){
return(a->isSet());
}
return false;
}
string Arg::getOption(string arg){
Argument *a = getArgument(arg);
if(a!=nullptr){
return(a->getOption());
}
return {};
}
void Arg::nameConflict(){
set<string> conflicting;
for(unsigned i=0;i<arguments.size();i++){
for(string n : arguments[i].getArg()){
for(unsigned j=0;j<arguments.size();j++){
if(i!=j){
vector<string> tmp{arguments[j].getArg()};
if(find(tmp.begin(),tmp.end(),n)!=tmp.end()){
conflicting.insert(n);
}
}
}
}
}
bool error{false};
string errorMsg{};
for(string n : conflicting){
if(error){
errorMsg+="\n";
}
error = true;
errorMsg += "Conflicting name or alias: "+n;
}
throwException(errorMsg);
}
void Arg::setProgramName(string name){
this->programName = name;
}
void Arg::setHelp(){
helpSetted = true;
newArgument("help|h",false,"Display options available.");
}
vector<string> Arg::split(const string s, char c) {
vector<string> tokens;
string token;
istringstream tokenStream(s);
while (getline(tokenStream, token, c)) {
if (!token.empty()) {
tokens.push_back(token);
}
}
return tokens;
}
| 22.757732
| 72
| 0.512797
|
GAStudyGroup
|
1aba131b0dfdbc8f2f780904bd7fd8947f4e4925
| 5,240
|
cpp
|
C++
|
StatsAPI/statsapi.cpp
|
freem/SMOnline-v1
|
b7202ebf1b2d291952000d8c1673ea6175eb4bdd
|
[
"MIT"
] | 1
|
2021-05-24T09:23:49.000Z
|
2021-05-24T09:23:49.000Z
|
StatsAPI/statsapi.cpp
|
freem/SMOnline-v1
|
b7202ebf1b2d291952000d8c1673ea6175eb4bdd
|
[
"MIT"
] | null | null | null |
StatsAPI/statsapi.cpp
|
freem/SMOnline-v1
|
b7202ebf1b2d291952000d8c1673ea6175eb4bdd
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <vector>
#include "statsapi.h"
using namespace std;
void main(int argc, char* argv[])
{
statsAPI* api = NULL;
vector<CString> args;
if ((argc < 2) || (argc > 21))
return;
args.resize(argc - 1);
for(unsigned int i = 1; i < argc; i++)
args[i - 1] = argv[i];
api = new statsAPI;
api->ProcessCommandsV(args);
if (api)
{
delete api;
api = NULL;
}
}
statsAPI::statsAPI()
{
m_lktype = NONE;
m_database = NULL;
m_startInfo.Database = "stepmani_newstats"; //Not implemented
m_startInfo.Password = "1000Hilltop";
m_startInfo.Port = 3306;
m_startInfo.ServerName = "stepmaniaonline.com";
m_startInfo.UserName = "stepmani_stats";
}
statsAPI::~statsAPI()
{
//Make the API signal the end of the data when destructing.
cout << "END:END";
if (m_database)
delete m_database;
}
void statsAPI::ProcessCommandsV(vector<CString>& commands)
{
CString flag, value;
unsigned int pos = 0;
for (unsigned int i = 0; i < commands.size(); i++)
{
pos = commands[i].Find("=");
if (pos == CString::npos)
{
PrintError("Command \"" + commands[i] + "\" invalid. Ignoring.");
return;
}
flag = commands[i].substr(0,pos);
value = commands[i].substr(pos+1);
if (flag == "id")
{
m_id = value;
m_lktype = ID;
}
else if (flag == "name")
{
m_name = value;
m_lktype = NAME;
}
else if(flag == "op")
{
if (OpenSQLConnection())
ParseOperation(value);
else
PrintError(CString("SQL connection failed"));
}
else
{
PrintError("Unknown command \"" + commands[i] +"\".");
}
}
}
void statsAPI::PrintError(CString& error)
{
cout << "ERROR:" << error << endl;
}
bool statsAPI::ParseOperation(CString& op)
{
if (op == "lr")
{
switch (m_lktype)
{
case NONE:
break;
case NAME:
m_id = QueryID(m_name);
if (m_id != "Unknown" )
m_lktype = ID;
else
{
PrintError("Unknown name " + m_name);
return false;
}
case ID:
PrintQuery(QueryLastRound(m_id), "lr");
break;
}
return true;
}
else if (op == "total")
{
return true;
}
else
PrintError("Unknown operation \"" + op + "\". Ignoring.");
return false;
}
bool statsAPI::OpenSQLConnection()
{
try {
m_database = new ezMySQLConnection(m_startInfo);
m_database->Connect();
}
catch (const ezSQLException &e) {
PrintError(CString("SQL ERROR THROWN! Dec:" + e.Description));
return false;
}
return m_database->m_bLoggedIn;
}
CString statsAPI::QueryID(const CString& name)
{
m_query.m_InitialQuery = "select user_id from `stepmani_stats`.`phpbb_users` where username=\"" + name + "\" limit 0,1";
m_database->BlockingQuery( m_query );
if (m_result.isError)
throw;
m_result = m_query.m_ResultInfo;
if (m_result.FieldContents.size() <= 0)
return "Unknown";
return m_result.FieldContents[0][0].ToString();
}
void statsAPI::PrintQuery( ezSQLQuery &tQuery, string prefix )
{
//In the event we have an error, show it
if ( tQuery.m_ResultInfo.errorNum != 0 )
{
PrintError(CString(tQuery.m_ResultInfo.errorDesc));
exit ( 0 );
}
if ( tQuery.m_ResultInfo.FieldContents.size() == 0 )
{
PrintError(CString("No data for this user."));
exit (0);
}
//Record seed for finding rank.
//show table header
unsigned i = 0;
for ( i = 0; i < tQuery.m_ResultInfo.Header.size(); i++ )
{
cout << prefix<<tQuery.m_ResultInfo.Header[i].Field<<":";
if ( tQuery.m_ResultInfo.FieldContents.size() > 0 )
if ( tQuery.m_ResultInfo.FieldContents[0].size() > i )
{
cout<< tQuery.m_ResultInfo.FieldContents[0][i].ToString()<<endl;
// if ( tQuery.m_ResultInfo.Header[i].Field == "seed" )
// seed = tQuery.m_ResultInfo.FieldContents[0][i].ToString();
}
}
}
ezSQLQuery statsAPI::QueryLastRound(const CString& ID)
{
m_query.m_InitialQuery = "select * from player_stats where pid=" + ID + " order by round_ID desc limit 0,1";
m_database->BlockingQuery( m_query );
return m_query;
}
/*
* (c) 2003-2004 Joshua Allen, Charles Lohr
* All rights reserved.
*
* 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, and/or sell copies of the Software, and to permit persons to
* whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* 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 OF
* THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS
* INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT
* OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
* OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
| 24.036697
| 121
| 0.676718
|
freem
|
1abc839ce6fb2fcc80893976bb0e5bdc0d297b2a
| 165
|
hpp
|
C++
|
algorithm/tests/SortTests.hpp
|
AirChen/AlgorithmCpp
|
a1af7ee437278682d9d0319bab76d85473c3baa0
|
[
"MIT"
] | null | null | null |
algorithm/tests/SortTests.hpp
|
AirChen/AlgorithmCpp
|
a1af7ee437278682d9d0319bab76d85473c3baa0
|
[
"MIT"
] | null | null | null |
algorithm/tests/SortTests.hpp
|
AirChen/AlgorithmCpp
|
a1af7ee437278682d9d0319bab76d85473c3baa0
|
[
"MIT"
] | null | null | null |
//
// SortTests.hpp
// tests
//
// Created by tuRen on 2021/5/17.
//
#ifndef SortTests_hpp
#define SortTests_hpp
#include <stdio.h>
#endif /* SortTests_hpp */
| 11.785714
| 34
| 0.660606
|
AirChen
|
1abdfc77cd9a9c7b46e8dc87f3257e84faa19fcb
| 2,921
|
cpp
|
C++
|
qubus/src/isl/flow.cpp
|
qubusproject/Qubus
|
0feb8d6df00459c5af402545dbe7c82ee3ec4b7c
|
[
"BSL-1.0"
] | null | null | null |
qubus/src/isl/flow.cpp
|
qubusproject/Qubus
|
0feb8d6df00459c5af402545dbe7c82ee3ec4b7c
|
[
"BSL-1.0"
] | null | null | null |
qubus/src/isl/flow.cpp
|
qubusproject/Qubus
|
0feb8d6df00459c5af402545dbe7c82ee3ec4b7c
|
[
"BSL-1.0"
] | null | null | null |
#include <qubus/isl/flow.hpp>
namespace qubus
{
namespace isl
{
union_access_info::union_access_info(isl_union_access_info* handle_) : handle_(handle_)
{
}
union_access_info::union_access_info(const union_access_info& other)
: handle_(isl_union_access_info_copy(other.native_handle()))
{
}
union_access_info::~union_access_info()
{
isl_union_access_info_free(handle_);
}
union_access_info& union_access_info::operator=(union_access_info other)
{
isl_union_access_info_free(handle_);
handle_ = other.release();
return *this;
}
void union_access_info::set_must_source(isl::union_map source)
{
handle_ = isl_union_access_info_set_must_source(handle_, source.release());
}
void union_access_info::set_may_source(isl::union_map source)
{
handle_ = isl_union_access_info_set_may_source(handle_, source.release());
}
void union_access_info::set_schedule(isl::schedule sched)
{
handle_ = isl_union_access_info_set_schedule(handle_, sched.release());
}
isl_union_access_info* union_access_info::native_handle() const
{
return handle_;
}
isl_union_access_info* union_access_info::release() noexcept
{
isl_union_access_info* temp = handle_;
handle_ = nullptr;
return temp;
}
union_access_info union_access_info::from_sink(union_map sink)
{
return union_access_info(isl_union_access_info_from_sink(sink.release()));
}
union_flow::union_flow(isl_union_flow* handle_) : handle_(handle_)
{
}
union_flow::~union_flow()
{
isl_union_flow_free(handle_);
}
union_map union_flow::get_must_dependence() const
{
return union_map(isl_union_flow_get_must_dependence(handle_));
}
union_map union_flow::get_may_dependence() const
{
return union_map(isl_union_flow_get_may_dependence(handle_));
}
isl_union_flow* union_flow::native_handle() const
{
return handle_;
}
isl_union_flow* union_flow::release() noexcept
{
isl_union_flow* temp = handle_;
handle_ = nullptr;
return temp;
}
union_flow compute_flow(union_access_info access_info)
{
return union_flow(isl_union_access_info_compute_flow(access_info.release()));
}
int compute_flow(union_map sink, union_map must_source, union_map may_source, union_map schedule,
union_map& must_dep, union_map& may_dep, union_map& must_no_source,
union_map& may_no_source)
{
isl_union_map* must_dep_;
isl_union_map* may_dep_;
isl_union_map* must_no_source_;
isl_union_map* may_no_source_;
int result = isl_union_map_compute_flow(sink.release(), must_source.release(),
may_source.release(), schedule.release(), &must_dep_,
&may_dep_, &must_no_source_, &may_no_source_);
must_dep = union_map(must_dep_);
may_dep = union_map(may_dep_);
must_no_source = union_map(must_no_source_);
may_no_source = union_map(may_no_source_);
return result;
}
}
}
| 23.556452
| 97
| 0.741869
|
qubusproject
|
1ac16c952417ad528f3a24ca9c19effbbebb83a6
| 3,876
|
cpp
|
C++
|
GUIproject/CourseWorkHypermarket/productlist.cpp
|
ashnaider/CourseWorkHypermarket
|
9dd52dadf987020c2490f2a9a9cdcaa5b52fb12a
|
[
"MIT"
] | 3
|
2020-05-27T18:37:43.000Z
|
2020-06-21T05:40:57.000Z
|
GUIproject/CourseWorkHypermarket/productlist.cpp
|
ashnaider/CourseWorkHypermarket
|
9dd52dadf987020c2490f2a9a9cdcaa5b52fb12a
|
[
"MIT"
] | null | null | null |
GUIproject/CourseWorkHypermarket/productlist.cpp
|
ashnaider/CourseWorkHypermarket
|
9dd52dadf987020c2490f2a9a9cdcaa5b52fb12a
|
[
"MIT"
] | null | null | null |
#include "productlist.h"
#include "product.h"
#include <sstream>
#include <string>
#include <vector>
ProductList::ProductList(QString productClass)
{
utilities = new Utilities;
QString filePath = utilities->generateFilePathForProduct(productClass);
productsInfo = utilities->readFileByWord(filePath, true);
productInfoHeader = productsInfo[0];
productsInfo.erase(productsInfo.begin());
allocateProducts(productClass);
}
void ProductList::allocateProducts(QString productClass) {
currectProductClass = productClass.toStdString();
for (const auto& line : productsInfo) {
std::string firm = line[0];
std::string name = line[1];
double price = std::stod(line[2]);
double maxDiscount = std::stod(line[3]);
if (productClass == "MobilePhones") {
bool isContract = (line[4] == "1") ? true : false;
int maxSimCards = std::stoi(line[5]);
fieldsQuantity = 6;
MobilePhone *mobilePhone;
mobilePhone = new MobilePhone(firm, name, price, maxDiscount,
isContract, maxSimCards);
ptrVecProductList.push_back(mobilePhone);
} else if (productClass == "Smartphones") {
bool isContract = (line[4] == "1") ? true : false;
int maxSimCards = std::stoi(line[5]);
std::string OS = line[6];
std::string preinstalledProgramms = line[7];
fieldsQuantity = 8;
std::stringstream sspp(preinstalledProgramms);
std::vector<std::string> pp;
std::string temp;
while (sspp >> temp) {
pp.push_back(temp);
}
Smartphone *smartphone;
smartphone = new Smartphone(firm, name, price, maxDiscount,
isContract, maxSimCards,
OS, pp);
ptrVecProductList.push_back(smartphone);
} else if (productClass == "Laptops") {
double diagonalSize = std::stod(line[4]);
double weight = std::stod(line[5]);
int cpuCores = std::stoi(line[6]);
int mainMemory = std::stoi(line[7]);
fieldsQuantity = 8;
Laptop *laptop;
laptop = new Laptop(firm, name, price, maxDiscount,
diagonalSize, weight, cpuCores, mainMemory);
ptrVecProductList.push_back(laptop);
}
}
}
const Product* ProductList::getProductByIndex(int index) {
if (index >= 0 && index < ptrVecProductList.size()) {
return ptrVecProductList[index];
} else {
return { };
}
}
int ProductList::GetFieldsQuantity() const {
return fieldsQuantity;
}
QString ProductList::GetQStringProductInfo(const Product *product) const {
QString result = QString::fromStdString(product->GetFirm()) +
"\t" +
QString::fromStdString(product->GetName()) +
"\t" +
QString::number(product->GetPrice()) +
"\t";
return result;
}
std::vector<std::string> ProductList::GetProductInfoInVec(int pNum) const {
return productsInfo[pNum];
}
QList<QString> ProductList::GetProductInfoHeader() const {
QList<QString> result;
for (const auto& word : productInfoHeader) {
result.push_back(QString::fromStdString(word));
}
return result;
}
ProductList::~ProductList() {
delete utilities;
for (auto& product : ptrVecProductList) {
delete product;
}
productsInfo.clear();
}
| 32.033058
| 81
| 0.54257
|
ashnaider
|
1ac39ca5b2ddb057e71738c30bbe6b4536a54da3
| 378
|
hpp
|
C++
|
simsync/include/simsync/synchronization/thread_start.hpp
|
mariobadr/simsync-pmam
|
c541d2bf3a52eec8579e254a0300442bc3d6f1d4
|
[
"Apache-2.0"
] | null | null | null |
simsync/include/simsync/synchronization/thread_start.hpp
|
mariobadr/simsync-pmam
|
c541d2bf3a52eec8579e254a0300442bc3d6f1d4
|
[
"Apache-2.0"
] | null | null | null |
simsync/include/simsync/synchronization/thread_start.hpp
|
mariobadr/simsync-pmam
|
c541d2bf3a52eec8579e254a0300442bc3d6f1d4
|
[
"Apache-2.0"
] | null | null | null |
#ifndef SIMSYNC_THREAD_START_HPP
#define SIMSYNC_THREAD_START_HPP
#include <simsync/synchronization/event.hpp>
namespace simsync {
class thread_start : public event {
public:
explicit thread_start(int32_t thread_id, thread_model &tm);
transition synchronize() override;
private:
void print(std::ostream &stream) const override;
};
}
#endif //SIMSYNC_THREAD_START_HPP
| 19.894737
| 61
| 0.793651
|
mariobadr
|
1ac5f29f8be19da29a2f75af508c1f322ef4907d
| 296
|
cpp
|
C++
|
src/misc/memswap.cpp
|
Damdoshi/LibLapin
|
800e0f17ed8f3c47797c48feea4c280bb0e4bdc9
|
[
"BSD-3-Clause"
] | 38
|
2016-07-30T09:35:19.000Z
|
2022-03-04T10:13:48.000Z
|
src/misc/memswap.cpp
|
Elania-Marvers/LibLapin
|
800e0f17ed8f3c47797c48feea4c280bb0e4bdc9
|
[
"BSD-3-Clause"
] | 15
|
2017-02-12T19:20:52.000Z
|
2021-06-09T09:30:52.000Z
|
src/misc/memswap.cpp
|
Elania-Marvers/LibLapin
|
800e0f17ed8f3c47797c48feea4c280bb0e4bdc9
|
[
"BSD-3-Clause"
] | 12
|
2016-10-06T09:06:59.000Z
|
2022-03-04T10:14:00.000Z
|
// Jason Brillante "Damdoshi"
// Hanged Bunny Studio 2014-2018
//
// Lapin library
#include "lapin_private.h"
void bunny_memswap(void *a,
void *b,
size_t s)
{
void *c = bunny_alloca(s);
memcpy(c, a, s);
memcpy(a, b, s);
memcpy(b, c, s);
bunny_freea(c);
}
| 15.578947
| 32
| 0.577703
|
Damdoshi
|
1ac66153d28c9feb374678c860bffb6aca1c7739
| 4,534
|
inl
|
C++
|
include/ecst/context/system/instance/data_proxy/impl/base.inl
|
SuperV1234/ecst
|
b3c42e2c28978f1cd8ea620ade62613c6c875432
|
[
"AFL-3.0"
] | 475
|
2016-05-03T13:34:30.000Z
|
2021-11-26T07:02:47.000Z
|
include/ecst/context/system/instance/data_proxy/impl/base.inl
|
vittorioromeo/ecst
|
b3c42e2c28978f1cd8ea620ade62613c6c875432
|
[
"AFL-3.0"
] | 28
|
2016-08-30T06:37:40.000Z
|
2017-11-24T11:14:07.000Z
|
include/ecst/context/system/instance/data_proxy/impl/base.inl
|
vittorioromeo/ecst
|
b3c42e2c28978f1cd8ea620ade62613c6c875432
|
[
"AFL-3.0"
] | 60
|
2016-05-11T22:16:15.000Z
|
2021-08-02T20:42:35.000Z
|
// Copyright (c) 2015-2016 Vittorio Romeo
// License: Academic Free License ("AFL") v. 3.0
// AFL License page: http://opensource.org/licenses/AFL-3.0
// http://vittorioromeo.info | vittorio.romeo@outlook.com
#pragma once
#include "./base.hpp"
#define ECST_IMPL_DP_BASE_TEMPLATE \
template <typename TSystemSignature, typename TContext, \
typename TInstance, typename TDerived>
#define ECST_IMPL_DP_BASE base<TSystemSignature, TContext, TInstance, TDerived>
ECST_CONTEXT_SYSTEM_NAMESPACE
{
namespace data_proxy
{
ECST_IMPL_DP_BASE_TEMPLATE
auto& ECST_IMPL_DP_BASE::state_wrapper() noexcept
{
// CRTP is used to efficiently get the state index.
return vrmc::to_derived<TDerived>(*this).state_wrapper();
}
ECST_IMPL_DP_BASE_TEMPLATE
auto& ECST_IMPL_DP_BASE::state() noexcept
{
return state_wrapper().as_state();
}
ECST_IMPL_DP_BASE_TEMPLATE
auto& ECST_IMPL_DP_BASE::output_data() noexcept
{
return state_wrapper().as_data();
}
ECST_IMPL_DP_BASE_TEMPLATE
template <typename TSystemTag>
constexpr auto ECST_IMPL_DP_BASE::can_get_output_of(
TSystemTag st) noexcept
{
constexpr auto ssl =
settings::system_signature_list(settings_type{});
constexpr auto my_ss = TSystemSignature{};
constexpr auto target_ss =
signature_list::system::signature_by_tag(ssl, st);
return signature_list::system::has_dependency_recursive(
ssl, my_ss, target_ss);
}
ECST_IMPL_DP_BASE_TEMPLATE
ECST_IMPL_DP_BASE::base( // .
instance_type& instance, // .
context_type& context // .
) noexcept : _instance{instance}, // .
_context{context} // .
{
}
ECST_IMPL_DP_BASE_TEMPLATE
template <typename TComponentTag>
decltype(auto) ECST_IMPL_DP_BASE::get(
TComponentTag ct, entity_id eid) noexcept
{
constexpr auto can_write =
signature::system::can_write<TSystemSignature>(ct);
constexpr auto can_read =
signature::system::can_read<TSystemSignature>(ct);
return static_if(can_write)
.then([ ct, eid ](auto& x_ctx) -> auto&
{
return x_ctx.get_component(ct, eid);
})
.else_if(can_read)
.then([ ct, eid ](auto& x_ctx) -> const auto&
{
return x_ctx.get_component(ct, eid);
})
.else_([](auto&)
{
// TODO: nicer error message
struct cant_access_that_component;
return cant_access_that_component{};
})(_context);
}
ECST_IMPL_DP_BASE_TEMPLATE
template <typename TComponentTag>
auto ECST_IMPL_DP_BASE::has(
TComponentTag ct, entity_id eid) const noexcept
{
return _context.has_component(ct, eid);
}
ECST_IMPL_DP_BASE_TEMPLATE
template <typename TF>
void ECST_IMPL_DP_BASE::defer(TF&& f)
{
state()._deferred_fns.add(FWD(f));
}
ECST_IMPL_DP_BASE_TEMPLATE
void ECST_IMPL_DP_BASE::kill_entity(entity_id eid)
{
state()._to_kill.add(eid);
}
ECST_IMPL_DP_BASE_TEMPLATE
auto& ECST_IMPL_DP_BASE::output() noexcept
{
ECST_S_ASSERT(
signature::system::has_data_output<system_signature_type>());
return output_data();
}
ECST_IMPL_DP_BASE_TEMPLATE
template <typename TSystemTag>
auto& ECST_IMPL_DP_BASE::system(TSystemTag st) noexcept
{
return _context.system(st);
}
ECST_IMPL_DP_BASE_TEMPLATE
template <typename TSystemTag, typename TF>
decltype(auto) ECST_IMPL_DP_BASE::for_previous_outputs(
TSystemTag st, TF&& f) noexcept
{
ECST_S_ASSERT_DT(can_get_output_of(st));
return _context.for_system_outputs(st, FWD(f));
}
}
}
ECST_CONTEXT_SYSTEM_NAMESPACE_END
#undef ECST_IMPL_DP_BASE
#undef ECST_IMPL_DP_BASE_TEMPLATE
| 31.268966
| 79
| 0.571901
|
SuperV1234
|
1ac7e8aeb3dc27b7aa08ef5d61db26db632550de
| 4,784
|
cc
|
C++
|
media/audio/audio_output_dispatcher.cc
|
gavinp/chromium
|
681563ea0f892a051f4ef3d5e53438e0bb7d2261
|
[
"BSD-3-Clause"
] | 1
|
2016-03-10T09:13:57.000Z
|
2016-03-10T09:13:57.000Z
|
media/audio/audio_output_dispatcher.cc
|
gavinp/chromium
|
681563ea0f892a051f4ef3d5e53438e0bb7d2261
|
[
"BSD-3-Clause"
] | 1
|
2022-03-13T08:39:05.000Z
|
2022-03-13T08:39:05.000Z
|
media/audio/audio_output_dispatcher.cc
|
gavinp/chromium
|
681563ea0f892a051f4ef3d5e53438e0bb7d2261
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "media/audio/audio_output_dispatcher.h"
#include "base/bind.h"
#include "base/compiler_specific.h"
#include "base/message_loop.h"
#include "base/time.h"
#include "media/audio/audio_io.h"
AudioOutputDispatcher::AudioOutputDispatcher(
AudioManager* audio_manager, const AudioParameters& params,
base::TimeDelta close_delay)
: audio_manager_(audio_manager),
message_loop_(MessageLoop::current()),
params_(params),
pause_delay_(base::TimeDelta::FromMilliseconds(
2 * params.frames_per_buffer() *
base::Time::kMillisecondsPerSecond / params.sample_rate())),
paused_proxies_(0),
ALLOW_THIS_IN_INITIALIZER_LIST(weak_this_(this)),
close_timer_(FROM_HERE,
close_delay,
weak_this_.GetWeakPtr(),
&AudioOutputDispatcher::ClosePendingStreams) {
// We expect to be instantiated on the audio thread. Otherwise the
// message_loop_ member will point to the wrong message loop!
DCHECK(audio_manager->GetMessageLoop()->BelongsToCurrentThread());
}
AudioOutputDispatcher::~AudioOutputDispatcher() {
DCHECK_EQ(MessageLoop::current(), message_loop_);
}
bool AudioOutputDispatcher::StreamOpened() {
DCHECK_EQ(MessageLoop::current(), message_loop_);
paused_proxies_++;
// Ensure that there is at least one open stream.
if (idle_streams_.empty() && !CreateAndOpenStream()) {
return false;
}
close_timer_.Reset();
return true;
}
AudioOutputStream* AudioOutputDispatcher::StreamStarted() {
DCHECK_EQ(MessageLoop::current(), message_loop_);
if (idle_streams_.empty() && !CreateAndOpenStream()) {
return NULL;
}
AudioOutputStream* stream = idle_streams_.back();
idle_streams_.pop_back();
DCHECK_GT(paused_proxies_, 0u);
paused_proxies_--;
close_timer_.Reset();
// Schedule task to allocate streams for other proxies if we need to.
message_loop_->PostTask(FROM_HERE, base::Bind(
&AudioOutputDispatcher::OpenTask, weak_this_.GetWeakPtr()));
return stream;
}
void AudioOutputDispatcher::StreamStopped(AudioOutputStream* stream) {
DCHECK_EQ(MessageLoop::current(), message_loop_);
paused_proxies_++;
pausing_streams_.push_front(stream);
// Don't recycle stream until two buffers worth of time has elapsed.
message_loop_->PostDelayedTask(
FROM_HERE,
base::Bind(&AudioOutputDispatcher::StopStreamTask,
weak_this_.GetWeakPtr()),
pause_delay_);
}
void AudioOutputDispatcher::StopStreamTask() {
DCHECK_EQ(MessageLoop::current(), message_loop_);
if (pausing_streams_.empty())
return;
AudioOutputStream* stream = pausing_streams_.back();
pausing_streams_.pop_back();
idle_streams_.push_back(stream);
close_timer_.Reset();
}
void AudioOutputDispatcher::StreamClosed() {
DCHECK_EQ(MessageLoop::current(), message_loop_);
while (!pausing_streams_.empty()) {
idle_streams_.push_back(pausing_streams_.back());
pausing_streams_.pop_back();
}
DCHECK_GT(paused_proxies_, 0u);
paused_proxies_--;
while (idle_streams_.size() > paused_proxies_) {
idle_streams_.back()->Close();
idle_streams_.pop_back();
}
}
void AudioOutputDispatcher::Shutdown() {
DCHECK_EQ(MessageLoop::current(), message_loop_);
// Cancel any pending tasks to close paused streams or create new ones.
weak_this_.InvalidateWeakPtrs();
// No AudioOutputProxy objects should hold a reference to us when we get
// to this stage.
DCHECK(HasOneRef()) << "Only the AudioManager should hold a reference";
AudioOutputStreamList::iterator it = idle_streams_.begin();
for (; it != idle_streams_.end(); ++it)
(*it)->Close();
idle_streams_.clear();
it = pausing_streams_.begin();
for (; it != pausing_streams_.end(); ++it)
(*it)->Close();
pausing_streams_.clear();
}
bool AudioOutputDispatcher::CreateAndOpenStream() {
AudioOutputStream* stream = audio_manager_->MakeAudioOutputStream(params_);
if (!stream)
return false;
if (!stream->Open()) {
stream->Close();
return false;
}
idle_streams_.push_back(stream);
return true;
}
void AudioOutputDispatcher::OpenTask() {
// Make sure that we have at least one stream allocated if there
// are paused streams.
if (paused_proxies_ > 0 && idle_streams_.empty() &&
pausing_streams_.empty()) {
CreateAndOpenStream();
}
close_timer_.Reset();
}
// This method is called by |close_timer_|.
void AudioOutputDispatcher::ClosePendingStreams() {
DCHECK_EQ(MessageLoop::current(), message_loop_);
while (!idle_streams_.empty()) {
idle_streams_.back()->Close();
idle_streams_.pop_back();
}
}
| 27.976608
| 77
| 0.718436
|
gavinp
|
1ac851422692a5f3ef1293a6065f0499859d4ede
| 3,589
|
cpp
|
C++
|
src/app.cpp
|
VIGameStudio/Particles
|
160beb20b3f23cf0973fd57043d901b3f01efa42
|
[
"MIT"
] | null | null | null |
src/app.cpp
|
VIGameStudio/Particles
|
160beb20b3f23cf0973fd57043d901b3f01efa42
|
[
"MIT"
] | null | null | null |
src/app.cpp
|
VIGameStudio/Particles
|
160beb20b3f23cf0973fd57043d901b3f01efa42
|
[
"MIT"
] | null | null | null |
#include "app.hpp"
/// App
#include "imgui.h"
#include "imgui-SFML.h"
#include "alloc.hpp"
#include "particlefx.hpp"
#include "particle_editor.hpp"
#include "vec2.hpp"
#define MAX_PARTICLES 32
#define P_RADIUS 10
#define P_SQRADIUS P_RADIUS*P_RADIUS
LinearAllocator* allocator;
std::vector<ParticleEmitter*> particles;
size_t active = 0;
ParticleEditor editor;
sf::CircleShape circle;
bool dragging = false;
bool App::init(const std::string& respath)
{
const size_t allocSize = sizeof(ParticleEmitter) * MAX_PARTICLES;
allocator = new LinearAllocator(allocSize, malloc(allocSize));
particles.emplace_back(mem::New<ParticleEmitter>(*allocator));
particles.emplace_back(mem::New<ParticleEmitter>(*allocator));
particles.emplace_back(mem::New<ParticleEmitter>(*allocator));
particles.emplace_back(mem::New<ParticleEmitter>(*allocator));
particles.emplace_back(mem::New<ParticleEmitter>(*allocator));
particles.emplace_back(mem::New<ParticleEmitter>(*allocator));
particles.emplace_back(mem::New<ParticleEmitter>(*allocator));
particles.emplace_back(mem::New<ParticleEmitter>(*allocator));
particles.emplace_back(mem::New<ParticleEmitter>(*allocator));
editor.setup(respath, "/textures/particle.png");
circle.setRadius(P_RADIUS);
circle.setOutlineThickness(1.f);
circle.setOutlineColor(sf::Color::Green);
circle.setFillColor(sf::Color::Transparent);
reset();
return true;
}
void App::reset()
{
for(auto p : particles)
p->resetAll();
}
void App::input(const sf::Event& event)
{
if(event.type == sf::Event::Resized) {
views[0].setSize(event.size.width, event.size.height);
}
else
if(event.type == sf::Event::KeyPressed) {
if(event.key.code == sf::Keyboard::R)
reset();
}
else
if(event.type == sf::Event::MouseButtonPressed) {
const sf::Vector2f mpos = getWindow().mapPixelToCoords(sf::Mouse::getPosition(getWindow()));
for(size_t i=0; i<particles.size(); ++i) {
float sqDist = vec2::magnitudeSq(particles[i]->emitter - mpos);
if(sqDist < P_SQRADIUS) {
active = i;
dragging = true;
}
}
}
else
if(event.type == sf::Event::MouseButtonReleased)
dragging = false;
}
void App::fixed(float t, float dt)
{}
void App::update(const sf::Time& elapsed)
{
ParticleEmitter* current = particles[active];
if(dragging) {
const sf::Vector2f mpos = getWindow().mapPixelToCoords(sf::Mouse::getPosition(getWindow()));
vec2::lerp(current->emitter, current->emitter, mpos, 0.2f);
}
for(auto p : particles)
p->update(elapsed);
if (ImGui::BeginMainMenuBar())
{
if (ImGui::BeginMenu("File"))
{
if(ImGui::MenuItem("Open")) editor.open(*current);
if(ImGui::MenuItem("Save")) editor.save(*current);
ImGui::EndMenu();
}
ImGui::EndMainMenuBar();
}
editor.update(*current, elapsed);
}
void App::pre_draw()
{
}
void App::draw(const sf::View& view)
{
getWindow().setView(view);
for(auto p : particles) {
getWindow().draw(*p);
circle.setPosition(p->emitter-sf::Vector2f(P_RADIUS, P_RADIUS));
getWindow().draw(circle);
}
}
void App::post_draw()
{}
void App::clean()
{
}
/// Main
#include "core/engine.hpp"
int main(int argc, char ** args)
{
if (argc < 2) {
std::cout << "Please specify a res path!\n";
return EXIT_FAILURE;
}
return Engine::start<App>(args[1]);
}
| 24.414966
| 100
| 0.637503
|
VIGameStudio
|
1ac8b3251f1aa9e69553c678c880a19926989df8
| 1,503
|
hpp
|
C++
|
include/Lodtalk/Math.hpp
|
ronsaldo/lodtalk
|
4668e8923f508c8a9e87a00242ab67b26fb0c9a4
|
[
"MIT"
] | 3
|
2017-02-10T18:18:58.000Z
|
2019-02-21T02:35:29.000Z
|
include/Lodtalk/Math.hpp
|
ronsaldo/lodtalk
|
4668e8923f508c8a9e87a00242ab67b26fb0c9a4
|
[
"MIT"
] | null | null | null |
include/Lodtalk/Math.hpp
|
ronsaldo/lodtalk
|
4668e8923f508c8a9e87a00242ab67b26fb0c9a4
|
[
"MIT"
] | null | null | null |
#ifndef LODTALK_MATH_HPP
#define LODTALK_MATH_HPP
#include "Lodtalk/ObjectModel.hpp"
namespace Lodtalk
{
inline SmallIntegerValue divideRoundNeg(SmallIntegerValue dividend, SmallIntegerValue divisor)
{
// This algorithm was taken from the Squeak VM.
assert(divisor != 0);
if (dividend >= 0)
{
if (divisor > 0)
{
// Positive result.
return dividend / divisor;
}
else
{
// Negative result. Round towards minus infinite.
auto positiveDivisor = -divisor;
return -(dividend + positiveDivisor - 1) / divisor;
}
}
else
{
auto positiveDividend = -dividend;
if (divisor > 0)
{
// Negative result. Round towards minus infinite.
return -(positiveDividend + divisor - 1) / divisor;
}
else
{
// Positive result.
return dividend / divisor;
}
}
}
inline SmallIntegerValue moduleRoundNeg(SmallIntegerValue dividend, SmallIntegerValue divisor)
{
// This algorithm was taken from the Squeak VM.
assert(divisor != 0);
auto result = dividend % divisor;
// Make sure the result has the same sign as the divisor.
if (divisor < 0)
{
if (result > 0)
result += divisor;
}
else
{
if (result < 0)
result += divisor;
}
return result;
}
} // End of namespace Lodtalk
#endif //LODTALK_MATH_HPP
| 22.102941
| 94
| 0.571524
|
ronsaldo
|
1ad0e382a2b2a74cf034d6474b5ff0b8f8b86f5a
| 1,669
|
hpp
|
C++
|
src/neuron/SwcNode.hpp
|
yzx9/NeuronSdfViewer
|
454164dfccf80b806aac3cd7cca09e2cb8bd3c2a
|
[
"MIT"
] | 1
|
2021-12-31T10:29:56.000Z
|
2021-12-31T10:29:56.000Z
|
src/neuron/SwcNode.hpp
|
yzx9/NeuronSdfViewer
|
454164dfccf80b806aac3cd7cca09e2cb8bd3c2a
|
[
"MIT"
] | null | null | null |
src/neuron/SwcNode.hpp
|
yzx9/NeuronSdfViewer
|
454164dfccf80b806aac3cd7cca09e2cb8bd3c2a
|
[
"MIT"
] | null | null | null |
#pragma once
#include <string>
#include <regex>
#include <memory>
class SwcNode
{
public:
int id;
int type;
float x;
float y;
float z;
float raidus;
int parent;
std::unique_ptr<SwcNode> child;
std::unique_ptr<SwcNode> next;
static bool try_parse(const std::string &s, std::unique_ptr<SwcNode> &out)
{
constexpr auto pattern =
"\\s*"
"(\\d+)\\s" // index
"(\\d+)\\s" // type
"(-?\\d*(?:\\.\\d+)?)\\s" // x
"(-?\\d*(?:\\.\\d+)?)\\s" // y
"(-?\\d*(?:\\.\\d+)?)\\s" // z
"(-?\\d*(?:\\.\\d+)?)\\s" // radius
"(-1|\\d+)\\s*"; // parent
const static std::regex regex(pattern);
std::smatch match;
if (!std::regex_match(s, match, regex))
return false;
out = std::make_unique<SwcNode>();
out->id = std::stoi(match[1]);
out->type = std::stoi(match[2]);
out->x = std::stof(match[3]);
out->y = std::stof(match[4]);
out->z = std::stof(match[5]);
out->raidus = std::stof(match[6]);
out->parent = std::stoi(match[7]);
out->child = nullptr;
out->next = nullptr;
return true;
};
void add_brother(std::unique_ptr<SwcNode> brother)
{
if (next)
next->add_brother(std::move(brother));
else
next = std::move(brother);
};
void add_child(std::unique_ptr<SwcNode> new_child)
{
if (child)
child->add_brother(std::move(new_child));
else
child = std::move(new_child);
}
};
| 24.910448
| 78
| 0.461354
|
yzx9
|
1ad1c9ba27ea9312c984187f93241cd191ae6094
| 436
|
inl
|
C++
|
include/generator_python.inl
|
Three7Six/FastBinaryEncoding
|
2d74ad66afe1cd30988fbbde059a25a2d6f215c6
|
[
"MIT"
] | 1
|
2019-11-16T17:50:52.000Z
|
2019-11-16T17:50:52.000Z
|
include/generator_python.inl
|
Three7Six/FastBinaryEncoding
|
2d74ad66afe1cd30988fbbde059a25a2d6f215c6
|
[
"MIT"
] | null | null | null |
include/generator_python.inl
|
Three7Six/FastBinaryEncoding
|
2d74ad66afe1cd30988fbbde059a25a2d6f215c6
|
[
"MIT"
] | null | null | null |
/*!
\file generator_python.inl
\brief Fast binary encoding Python generator inline implementation
\author Ivan Shynkarenka
\date 24.04.2018
\copyright MIT License
*/
namespace FBE {
inline GeneratorPython::GeneratorPython(const std::string& input, const std::string& output, int indent, char space)
: Generator(input, output, indent, space), _final(false), _json(false), _sender(false)
{
}
} // namespace FBE
| 25.647059
| 116
| 0.720183
|
Three7Six
|
1ada9add6985b6dd3426f201a064ccf6154cef73
| 7,724
|
cc
|
C++
|
content/renderer/pepper/pepper_plugin_instance_throttler_unittest.cc
|
kjthegod/chromium
|
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1
|
2019-11-28T10:46:52.000Z
|
2019-11-28T10:46:52.000Z
|
content/renderer/pepper/pepper_plugin_instance_throttler_unittest.cc
|
kjthegod/chromium
|
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null |
content/renderer/pepper/pepper_plugin_instance_throttler_unittest.cc
|
kjthegod/chromium
|
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2
|
2015-03-27T11:15:39.000Z
|
2016-08-17T14:19:56.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 "base/bind.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop/message_loop.h"
#include "content/public/common/content_switches.h"
#include "content/public/renderer/render_frame.h"
#include "content/renderer/pepper/pepper_plugin_instance_throttler.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/WebKit/public/web/WebInputEvent.h"
#include "third_party/WebKit/public/web/WebPluginParams.h"
#include "ui/gfx/canvas.h"
using testing::_;
using testing::Return;
class GURL;
namespace content {
class PepperPluginInstanceThrottlerTest : public testing::Test {
protected:
PepperPluginInstanceThrottlerTest() : change_callback_calls_(0) {}
void SetUp() override {
blink::WebRect rect;
rect.width = 100;
rect.height = 100;
throttler_.reset(new PepperPluginInstanceThrottler(
nullptr, rect, true /* is_flash_plugin */, GURL("http://example.com"),
content::RenderFrame::POWER_SAVER_MODE_PERIPHERAL_THROTTLED,
base::Bind(&PepperPluginInstanceThrottlerTest::ChangeCallback,
base::Unretained(this))));
}
PepperPluginInstanceThrottler* throttler() {
DCHECK(throttler_.get());
return throttler_.get();
}
void DisablePowerSaverByRetroactiveWhitelist() {
throttler()->DisablePowerSaver(
PepperPluginInstanceThrottler::UNTHROTTLE_METHOD_BY_WHITELIST);
}
int change_callback_calls() { return change_callback_calls_; }
void EngageThrottle() {
throttler_->SetPluginThrottled(true);
}
void SendEventAndTest(blink::WebInputEvent::Type event_type,
bool expect_consumed,
bool expect_throttled,
int expect_change_callback_count) {
blink::WebMouseEvent event;
event.type = event_type;
event.modifiers = blink::WebInputEvent::Modifiers::LeftButtonDown;
EXPECT_EQ(expect_consumed, throttler()->ConsumeInputEvent(event));
EXPECT_EQ(expect_throttled, throttler()->is_throttled());
EXPECT_EQ(expect_change_callback_count, change_callback_calls());
}
private:
void ChangeCallback() { ++change_callback_calls_; }
scoped_ptr<PepperPluginInstanceThrottler> throttler_;
int change_callback_calls_;
base::MessageLoop loop_;
};
TEST_F(PepperPluginInstanceThrottlerTest, ThrottleAndUnthrottleByClick) {
EXPECT_FALSE(throttler()->is_throttled());
EXPECT_EQ(0, change_callback_calls());
EngageThrottle();
EXPECT_TRUE(throttler()->is_throttled());
EXPECT_EQ(1, change_callback_calls());
// MouseUp while throttled should be consumed and disengage throttling.
SendEventAndTest(blink::WebInputEvent::Type::MouseUp, true, false, 2);
}
TEST_F(PepperPluginInstanceThrottlerTest, ThrottleByKeyframe) {
EXPECT_FALSE(throttler()->is_throttled());
EXPECT_EQ(0, change_callback_calls());
SkBitmap boring_bitmap;
gfx::Canvas canvas(gfx::Size(20, 10), 1.0f, true);
canvas.FillRect(gfx::Rect(20, 10), SK_ColorBLACK);
canvas.FillRect(gfx::Rect(10, 10), SK_ColorWHITE);
SkBitmap interesting_bitmap =
skia::GetTopDevice(*canvas.sk_canvas())->accessBitmap(false);
// Don't throttle for a boring frame.
throttler()->OnImageFlush(&boring_bitmap);
EXPECT_FALSE(throttler()->is_throttled());
EXPECT_EQ(0, change_callback_calls());
// Don't throttle for non-consecutive interesting frames.
throttler()->OnImageFlush(&interesting_bitmap);
throttler()->OnImageFlush(&boring_bitmap);
throttler()->OnImageFlush(&interesting_bitmap);
throttler()->OnImageFlush(&boring_bitmap);
throttler()->OnImageFlush(&interesting_bitmap);
throttler()->OnImageFlush(&boring_bitmap);
EXPECT_FALSE(throttler()->is_throttled());
EXPECT_EQ(0, change_callback_calls());
// Throttle after consecutive interesting frames.
throttler()->OnImageFlush(&interesting_bitmap);
throttler()->OnImageFlush(&interesting_bitmap);
throttler()->OnImageFlush(&interesting_bitmap);
throttler()->OnImageFlush(&interesting_bitmap);
EXPECT_TRUE(throttler()->is_throttled());
EXPECT_EQ(1, change_callback_calls());
}
TEST_F(PepperPluginInstanceThrottlerTest, IgnoreThrottlingAfterMouseUp) {
EXPECT_FALSE(throttler()->is_throttled());
EXPECT_EQ(0, change_callback_calls());
// MouseUp before throttling engaged should not be consumed, but should
// prevent subsequent throttling from engaging.
SendEventAndTest(blink::WebInputEvent::Type::MouseUp, false, false, 0);
EngageThrottle();
EXPECT_FALSE(throttler()->is_throttled());
EXPECT_EQ(0, change_callback_calls());
}
TEST_F(PepperPluginInstanceThrottlerTest, FastWhitelisting) {
EXPECT_FALSE(throttler()->is_throttled());
EXPECT_EQ(0, change_callback_calls());
DisablePowerSaverByRetroactiveWhitelist();
EngageThrottle();
EXPECT_FALSE(throttler()->is_throttled());
EXPECT_EQ(1, change_callback_calls());
}
TEST_F(PepperPluginInstanceThrottlerTest, SlowWhitelisting) {
EXPECT_FALSE(throttler()->is_throttled());
EXPECT_EQ(0, change_callback_calls());
EngageThrottle();
EXPECT_TRUE(throttler()->is_throttled());
EXPECT_EQ(1, change_callback_calls());
DisablePowerSaverByRetroactiveWhitelist();
EXPECT_FALSE(throttler()->is_throttled());
EXPECT_EQ(2, change_callback_calls());
}
TEST_F(PepperPluginInstanceThrottlerTest, EventConsumption) {
EXPECT_FALSE(throttler()->is_throttled());
EXPECT_EQ(0, change_callback_calls());
EngageThrottle();
EXPECT_TRUE(throttler()->is_throttled());
EXPECT_EQ(1, change_callback_calls());
// Consume but don't unthrottle on a variety of other events.
SendEventAndTest(blink::WebInputEvent::Type::MouseDown, true, true, 1);
SendEventAndTest(blink::WebInputEvent::Type::MouseWheel, true, true, 1);
SendEventAndTest(blink::WebInputEvent::Type::MouseMove, true, true, 1);
SendEventAndTest(blink::WebInputEvent::Type::KeyDown, true, true, 1);
SendEventAndTest(blink::WebInputEvent::Type::KeyUp, true, true, 1);
// Consume and unthrottle on MouseUp
SendEventAndTest(blink::WebInputEvent::Type::MouseUp, true, false, 2);
// Don't consume events after unthrottle.
SendEventAndTest(blink::WebInputEvent::Type::MouseDown, false, false, 2);
SendEventAndTest(blink::WebInputEvent::Type::MouseWheel, false, false, 2);
SendEventAndTest(blink::WebInputEvent::Type::MouseMove, false, false, 2);
SendEventAndTest(blink::WebInputEvent::Type::KeyDown, false, false, 2);
SendEventAndTest(blink::WebInputEvent::Type::KeyUp, false, false, 2);
// Subsequent MouseUps should also not be consumed.
SendEventAndTest(blink::WebInputEvent::Type::MouseUp, false, false, 2);
}
TEST_F(PepperPluginInstanceThrottlerTest, ThrottleOnLeftClickOnly) {
EXPECT_FALSE(throttler()->is_throttled());
EXPECT_EQ(0, change_callback_calls());
EngageThrottle();
EXPECT_TRUE(throttler()->is_throttled());
EXPECT_EQ(1, change_callback_calls());
blink::WebMouseEvent event;
event.type = blink::WebInputEvent::Type::MouseUp;
event.modifiers = blink::WebInputEvent::Modifiers::RightButtonDown;
EXPECT_FALSE(throttler()->ConsumeInputEvent(event));
EXPECT_TRUE(throttler()->is_throttled());
event.modifiers = blink::WebInputEvent::Modifiers::MiddleButtonDown;
EXPECT_TRUE(throttler()->ConsumeInputEvent(event));
EXPECT_TRUE(throttler()->is_throttled());
event.modifiers = blink::WebInputEvent::Modifiers::LeftButtonDown;
EXPECT_TRUE(throttler()->ConsumeInputEvent(event));
EXPECT_FALSE(throttler()->is_throttled());
}
} // namespace content
| 35.59447
| 78
| 0.752201
|
kjthegod
|
1adff208083bea1d0805b338aabccdebbc09a1d9
| 315
|
inl
|
C++
|
src/readers/F3DExodusIIReader.inl
|
Meakk/f3d
|
40db15ab2a6500ea67bfee5d35714b5c5e2d993c
|
[
"BSD-3-Clause"
] | 318
|
2021-11-14T02:22:32.000Z
|
2022-03-31T02:32:52.000Z
|
src/readers/F3DExodusIIReader.inl
|
Meakk/f3d
|
40db15ab2a6500ea67bfee5d35714b5c5e2d993c
|
[
"BSD-3-Clause"
] | 223
|
2021-11-12T20:52:41.000Z
|
2022-03-29T21:35:18.000Z
|
src/readers/F3DExodusIIReader.inl
|
Meakk/f3d
|
40db15ab2a6500ea67bfee5d35714b5c5e2d993c
|
[
"BSD-3-Clause"
] | 24
|
2021-11-12T22:12:24.000Z
|
2022-03-28T12:42:17.000Z
|
void ApplyCustomReader(vtkAlgorithm* reader, const std::string&) const override
{
vtkExodusIIReader* exReader = vtkExodusIIReader::SafeDownCast(reader);
exReader->UpdateInformation();
exReader->SetAllArrayStatus(vtkExodusIIReader::NODAL, 1);
exReader->SetAllArrayStatus(vtkExodusIIReader::ELEM_BLOCK, 1);
}
| 39.375
| 79
| 0.8
|
Meakk
|
1ae6ee53a1b5bd07a80998f710a02123d3fe9285
| 5,254
|
hpp
|
C++
|
Altis_Life.Altis/config/Config_Process.hpp
|
TomLorenzi/AltasiaV2-Public
|
324e20c4730587de8f7e3eab8acbe9cb02912a1a
|
[
"MIT"
] | null | null | null |
Altis_Life.Altis/config/Config_Process.hpp
|
TomLorenzi/AltasiaV2-Public
|
324e20c4730587de8f7e3eab8acbe9cb02912a1a
|
[
"MIT"
] | null | null | null |
Altis_Life.Altis/config/Config_Process.hpp
|
TomLorenzi/AltasiaV2-Public
|
324e20c4730587de8f7e3eab8acbe9cb02912a1a
|
[
"MIT"
] | null | null | null |
/*
* class:
* MaterialsReq (Needed to process) = Array - Format -> {{"ITEM CLASS",HOWMANY}}
* MaterialsGive (Returned items) = Array - Format -> {{"ITEM CLASS",HOWMANY}}
* Text (Progess Bar Text) = Localised String
* NoLicenseCost (Cost to process w/o license) = Scalar
*
* Example for multiprocess:
*
* class Example {
* MaterialsReq[] = {{"cocaine_processed",1},{"heroin_processed",1}};
* MaterialsGive[] = {{"diamond_cut",1}};
* Text = "STR_Process_Example";
* //ScrollText = "Process Example";
* NoLicenseCost = 4000;
* };
*/
class ProcessAction {
class oil {
MaterialsReq[] = {{"oil_unprocessed",1}};
MaterialsGive[] = {{"oil_processed",1}};
Text = "STR_Process_Oil";
//ScrollText = "Process Oil";
NoLicenseCost = 1200;
};
class diamond {
MaterialsReq[] = {{"diamond_uncut",1}};
MaterialsGive[] = {{"diamond_cut",1}};
Text = "STR_Process_Diamond";
//ScrollText = "Cut Diamonds";
NoLicenseCost = 1350;
};
class heroin {
MaterialsReq[] = {{"heroin_unprocessed",1}};
MaterialsGive[] = {{"heroin_processed",1}};
Text = "STR_Process_Heroin";
//ScrollText = "Process Heroin";
NoLicenseCost = 1750;
};
class copper {
MaterialsReq[] = {{"copper_unrefined",1}};
MaterialsGive[] = {{"copper_refined",1}};
Text = "STR_Process_Copper";
//ScrollText = "Refine Copper";
NoLicenseCost = 750;
};
class iron {
MaterialsReq[] = {{"iron_unrefined",1}};
MaterialsGive[] = {{"iron_refined",1}};
Text = "STR_Process_Iron";
//ScrollText = "Refine Iron";
NoLicenseCost = 1120;
};
class sand {
MaterialsReq[] = {{"sand",1}};
MaterialsGive[] = {{"glass",1}};
Text = "STR_Process_Sand";
//ScrollText = "Melt Sand into Glass";
NoLicenseCost = 650;
};
class salt {
MaterialsReq[] = {{"salt_unrefined",1}};
MaterialsGive[] = {{"salt_refined",1}};
Text = "STR_Process_Salt";
//ScrollText = "Refine Salt";
NoLicenseCost = 450;
};
class cocaine {
MaterialsReq[] = {{"cocaine_unprocessed",1}};
MaterialsGive[] = {{"cocaine_processed",1}};
Text = "STR_Process_Cocaine";
//ScrollText = "Process Cocaine";
NoLicenseCost = 1500;
};
class marijuana {
MaterialsReq[] = {{"cannabis",1}};
MaterialsGive[] = {{"marijuana",1}};
Text = "STR_Process_Marijuana";
//ScrollText = "Harvest Marijuana";
NoLicenseCost = 500;
};
class nos {
MaterialsReq[] = {{"marijuana",1}};
MaterialsGive[] = {{"joint",1}};
Text = "STR_Process_Joint";
NoLicenseCost = 500;
};
class cement {
MaterialsReq[] = {{"rock",1}};
MaterialsGive[] = {{"cement",1}};
Text = "STR_Process_Cement";
//ScrollText = "Mix Cement";
NoLicenseCost = 350;
};
class wood {
MaterialsReq[] = {{"wood",1}};
MaterialsGive[] = {{"paper",1}};
Text = "STR_Process_Wood";
NoLicenseCost = 350;
};
class paper {
MaterialsReq[] = {{"paper",1}};
MaterialsGive[] = {{"fakeMoney",1}};
Text = "STR_Process_FakeMoney";
NoLicenseCost = 350;
};
class cigarette {
MaterialsReq[] = {{"tabac",1}};
MaterialsGive[] = {{"cigarette",1}};
Text = "STR_Process_Cigarette";
NoLicenseCost = 350;
};
class cigar {
MaterialsReq[] = {{"tabac",1}};
MaterialsGive[] = {{"cigar",1}};
Text = "STR_Process_Cigar";
NoLicenseCost = 350;
};
class uraClean {
MaterialsReq[] = {{"uraWaste",1}};
MaterialsGive[] = {{"uraClean",1}};
Text = "STR_Process_UraClean";
NoLicenseCost = 350;
};
class uraRich {
MaterialsReq[] = {{"uraClean",1}};
MaterialsGive[] = {{"uraRich",1}};
Text = "STR_Process_UraRich";
NoLicenseCost = 350;
};
class uraFinal {
MaterialsReq[] = {{"uraRich",1}};
MaterialsGive[] = {{"uraFinal",1}};
Text = "STR_Process_UraFinal";
NoLicenseCost = 350;
};
class diamondHub {
MaterialsReq[] = {{"diamond_cut",1}};
MaterialsGive[] = {{"bague",1}};
Text = "STR_Process_Bague";
NoLicenseCost = 350;
};
class OxyScrap {
MaterialsReq[] = {{"copper_refined",1}};
MaterialsGive[] = {{"tuyau",1}};
Text = "STR_Process_Tuyau";
NoLicenseCost = 350;
};
class carte_graph {
MaterialsReq[] = {{"carte_graph_endom",1}};
MaterialsGive[] = {{"carte_graph",1}};
Text = "STR_Process_Carte_Graph";
NoLicenseCost = 350;
};
class bitcoin {
MaterialsReq[] = {{"carte_graph",18}};
MaterialsGive[] = {{"bitcoin",1}};
Text = "STR_Process_Bitcoin";
NoLicenseCost = 350;
};
class ordi {
MaterialsReq[] = {{"carte_graph",1}};
MaterialsGive[] = {{"ordi",1}};
Text = "STR_Process_Ordi";
NoLicenseCost = 350;
};
};
| 27.507853
| 85
| 0.533879
|
TomLorenzi
|
1ae9cfbf8cb82475063bd9410a9aa6fccb9208cf
| 64,799
|
cc
|
C++
|
deps/sparsehash/src/hashtable_unittest.cc
|
PelionIoT/twlib
|
7a2219924e66cb33810dad5a8314b0f0cff49018
|
[
"DOC",
"MIT"
] | 1
|
2017-09-15T19:48:30.000Z
|
2017-09-15T19:48:30.000Z
|
deps/sparsehash/src/hashtable_unittest.cc
|
PelionIoT/twlib
|
7a2219924e66cb33810dad5a8314b0f0cff49018
|
[
"DOC",
"MIT"
] | null | null | null |
deps/sparsehash/src/hashtable_unittest.cc
|
PelionIoT/twlib
|
7a2219924e66cb33810dad5a8314b0f0cff49018
|
[
"DOC",
"MIT"
] | 1
|
2019-10-23T08:48:56.000Z
|
2019-10-23T08:48:56.000Z
|
// Copyright (c) 2005, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// ---
// Author: Craig Silverstein
//
// This tests <google/sparsehash/densehashtable.h>
// This tests <google/dense_hash_set>
// This tests <google/dense_hash_map>
// This tests <google/sparsehash/sparsehashtable.h>
// This tests <google/sparse_hash_set>
// This tests <google/sparse_hash_map>
// Since {dense,sparse}hashtable is templatized, it's important that
// we test every function in every class in this file -- not just to
// see if it works, but even if it compiles.
#include "config.h"
#include <stdio.h>
#include <sys/stat.h> // for stat()
#ifdef HAVE_UNISTD_H
#include <unistd.h> // for unlink()
#endif
#include <string.h>
#include <time.h> // for silly random-number-seed generator
#include <math.h> // for sqrt()
#include <map>
#include <set>
#include <iterator> // for insert_iterator
#include <iostream>
#include <iomanip> // for setprecision()
#include <string>
#include <stdexcept> // for std::length_error
#include HASH_FUN_H // defined in config.h
#include <google/type_traits.h>
#include <google/sparsehash/libc_allocator_with_realloc.h>
#include <google/dense_hash_map>
#include <google/dense_hash_set>
#include <google/sparsehash/densehashtable.h>
#include <google/sparse_hash_map>
#include <google/sparse_hash_set>
#include <google/sparsehash/sparsehashtable.h>
// Otherwise, VC++7 warns about size_t -> int in the cout logging lines
#ifdef _MSC_VER
#pragma warning(disable:4267)
#endif
using GOOGLE_NAMESPACE::sparse_hash_map;
using GOOGLE_NAMESPACE::dense_hash_map;
using GOOGLE_NAMESPACE::sparse_hash_set;
using GOOGLE_NAMESPACE::dense_hash_set;
using GOOGLE_NAMESPACE::sparse_hashtable;
using GOOGLE_NAMESPACE::dense_hashtable;
using GOOGLE_NAMESPACE::libc_allocator_with_realloc;
using STL_NAMESPACE::map;
using STL_NAMESPACE::set;
using STL_NAMESPACE::vector;
using STL_NAMESPACE::pair;
using STL_NAMESPACE::make_pair;
using STL_NAMESPACE::string;
using STL_NAMESPACE::insert_iterator;
using STL_NAMESPACE::allocator;
using STL_NAMESPACE::equal_to;
using STL_NAMESPACE::ostream;
typedef unsigned char uint8;
#define LOGF STL_NAMESPACE::cout // where we log to; LOGF is a historical name
#define CHECK(cond) do { \
if (!(cond)) { \
LOGF << "Test failed: " #cond "\n"; \
exit(1); \
} \
} while (0)
#define CHECK_EQ(a, b) CHECK((a) == (b))
#define CHECK_LT(a, b) CHECK((a) < (b))
#define CHECK_GT(a, b) CHECK((a) > (b))
#define CHECK_LE(a, b) CHECK((a) <= (b))
#define CHECK_GE(a, b) CHECK((a) >= (b))
#ifndef _MSC_VER // windows defines its own version
static string TmpFile(const char* basename) {
return string("/tmp/") + basename;
}
#endif
const char *words[] = {"Baffin\n", // in /usr/dict/words
"Boffin\n", // not in
"baffin\n", // not in
"genial\n", // last word in
"Aarhus\n", // first word alphabetically
"Zurich\n", // last word alphabetically
"Getty\n",
};
const char *nwords[] = {"Boffin\n",
"baffin\n",
};
const char *default_dict[] = {"Aarhus\n",
"aback\n",
"abandon\n",
"Baffin\n",
"baffle\n",
"bagged\n",
"congenial\n",
"genial\n",
"Getty\n",
"indiscreet\n",
"linens\n",
"pence\n",
"reassure\n",
"sequel\n",
"zoning\n",
"zoo\n",
"Zurich\n",
};
// Likewise, it's not standard to hash a string pre-tr1. Luckily, it is a char*
#ifdef HAVE_UNORDERED_MAP
typedef SPARSEHASH_HASH<string> StrHash;
struct CharStarHash {
size_t operator()(const char* s) const {
return StrHash()(string(s));
}
// These are used by MSVC:
bool operator()(const char* a, const char* b) const {
return strcmp(a, b) < 0;
}
static const size_t bucket_size = 4; // These are required by MSVC
static const size_t min_buckets = 8; // 4 and 8 are the defaults
};
#else
typedef SPARSEHASH_HASH<const char*> CharStarHash;
struct StrHash {
size_t operator()(const string& s) const {
return SPARSEHASH_HASH<const char*>()(s.c_str());
}
// These are used by MSVC:
bool operator()(const string& a, const string& b) const {
return a < b;
}
static const size_t bucket_size = 4; // These are required by MSVC
static const size_t min_buckets = 8; // 4 and 8 are the defaults
};
#endif
// Let us log the pairs that make up a hash_map
template<class P1, class P2>
ostream& operator<<(ostream& s, const pair<P1, P2>& p) {
s << "pair(" << p.first << ", " << p.second << ")";
return s;
}
struct strcmp_fnc {
bool operator()(const char* s1, const char* s2) const {
return ((s1 == 0 && s2 == 0) ||
(s1 && s2 && *s1 == *s2 && strcmp(s1, s2) == 0));
}
};
namespace {
template <class T, class H, class I, class S, class C, class A>
void set_empty_key(sparse_hashtable<T,T,H,I,S,C,A> *ht, T val) {
}
template <class T, class H, class C, class A>
void set_empty_key(sparse_hash_set<T,H,C,A> *ht, T val) {
}
template <class K, class V, class H, class C, class A>
void set_empty_key(sparse_hash_map<K,V,H,C,A> *ht, K val) {
}
template <class T, class H, class I, class S, class C, class A>
void set_empty_key(dense_hashtable<T,T,H,I,S,C,A> *ht, T val) {
ht->set_empty_key(val);
}
template <class T, class H, class C, class A>
void set_empty_key(dense_hash_set<T,H,C,A> *ht, T val) {
ht->set_empty_key(val);
}
template <class K, class V, class H, class C, class A>
void set_empty_key(dense_hash_map<K,V,H,C,A> *ht, K val) {
ht->set_empty_key(val);
}
template <class T, class H, class I, class S, class C, class A>
bool clear_no_resize(sparse_hashtable<T,T,H,I,S,C,A> *ht) {
return false;
}
template <class T, class H, class C, class A>
bool clear_no_resize(sparse_hash_set<T,H,C,A> *ht) {
return false;
}
template <class K, class V, class H, class C, class A>
bool clear_no_resize(sparse_hash_map<K,V,H,C,A> *ht) {
return false;
}
template <class T, class H, class I, class S, class C, class A>
bool clear_no_resize(dense_hashtable<T,T,H,I,S,C,A> *ht) {
ht->clear_no_resize();
return true;
}
template <class T, class H, class C, class A>
bool clear_no_resize(dense_hash_set<T,H,C,A> *ht) {
ht->clear_no_resize();
return true;
}
template <class K, class V, class H, class C, class A>
bool clear_no_resize(dense_hash_map<K,V,H,C,A> *ht) {
ht->clear_no_resize();
return true;
}
template <class T, class H, class I, class S, class C, class A>
void insert(dense_hashtable<T,T,H,I,S,C,A> *ht, T val) {
ht->insert(val);
}
template <class T, class H, class C, class A>
void insert(dense_hash_set<T,H,C,A> *ht, T val) {
ht->insert(val);
}
template <class K, class V, class H, class C, class A>
void insert(dense_hash_map<K,V,H,C,A> *ht, K val) {
ht->insert(pair<K,V>(val,V()));
}
template <class T, class H, class I, class S, class C, class A>
void insert(sparse_hashtable<T,T,H,I,S,C,A> *ht, T val) {
ht->insert(val);
}
template <class T, class H, class C, class A>
void insert(sparse_hash_set<T,H,C,A> *ht, T val) {
ht->insert(val);
}
template <class K, class V, class H, class C, class A>
void insert(sparse_hash_map<K,V,H,C,A> *ht, K val) {
ht->insert(pair<K,V>(val,V()));
}
template <class HT, class Iterator>
void insert(HT *ht, Iterator begin, Iterator end) {
ht->insert(begin, end);
}
// For hashtable's and hash_set's, the iterator insert works fine (and
// is used). But for the hash_map's, the iterator insert expects the
// iterators to point to pair's. So by looping over and calling insert
// on each element individually, the code below automatically expands
// into inserting a pair.
template <class K, class V, class H, class C, class A, class Iterator>
void insert(dense_hash_map<K,V,H,C,A> *ht, Iterator begin, Iterator end) {
while (begin != end) {
insert(ht, *begin);
++begin;
}
}
template <class K, class V, class H, class C, class A, class Iterator>
void insert(sparse_hash_map<K,V,H,C,A> *ht, Iterator begin, Iterator end) {
while (begin != end) {
insert(ht, *begin);
++begin;
}
}
// Just like above, but uses operator[] when possible.
template <class T, class H, class I, class S, class C, class A>
void bracket_insert(dense_hashtable<T,T,H,I,S,C,A> *ht, T val) {
ht->insert(val);
}
template <class T, class H, class C, class A>
void bracket_insert(dense_hash_set<T,H,C,A> *ht, T val) {
ht->insert(val);
}
template <class K, class V, class H, class C, class A>
void bracket_insert(dense_hash_map<K,V,H,C,A> *ht, K val) {
(*ht)[val] = V();
}
template <class T, class H, class I, class S, class C, class A>
void bracket_insert(sparse_hashtable<T,T,H,I,S,C,A> *ht, T val) {
ht->insert(val);
}
template <class T, class H, class C, class A>
void bracket_insert(sparse_hash_set<T,H,C,A> *ht, T val) {
ht->insert(val);
}
template <class K, class V, class H, class C, class A>
void bracket_insert(sparse_hash_map<K,V,H,C,A> *ht, K val) {
(*ht)[val] = V();
}
template <class HT, class Iterator>
void bracket_insert(HT *ht, Iterator begin, Iterator end) {
ht->bracket_insert(begin, end);
}
template <class K, class V, class H, class C, class A, class Iterator>
void bracket_insert(dense_hash_map<K,V,H,C,A> *ht,
Iterator begin, Iterator end) {
while (begin != end) {
bracket_insert(ht, *begin);
++begin;
}
}
template <class K, class V, class H, class C, class A, class Iterator>
void bracket_insert(sparse_hash_map<K,V,H,C,A> *ht,
Iterator begin, Iterator end) {
while (begin != end) {
bracket_insert(ht, *begin);
++begin;
}
}
// A version of insert that uses the insert_iterator. But insert_iterator
// isn't defined for the low level hashtable classes, so we just punt to insert.
template <class T, class H, class I, class S, class C, class A>
void iterator_insert(dense_hashtable<T,T,H,I,S,C,A>* ht, T val,
insert_iterator<dense_hashtable<T,T,H,I,S,C,A> >* ) {
ht->insert(val);
}
template <class T, class H, class C, class A>
void iterator_insert(dense_hash_set<T,H,C,A>* , T val,
insert_iterator<dense_hash_set<T,H,C,A> >* ii) {
*(*ii)++ = val;
}
template <class K, class V, class H, class C, class A>
void iterator_insert(dense_hash_map<K,V,H,C,A>* , K val,
insert_iterator<dense_hash_map<K,V,H,C,A> >* ii) {
*(*ii)++ = pair<K,V>(val,V());
}
template <class T, class H, class I, class S, class C, class A>
void iterator_insert(sparse_hashtable<T,T,H,I,S,C,A>* ht, T val,
insert_iterator<sparse_hashtable<T,T,H,I,S,C,A> >* ) {
ht->insert(val);
}
template <class T, class H, class C, class A>
void iterator_insert(sparse_hash_set<T,H,C,A>* , T val,
insert_iterator<sparse_hash_set<T,H,C,A> >* ii) {
*(*ii)++ = val;
}
template <class K, class V, class H, class C, class A>
void iterator_insert(sparse_hash_map<K,V,H,C,A> *, K val,
insert_iterator<sparse_hash_map<K,V,H,C,A> >* ii) {
*(*ii)++ = pair<K,V>(val,V());
}
void write_item(FILE *fp, const char *val) {
fwrite(val, strlen(val), 1, fp); // \n serves to separate
}
// The weird 'const' declarations are desired by the compiler. Yucko.
void write_item(FILE *fp, const pair<char*const,int> &val) {
fwrite(val.first, strlen(val.first), 1, fp);
}
void write_item(FILE *fp, const string &val) {
fwrite(val.data(), val.length(), 1, fp); // \n serves to separate
}
// The weird 'const' declarations are desired by the compiler. Yucko.
void write_item(FILE *fp, const pair<const string,int> &val) {
fwrite(val.first.data(), val.first.length(), 1, fp);
}
char* read_line(FILE* fp, char* line, int linesize) {
if ( fgets(line, linesize, fp) == NULL )
return NULL;
// normalize windows files :-(
const size_t linelen = strlen(line);
if ( linelen >= 2 && line[linelen-2] == '\r' && line[linelen-1] == '\n' ) {
line[linelen-2] = '\n';
line[linelen-1] = '\0';
}
return line;
}
void read_item(FILE *fp, char*const* val) {
char line[1024];
read_line(fp, line, sizeof(line));
char **p = const_cast<char**>(val);
*p = strdup(line);
}
void read_item(FILE *fp, pair<char*const,int> *val) {
char line[1024];
read_line(fp, line, sizeof(line));
char **p = const_cast<char**>(&val->first);
*p = strdup(line);
}
void read_item(FILE *fp, const string* val) {
char line[1024];
read_line(fp, line, sizeof(line));
new(const_cast<string*>(val)) string(line); // need to use placement new
}
void read_item(FILE *fp, pair<const string,int> *val) {
char line[1024];
read_line(fp, line, sizeof(line));
new(const_cast<string*>(&val->first)) string(line);
}
void free_item(char*const* val) {
free(*val);
}
void free_item(pair<char*const,int> *val) {
free(val->first);
}
int get_int_item(int int_item) {
return int_item;
}
int get_int_item(pair<int, int> val) {
return val.first;
}
int getintkey(int i) { return i; }
int getintkey(const pair<int, int> &p) { return p.first; }
template<typename T>
class DenseStringMap : public dense_hash_map<string, T> {
public:
DenseStringMap() { this->set_empty_key(string()); }
};
class DenseStringSet : public dense_hash_set<string> {
public:
DenseStringSet() { this->set_empty_key(string()); }
};
// Allocator that uses uint8 as size_type to test overflowing on insert.
// Also, to test allocators with state, if you pass in an int*, we
// increment it on every alloc and realloc call. Because we use this
// allocator in a vector, we need to define != and swap for gcc.
template<typename T, typename SizeT, int MAX_SIZE>
struct Alloc {
typedef T value_type;
typedef SizeT size_type;
typedef ptrdiff_t difference_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
Alloc(int* count = NULL) : count_(count) {}
~Alloc() {}
pointer address(reference r) const { return &r; }
const_pointer address(const_reference r) const { return &r; }
pointer allocate(size_type n, const_pointer = 0) {
if (count_) ++(*count_);
return static_cast<pointer>(malloc(n * sizeof(value_type)));
}
void deallocate(pointer p, size_type n) {
free(p);
}
pointer reallocate(pointer p, size_type n) {
if (count_) ++(*count_);
return static_cast<pointer>(realloc(p, n * sizeof(value_type)));
}
size_type max_size() const {
return static_cast<size_type>(MAX_SIZE);
}
void construct(pointer p, const value_type& val) {
new(p) value_type(val);
}
void destroy(pointer p) { p->~value_type(); }
bool is_custom_alloc() const { return true; }
template <class U>
Alloc(const Alloc<U, SizeT, MAX_SIZE>& that) : count_(that.count_) {}
template <class U>
struct rebind {
typedef Alloc<U, SizeT, MAX_SIZE> other;
};
bool operator!=(const Alloc<T,SizeT,MAX_SIZE>& that) {
return this->count_ != that.count_;
}
private:
template<typename U, typename U_SizeT, int U_MAX_SIZE> friend class Alloc;
int* count_;
};
} // end anonymous namespace
// Performs tests where the hashtable's value type is assumed to be int.
template <class htint>
void test_int() {
htint x;
htint y(1000);
htint z(64);
set_empty_key(&x, 0xefefef);
set_empty_key(&y, 0xefefef);
set_empty_key(&z, 0xefefef);
CHECK(y.empty());
insert(&y, 1);
CHECK(!y.empty());
insert(&y, 11);
insert(&y, 111);
insert(&y, 1111);
insert(&y, 11111);
insert(&y, 111111);
insert(&y, 1111111); // 1M, more or less
insert(&y, 11111111);
insert(&y, 111111111);
insert(&y, 1111111111); // 1B, more or less
for ( int i = 0; i < 64; ++i )
insert(&z, i);
// test the second half of the insert with an insert_iterator
insert_iterator<htint> insert_iter(z, z.begin());
for ( int i = 32; i < 64; ++i )
iterator_insert(&z, i, &insert_iter);
// only perform the following CHECKs for
// dense{hashtable, _hash_set, _hash_map}
if (clear_no_resize(&x)) {
// make sure x has to increase its number of buckets
typename htint::size_type empty_bucket_count = x.bucket_count();
int last_element = 0;
while (x.bucket_count() == empty_bucket_count) {
insert(&x, last_element);
++last_element;
}
// if clear_no_resize is supported (i.e. htint is a
// dense{hashtable,_hash_set,_hash_map}), it should leave the bucket_count
// as is.
typename htint::size_type last_bucket_count = x.bucket_count();
clear_no_resize(&x);
CHECK(last_bucket_count == x.bucket_count());
CHECK(x.empty());
LOGF << "x has " << x.bucket_count() << " buckets\n";
LOGF << "x size " << x.size() << "\n";
// when inserting the same number of elements again, no resize should be
// necessary
for (int i = 0; i < last_element; ++i) {
insert(&x, i);
CHECK(x.bucket_count() == last_bucket_count);
}
}
for ( typename htint::const_iterator it = y.begin(); it != y.end(); ++it )
LOGF << "y: " << get_int_item(*it) << "\n";
z.insert(y.begin(), y.end());
swap(y,z);
for ( typename htint::iterator it = y.begin(); it != y.end(); ++it )
LOGF << "y+z: " << get_int_item(*it) << "\n";
LOGF << "z has " << z.bucket_count() << " buckets\n";
LOGF << "y has " << y.bucket_count() << " buckets\n";
LOGF << "z size: " << z.size() << "\n";
for (int i = 0; i < 64; ++i)
CHECK(y.find(i) != y.end());
CHECK(z.size() == 10);
z.set_deleted_key(1010101010); // an unused value
CHECK(z.deleted_key() == 1010101010);
z.erase(11111);
CHECK(z.size() == 9);
insert(&z, 11111); // should retake deleted value
CHECK(z.size() == 10);
// Do the delete/insert again. Last time we probably resized; this time no
z.erase(11111);
insert(&z, 11111); // should retake deleted value
CHECK(z.size() == 10);
z.erase(-11111); // shouldn't do anything
CHECK(z.size() == 10);
z.erase(1);
CHECK(z.size() == 9);
typename htint::iterator itdel = z.find(1111);
pair<typename htint::iterator,typename htint::iterator> itdel2
= z.equal_range(1111);
CHECK(itdel2.first != z.end());
CHECK(&*itdel2.first == &*itdel); // while we're here, check equal_range()
CHECK(itdel2.second == ++itdel2.first);
pair<typename htint::const_iterator,typename htint::const_iterator> itdel3
= const_cast<const htint*>(&z)->equal_range(1111);
CHECK(itdel3.first != z.end());
CHECK(&*itdel3.first == &*itdel);
CHECK(itdel3.second == ++itdel3.first);
z.erase(itdel);
CHECK(z.size() == 8);
itdel2 = z.equal_range(1111);
CHECK(itdel2.first == z.end());
CHECK(itdel2.second == itdel2.first);
itdel3 = const_cast<const htint*>(&z)->equal_range(1111);
CHECK(itdel3.first == z.end());
CHECK(itdel3.second == itdel3.first);
itdel = z.find(2222); // should be end()
z.erase(itdel); // shouldn't do anything
CHECK(z.size() == 8);
for ( typename htint::const_iterator it = z.begin(); it != z.end(); ++it )
LOGF << "y: " << get_int_item(*it) << "\n";
z.set_deleted_key(1010101011); // a different unused value
CHECK(z.deleted_key() == 1010101011);
for ( typename htint::const_iterator it = z.begin(); it != z.end(); ++it )
LOGF << "y: " << get_int_item(*it) << "\n";
LOGF << "That's " << z.size() << " elements\n";
z.erase(z.begin(), z.end());
CHECK(z.empty());
y.clear();
CHECK(y.empty());
LOGF << "y has " << y.bucket_count() << " buckets\n";
// Let's do some crash-testing with operator[]
y.set_deleted_key(-1);
for (int iters = 0; iters < 10; iters++) {
// We start at 33 because after shrinking, we'll be at 32 buckets.
for (int i = 33; i < 133; i++) {
bracket_insert(&y, i);
}
clear_no_resize(&y);
// This will force a shrink on the next insert, which we want to test.
insert(&y, 0);
y.erase(0);
}
}
// Performs tests where the hashtable's value type is assumed to be char*.
// The read_write parameters specifies whether the read/write tests
// should be performed. Note that densehashtable::write_metdata is not
// implemented, so we only do the read/write tests for the
// sparsehashtable varieties.
template <class ht>
void test_charptr(bool read_write) {
ht w;
set_empty_key(&w, (char*) NULL);
insert(&w, const_cast<char **>(nwords),
const_cast<char **>(nwords) + sizeof(nwords) / sizeof(*nwords));
LOGF << "w has " << w.size() << " items\n";
CHECK(w.size() == 2);
CHECK(w == w);
ht x;
set_empty_key(&x, (char*) NULL);
long dict_size = 1; // for size stats -- can't be 0 'cause of division
map<string, int> counts;
// Hash the dictionary
{
// automake says 'look for all data files in $srcdir.' OK.
string filestr = (string(getenv("srcdir") ? getenv("srcdir") : ".") +
"/src/words");
const char* file = filestr.c_str();
FILE *fp = fopen(file, "rb");
if ( fp == NULL ) {
LOGF << "Can't open " << file << ", using small, built-in dict...\n";
for (int i = 0; i < sizeof(default_dict)/sizeof(*default_dict); ++i) {
insert(&x, strdup(default_dict[i]));
counts[default_dict[i]] = 0;
}
} else {
char line[1024];
while ( read_line(fp, line, sizeof(line)) ) {
insert(&x, strdup(line));
counts[line] = 0;
}
LOGF << "Read " << x.size() << " words from " << file << "\n";
fclose(fp);
struct stat buf;
stat(file, &buf);
dict_size = buf.st_size;
LOGF << "Size of " << file << ": " << buf.st_size << " bytes\n";
}
for (char **word = const_cast<char **>(words);
word < const_cast<char **>(words) + sizeof(words) / sizeof(*words);
++word ) {
if (x.find(*word) == x.end()) {
CHECK(w.find(*word) != w.end());
} else {
CHECK(w.find(*word) == w.end());
}
}
}
CHECK(counts.size() == x.size());
// Save the hashtable.
if (read_write) {
const string file_string = TmpFile(".hashtable_unittest_dicthash");
const char* file = file_string.c_str();
FILE *fp = fopen(file, "wb");
if ( fp == NULL ) {
// maybe we can't write to /tmp/. Try the current directory
file = ".hashtable_unittest_dicthash";
fp = fopen(file, "wb");
}
if ( fp == NULL ) {
LOGF << "Can't open " << file << " skipping hashtable save...\n";
} else {
x.write_metadata(fp); // this only writes meta-information
int write_count = 0;
for ( typename ht::iterator it = x.begin(); it != x.end(); ++it ) {
write_item(fp, *it);
free_item(&(*it));
++write_count;
}
LOGF << "Wrote " << write_count << " words to " << file << "\n";
fclose(fp);
struct stat buf;
stat(file, &buf);
LOGF << "Size of " << file << ": " << buf.st_size << " bytes\n";
LOGF << STL_NAMESPACE::setprecision(3)
<< "Hashtable overhead "
<< (buf.st_size - dict_size) * 100.0 / dict_size
<< "% ("
<< (buf.st_size - dict_size) * 8.0 / write_count
<< " bits/entry)\n";
x.clear();
// Load the hashtable
fp = fopen(file, "rb");
if ( fp == NULL ) {
LOGF << "Can't open " << file << " skipping hashtable reload...\n";
} else {
x.read_metadata(fp); // reads metainformation
LOGF << "Hashtable size: " << x.size() << "\n";
int read_count = 0;
for ( typename ht::iterator it = x.begin(); it != x.end(); ++it ) {
read_item(fp, &(*it));
++read_count;
}
LOGF << "Read " << read_count << " words from " << file << "\n";
fclose(fp);
unlink(file);
for ( char **word = const_cast<char **>(words);
word < const_cast<char **>(words) + sizeof(words) / sizeof(*words);
++word ) {
if (x.find(*word) == x.end()) {
CHECK(w.find(*word) != w.end());
} else {
CHECK(w.find(*word) == w.end());
}
}
}
}
}
for ( typename ht::iterator it = x.begin(); it != x.end(); ++it ) {
free_item(&(*it));
}
}
// Perform tests where the hashtable's value type is assumed to
// be string.
// TODO(austern): factor out the bulk of test_charptr and test_string
// into a common function.
template <class ht>
void test_string(bool read_write) {
ht w;
set_empty_key(&w, string("-*- empty key -*-"));
const int N = sizeof(nwords) / sizeof(*nwords);
string* nwords1 = new string[N];
for (int i = 0; i < N; ++i)
nwords1[i] = nwords[i];
insert(&w, nwords1, nwords1 + N);
delete[] nwords1;
LOGF << "w has " << w.size() << " items\n";
CHECK(w.size() == 2);
CHECK(w == w);
ht x;
set_empty_key(&x, string("-*- empty key -*-"));
long dict_size = 1; // for size stats -- can't be 0 'cause of division
map<string, int> counts;
// Hash the dictionary
{
// automake says 'look for all data files in $srcdir.' OK.
string filestr = (string(getenv("srcdir") ? getenv("srcdir") : ".") +
"/src/words");
const char* file = filestr.c_str();
FILE *fp = fopen(file, "rb");
if ( fp == NULL ) {
LOGF << "Can't open " << file << ", using small, built-in dict...\n";
for (int i = 0; i < sizeof(default_dict)/sizeof(*default_dict); ++i) {
insert(&x, string(default_dict[i]));
counts[default_dict[i]] = 0;
}
} else {
char line[1024];
while ( fgets(line, sizeof(line), fp) ) {
insert(&x, string(line));
counts[line] = 0;
}
LOGF << "Read " << x.size() << " words from " << file << "\n";
fclose(fp);
struct stat buf;
stat(file, &buf);
dict_size = buf.st_size;
LOGF << "Size of " << file << ": " << buf.st_size << " bytes\n";
}
for ( const char* const* word = words;
word < words + sizeof(words) / sizeof(*words);
++word ) {
if (x.find(*word) == x.end()) {
CHECK(w.find(*word) != w.end());
} else {
CHECK(w.find(*word) == w.end());
}
}
}
CHECK(counts.size() == x.size());
{
// verify that size() works correctly
int xcount = 0;
for ( typename ht::iterator it = x.begin(); it != x.end(); ++it ) {
++xcount;
}
CHECK(x.size() == xcount);
}
// Save the hashtable.
if (read_write) {
const string file_string = TmpFile(".hashtable_unittest_dicthash_str");
const char* file = file_string.c_str();
FILE *fp = fopen(file, "wb");
if ( fp == NULL ) {
// maybe we can't write to /tmp/. Try the current directory
file = ".hashtable_unittest_dicthash_str";
fp = fopen(file, "wb");
}
if ( fp == NULL ) {
LOGF << "Can't open " << file << " skipping hashtable save...\n";
} else {
x.write_metadata(fp); // this only writes meta-information
int write_count = 0;
for ( typename ht::iterator it = x.begin(); it != x.end(); ++it ) {
write_item(fp, *it);
++write_count;
}
LOGF << "Wrote " << write_count << " words to " << file << "\n";
fclose(fp);
struct stat buf;
stat(file, &buf);
LOGF << "Size of " << file << ": " << buf.st_size << " bytes\n";
LOGF << STL_NAMESPACE::setprecision(3)
<< "Hashtable overhead "
<< (buf.st_size - dict_size) * 100.0 / dict_size
<< "% ("
<< (buf.st_size - dict_size) * 8.0 / write_count
<< " bits/entry)\n";
x.clear();
// Load the hashtable
fp = fopen(file, "rb");
if ( fp == NULL ) {
LOGF << "Can't open " << file << " skipping hashtable reload...\n";
} else {
x.read_metadata(fp); // reads metainformation
LOGF << "Hashtable size: " << x.size() << "\n";
int count = 0;
for ( typename ht::iterator it = x.begin(); it != x.end(); ++it ) {
read_item(fp, &(*it));
++count;
}
LOGF << "Read " << count << " words from " << file << "\n";
fclose(fp);
unlink(file);
for ( const char* const* word = words;
word < words + sizeof(words) / sizeof(*words);
++word ) {
if (x.find(*word) == x.end()) {
CHECK(w.find(*word) != w.end());
} else {
CHECK(w.find(*word) == w.end());
}
}
}
}
}
// ensure that destruction is done properly in clear_no_resize()
if (!clear_no_resize(&w)) w.clear();
}
// The read_write parameters specifies whether the read/write tests
// should be performed. Note that densehashtable::write_metdata is not
// implemented, so we only do the read/write tests for the
// sparsehashtable varieties.
template<class ht, class htstr, class htint>
void test(bool read_write) {
test_int<htint>();
test_string<htstr>(read_write);
test_charptr<ht>(read_write);
}
// For data types with trivial copy-constructors and destructors, we
// should use an optimized routine for data-copying, that involves
// memmove. We test this by keeping count of how many times the
// copy-constructor is called; it should be much less with the
// optimized code.
class Memmove {
public:
Memmove(): i_(0) {}
explicit Memmove(int i): i_(i) {}
Memmove(const Memmove& that) {
this->i_ = that.i_;
num_copies_++;
}
int i_;
static int num_copies_;
};
int Memmove::num_copies_ = 0;
// This is what tells the hashtable code it can use memmove for this class:
_START_GOOGLE_NAMESPACE_
template<> struct has_trivial_copy<Memmove> : true_type { };
template<> struct has_trivial_destructor<Memmove> : true_type { };
_END_GOOGLE_NAMESPACE_
class NoMemmove {
public:
NoMemmove(): i_(0) {}
explicit NoMemmove(int i): i_(i) {}
NoMemmove(const NoMemmove& that) {
this->i_ = that.i_;
num_copies_++;
}
int i_;
static int num_copies_;
};
int NoMemmove::num_copies_ = 0;
void TestSimpleDataTypeOptimizations() {
{
sparse_hash_map<int, Memmove> memmove;
sparse_hash_map<int, NoMemmove> nomemmove;
Memmove::num_copies_ = 0; // reset
NoMemmove::num_copies_ = 0; // reset
for (int i = 10000; i > 0; i--) {
memmove[i] = Memmove(i);
}
for (int i = 10000; i > 0; i--) {
nomemmove[i] = NoMemmove(i);
}
LOGF << "sparse_hash_map copies for unoptimized/optimized cases: "
<< NoMemmove::num_copies_ << "/" << Memmove::num_copies_ << "\n";
CHECK(NoMemmove::num_copies_ > Memmove::num_copies_);
}
// dense_hash_map doesn't use this optimization, so no need to test it.
}
void TestShrinking() {
// We want to make sure that when we create a hashtable, and then
// add and delete one element, the size of the hashtable doesn't
// change.
{
sparse_hash_set<int> s;
s.set_deleted_key(0);
const int old_bucket_count = s.bucket_count();
s.insert(4);
s.erase(4);
s.insert(4);
s.erase(4);
CHECK_EQ(old_bucket_count, s.bucket_count());
}
{
dense_hash_set<int> s;
s.set_deleted_key(0);
s.set_empty_key(1);
const int old_bucket_count = s.bucket_count();
s.insert(4);
s.erase(4);
s.insert(4);
s.erase(4);
CHECK_EQ(old_bucket_count, s.bucket_count());
}
{
sparse_hash_set<int> s(2); // start small: only expects 2 items
CHECK_LT(s.bucket_count(), 32); // verify we actually do start small
s.set_deleted_key(0);
const int old_bucket_count = s.bucket_count();
s.insert(4);
s.erase(4);
s.insert(4);
s.erase(4);
CHECK_EQ(old_bucket_count, s.bucket_count());
}
{
dense_hash_set<int> s(2); // start small: only expects 2 items
CHECK_LT(s.bucket_count(), 32); // verify we actually do start small
s.set_deleted_key(0);
s.set_empty_key(1);
const int old_bucket_count = s.bucket_count();
s.insert(4);
s.erase(4);
s.insert(4);
s.erase(4);
CHECK_EQ(old_bucket_count, s.bucket_count());
}
}
class TestHashFcn : public SPARSEHASH_HASH<int> {
public:
explicit TestHashFcn(int i)
: id_(i) {
}
int id() const {
return id_;
}
private:
int id_;
};
class TestEqualTo : public equal_to<int> {
public:
explicit TestEqualTo(int i)
: id_(i) {
}
int id() const {
return id_;
}
private:
int id_;
};
// Test combining Hash and EqualTo function into 1 object
struct HashWithEqual {
int key_inc;
HashWithEqual() : key_inc(17) {}
explicit HashWithEqual(int i) : key_inc(i) {}
size_t operator()(const int& a) const { return a + key_inc; }
bool operator()(const int& a, const int& b) const { return a == b; }
};
// Here, NonHT is the non-hash version of HT: "map" to HT's "hash_map"
template<class HT, class NonHT>
void TestSparseConstructors() {
const TestHashFcn fcn(1);
const TestEqualTo eqt(2);
int alloc_count = 0;
const Alloc<int, int, 10000> alloc(&alloc_count);
{
const HT simple(0, fcn, eqt, alloc);
CHECK_EQ(fcn.id(), simple.hash_funct().id());
CHECK_EQ(eqt.id(), simple.key_eq().id());
CHECK(simple.get_allocator().is_custom_alloc());
}
{
const NonHT input;
const HT iterated(input.begin(), input.end(), 0, fcn, eqt, alloc);
CHECK_EQ(fcn.id(), iterated.hash_funct().id());
CHECK_EQ(eqt.id(), iterated.key_eq().id());
CHECK(iterated.get_allocator().is_custom_alloc());
}
// Now test each of the constructor types.
HT ht(0, fcn, eqt, alloc);
for (int i = 0; i < 1000; i++) {
insert(&ht, i * i);
}
CHECK_GT(alloc_count, 0);
alloc_count = 0;
HT ht_copy(ht);
CHECK(ht == ht_copy);
CHECK_GT(alloc_count, 0);
alloc_count = 0;
HT ht_equal(0, fcn, eqt, alloc);
ht_equal = ht;
CHECK(ht == ht_copy);
CHECK_GT(alloc_count, 0);
alloc_count = 0;
HT ht_iterator(ht.begin(), ht.end(), 0, fcn, eqt, alloc);
CHECK(ht == ht_iterator);
CHECK_GT(alloc_count, 0);
alloc_count = 0;
HT ht_size(ht.size(), fcn, eqt, alloc);
for (typename HT::const_iterator it = ht.begin(); it != ht.end(); ++it)
ht_size.insert(*it);
CHECK(ht == ht_size);
CHECK_GT(alloc_count, 0);
alloc_count = 0;
}
// Sadly, we need a separate version of this test because the iterator
// constructors require an extra arg in densehash-land.
template<class HT, class NonHT>
void TestDenseConstructors() {
const TestHashFcn fcn(1);
const TestEqualTo eqt(2);
int alloc_count;
const Alloc<int, int, 10000> alloc(&alloc_count);
{
const HT simple(0, fcn, eqt, alloc);
CHECK_EQ(fcn.id(), simple.hash_funct().id());
CHECK_EQ(eqt.id(), simple.key_eq().id());
CHECK(simple.get_allocator().is_custom_alloc());
}
{
const NonHT input;
const HT iterated(input.begin(), input.end(), -1, 0, fcn, eqt, alloc);
CHECK_EQ(fcn.id(), iterated.hash_funct().id());
CHECK_EQ(eqt.id(), iterated.key_eq().id());
CHECK(iterated.get_allocator().is_custom_alloc());
}
// Now test each of the constructor types.
HT ht(0, fcn, eqt, alloc);
ht.set_empty_key(-1);
for (int i = 0; i < 1000; i++) {
insert(&ht, i * i);
}
CHECK_GT(alloc_count, 0);
alloc_count = 0;
HT ht_copy(ht);
CHECK(ht == ht_copy);
CHECK_GT(alloc_count, 0);
alloc_count = 0;
HT ht_equal(0, fcn, eqt, alloc);
ht_equal = ht;
CHECK(ht == ht_copy);
CHECK_GT(alloc_count, 0);
alloc_count = 0;
HT ht_iterator(ht.begin(), ht.end(), ht.empty_key(), 0, fcn, eqt, alloc);
CHECK(ht == ht_iterator);
CHECK_GT(alloc_count, 0);
alloc_count = 0;
HT ht_size(ht.size(), fcn, eqt, alloc);
ht_size.set_empty_key(ht.empty_key());
for (typename HT::const_iterator it = ht.begin(); it != ht.end(); ++it)
ht_size.insert(*it);
CHECK(ht == ht_size);
CHECK_GT(alloc_count, 0);
alloc_count = 0;
}
static void TestCopyConstructor() {
{ // Copy an empty table with no empty key set.
dense_hash_map<int, string> table1;
dense_hash_map<int, string> table2(table1);
CHECK_EQ(32, table2.bucket_count()); // default number of buckets.
}
}
static void TestOperatorEquals() {
{
dense_hash_set<int> sa, sb;
sa.set_empty_key(-1);
sb.set_empty_key(-1);
CHECK(sa.empty_key() == -1);
sa.set_deleted_key(-2);
sb.set_deleted_key(-2);
CHECK(sa == sb);
sa.insert(1);
CHECK(sa != sb);
sa.insert(2);
CHECK(sa != sb);
sb.insert(2);
CHECK(sa != sb);
sb.insert(1);
CHECK(sa == sb);
sb.erase(1);
CHECK(sa != sb);
}
{
dense_hash_map<int, string> sa, sb;
sa.set_empty_key(-1);
sb.set_empty_key(-1);
CHECK(sa.empty_key() == -1);
sa.set_deleted_key(-2);
sb.set_deleted_key(-2);
CHECK(sa == sb);
sa.insert(make_pair(1, "a"));
CHECK(sa != sb);
sa.insert(make_pair(2, "b"));
CHECK(sa != sb);
sb.insert(make_pair(2, "b"));
CHECK(sa != sb);
sb.insert(make_pair(1, "a"));
CHECK(sa == sb);
sa[1] = "goodbye";
CHECK(sa != sb);
sb.erase(1);
CHECK(sa != sb);
}
{ // Copy table with a different empty key.
dense_hash_map<string, string, StrHash> table1;
table1.set_empty_key("key1");
CHECK(table1.empty_key() == "key1");
dense_hash_map<string, string, StrHash> table2;
table2.set_empty_key("key2");
table1.insert(make_pair("key", "value"));
table2.insert(make_pair("a", "b"));
table1 = table2;
CHECK_EQ("b", table1["a"]);
CHECK_EQ(1, table1.size());
}
{ // Assign to a map without an empty key.
dense_hash_map<string, string, StrHash> table1;
dense_hash_map<string, string, StrHash> table2;
table2.set_empty_key("key2");
CHECK(table2.empty_key() == "key2");
table2.insert(make_pair("key", "value"));
table1 = table2;
CHECK_EQ("value", table1["key"]);
}
{ // Copy a map without an empty key.
dense_hash_map<string, string, StrHash> table1;
dense_hash_map<string, string, StrHash> table2;
table1 = table2;
CHECK_EQ(0, table1.size());
table1.set_empty_key("key1");
CHECK(table1.empty_key() == "key1");
table1.insert(make_pair("key", "value"));
table1 = table2;
CHECK_EQ(0, table1.size());
table1.set_empty_key("key1");
table1.insert(make_pair("key", "value"));
CHECK_EQ("value", table1["key"]);
}
{
sparse_hash_map<string, string, StrHash> table1;
table1.set_deleted_key("key1");
table1.insert(make_pair("key", "value"));
sparse_hash_map<string, string, StrHash> table2;
table2.set_deleted_key("key");
table2 = table1;
CHECK_EQ(1, table2.size());
table2.erase("key");
CHECK(table2.empty());
}
}
// Test the interface for setting the resize parameters in a
// sparse_hash_set or dense_hash_set. If use_tr1_api is true,
// we use the newer tr1-inspired functions to set resize_parameters,
// rather than my old, home-grown API
template<class HS, bool USE_TR1_API>
static void TestResizingParameters() {
const int kSize = 16536;
// Check growing past various thresholds and then shrinking below
// them.
for (float grow_threshold = 0.2f;
grow_threshold <= 0.8f;
grow_threshold += 0.2f) {
HS hs;
hs.set_deleted_key(-1);
set_empty_key(&hs, -2);
if (USE_TR1_API) {
hs.max_load_factor(grow_threshold);
hs.min_load_factor(0.0);
} else {
hs.set_resizing_parameters(0.0, grow_threshold);
}
hs.resize(kSize);
size_t bucket_count = hs.bucket_count();
// Erase and insert an element to set consider_shrink = true,
// which should not cause a shrink because the threshold is 0.0.
insert(&hs, 1);
hs.erase(1);
for (int i = 0;; ++i) {
insert(&hs, i);
if (static_cast<float>(hs.size())/bucket_count < grow_threshold) {
CHECK(hs.bucket_count() == bucket_count);
} else {
CHECK(hs.bucket_count() > bucket_count);
break;
}
}
// Now set a shrink threshold 1% below the current size and remove
// items until the size falls below that.
const float shrink_threshold = static_cast<float>(hs.size()) /
hs.bucket_count() - 0.01f;
if (USE_TR1_API) {
hs.max_load_factor(1.0);
hs.min_load_factor(shrink_threshold);
} else {
hs.set_resizing_parameters(shrink_threshold, 1.0);
}
bucket_count = hs.bucket_count();
for (int i = 0;; ++i) {
hs.erase(i);
// A resize is only triggered by an insert, so add and remove a
// value every iteration to trigger the shrink as soon as the
// threshold is passed.
hs.erase(i+1);
insert(&hs, i+1);
if (static_cast<float>(hs.size())/bucket_count > shrink_threshold) {
CHECK(hs.bucket_count() == bucket_count);
} else {
CHECK(hs.bucket_count() < bucket_count);
break;
}
}
}
}
// This tests for a problem we had where we could repeatedly "resize"
// a hashtable to the same size it was before, on every insert.
template<class HT>
static void TestHashtableResizing() {
HT ht;
ht.set_deleted_key(-1);
set_empty_key(&ht, -2);
const int kSize = 1<<10; // Pick any power of 2
const float kResize = 0.8f; // anything between 0.5 and 1 is fine.
const int kThreshold = static_cast<int>(kSize * kResize - 1);
ht.set_resizing_parameters(0, kResize);
// Get right up to the resizing threshold.
for (int i = 0; i <= kThreshold; i++) {
ht.insert(i);
}
// The bucket count should equal kSize.
CHECK_EQ(ht.bucket_count(), kSize);
// Now start doing erase+insert pairs. This should cause us to
// copy the hashtable at most once.
const int pre_copies = ht.num_table_copies();
for (int i = 0; i < kSize; i++) {
if (i % 100 == 0)
LOGF << "erase/insert: " << i
<< " buckets: " << ht.bucket_count()
<< " size: " << ht.size() << "\n";
ht.erase(kThreshold);
ht.insert(kThreshold);
}
CHECK_LT(ht.num_table_copies(), pre_copies + 2);
// Now create a hashtable where we go right to the threshold, then
// delete everything and do one insert. Even though our hashtable
// is now tiny, we should still have at least kSize buckets, because
// our shrink threshhold is 0.
HT ht2;
ht2.set_deleted_key(-1);
set_empty_key(&ht2, -2);
ht2.set_resizing_parameters(0, kResize);
CHECK_LT(ht2.bucket_count(), kSize);
for (int i = 0; i <= kThreshold; i++) {
ht2.insert(i);
}
CHECK_EQ(ht2.bucket_count(), kSize);
for (int i = 0; i <= kThreshold; i++) {
ht2.erase(i);
CHECK_EQ(ht2.bucket_count(), kSize);
}
ht2.insert(kThreshold+1);
CHECK_GE(ht2.bucket_count(), kSize);
}
// Tests the some of the tr1-inspired API features.
template<class HS>
static void TestTR1API() {
HS hs;
hs.set_deleted_key(-1);
set_empty_key(&hs, -2);
typename HS::size_type expected_bucknum = hs.bucket(1);
insert(&hs, 1);
typename HS::size_type bucknum = hs.bucket(1);
CHECK(expected_bucknum == bucknum);
typename HS::const_local_iterator b = hs.begin(bucknum);
typename HS::const_local_iterator e = hs.end(bucknum);
CHECK(b != e);
CHECK(getintkey(*b) == 1);
b++;
CHECK(b == e);
hs.erase(1);
bucknum = hs.bucket(1);
CHECK(expected_bucknum == bucknum);
b = hs.begin(bucknum);
e = hs.end(bucknum);
CHECK(b == e);
// For very small sets, the min-bucket-size gets in the way, so
// let's make our hash_set bigger.
for (int i = 0; i < 10000; i++)
insert(&hs, i);
float f = hs.load_factor();
CHECK(f >= hs.min_load_factor());
CHECK(f <= hs.max_load_factor());
}
// People can do better than to have a hash_map of hash_maps, but we
// should still support it. HT should map from string to another
// hashtable (map or set) or some kind. Mostly we're just checking
// for memory leaks or crashes here.
template<class HT>
static void TestNestedHashtable() {
HT ht;
set_empty_key(&ht, string());
ht["hi"]; // creates a sub-ht with default values
ht["lo"]; // creates a sub-ht with default values
HT ht2 = ht;
}
class MemUsingKey {
public:
// TODO(csilvers): nix this when requirement for zero-arg keys goes away
MemUsingKey() : data_(new int) {
net_allocations_++;
}
MemUsingKey(int i) : data_(new int(i)) {
net_allocations_++;
}
MemUsingKey(const MemUsingKey& that) : data_(new int(*that.data_)) {
net_allocations_++;
}
~MemUsingKey() {
delete data_;
net_allocations_--;
CHECK_GE(net_allocations_, 0);
}
MemUsingKey& operator=(const MemUsingKey& that) {
delete data_;
data_ = new int(*that.data_);
return *this;
}
struct Hash {
size_t operator()(const MemUsingKey& x) const { return *x.data_; }
};
struct Equal {
bool operator()(const MemUsingKey& x, const MemUsingKey& y) const {
return *x.data_ == *y.data_;
}
};
static int net_allocations() { return net_allocations_; }
private:
int* data_;
static int net_allocations_;
};
class MemUsingValue {
public:
// This also tests that value does not need to have a zero-arg constructor
explicit MemUsingValue(const char* data) : data_(NULL) {
Strcpy(data);
}
MemUsingValue(const MemUsingValue& that) : data_(NULL) {
Strcpy(that.data_);
}
~MemUsingValue() {
if (data_) {
free(data_);
net_allocations_--;
CHECK_GE(net_allocations_, 0);
}
}
MemUsingValue& operator=(const MemUsingValue& that) {
if (data_) {
free(data_);
net_allocations_--;
CHECK_GE(net_allocations_, 0);
}
Strcpy(that.data_);
return *this;
}
static int net_allocations() { return net_allocations_; }
private:
void Strcpy(const char* data) {
if (data) {
data_ = (char*)malloc(strlen(data) + 1); // use malloc this time
strcpy(data_, data); // strdup isn't so portable
net_allocations_++;
} else {
data_ = NULL;
}
}
char* data_;
static int net_allocations_;
};
// TODO(csilvers): nix this when set_empty_key doesn't require zero-arg value
class MemUsingValueWithZeroArgConstructor : public MemUsingValue {
public:
MemUsingValueWithZeroArgConstructor(const char* data=NULL)
: MemUsingValue(data) { }
MemUsingValueWithZeroArgConstructor(
const MemUsingValueWithZeroArgConstructor& that)
: MemUsingValue(that) { }
MemUsingValueWithZeroArgConstructor& operator=(
const MemUsingValueWithZeroArgConstructor& that) {
*static_cast<MemUsingValue*>(this)
= *static_cast<const MemUsingValue*>(&that);
return *this;
}
};
int MemUsingKey::net_allocations_ = 0;
int MemUsingValue::net_allocations_ = 0;
void TestMemoryManagement() {
MemUsingKey deleted_key(-1);
MemUsingKey empty_key(-2);
{
// TODO(csilvers): fix sparsetable to allow missing zero-arg value ctor
sparse_hash_map<MemUsingKey, MemUsingValueWithZeroArgConstructor,
MemUsingKey::Hash, MemUsingKey::Equal> ht;
ht.set_deleted_key(deleted_key);
for (int i = 0; i < 1000; i++) {
ht.insert(pair<MemUsingKey,MemUsingValueWithZeroArgConstructor>(
i, MemUsingValueWithZeroArgConstructor("hello!")));
ht.erase(i);
CHECK_EQ(0, MemUsingValue::net_allocations());
}
}
// Various copies of deleted_key will be hanging around until the
// hashtable is destroyed, so it's only safe to do this test now.
CHECK_EQ(2, MemUsingKey::net_allocations()); // for deleted+empty_key
{
dense_hash_map<MemUsingKey, MemUsingValueWithZeroArgConstructor,
MemUsingKey::Hash, MemUsingKey::Equal> ht;
ht.set_empty_key(empty_key);
ht.set_deleted_key(deleted_key);
for (int i = 0; i < 1000; i++) {
// As long as we have a zero-arg constructor for the value anyway,
// use operator[] rather than the more verbose insert().
ht[i] = MemUsingValueWithZeroArgConstructor("hello!");
ht.erase(i);
CHECK_EQ(0, MemUsingValue::net_allocations());
}
}
CHECK_EQ(2, MemUsingKey::net_allocations()); // for deleted+empty_key
}
void TestHugeResize() {
try {
dense_hash_map<int, int> ht;
ht.resize(static_cast<size_t>(-1));
LOGF << "dense_hash_map resize should have failed\n";
abort();
} catch (const std::length_error&) {
// Good, the resize failed.
}
try {
sparse_hash_map<int, int> ht;
ht.resize(static_cast<size_t>(-1));
LOGF << "sparse_hash_map resize should have failed\n";
abort();
} catch (const std::length_error&) {
// Good, the resize failed.
}
static const int kMax = 256;
vector<int> test_data(kMax);
for (int i = 0; i < kMax; ++i) {
test_data[i] = i+1000;
}
sparse_hash_set<int, SPARSEHASH_HASH<int>, equal_to<int>, Alloc<int, uint8, 10> > shs;
dense_hash_set<int, SPARSEHASH_HASH<int>, equal_to<int>, Alloc<int, uint8, 10> > dhs;
dhs.set_empty_key(-1);
// Test we are using the correct allocator
CHECK(shs.get_allocator().is_custom_alloc());
CHECK(dhs.get_allocator().is_custom_alloc());
// Test size_type overflow in insert(it, it)
try {
dhs.insert(test_data.begin(), test_data.end());
LOGF << "dense_hash_map insert(it,it) should have failed\n";
abort();
} catch (const std::length_error&) {
}
try {
shs.insert(test_data.begin(), test_data.end());
LOGF << "sparse_hash_map insert(it,it) should have failed\n";
abort();
} catch (const std::length_error&) {
}
// Test max_size overflow
try {
dhs.insert(test_data.begin(), test_data.begin() + 11);
LOGF << "dense_hash_map max_size check should have failed\n";
abort();
} catch (const std::length_error&) {
}
try {
shs.insert(test_data.begin(), test_data.begin() + 11);
LOGF << "sparse_hash_map max_size check should have failed\n";
abort();
} catch (const std::length_error&) {
}
// Test min-buckets overflow, when we want to resize too close to size_type
try {
dhs.resize(250);
} catch (const std::length_error&) {
}
try {
shs.resize(250);
} catch (const std::length_error&) {
}
// Test size_type overflow in resize_delta()
sparse_hash_set<int, SPARSEHASH_HASH<int>, equal_to<int>, Alloc<int, uint8, 1000> > shs2;
dense_hash_set<int, SPARSEHASH_HASH<int>, equal_to<int>, Alloc<int, uint8, 1000> > dhs2;
dhs2.set_empty_key(-1);
for (int i = 0; i < 9; i++) {
dhs2.insert(i);
shs2.insert(i);
}
try {
dhs2.insert(test_data.begin(), test_data.begin() + 250);
LOGF << "dense_hash_map insert-check should have failed (9+250 > 256)\n";
abort();
} catch (const std::length_error&) {
}
try {
shs2.insert(test_data.begin(), test_data.begin() + 250);
LOGF << "sparse_hash_map insert-check should have failed (9+250 > 256)\n";
abort();
} catch (const std::length_error&) {
}
}
class DataCounter {
public:
DataCounter() {
++ctors_;
}
static int ctors() { int r = ctors_; ctors_ = 0; return r; }
private:
static int ctors_;
};
int DataCounter::ctors_ = 0;
class HashCounter {
public:
size_t operator()(int x) const {
++hashes_;
return x;
}
static int hashes() { int r = hashes_; hashes_ = 0; return r; }
private:
static int hashes_;
};
int HashCounter::hashes_ = 0;
template<class HT>
void TestHashCounts() {
HT ht;
set_empty_key(&ht, -1);
const int kIter = 2000; // enough for some resizing to happen
ht.clear();
for (int i = 0; i < kIter; i++)
insert(&ht, i);
const int insert_hashes = HashCounter::hashes();
int actual_ctors = DataCounter::ctors();
// dense_hash_* has an extra ctor during resizes, for emptykey,
// so allow for a log_2(kIter) slack, which we estimate as .01*kIter.
if (actual_ctors != 0) // will be 0 for hash_sets, >0 for maps.
CHECK_LT(kIter, actual_ctors + kIter/100);
// Make sure that do-nothing inserts don't result in extra hashes or
// ctors. insert() itself (in this test file) does one ctor call;
// that should be all we see.
for (int i = 0; i < kIter; i++)
insert(&ht, i);
CHECK_EQ(kIter, HashCounter::hashes());
actual_ctors = DataCounter::ctors();
if (actual_ctors != 0) // will be 0 for hash_sets, >0 for maps.
CHECK_EQ(kIter, actual_ctors); // no resizing is happening here.
// Make sure we never do any extraneous hashes in find() calls.
for (int i = 0; i < kIter; i++)
(void)ht.find(i);
CHECK_EQ(kIter, HashCounter::hashes());
CHECK_EQ(0, DataCounter::ctors());
// Make sure that whether we use insert() or operator[], we hash the
// same. Actually that's not quite true: we do an extra hash per
// hashtable-resize with operator[] (we could avoid this, but I
// don't think it's worth the work), so allow for a log_2(kIter)
// slack, which we estimate as .01*kIter.
HT ht2;
set_empty_key(&ht2, -1);
for (int i = 0; i < kIter; i++)
bracket_insert(&ht2, i);
CHECK_LT(HashCounter::hashes(), insert_hashes + kIter/100);
actual_ctors = DataCounter::ctors();
// We expect two ctor calls per insert, one by operator[] when it
// creates a new object that wasn't in the hashtable before, and one
// by bracket_insert() itself.
if (actual_ctors != 0) // will be 0 for hash_sets, >0 for maps.
CHECK_LT(kIter*2, actual_ctors + kIter/100);
// Like insert(), bracket_insert() itself does one ctor call. But
// the hashtable implementation shouldn't do any, since these
// objects already exist.
for (int i = 0; i < kIter; i++)
bracket_insert(&ht, i);
CHECK_EQ(kIter, HashCounter::hashes());
actual_ctors = DataCounter::ctors();
if (actual_ctors != 0) // will be 0 for hash_sets, >0 for maps.
CHECK_EQ(kIter, actual_ctors);
}
template<class Key>
struct SetKey {
void operator()(Key* key, const Key& new_key) const {
*key = new_key;
}
};
template<class Value>
struct Identity {
Value& operator()(Value& v) const { return v; }
const Value& operator()(const Value& v) const { return v; }
};
int main(int argc, char **argv) {
typedef sparse_hash_set<int, SPARSEHASH_HASH<int>,equal_to<int>, Alloc<int,int,8> > Shs;
typedef dense_hash_set<int, SPARSEHASH_HASH<int>,equal_to<int>, Alloc<int,int,8> > Dhs;
Shs shs;
Dhs dhs;
LOGF << "<sizeof, max_size>: sparse_hash_set<int>=(" << sizeof(Shs)
<< "," << static_cast<size_t>(shs.max_size())
<< "); dense_hash_set<int>=(" << sizeof(Dhs)
<< "," << static_cast<size_t>(dhs.max_size()) << ")";
TestCopyConstructor();
TestOperatorEquals();
// SPARSEHASH_HASH is defined in sparseconfig.h. It resolves to the
// system hash function (usually, but not always, named "hash") on
// whatever system we're on.
// First try with the low-level hashtable interface
LOGF << "\n\nTEST WITH DENSE_HASHTABLE\n\n";
test<dense_hashtable<char *, char *, CharStarHash,
Identity<char *>, SetKey<char *>, strcmp_fnc,
libc_allocator_with_realloc<char *> >,
dense_hashtable<string, string, StrHash,
Identity<string>, SetKey<string>, equal_to<string>,
libc_allocator_with_realloc<string> >,
dense_hashtable<int, int, SPARSEHASH_HASH<int>,
Identity<int>, SetKey<int>, equal_to<int>,
libc_allocator_with_realloc<int> > >(false);
test<dense_hashtable<char *, char *, CharStarHash,
Identity<char *>, SetKey<char *>, strcmp_fnc,
allocator<char *> >,
dense_hashtable<string, string, StrHash,
Identity<string>, SetKey<string>, equal_to<string>,
allocator<string> >,
dense_hashtable<int, int, SPARSEHASH_HASH<int>,
Identity<int>, SetKey<int>, equal_to<int>,
allocator<int> > >(
false);
// Now try with hash_set, which should be equivalent
LOGF << "\n\nTEST WITH DENSE_HASH_SET\n\n";
test<dense_hash_set<char *, CharStarHash, strcmp_fnc>,
dense_hash_set<string, StrHash>,
dense_hash_set<int> >(false);
test<dense_hash_set<char *, CharStarHash, strcmp_fnc, allocator<char *> >,
dense_hash_set<string, StrHash, equal_to<string>, allocator<string> >,
dense_hash_set<int, SPARSEHASH_HASH<int>, equal_to<int>, allocator<int> > >(false);
TestResizingParameters<dense_hash_set<int>, true>(); // use tr1 API
TestResizingParameters<dense_hash_set<int>, false>(); // use older API
TestResizingParameters<dense_hash_set<int, SPARSEHASH_HASH<int>, equal_to<int>,
allocator<int> >, true>(); // use tr1 API
TestResizingParameters<dense_hash_set<int, SPARSEHASH_HASH<int>, equal_to<int>,
allocator<int> >, false>(); // use older API
TestHashtableResizing<dense_hashtable<int, int, SPARSEHASH_HASH<int>,
Identity<int>, SetKey<int>, equal_to<int>,
libc_allocator_with_realloc<int> > >();
TestHashtableResizing<sparse_hashtable<int, int, SPARSEHASH_HASH<int>,
Identity<int>, SetKey<int>, equal_to<int>,
allocator<int> > >();
// Now try with hash_map, which differs only in insert()
LOGF << "\n\nTEST WITH DENSE_HASH_MAP\n\n";
test<dense_hash_map<char *, int, CharStarHash, strcmp_fnc>,
dense_hash_map<string, int, StrHash>,
dense_hash_map<int, int> >(false);
test<dense_hash_map<char *, int, CharStarHash, strcmp_fnc,
allocator<char *> >,
dense_hash_map<string, int, StrHash, equal_to<string>,
allocator<string> >,
dense_hash_map<int, int, SPARSEHASH_HASH<int>, equal_to<int>,
allocator<int> > >(false);
// First try with the low-level hashtable interface
LOGF << "\n\nTEST WITH SPARSE_HASHTABLE\n\n";
test<sparse_hashtable<char *, char *, CharStarHash,
Identity<char *>, SetKey<char *>, strcmp_fnc,
libc_allocator_with_realloc<char *> >,
sparse_hashtable<string, string, StrHash,
Identity<string>, SetKey<string>, equal_to<string>,
libc_allocator_with_realloc<string> >,
sparse_hashtable<int, int, SPARSEHASH_HASH<int>,
Identity<int>, SetKey<int>, equal_to<int>,
libc_allocator_with_realloc<int> > >(true);
test<sparse_hashtable<char *, char *, CharStarHash,
Identity<char *>, SetKey<char *>, strcmp_fnc,
allocator<char *> >,
sparse_hashtable<string, string, StrHash,
Identity<string>, SetKey<string>, equal_to<string>,
allocator<string> >,
sparse_hashtable<int, int, SPARSEHASH_HASH<int>,
Identity<int>, SetKey<int>, equal_to<int>,
allocator<int> > >(true);
// Now try with hash_set, which should be equivalent
LOGF << "\n\nTEST WITH SPARSE_HASH_SET\n\n";
test<sparse_hash_set<char *, CharStarHash, strcmp_fnc>,
sparse_hash_set<string, StrHash>,
sparse_hash_set<int> >(true);
test<sparse_hash_set<char *, CharStarHash, strcmp_fnc, allocator<int> >,
sparse_hash_set<string, StrHash, equal_to<string>, allocator<int> >,
sparse_hash_set<int, SPARSEHASH_HASH<int>, equal_to<int>, allocator<int> > >(true);
TestResizingParameters<sparse_hash_set<int>, true>();
TestResizingParameters<sparse_hash_set<int>, false>();
TestResizingParameters<sparse_hash_set<int, SPARSEHASH_HASH<int>, equal_to<int>,
allocator<int> >, true>();
TestResizingParameters<sparse_hash_set<int, SPARSEHASH_HASH<int>, equal_to<int>,
allocator<int> >, false>();
// Now try with hash_map, which differs only in insert()
LOGF << "\n\nTEST WITH SPARSE_HASH_MAP\n\n";
test<sparse_hash_map<char *, int, CharStarHash, strcmp_fnc>,
sparse_hash_map<string, int, StrHash>,
sparse_hash_map<int, int> >(true);
test<sparse_hash_map<char *, int, CharStarHash, strcmp_fnc,
allocator<char *> >,
sparse_hash_map<string, int, StrHash, equal_to<string>,
allocator<string> >,
sparse_hash_map<int, int, SPARSEHASH_HASH<int>, equal_to<int>,
allocator<int> > >(true);
// Test that we use the optimized routines for simple data types
LOGF << "\n\nTesting simple-data-type optimizations\n";
TestSimpleDataTypeOptimizations();
// Test shrinking to very small sizes
LOGF << "\n\nTesting shrinking behavior\n";
TestShrinking();
LOGF << "\n\nTesting constructors, hashers, and key_equals\n";
TestSparseConstructors< sparse_hash_map<int, int, TestHashFcn, TestEqualTo,
Alloc<int,int,10000> >,
map<int, int> >();
TestSparseConstructors< sparse_hash_set<int, TestHashFcn, TestEqualTo,
Alloc<int,int,10000> >,
set<int, int> >();
TestDenseConstructors< dense_hash_map<int, int, TestHashFcn, TestEqualTo,
Alloc<int,int,10000> >,
map<int, int> >();
TestDenseConstructors< dense_hash_set<int, TestHashFcn, TestEqualTo,
Alloc<int,int,10000> >,
set<int, int> >();
LOGF << "\n\nTesting tr1 API\n";
TestTR1API<sparse_hash_map<int, int> >();
TestTR1API<dense_hash_map<int, int> >();
TestTR1API<sparse_hash_set<int> >();
TestTR1API<dense_hash_set<int> >();
TestTR1API<dense_hash_map<int, int, HashWithEqual, HashWithEqual> >();
TestTR1API<sparse_hash_map<int, int, HashWithEqual, HashWithEqual> >();
TestTR1API<dense_hash_set<int, HashWithEqual, HashWithEqual> >();
TestTR1API<sparse_hash_set<int, HashWithEqual, HashWithEqual> >();
LOGF << "\n\nTesting nested hashtables\n";
TestNestedHashtable<sparse_hash_map<string, sparse_hash_map<string, int> > >();
TestNestedHashtable<sparse_hash_map<string, sparse_hash_set<string> > >();
TestNestedHashtable<dense_hash_map<string, DenseStringMap<int> > >();
TestNestedHashtable<dense_hash_map<string, DenseStringSet> >();
// Test memory management when the keys and values are non-trivial
LOGF << "\n\nTesting memory management\n";
TestMemoryManagement();
TestHugeResize();
// Make sure we don't hash more than we need to
LOGF << "\n\nTesting hash counts\n";
TestHashCounts<sparse_hash_map<int, DataCounter, HashCounter> >();
TestHashCounts<sparse_hash_set<int, HashCounter> >();
TestHashCounts<dense_hash_map<int, DataCounter, HashCounter> >();
TestHashCounts<dense_hash_set<int, HashCounter> >();
LOGF << "\nAll tests pass.\n";
return 0;
}
| 32.710247
| 91
| 0.621939
|
PelionIoT
|
1aeb56dbe4e30c69fbc1793cc1cc979b07f51758
| 3,955
|
cpp
|
C++
|
base/pbr/VulkanObjModel.cpp
|
wessles/vkmerc
|
cb087f425cdbc0b204298833474cf62874505388
|
[
"Unlicense"
] | 6
|
2020-10-09T02:48:54.000Z
|
2021-07-30T06:31:20.000Z
|
base/pbr/VulkanObjModel.cpp
|
wessles/vkmerc
|
cb087f425cdbc0b204298833474cf62874505388
|
[
"Unlicense"
] | null | null | null |
base/pbr/VulkanObjModel.cpp
|
wessles/vkmerc
|
cb087f425cdbc0b204298833474cf62874505388
|
[
"Unlicense"
] | null | null | null |
#include "VulkanObjModel.h"
#include <unordered_map>
#include <filesystem>
#include <iostream>
#include <glm/glm.hpp>
#include <glm/gtx/string_cast.hpp>
#define TINYOBJLOADER_IMPLEMENTATION
#include <tiny_obj_loader.h>
#include "../VulkanMesh.h"
#include "../scene/Scene.h"
#include "PbrMaterial.h"
static std::string GetBaseDir(const std::string& filepath) {
if (filepath.find_last_of("/\\") != std::string::npos)
return filepath.substr(0, filepath.find_last_of("/\\"));
return "";
}
namespace vku {
VulkanObjModel::VulkanObjModel(const std::string& filename, Scene* scene, Pass* pass, std::map<std::string, std::string> macros) {
VulkanMeshData meshData{};
std::string base_dir = GetBaseDir(filename);
if (base_dir.empty()) {
base_dir = ".";
}
#ifdef _WIN32
base_dir += "\\";
#else
base_dir += "/";
#endif
tinyobj::attrib_t attrib;
std::vector<tinyobj::shape_t> shapes;
std::vector<tinyobj::material_t> materials;
std::string warn, err;
if (!tinyobj::LoadObj(&attrib, &shapes, &materials, &warn, &err, filename.c_str(), base_dir.c_str())) {
throw std::runtime_error(warn + err);
}
if (warn.size() + err.size() > 0) {
std::cout << "OBJ warning: " << (warn + err) << std::endl;
}
// load mesh data
std::unordered_map<Vertex, uint32_t> uniqueVertices{};
for (const auto& shape : shapes) {
for (const auto& index : shape.mesh.indices) {
Vertex vertex{};
vertex.pos = {
attrib.vertices[3 * index.vertex_index + 0],
attrib.vertices[3 * index.vertex_index + 1],
attrib.vertices[3 * index.vertex_index + 2]
};
// calculate bounding box
min.x = std::min(min.x, vertex.pos.x);
min.y = std::min(min.y, vertex.pos.y);
min.z = std::min(min.z, vertex.pos.z);
max.x = std::max(max.x, vertex.pos.x);
max.y = std::max(max.y, vertex.pos.y);
max.z = std::max(max.z, vertex.pos.z);
vertex.normal = {
attrib.normals[3 * index.normal_index + 0],
attrib.normals[3 * index.normal_index + 1],
attrib.normals[3 * index.normal_index + 2],
};
vertex.texCoord = {
attrib.texcoords[2 * index.texcoord_index + 0],
1.0f - attrib.texcoords[2 * index.texcoord_index + 1]
};
vertex.color = { 1.0f, 1.0f, 1.0f };
if (uniqueVertices.count(vertex) == 0) {
uniqueVertices[vertex] = static_cast<uint32_t>(meshData.vertices.size());
meshData.vertices.push_back(vertex);
}
meshData.indices.push_back(uniqueVertices[vertex]);
}
}
aabb = glm::translate(glm::mat4(1.0f), min) * glm::scale(glm::mat4(1.0f), max - min);
this->meshBuf = new VulkanMeshBuffer(scene->device, meshData);
// load material, based on default Blender BSDF .mtl export
if (materials.size() > 0) {
tinyobj::material_t mat = materials[0];
glm::vec4 albedo = glm::vec4(static_cast<float>(mat.diffuse[0]), static_cast<float>(mat.diffuse[1]), static_cast<float>(mat.diffuse[2]), 1.0f);
glm::vec4 emission = glm::vec4(static_cast<float>(mat.emission[0]), static_cast<float>(mat.emission[1]), static_cast<float>(mat.emission[2]), 1.0f);
float metallic = mat.specular[0];
float roughness = 1.0f - (static_cast<float>(mat.shininess) / 1000.0f);
PbrUniform uniform{};
uniform.albedo = albedo;
uniform.emissive = emission;
uniform.metallic = metallic;
uniform.roughness = roughness;
this->mat = new TexturelessPbrMaterial(uniform, scene, pass, macros);
}
}
VulkanObjModel::~VulkanObjModel() {
delete meshBuf;
delete mat;
}
void VulkanObjModel::render(VkCommandBuffer cmdBuf, uint32_t swapIdx, bool noMaterial) {
if (!noMaterial) {
mat->mat->bind(cmdBuf);
mat->matInstance->bind(cmdBuf, swapIdx);
}
vkCmdPushConstants(cmdBuf, mat->mat->pipelineLayout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(glm::mat4), &this->localTransform);
meshBuf->draw(cmdBuf);
}
glm::mat4 VulkanObjModel::getAABBTransform()
{
return localTransform * aabb;
}
}
| 29.736842
| 159
| 0.668015
|
wessles
|
1aec5d14b869793dd0ebb8bd7d89960e250e6ada
| 2,321
|
cc
|
C++
|
depends/dbcommon/test/unit/common/test-tuple-batch-store.cc
|
YangHao666666/hawq
|
10cff8350f1ba806c6fec64eb67e0e6f6f24786c
|
[
"Artistic-1.0-Perl",
"ISC",
"bzip2-1.0.5",
"TCL",
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"MIT",
"PostgreSQL",
"BSD-3-Clause"
] | 1
|
2020-05-11T01:39:13.000Z
|
2020-05-11T01:39:13.000Z
|
depends/dbcommon/test/unit/common/test-tuple-batch-store.cc
|
YangHao666666/hawq
|
10cff8350f1ba806c6fec64eb67e0e6f6f24786c
|
[
"Artistic-1.0-Perl",
"ISC",
"bzip2-1.0.5",
"TCL",
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"MIT",
"PostgreSQL",
"BSD-3-Clause"
] | 1
|
2021-03-01T02:57:26.000Z
|
2021-03-01T02:57:26.000Z
|
depends/dbcommon/test/unit/common/test-tuple-batch-store.cc
|
YangHao666666/hawq
|
10cff8350f1ba806c6fec64eb67e0e6f6f24786c
|
[
"Artistic-1.0-Perl",
"ISC",
"bzip2-1.0.5",
"TCL",
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"MIT",
"PostgreSQL",
"BSD-3-Clause"
] | 1
|
2020-05-03T07:29:21.000Z
|
2020-05-03T07:29:21.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 "dbcommon/common/tuple-batch-store.h"
#include "dbcommon/testutil/tuple-batch-utils.h"
#include "dbcommon/utils/global.h"
#include "gtest/gtest.h"
namespace dbcommon {
TEST(TestTupleBatchStore, Test) {
auto filesystem(FSManager.get("file://localhost"));
TupleBatchUtility tbu;
auto desc = tbu.generateTupleDesc(
"schema: boolean int8 int16 int32 int64 float double "
"bpchar bpchar(10) varchar varchar(5) string binary timestamp "
"time date");
auto tb0 = tbu.generateTupleBatchRandom(*desc, 0, 20, true, false);
auto tb1 = tbu.generateTupleBatchRandom(*desc, 0, 233, true, true);
auto tb2 = tbu.generateTupleBatchRandom(*desc, 0, 666, false, true);
auto tb3 = tbu.generateTupleBatchRandom(*desc, 0, 555, false, false);
std::string filename = "/tmp/TestTupleBatchStore";
NTupleBatchStore tbs(filesystem, filename, NTupleBatchStore::Mode::OUTPUT);
tbs.PutIntoNTupleBatchStore(tb0->clone());
tbs.PutIntoNTupleBatchStore(tb1->clone());
tbs.PutIntoNTupleBatchStore(tb2->clone());
tbs.PutIntoNTupleBatchStore(tb3->clone());
tbs.writeEOF();
NTupleBatchStore tbsLoad(filesystem, filename, NTupleBatchStore::Mode::INPUT);
EXPECT_EQ(tb0->toString(), tbsLoad.GetFromNTupleBatchStore()->toString());
EXPECT_EQ(tb1->toString(), tbsLoad.GetFromNTupleBatchStore()->toString());
EXPECT_EQ(tb2->toString(), tbsLoad.GetFromNTupleBatchStore()->toString());
EXPECT_EQ(tb3->toString(), tbsLoad.GetFromNTupleBatchStore()->toString());
}
} // namespace dbcommon
| 41.446429
| 80
| 0.744076
|
YangHao666666
|
8c1d6f83dd2669c716d71f751abe3b49418da6ad
| 3,375
|
cpp
|
C++
|
vector.cpp
|
csiro-robotics/Morphogenesis
|
4d390609f941a58f09529371d185a344573de35f
|
[
"BSD-3-Clause"
] | null | null | null |
vector.cpp
|
csiro-robotics/Morphogenesis
|
4d390609f941a58f09529371d185a344573de35f
|
[
"BSD-3-Clause"
] | null | null | null |
vector.cpp
|
csiro-robotics/Morphogenesis
|
4d390609f941a58f09529371d185a344573de35f
|
[
"BSD-3-Clause"
] | null | null | null |
#include "vector.h"
#include "matrix.h"
#define VTYPE float
Vector3DF &Vector3DF::operator*= (const MatrixF &op)
{
double *m = op.GetDataF ();
float xa, ya, za;
xa = x * float(*m++); ya = x * float(*m++); za = x * float(*m++); m++;
xa += y * float(*m++); ya += y * float(*m++); za += y * float(*m++); m++;
xa += z * float(*m++); ya += z * float(*m++); za += z * float(*m++); m++;
xa += float(*m++); ya += float(*m++); za += float(*m++);
x = xa; y = ya; z = za;
return *this;
}
// p' = Mp
Vector3DF &Vector3DF::operator*= (const Matrix4F &op)
{
float xa, ya, za;
xa = x * op.data[0] + y * op.data[4] + z * op.data[8] + op.data[12];
ya = x * op.data[1] + y * op.data[5] + z * op.data[9] + op.data[13];
za = x * op.data[2] + y * op.data[6] + z * op.data[10] + op.data[14];
x = xa; y = ya; z = za;
return *this;
}
Vector3DF& Vector3DF::Clamp (float a, float b)
{
x = (x<a) ? a : ((x>b) ? b : x);
y = (y<a) ? a : ((y>b) ? b : y);
z = (z<a) ? a : ((z>b) ? b : z);
return *this;
}
#define min3(a,b,c) ( (a<b) ? ((a<c) ? a : c) : ((b<c) ? b : c) )
#define max3(a,b,c) ( (a>b) ? ((a>c) ? a : c) : ((b>c) ? b : c) )
Vector3DF Vector3DF::RGBtoHSV ()
{
float h,s,v;
float minv, maxv;
int i;
float f;
minv = min3(x, y, z);
maxv = max3(x, y, z);
if (minv==maxv) {
v = (float) maxv;
h = 0.0;
s = 0.0;
} else {
v = (float) maxv;
s = (maxv - minv) / maxv;
f = (x == minv) ? y - z : ((y == minv) ? z - x : x - y);
i = (x == minv) ? 3 : ((y == minv) ? 5 : 1);
h = (i - f / (maxv - minv) ) / 6.0f;
}
return Vector3DF(h,s,v);
}
Vector3DF Vector3DF::HSVtoRGB ()
{
double m, n, f;
int i = floor ( x*6.0 );
f = x*6.0 - i;
if ( i % 2 == 0 ) f = 1.0 - f;
m = z * (1.0 - y );
n = z * (1.0 - y * f );
switch ( i ) {
case 6:
case 0: return Vector3DF( z, n, m ); break;
case 1: return Vector3DF( n, z, m ); break;
case 2: return Vector3DF( m, z, n ); break;
case 3: return Vector3DF( m, n, z ); break;
case 4: return Vector3DF( n, m, z ); break;
case 5: return Vector3DF( z, m, n ); break;
};
return Vector3DF(1,1,1);
}
Vector4DF &Vector4DF::operator*= (const MatrixF &op)
{
double *m = op.GetDataF ();
VTYPE xa, ya, za, wa;
xa = x * float(*m++); ya = x * float(*m++); za = x * float(*m++); wa = x * float(*m++);
xa += y * float(*m++); ya += y * float(*m++); za += y * float(*m++); wa += y * float(*m++);
xa += z * float(*m++); ya += z * float(*m++); za += z * float(*m++); wa += z * float(*m++);
xa += w * float(*m++); ya += w * float(*m++); za += w * float(*m++); wa += w * float(*m++);
x = xa; y = ya; z = za; w = wa;
return *this;
}
Vector4DF &Vector4DF::operator*= (const Matrix4F &op)
{
float xa, ya, za, wa;
xa = x * op.data[0] + y * op.data[4] + z * op.data[8] + w * op.data[12];
ya = x * op.data[1] + y * op.data[5] + z * op.data[9] + w * op.data[13];
za = x * op.data[2] + y * op.data[6] + z * op.data[10] + w * op.data[14];
wa = x * op.data[3] + y * op.data[7] + z * op.data[11] + w * op.data[15];
x = xa; y = ya; z = za; w = wa;
return *this;
}
Vector4DF &Vector4DF::operator*= (const float* op)
{
float xa, ya, za, wa;
xa = x * op[0] + y * op[4] + z * op[8] + w * op[12];
ya = x * op[1] + y * op[5] + z * op[9] + w * op[13];
za = x * op[2] + y * op[6] + z * op[10] + w * op[14];
wa = x * op[3] + y * op[7] + z * op[11] + w * op[15];
x = xa; y = ya; z = za; w = wa;
return *this;
}
| 28.601695
| 92
| 0.47437
|
csiro-robotics
|
8c1dde0196518bd1550bee9b3f84249cf7060d1c
| 198
|
cpp
|
C++
|
test_index_reference.cpp
|
insertinterestingnamehere/cython_overload_except
|
00d76ad8020fcb21948545de8161da65f7f4acd8
|
[
"BSD-2-Clause"
] | null | null | null |
test_index_reference.cpp
|
insertinterestingnamehere/cython_overload_except
|
00d76ad8020fcb21948545de8161da65f7f4acd8
|
[
"BSD-2-Clause"
] | null | null | null |
test_index_reference.cpp
|
insertinterestingnamehere/cython_overload_except
|
00d76ad8020fcb21948545de8161da65f7f4acd8
|
[
"BSD-2-Clause"
] | null | null | null |
#include "add.cpp"
#include <iostream>
int main(){
wrapped_int a = 3;
long long b = 2;
std::cout << a[b].val << std::endl;
wrapped_int &temp = a[b];
std::cout << temp.val << std::endl;
}
| 18
| 37
| 0.580808
|
insertinterestingnamehere
|
8c1e21fcc1bfc1f79fd2dad6a5aa8ff6dc21c3ff
| 2,280
|
cpp
|
C++
|
app/main.cpp
|
shivamakhauri04/midterm_project
|
4d062d90cb459d035fa9453aa837463b1e72f5a5
|
[
"MIT"
] | null | null | null |
app/main.cpp
|
shivamakhauri04/midterm_project
|
4d062d90cb459d035fa9453aa837463b1e72f5a5
|
[
"MIT"
] | 9
|
2019-10-19T06:55:30.000Z
|
2019-10-21T15:08:33.000Z
|
app/main.cpp
|
shivamakhauri04/midterm_project
|
4d062d90cb459d035fa9453aa837463b1e72f5a5
|
[
"MIT"
] | 1
|
2019-10-19T02:12:38.000Z
|
2019-10-19T02:12:38.000Z
|
/**
* @file main.cpp
* @author Shivam Akhauri (Driver),Toyas Dhake (Navigator),
* @date 20 October 2019
* @copyright 2019 Toyas Dhake, Shivam Akhauri
* @brief Main file for implementation of the Depth Perception project.
*/
#include <dlib/opencv.h>
#include <dlib/gui_widgets.h>
#include <dlib/image_processing/frontal_face_detector.h>
#include <iostream>
#include <distance.hpp>
#include <face.hpp>
#include <opencv2/highgui/highgui.hpp>
int main() {
// Constructor call for distance calculation
CalculateDistance calculateDistance;
// Initialise the video frame buffer of the camera
cv::VideoCapture cap(0);
// Check if the opencv was able to communicate with the camera
if (!cap.isOpened()) {
std::cout << "Unable to connect to camera" << std::endl;
return 1;
}
dlib::frontal_face_detector detector = dlib::get_frontal_face_detector();
// Assign a window named win to show the current frame
dlib::image_window win;
// Grab each frame and calculate distance till the window is closed
while (!win.is_closed()) {
// read each frame in the buffer one by one
cv::Mat temp;
// if not able to read a frame in the buffer, close the application
if (!cap.read(temp)) {
break;
}
std::vector<Face> faces = calculateDistance.getDistance(temp, detector);
// This is vector of faces with their distance
dlib::cv_image<dlib::bgr_pixel> cimg(temp);
// Display the frame all on the screen
win.clear_overlay();
win.set_image(cimg);
for (auto&& face : faces) {
// draw a bounding box around the face
dlib::rectangle rect(face.getX(), face.getY(), face.getW(),
face.getH());
// write the distance and the x,y coordinates
// of the detected face below the bounding box
win.add_overlay(dlib::image_window::overlay_rect(rect,
dlib::rgb_pixel(0, 255, 0),
std::to_string(face.getX()) + ", " +
std::to_string(face.getY()) + ", " +
std::to_string(face.getDistance())+" m"));
}
}
return 0;
}
| 38.644068
| 80
| 0.601316
|
shivamakhauri04
|
8c20e2958890ef25c6c2b2117176bf264b857fb7
| 5,608
|
cpp
|
C++
|
applications/SavageHutter/SlopeLimiters/TvbLimiter1D.cpp
|
hpgem/hpgem
|
b2f7ac6bdef3262af0c3e8559cb991357a96457f
|
[
"BSD-3-Clause-Clear"
] | 5
|
2020-04-01T15:35:26.000Z
|
2022-02-22T02:48:12.000Z
|
applications/SavageHutter/SlopeLimiters/TvbLimiter1D.cpp
|
hpgem/hpgem
|
b2f7ac6bdef3262af0c3e8559cb991357a96457f
|
[
"BSD-3-Clause-Clear"
] | 139
|
2020-01-06T12:42:24.000Z
|
2022-03-10T20:58:14.000Z
|
applications/SavageHutter/SlopeLimiters/TvbLimiter1D.cpp
|
hpgem/hpgem
|
b2f7ac6bdef3262af0c3e8559cb991357a96457f
|
[
"BSD-3-Clause-Clear"
] | 4
|
2020-04-10T09:19:33.000Z
|
2021-08-21T07:20:42.000Z
|
/*
This file forms part of hpGEM. This package has been developed over a number of
years by various people at the University of Twente and a full list of
contributors can be found at http://hpgem.org/about-the-code/team
This code is distributed using BSD 3-Clause License. A copy of which can found
below.
Copyright (c) 2014, University of Twente
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 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.
*/
#include "TvbLimiter1D.h"
#include "Base/Face.h"
using namespace hpgem;
TvbLimiter1D::TvbLimiter1D(std::size_t numberOfVariables)
: SlopeLimiter(numberOfVariables) {}
void TvbLimiter1D::limitSlope(Base::Element *element) {
for (std::size_t iVar = 0; iVar < numberOfVariables_; ++iVar) {
if (!hasSmallSlope(element, iVar)) {
limitWithMinMod(element, iVar);
}
}
}
///\details Doing it the DG way for p=1 does not lead to conservation of mass,
/// so for now, do it the FVM way. Don't look at the slope in this element at
/// all, just at the averages of this element and the adjacent elements. We also
/// assume that we limit only once per time step. Lastly, it is assumed that the
/// first two basis functions are the nodal basis functions
void TvbLimiter1D::limitWithMinMod(Base::Element *element,
const std::size_t iVar) {
// this does not work for boundaries, probably also not for triangular mesh.
// maybe write getNeighbour(face), which deals with nullpointers in case of
// a boundary?
const Base::Element *elemL;
const Base::Element *elemR;
if (element->getFace(0)->isInternal())
elemL = element->getFace(0)->getPtrElementLeft();
else
return; // for now, just don't use the limiter here...
if (element->getFace(1)->isInternal())
elemR = element->getFace(1)->getPtrElementRight();
else
return; // for now, just don't use the limiter here...
logger.assert_always(elemR->getID() == element->getID() + 1 &&
element->getID() == elemL->getID() + 1,
"elements not in correct order");
const double u0 = Helpers::computeAverageOfSolution<1>(
element, element->getTimeIntegrationVector(0),
elementIntegrator_)(iVar);
const double uElemR = Helpers::computeAverageOfSolution<1>(
const_cast<Base::Element *>(elemR), elemR->getTimeIntegrationVector(0),
elementIntegrator_)(iVar);
const double uElemL = Helpers::computeAverageOfSolution<1>(
const_cast<Base::Element *>(elemL), elemL->getTimeIntegrationVector(0),
elementIntegrator_)(iVar);
logger(INFO, "uLeft: %\nu0: %\nuRight: %", uElemL, u0, uElemR);
LinearAlgebra::MiddleSizeVector newCoeffs =
LinearAlgebra::MiddleSizeVector(element->getNumberOfBasisFunctions());
if (Helpers::sign(uElemR - u0) != Helpers::sign(u0 - uElemL)) // phi(r) = 0
{
newCoeffs[0] = u0;
newCoeffs[1] = u0;
logger(INFO, "phi = 0");
} else {
if ((u0 - uElemL) / (uElemR - u0) < 1) // phi(r) = r
{
newCoeffs[0] = .5 * u0 + .5 * uElemL;
newCoeffs[1] = 1.5 * u0 - .5 * uElemL;
logger(INFO, "phi = r");
} else // phi(r) = 1
{
newCoeffs[0] = 1.5 * u0 - .5 * uElemR;
newCoeffs[1] = .5 * u0 + .5 * uElemR;
logger(INFO, "phi = 1");
}
}
logger(INFO, "new coefficients: % \n \n", newCoeffs);
element->setTimeIntegrationSubvector(0, iVar, newCoeffs);
}
bool TvbLimiter1D::hasSmallSlope(const Base::Element *element,
const std::size_t iVar) {
const PointReferenceT &pRefL =
element->getReferenceGeometry()->getReferenceNodeCoordinate(0);
const PointReferenceT &pRefR =
element->getReferenceGeometry()->getReferenceNodeCoordinate(1);
const double uPlus = element->getSolution(0, pRefR)[iVar];
const double uMinus = element->getSolution(0, pRefL)[iVar];
const double M = 1;
return (std::abs(uPlus - uMinus) <
M * (2 * element->calcJacobian(pRefL).determinant()) *
(2 * element->calcJacobian(pRefL).determinant()));
}
| 43.472868
| 80
| 0.67582
|
hpgem
|
8c26d6f600c31e11a935c11e6908364b90d2dbf3
| 2,408
|
cpp
|
C++
|
old/extgcd.inc.cpp
|
kmyk/competitive-programming-library
|
77efa23a69f06202bb43f4dc6b0550e4cdb48e0b
|
[
"MIT"
] | 55
|
2018-01-11T02:20:02.000Z
|
2022-03-24T06:18:54.000Z
|
number/extgcd.inc.cpp
|
Mohammad-Yasser/competitive-programming-library
|
4656ac0d625abce98b901965c7607c1b908b093f
|
[
"MIT"
] | 10
|
2016-10-29T08:20:04.000Z
|
2021-02-27T13:14:53.000Z
|
number/extgcd.inc.cpp
|
Mohammad-Yasser/competitive-programming-library
|
4656ac0d625abce98b901965c7607c1b908b093f
|
[
"MIT"
] | 11
|
2016-10-29T06:00:53.000Z
|
2021-06-16T14:32:43.000Z
|
/**
* @brief extended gcd
* @description for given a and b, find x, y and gcd(a, b) such that ax + by = 1
* @note O(log n)
* @see https://topcoder.g.hatena.ne.jp/spaghetti_source/20130126/1359171466
*/
tuple<ll, ll, ll> extgcd(ll a, ll b) {
ll x = 0, y = 1;
for (ll u = 1, v = 0; a; ) {
ll q = b / a;
x -= q * u; swap(x, u);
y -= q * v; swap(y, v);
b -= q * a; swap(b, a);
}
return make_tuple(x, y, b);
}
unittest {
random_device device;
default_random_engine gen(device());
REP (iteration, 1000) {
ll a = uniform_int_distribution<ll>(1, 10000)(gen);
ll b = uniform_int_distribution<ll>(1, 10000)(gen);
ll x, y, d; tie(x, y, d) = extgcd(a, b);
assert (a * x + b * y == d);
assert (d == __gcd(a, b));
}
}
/**
* @note recursive version (slow)
*/
pair<int, int> extgcd_recursive(int a, int b) {
if (b == 0) return { 1, 0 };
int na, nb; tie(na, nb) = extgcd(b, a % b);
return { nb, na - a/b * nb };
}
/**
* @note x and m must be relatively prime
* @note O(log m)
*/
ll modinv(ll x, int m) {
assert (1 <= x and x < m);
ll y, d; tie(y, ignore, d) = extgcd(x, m);
if (d != 1) return 0; // no inverse
assert (x * y % m == 1);
return (y % m + m) % m;
}
/**
* @brief chinese remainder theorem
* @note the unit element is (0, 1)
*/
pair<ll, ll> crt(pair<ll, ll> eqn1, pair<ll, ll> eqn2) {
ll x1, m1; tie(x1, m1) = eqn1;
ll x2, m2; tie(x2, m2) = eqn2;
ll x = x1 + m1 * (x2 - x1) * modinv(m1 % m2, m2);
ll m = m1 * m2;
return { (x % m + m) % m, m };
}
ll multmod(ll a, ll b, ll m) {
a = (a % m + m) % m;
b = (b % m + m) % m;
ll c = 0;
REP (i, 63) {
if (b & (1ll << i)) {
c += a;
if (c > m) c -= m;
}
a *= 2;
if (a > m) a -= m;
}
return c;
}
pair<ll, ll> crt(pair<ll, ll> eqn1, pair<ll, ll> eqn2) {
ll x1, m1; tie(x1, m1) = eqn1;
ll x2, m2; tie(x2, m2) = eqn2;
if (m1 == 0 or m2 == 0) return make_pair(0ll, 0ll);
assert (1 <= m1 and 1 <= m2);
ll m1_inv, d; tie(m1_inv, ignore, d) = extgcd(m1, m2);
if ((x1 - x2) % d) return make_pair(0ll, 0ll);
ll m = m1 * m2 / d;
// ll x = x1 + (m1 / d) * (x2 - x1) % m * (m1_inv % m) % m;
ll x = x1 + multmod(multmod(m1 / d, x2 - x1, m), m1_inv, m);
return make_pair((x % m + m) % m, m);
}
| 26.755556
| 80
| 0.475914
|
kmyk
|
8c28ff85a56ee2abce629feee801ca4185d9fd4e
| 355
|
cpp
|
C++
|
tests/mixed/mixed_invalid_unwrap_test.cpp
|
pacmancoder/exl
|
ffd66d30e76d60aa7e4efe75274e4a8a35427961
|
[
"BSL-1.0"
] | 1
|
2019-05-02T12:00:50.000Z
|
2019-05-02T12:00:50.000Z
|
tests/mixed/mixed_invalid_unwrap_test.cpp
|
pacmancoder/exl
|
ffd66d30e76d60aa7e4efe75274e4a8a35427961
|
[
"BSL-1.0"
] | 14
|
2019-02-13T17:21:07.000Z
|
2019-03-08T21:40:38.000Z
|
tests/mixed/mixed_invalid_unwrap_test.cpp
|
pacmancoder/exl
|
ffd66d30e76d60aa7e4efe75274e4a8a35427961
|
[
"BSL-1.0"
] | null | null | null |
// Copyright (C) 2019 Vladislav Nikonov <mail@pacmancoder.xyz>
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt)
#include <exl/mixed.hpp>
#include <termination_test.hpp>
void termination_test()
{
exl::mixed<char, int> m(422);
m.unwrap<char>();
}
| 25.357143
| 83
| 0.715493
|
pacmancoder
|
8c2a7228c91fe29e32f4bdf0d3796f4e551b287c
| 5,812
|
hpp
|
C++
|
src/libv/diff/diff.hpp
|
cpplibv/libv
|
293e382f459f0acbc540de8ef6283782b38d2e63
|
[
"Zlib"
] | 2
|
2018-04-11T03:07:03.000Z
|
2019-03-29T15:24:12.000Z
|
src/libv/diff/diff.hpp
|
cpplibv/libv
|
293e382f459f0acbc540de8ef6283782b38d2e63
|
[
"Zlib"
] | null | null | null |
src/libv/diff/diff.hpp
|
cpplibv/libv
|
293e382f459f0acbc540de8ef6283782b38d2e63
|
[
"Zlib"
] | 1
|
2021-06-13T06:39:06.000Z
|
2021-06-13T06:39:06.000Z
|
// Project: libv.diff, File: src/libv/diff/diff.hpp, Author: Császár Mátyás [Vader]
#pragma once
// libv
#include <libv/utility/bytes/input_bytes.hpp>
#include <libv/utility/bytes/output_bytes.hpp>
// std
#include <optional>
#include <string>
#include <vector>
namespace libv {
namespace diff {
// -------------------------------------------------------------------------------------------------
static constexpr size_t default_match_block_size = 64;
// -------------------------------------------------------------------------------------------------
struct diff_info {
private:
static constexpr size_t invalid = std::numeric_limits<size_t>::max();
public:
size_t old_size = invalid;
size_t new_size = invalid;
public:
[[nodiscard]] constexpr inline bool valid() const noexcept {
return
old_size != invalid &&
new_size != invalid;
}
[[nodiscard]] explicit constexpr inline operator bool() const noexcept {
return valid();
}
[[nodiscard]] constexpr inline bool operator!() const noexcept {
return !valid();
}
};
namespace detail { // ------------------------------------------------------------------------------
void aux_create_diff(libv::input_bytes old, libv::input_bytes new_, libv::output_bytes out_diff, size_t match_block_size);
[[nodiscard]] diff_info aux_get_diff_info(libv::input_bytes diff);
[[nodiscard]] bool aux_check_diff(libv::input_bytes old, libv::input_bytes new_, libv::input_bytes diff);
[[nodiscard]] bool apply_patch(libv::input_bytes old, libv::input_bytes diff, libv::output_bytes out_new);
} // namespace -------------------------------------------------------------------------------------
/// Create a diff from \c old to \c new and appends at the end of \c diff.
///
/// \param old - The old version of the data
/// \param new_ - The new version of the data
/// \param match_block_size - Smaller block size improves compression but at the cost of performance. Recommended 16-16384
/// \return The resulting diff that can be applied to \c old to get \c new
template <typename In0, typename In1, typename Out>
inline void create_diff(In0&& old, In1&& new_, Out&& out_diff, size_t match_block_size = default_match_block_size) {
detail::aux_create_diff(libv::input_bytes(old), libv::input_bytes(new_), libv::output_bytes(out_diff), match_block_size);
}
/// Returns a diff created from \c old to \c new.
///
/// \template T - The output type used for diff (std::string or std::vector<std::byte>)
/// \param old - The old version of the data
/// \param new_ - The new version of the data
/// \param match_block_size - Smaller block size improves compression but at the cost of performance. Recommended 16-16384
/// \return The resulting diff that can be applied to \c old to get \c new
template <typename T, typename In0, typename In1>
[[nodiscard]] inline T create_diff(In0&& old, In1&& new_, size_t match_block_size = default_match_block_size) {
T diff;
create_diff(old, new_, diff, match_block_size);
return diff;
}
template <typename In0, typename In1>
[[nodiscard]] inline std::string create_diff_str(In0&& old, In1&& new_, size_t match_block_size = default_match_block_size) {
return create_diff<std::string>(old, new_, match_block_size);
}
template <typename In0, typename In1>
[[nodiscard]] inline std::vector<std::byte> create_diff_bin(In0&& old, In1&& new_, size_t match_block_size = default_match_block_size) {
return create_diff<std::vector<std::byte>>(old, new_, match_block_size);
}
/// \return Returns a non valid diff_info object upon failure, otherwise returns the diff info
template <typename In0>
[[nodiscard]] diff_info get_diff_info(In0&& diff) {
return detail::aux_get_diff_info(libv::input_bytes(diff));
}
/// Check if the \c diff applied to \c old will result in \c new.
///
/// \param old - The old version of the data
/// \param new_ - The new version of the data
/// \param diff - The diff that will be applied to \c old
/// \return Returns true if \c diff can be applied to \c old and it results in \c new
template <typename In0, typename In1, typename In2>
[[nodiscard]] inline bool check_diff(In0&& old, In1&& new_, In2&& diff) {
return detail::aux_check_diff(libv::input_bytes(old), libv::input_bytes(new_), libv::input_bytes(diff));
}
/// Applies \c diff to \c old.
///
/// \param old - The old version of the data
/// \param diff - The diff that will be applied to \c old
/// \return Returns the new version of the data after applying the \c diff or an empty optional if the \c diff cannot be applied to \olc
template <typename In0, typename In1, typename Out>
[[nodiscard]] inline bool apply_patch(In0&& old, In1&& diff, Out&& out_new) {
return detail::apply_patch(libv::input_bytes(old), libv::input_bytes(diff), libv::output_bytes(out_new));
}
/// Applies \c diff to \c old.
///
/// \param old - The old version of the data
/// \param diff - The diff that will be applied to \c old
/// \return Returns the new version of the data after applying the \c diff or an empty optional if the \c diff cannot be applied to \olc
template <typename T, typename In0, typename In1>
[[nodiscard]] inline std::optional<T> apply_patch(In0&& old, In1&& diff) {
std::optional<T> new_(std::in_place);
const auto success = apply_patch(old, diff, *new_);
if (!success)
new_.reset();
return new_;
}
template <typename In0, typename In1>
[[nodiscard]] inline std::optional<std::string> apply_patch_str(In0&& old, In1&& diff) {
return apply_patch<std::string>(old, diff);
}
template <typename In0, typename In1>
[[nodiscard]] inline std::optional<std::vector<std::byte>> apply_patch_bin(In0&& old, In1&& diff) {
return apply_patch<std::vector<std::byte>>(old, diff);
}
// -------------------------------------------------------------------------------------------------
} // namespace diff
} // namespace libv
| 39.808219
| 136
| 0.668789
|
cpplibv
|
8c2ad38fa61b19ad767dd011d39cf3a68dc734fd
| 2,690
|
cpp
|
C++
|
src/cpp/common-bio/Multiseq.cpp
|
UTbioinf/SMSC
|
0d5765518b3863d2363f264d9f256063c7f7ce71
|
[
"MIT"
] | null | null | null |
src/cpp/common-bio/Multiseq.cpp
|
UTbioinf/SMSC
|
0d5765518b3863d2363f264d9f256063c7f7ce71
|
[
"MIT"
] | 2
|
2019-05-31T06:36:36.000Z
|
2019-09-18T22:13:09.000Z
|
src/cpp/common-bio/Multiseq.cpp
|
UTbioinf/SMSC
|
0d5765518b3863d2363f264d9f256063c7f7ce71
|
[
"MIT"
] | 1
|
2021-12-01T10:30:58.000Z
|
2021-12-01T10:30:58.000Z
|
#include <fstream>
#include <cctype>
#include "Multiseq.h"
#include "util.h"
namespace loon
{
void Fasta::save_fasta(std::ostream& out)
{
out << ">" << tag << tag_remaining << std::endl;
for(size_t i = 0; i < seq.length(); i += 80)
out << seq.substr(i, 80) << std::endl;
}
char Fasta::base_rc(char c)
{
if(c >= 'a' && c <= 'z')
c = c - 'a' + 'A';
switch(c)
{
case 'A': return 'T';
case 'T': return 'A';
case 'G': return 'C';
case 'C': return 'G';
case 'R': return 'Y';
case 'Y': return 'R';
case 'S': return 'S';
case 'W': return 'W';
case 'M': return 'K';
case 'K': return 'M';
case 'B': return 'V';
case 'D': return 'H';
case 'H': return 'D';
case 'V': return 'B';
case 'N': return 'N';
case '-': return '-';
default:
ERROR_PRINT("Unknown base [%d: %c]", int(c), c);
exit(1);
}
}
void Fasta::compute_reverse_complement()
{
rev.clear();
rev.reserve( seq.length() );
for(std::string::reverse_iterator rit = seq.rbegin(); rit != seq.rend(); ++rit)
rev.push_back( base_rc( *rit ) );
}
void Multiseq::read_fasta(const char* fname)
{
std::ifstream fin(fname);
check_file_open(fin, fname);
std::string line;
while(std::getline(fin, line))
{
if(line[0] == '>')
{
this->push_back( Fasta() );
Fasta& fasta = this->back();
std::size_t space_pos = line.find(' ');
if(space_pos != std::string::npos)
{
fasta.tag = line.substr(1, space_pos-1);
fasta.tag_remaining = line.substr(space_pos);
}
else
fasta.tag = line.substr(1);
}
else if(line[0] != ';')
{
for(std::size_t i = 0; i<line.length(); ++i)
{
line[i] = expand_base( line[i] );
}
this->back().seq += line;
}
}
fin.close();
}
void Multiseq::save_fasta(const char* fname)
{
std::ofstream fout(fname);
check_file_open(fout, fname);
for(std::vector<Fasta>::iterator it = this->begin(); it != this->end(); ++it)
{
fout << ">" << (it->tag) << (it->tag_remaining) << std::endl;
for(size_t i = 0; i < it->seq.length(); i += 80)
fout << (it->seq.substr(i, 80)) << std::endl;
}
fout.close();
}
void Multiseq::compute_reverse_complement()
{
for(std::vector<Fasta>::iterator it = this->begin(); it != this->end(); ++it)
it->compute_reverse_complement();
}
}
| 24.907407
| 83
| 0.477695
|
UTbioinf
|
8c2b0f8c42e3757625f710420e30b7d152444f96
| 14,696
|
cpp
|
C++
|
LSL/GLUtils.cpp
|
AntonBogomolov/LightSpeedLimit
|
215d573f46eef63801cbd8df654f104401bae581
|
[
"MIT"
] | null | null | null |
LSL/GLUtils.cpp
|
AntonBogomolov/LightSpeedLimit
|
215d573f46eef63801cbd8df654f104401bae581
|
[
"MIT"
] | null | null | null |
LSL/GLUtils.cpp
|
AntonBogomolov/LightSpeedLimit
|
215d573f46eef63801cbd8df654f104401bae581
|
[
"MIT"
] | null | null | null |
#include "global.h"
#include "GLUtils.h"
#include "GLShaderObject.h"
#include "TextureManager.h"
#include "Texture.h"
#include "TextureAtlas.h"
#include "VertexArray.h"
#include "VertexBuffer.h"
#include "SceneGraphNode.h"
#include "ScreenObj.h"
#include "VideoManeger.h"
#include "DrawablePrimitive.h"
CGLUtils* CGLUtils::instance = NULL;
CVertexBuffer* CGLUtils::quad = NULL;
CVertexBuffer* CGLUtils::revQuad = NULL;
CVertexBuffer* CGLUtils::lQuad = NULL;
CDrawablePrimitive* CGLUtils::QuadNode = NULL;
CDrawablePrimitive* CGLUtils::revQuadNode = NULL;
byte* CGLUtils::glGetTexImage(const int texId, const int texW, const int texH)
{
GLuint* framebuffer = new GLuint[1];
glGenFramebuffers(1, framebuffer);
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer[0]);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, CTextureManager::getTexture(texId)->getID(), 0); // texId
int status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (status != GL_FRAMEBUFFER_COMPLETE)
{
// Log.e("glGetTexImage", "image load faild");
}
byte* buff = new byte[texW * texH * 4];
glReadPixels(0, 0, texW, texH, GL_RGBA, GL_UNSIGNED_BYTE, buff);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glDeleteFramebuffers(1, framebuffer);
return buff;
}
void CGLUtils::checkGlError(const string op)
{
int error;
while ((error = glGetError()) != GL_NO_ERROR)
{
}
}
CSceneGraphNodeDrawable* CGLUtils::getFullscreenDrawableNode()
{
if (!QuadNode) initFullscreenQuad();
return (CSceneGraphNodeDrawable*)QuadNode;
}
CSceneGraphNodeDrawable* CGLUtils::getFullscreenRevDrawableNode()
{
if (!revQuadNode) initFullscreenRevQuad();
return (CSceneGraphNodeDrawable*)revQuadNode;
}
CVertexBuffer* CGLUtils::initFullscreenQuad()
{
if (quad) delete quad;
quad = NULL;
quad = new CVertexBuffer();
if (!QuadNode) QuadNode = new CDrawablePrimitive();
GLfloat qverts[] = { 0, 0, 0, CVideoManeger::scrWidth, 0, 0, CVideoManeger::scrWidth, CVideoManeger::scrHeight, 0, 0, CVideoManeger::scrHeight, 0 };
GLfloat qcoords[] = { 0, 0, 1, 0, 1, 1, 0, 1 };
short qind[] = { 0, 1, 2, 0, 2, 3 };
quad->setVerticesData(qverts, 4 * 3);
quad->setTexData(qcoords, 4 * 2);
quad->setIndicesData(qind, 6);
QuadNode->setVBO(quad);
return quad;
}
void CGLUtils::drawFullscreenQuad(const CGLShaderObject* currShader)
{
if (quad == NULL) initFullscreenQuad();
if (quad)
{
quad->drawElements(0, currShader);
}
}
CVertexBuffer* CGLUtils::initFullscreenRevQuad()
{
if (revQuad) delete revQuad;
revQuad = NULL;
revQuad = new CVertexBuffer();
if (!revQuadNode) revQuadNode = new CDrawablePrimitive();
GLfloat qverts[] = { 0, 0, 0, CVideoManeger::scrWidth, 0, 0, CVideoManeger::scrWidth, CVideoManeger::scrHeight, 0, 0, CVideoManeger::scrHeight, 0 };
GLfloat qcoords[] = { 0, 1, 1, 1, 1, 0, 0, 0 };
short qind[] = { 0, 1, 2, 0, 2, 3 };
revQuad->setVerticesData(qverts, 4 * 3);
revQuad->setTexData(qcoords, 4 * 2);
revQuad->setIndicesData(qind, 6);
revQuadNode->setVBO(revQuad);
return revQuad;
}
void CGLUtils::drawFullscreenRevQuad(const CGLShaderObject* currShader)
{
if (revQuad == NULL) initFullscreenRevQuad();
if (revQuad)
{
revQuad->drawElements(0, currShader);
}
}
CVertexBuffer* CGLUtils::initLFullscreenQuad()
{
float flDataVert[] = { 0, 0, 0, 0, 0,
CVideoManeger::scrWidth, 0, 0, CVideoManeger::scrWidth, 0,
0, CVideoManeger::scrHeight, 0, 0, CVideoManeger::scrHeight,
CVideoManeger::scrWidth, 0, 0, CVideoManeger::scrWidth, 0,
0, CVideoManeger::scrHeight, 0, 0, CVideoManeger::scrHeight,
CVideoManeger::scrWidth, CVideoManeger::scrHeight, 0, CVideoManeger::scrWidth, CVideoManeger::scrHeight
};
return NULL;
}
void CGLUtils::drawLFullscreenQuad(const CGLShaderObject* currShader)
{
if (lQuad == NULL) initLFullscreenQuad();
}
void CGLUtils::fillVBOData( float* vert, float* tex, float* vtex, short* ind, const CTexCoord* sprite, const CTexCoord* vsprite,
const int index, const CScreenObj* obj, const int direction, const float offset)
{
bool hasAdditionalTexCoord = false;
if (vtex != NULL && vsprite != NULL) hasAdditionalTexCoord = true;
if (vert == NULL) return;
if (tex == NULL ) return;
if (ind == NULL ) return;
if (sprite == NULL) return;
const glm::vec2* points = obj->getPointsCoords();
int X1 = points[0].x;
int Y1 = points[0].y;
int X2 = points[1].x;
int Y2 = points[1].y;
int X3 = points[2].x;
int Y3 = points[2].y;
int X4 = points[3].x;
int Y4 = points[3].y;
vert[index * 12 + 0] = X1; vert[index * 12 + 1] = Y1; vert[index * 12 + 2] = 0;
vert[index * 12 + 3] = X2 + offset; vert[index * 12 + 4] = Y2; vert[index * 12 + 5] = 0;
vert[index * 12 + 6] = X3 + offset; vert[index * 12 + 7] = Y3 + offset; vert[index * 12 + 8] = 0;
vert[index * 12 + 9] = X4; vert[index * 12 + 10] =Y4 + offset; vert[index * 12 + 11] = 0;
switch (direction)
{
case Defines::DIR_DOWN:
tex[index * 8 + 0] = sprite->tx + sprite->twidth; tex[index * 8 + 1] = sprite->ty + sprite->theight;
tex[index * 8 + 2] = sprite->tx; tex[index * 8 + 3] = sprite->ty + sprite->theight;
tex[index * 8 + 4] = sprite->tx; tex[index * 8 + 5] = sprite->ty;
tex[index * 8 + 6] = sprite->tx + sprite->twidth; tex[index * 8 + 7] = sprite->ty;
if (hasAdditionalTexCoord)
{
vtex[index * 8 + 0] = vsprite->tx + vsprite->twidth; vtex[index * 8 + 1] = vsprite->ty + vsprite->theight;
vtex[index * 8 + 2] = vsprite->tx; vtex[index * 8 + 3] = vsprite->ty + vsprite->theight;
vtex[index * 8 + 4] = vsprite->tx; vtex[index * 8 + 5] = vsprite->ty;
vtex[index * 8 + 6] = vsprite->tx + vsprite->twidth; vtex[index * 8 + 7] = vsprite->ty;
}
break;
case Defines::DIR_LEFT:
tex[index * 8 + 0] = sprite->tx + sprite->twidth; tex[index * 8 + 1] = sprite->ty;
tex[index * 8 + 2] = sprite->tx + sprite->twidth; tex[index * 8 + 3] = sprite->ty + sprite->theight;
tex[index * 8 + 4] = sprite->tx; tex[index * 8 + 5] = sprite->ty + sprite->theight;
tex[index * 8 + 6] = sprite->tx; tex[index * 8 + 7] = sprite->ty;
if (hasAdditionalTexCoord)
{
vtex[index * 8 + 0] = vsprite->tx + vsprite->twidth; vtex[index * 8 + 1] = vsprite->ty;
vtex[index * 8 + 2] = vsprite->tx + vsprite->twidth; vtex[index * 8 + 3] = vsprite->ty + vsprite->theight;
vtex[index * 8 + 4] = vsprite->tx; vtex[index * 8 + 5] = vsprite->ty + vsprite->theight;
vtex[index * 8 + 6] = vsprite->tx; vtex[index * 8 + 7] = vsprite->ty;
}
break;
case Defines::DIR_RIGHT:
tex[index * 8 + 0] = sprite->tx; tex[index * 8 + 1] = sprite->ty + sprite->theight;
tex[index * 8 + 2] = sprite->tx; tex[index * 8 + 3] = sprite->ty;
tex[index * 8 + 4] = sprite->tx + sprite->twidth; tex[index * 8 + 5] = sprite->ty;
tex[index * 8 + 6] = sprite->tx + sprite->twidth; tex[index * 8 + 7] = sprite->ty + sprite->theight;
if (hasAdditionalTexCoord)
{
vtex[index * 8 + 0] = vsprite->tx; vtex[index * 8 + 1] = vsprite->ty + vsprite->theight;
vtex[index * 8 + 2] = vsprite->tx; vtex[index * 8 + 3] = vsprite->ty;
vtex[index * 8 + 4] = vsprite->tx + vsprite->twidth; vtex[index * 8 + 5] = vsprite->ty;
vtex[index * 8 + 6] = vsprite->tx + vsprite->twidth; vtex[index * 8 + 7] = vsprite->ty + vsprite->theight;
}
break;
default:
tex[index * 8 + 0] = sprite->tx; tex[index * 8 + 1] = sprite->ty;
tex[index * 8 + 2] = sprite->tx + sprite->twidth; tex[index * 8 + 3] = sprite->ty;
tex[index * 8 + 4] = sprite->tx + sprite->twidth; tex[index * 8 + 5] = sprite->ty + sprite->theight;
tex[index * 8 + 6] = sprite->tx; tex[index * 8 + 7] = sprite->ty + sprite->theight;
if (hasAdditionalTexCoord)
{
vtex[index * 8 + 0] = vsprite->tx; vtex[index * 8 + 1] = vsprite->ty;
vtex[index * 8 + 2] = vsprite->tx + vsprite->twidth; vtex[index * 8 + 3] = vsprite->ty;
vtex[index * 8 + 4] = vsprite->tx + vsprite->twidth; vtex[index * 8 + 5] = vsprite->ty + vsprite->theight;
vtex[index * 8 + 6] = vsprite->tx; vtex[index * 8 + 7] = vsprite->ty + vsprite->theight;
}
break;
}
ind[index * 6 + 0] = (short)(index * 4); ind[index * 6 + 1] = (short)(index * 4 + 1); ind[index * 6 + 2] = (short)(index * 4 + 2);
ind[index * 6 + 3] = (short)(index * 4); ind[index * 6 + 4] = (short)(index * 4 + 2); ind[index * 6 + 5] = (short)(index * 4 + 3);
}
void CGLUtils::fillVBOVertData(float* vert, const int index, const CScreenObj* obj, const float offset)
{
if (vert == NULL) return;
const glm::vec2* points = obj->getPointsCoords();
int X1 = points[0].x;
int Y1 = points[0].y;
int X2 = points[1].x;
int Y2 = points[1].y;
int X3 = points[2].x;
int Y3 = points[2].y;
int X4 = points[3].x;
int Y4 = points[3].y;
vert[index * 12 + 0] = X1; vert[index * 12 + 1] = Y1; vert[index * 12 + 2] = 0;
vert[index * 12 + 3] = X2 + offset; vert[index * 12 + 4] = Y2; vert[index * 12 + 5] = 0;
vert[index * 12 + 6] = X3 + offset; vert[index * 12 + 7] = Y3 + offset; vert[index * 12 + 8] = 0;
vert[index * 12 + 9] = X4; vert[index * 12 + 10] =Y4 + offset; vert[index * 12 + 11] = 0;
}
void CGLUtils::fillVBOTexData(float* tex, float* vtex, const CTexCoord* sprite, const CTexCoord* vsprite, const int index, const int direction, const float offset)
{
bool hasAdditionalTexCoord = false;
if (vtex != NULL && vsprite != NULL) hasAdditionalTexCoord = true;
if (tex == NULL) return;
if (sprite == NULL) return;
switch (direction)
{
case Defines::DIR_DOWN:
tex[index * 8 + 0] = sprite->tx + sprite->twidth; tex[index * 8 + 1] = sprite->ty + sprite->theight;
tex[index * 8 + 2] = sprite->tx; tex[index * 8 + 3] = sprite->ty + sprite->theight;
tex[index * 8 + 4] = sprite->tx; tex[index * 8 + 5] = sprite->ty;
tex[index * 8 + 6] = sprite->tx + sprite->twidth; tex[index * 8 + 7] = sprite->ty;
if (hasAdditionalTexCoord)
{
vtex[index * 8 + 0] = vsprite->tx + vsprite->twidth; vtex[index * 8 + 1] = vsprite->ty + vsprite->theight;
vtex[index * 8 + 2] = vsprite->tx; vtex[index * 8 + 3] = vsprite->ty + vsprite->theight;
vtex[index * 8 + 4] = vsprite->tx; vtex[index * 8 + 5] = vsprite->ty;
vtex[index * 8 + 6] = vsprite->tx + vsprite->twidth; vtex[index * 8 + 7] = vsprite->ty;
}
break;
case Defines::DIR_LEFT:
tex[index * 8 + 0] = sprite->tx + sprite->twidth; tex[index * 8 + 1] = sprite->ty;
tex[index * 8 + 2] = sprite->tx + sprite->twidth; tex[index * 8 + 3] = sprite->ty + sprite->theight;
tex[index * 8 + 4] = sprite->tx; tex[index * 8 + 5] = sprite->ty + sprite->theight;
tex[index * 8 + 6] = sprite->tx; tex[index * 8 + 7] = sprite->ty;
if (hasAdditionalTexCoord)
{
vtex[index * 8 + 0] = vsprite->tx + vsprite->twidth; vtex[index * 8 + 1] = vsprite->ty;
vtex[index * 8 + 2] = vsprite->tx + vsprite->twidth; vtex[index * 8 + 3] = vsprite->ty + vsprite->theight;
vtex[index * 8 + 4] = vsprite->tx; vtex[index * 8 + 5] = vsprite->ty + vsprite->theight;
vtex[index * 8 + 6] = vsprite->tx; vtex[index * 8 + 7] = vsprite->ty;
}
break;
case Defines::DIR_RIGHT:
tex[index * 8 + 0] = sprite->tx; tex[index * 8 + 1] = sprite->ty + sprite->theight;
tex[index * 8 + 2] = sprite->tx; tex[index * 8 + 3] = sprite->ty;
tex[index * 8 + 4] = sprite->tx + sprite->twidth; tex[index * 8 + 5] = sprite->ty;
tex[index * 8 + 6] = sprite->tx + sprite->twidth; tex[index * 8 + 7] = sprite->ty + sprite->theight;
if (hasAdditionalTexCoord)
{
vtex[index * 8 + 0] = vsprite->tx; vtex[index * 8 + 1] = vsprite->ty + vsprite->theight;
vtex[index * 8 + 2] = vsprite->tx; vtex[index * 8 + 3] = vsprite->ty;
vtex[index * 8 + 4] = vsprite->tx + vsprite->twidth; vtex[index * 8 + 5] = vsprite->ty;
vtex[index * 8 + 6] = vsprite->tx + vsprite->twidth; vtex[index * 8 + 7] = vsprite->ty + vsprite->theight;
}
break;
default:
tex[index * 8 + 0] = sprite->tx; tex[index * 8 + 1] = sprite->ty;
tex[index * 8 + 2] = sprite->tx + sprite->twidth; tex[index * 8 + 3] = sprite->ty;
tex[index * 8 + 4] = sprite->tx + sprite->twidth; tex[index * 8 + 5] = sprite->ty + sprite->theight;
tex[index * 8 + 6] = sprite->tx; tex[index * 8 + 7] = sprite->ty + sprite->theight;
if (hasAdditionalTexCoord)
{
vtex[index * 8 + 0] = vsprite->tx; vtex[index * 8 + 1] = vsprite->ty;
vtex[index * 8 + 2] = vsprite->tx + vsprite->twidth; vtex[index * 8 + 3] = vsprite->ty;
vtex[index * 8 + 4] = vsprite->tx + vsprite->twidth; vtex[index * 8 + 5] = vsprite->ty + vsprite->theight;
vtex[index * 8 + 6] = vsprite->tx; vtex[index * 8 + 7] = vsprite->ty + vsprite->theight;
}
break;
}
}
void CGLUtils::fillVBOIndData(short* ind, const int index)
{
if (ind == NULL) return;
ind[index * 6 + 0] = (short)(index * 4); ind[index * 6 + 1] = (short)(index * 4 + 1); ind[index * 6 + 2] = (short)(index * 4 + 2);
ind[index * 6 + 3] = (short)(index * 4); ind[index * 6 + 4] = (short)(index * 4 + 2); ind[index * 6 + 5] = (short)(index * 4 + 3);
}
void CGLUtils::fillVBOData(float* vert, short* ind, const int index, const float* geomData, const int geomDataCoordCnt, const float offset)
{
if (vert == NULL || ind == NULL || geomData == NULL) return;
if (geomDataCoordCnt < 1 || geomDataCoordCnt > 3) return;
int X = (int)geomData[index * geomDataCoordCnt + 0];
int Y = (int)geomData[index * geomDataCoordCnt + 1];
int Z = (int)geomData[index * geomDataCoordCnt + 2];
if (geomDataCoordCnt == 1)
{
X = (int)geomData[index * geomDataCoordCnt + 0];
Y = 0;
Z = 0;
}
if (geomDataCoordCnt == 2)
{
X = (int)geomData[index * geomDataCoordCnt + 0];
Y = (int)geomData[index * geomDataCoordCnt + 1];
Z = 0;
}
vert[index * 3 + 0] = X; vert[index * 3 + 1] = Y; vert[index * 3 + 2] = Z;
ind[index] = index;
}
CGLUtils::CGLUtils()
{
}
CGLUtils::~CGLUtils()
{
if (quad) delete quad;
if (lQuad) delete lQuad;
if (revQuad) delete revQuad;
if (QuadNode) delete QuadNode;
if (revQuadNode) delete revQuadNode;
}
CGLUtils* CGLUtils::GetInstance()
{
if (instance == NULL)
{
instance = new CGLUtils();
}
return instance;
}
void CGLUtils::resizeWindow()
{
glViewport(0, 0, CVideoManeger::scrWidth, CVideoManeger::scrHeight);
if (QuadNode)
{
GLfloat qverts[] = { 0, 0, 0, CVideoManeger::scrWidth, 0, 0, CVideoManeger::scrWidth, CVideoManeger::scrHeight, 0, 0, CVideoManeger::scrHeight, 0 };
QuadNode->getVBOForModify()->setVerticesData(qverts, 4 * 3);
}
if (revQuadNode)
{
GLfloat qverts[] = { 0, 0, 0, CVideoManeger::scrWidth, 0, 0, CVideoManeger::scrWidth, CVideoManeger::scrHeight, 0, 0, CVideoManeger::scrHeight, 0 };
revQuadNode->getVBOForModify()->setVerticesData(qverts, 4 * 3);
}
}
| 37.394402
| 163
| 0.62187
|
AntonBogomolov
|
8c30e0dc1e6c398403e44f85fb9ee154f306f186
| 2,165
|
cc
|
C++
|
chrome/browser/media/router/mojo/media_router_mojo_metrics_unittest.cc
|
google-ar/chromium
|
2441c86a5fd975f09a6c30cddb57dfb7fc239699
|
[
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 777
|
2017-08-29T15:15:32.000Z
|
2022-03-21T05:29:41.000Z
|
chrome/browser/media/router/mojo/media_router_mojo_metrics_unittest.cc
|
harrymarkovskiy/WebARonARCore
|
2441c86a5fd975f09a6c30cddb57dfb7fc239699
|
[
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 66
|
2017-08-30T18:31:18.000Z
|
2021-08-02T10:59:35.000Z
|
chrome/browser/media/router/mojo/media_router_mojo_metrics_unittest.cc
|
harrymarkovskiy/WebARonARCore
|
2441c86a5fd975f09a6c30cddb57dfb7fc239699
|
[
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 123
|
2017-08-30T01:19:34.000Z
|
2022-03-17T22:55:31.000Z
|
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/media/router/mojo/media_router_mojo_metrics.h"
#include "base/version.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace media_router {
TEST(MediaRouterMojoMetricsTest, TestGetMediaRouteProviderVersion) {
const base::Version kBrowserVersion("50.0.2396.71");
EXPECT_EQ(MediaRouteProviderVersion::SAME_VERSION_AS_CHROME,
MediaRouterMojoMetrics::GetMediaRouteProviderVersion(
base::Version("50.0.2396.71"), kBrowserVersion));
EXPECT_EQ(MediaRouteProviderVersion::SAME_VERSION_AS_CHROME,
MediaRouterMojoMetrics::GetMediaRouteProviderVersion(
base::Version("50.0.2100.0"), kBrowserVersion));
EXPECT_EQ(MediaRouteProviderVersion::SAME_VERSION_AS_CHROME,
MediaRouterMojoMetrics::GetMediaRouteProviderVersion(
base::Version("51.0.2117.0"), kBrowserVersion));
EXPECT_EQ(MediaRouteProviderVersion::ONE_VERSION_BEHIND_CHROME,
MediaRouterMojoMetrics::GetMediaRouteProviderVersion(
base::Version("49.0.2138.0"), kBrowserVersion));
EXPECT_EQ(MediaRouteProviderVersion::MULTIPLE_VERSIONS_BEHIND_CHROME,
MediaRouterMojoMetrics::GetMediaRouteProviderVersion(
base::Version("47.0.1134.0"), kBrowserVersion));
EXPECT_EQ(MediaRouteProviderVersion::UNKNOWN,
MediaRouterMojoMetrics::GetMediaRouteProviderVersion(
base::Version("blargh"), kBrowserVersion));
EXPECT_EQ(MediaRouteProviderVersion::UNKNOWN,
MediaRouterMojoMetrics::GetMediaRouteProviderVersion(
base::Version(""), kBrowserVersion));
EXPECT_EQ(MediaRouteProviderVersion::UNKNOWN,
MediaRouterMojoMetrics::GetMediaRouteProviderVersion(
base::Version("-1.0.0.0"), kBrowserVersion));
EXPECT_EQ(MediaRouteProviderVersion::UNKNOWN,
MediaRouterMojoMetrics::GetMediaRouteProviderVersion(
base::Version("0"), kBrowserVersion));
}
} // namespace media_router
| 49.204545
| 73
| 0.728868
|
google-ar
|
8c32011a805538118756eb62bf63bb51db53a544
| 377
|
cc
|
C++
|
below2.1/speeding.cc
|
danzel-py/Kattis-Problem-Archive
|
bce1929d654b1bceb104f96d68c74349273dd1ff
|
[
"Apache-2.0"
] | null | null | null |
below2.1/speeding.cc
|
danzel-py/Kattis-Problem-Archive
|
bce1929d654b1bceb104f96d68c74349273dd1ff
|
[
"Apache-2.0"
] | null | null | null |
below2.1/speeding.cc
|
danzel-py/Kattis-Problem-Archive
|
bce1929d654b1bceb104f96d68c74349273dd1ff
|
[
"Apache-2.0"
] | null | null | null |
#include <iostream>
using namespace std;
int main(){
int nu;
cin>>nu;
int t,p;
cin>>t>>p;
int mem, memp;
int max = 0;
for (int i = 0; i < nu-1; i++)
{
mem = t;
memp = p;
cin>>t>>p;
if((p - memp)/(t-mem)>max){
max = (p - memp)/(t-mem);
}
}
cout<<max;
return 0;
}
| 15.08
| 37
| 0.37931
|
danzel-py
|
8c38b1f3f05a74824dc7ef74d8f65ded63d62a3a
| 263
|
hpp
|
C++
|
tools/mem_usage/mem_usage.hpp
|
LioQing/personal-utils
|
e24d1ea1510087797c6b85bae89a3801a2e77f3d
|
[
"Unlicense"
] | null | null | null |
tools/mem_usage/mem_usage.hpp
|
LioQing/personal-utils
|
e24d1ea1510087797c6b85bae89a3801a2e77f3d
|
[
"Unlicense"
] | null | null | null |
tools/mem_usage/mem_usage.hpp
|
LioQing/personal-utils
|
e24d1ea1510087797c6b85bae89a3801a2e77f3d
|
[
"Unlicense"
] | null | null | null |
#pragma once
#include <cstdint>
namespace lio
{
enum MemArgs : uint8_t
{
USAGE = 0b001,
COUNT = 0b010,
PEAK = 0b100
};
extern size_t memory_count;
extern size_t memory_used;
extern size_t memory_peak;
void print_mem_isage(uint8_t args = USAGE);
}
| 13.842105
| 44
| 0.714829
|
LioQing
|
8c4025d9dbd5731fa3083db7d2c4fd5895e88a69
| 4,798
|
cpp
|
C++
|
Framework/Math/Scissor.cpp
|
dengwenyi88/Deferred_Lighting
|
b45b6590150a3119b0c2365f4795d93b3b4f0748
|
[
"MIT"
] | 110
|
2017-06-23T17:12:28.000Z
|
2022-02-22T19:11:38.000Z
|
RunTest/Framework3/Math/Scissor.cpp
|
dtrebilco/ECSAtto
|
86a04f0bdc521c79f758df94250c1898c39213c8
|
[
"MIT"
] | null | null | null |
RunTest/Framework3/Math/Scissor.cpp
|
dtrebilco/ECSAtto
|
86a04f0bdc521c79f758df94250c1898c39213c8
|
[
"MIT"
] | 3
|
2018-02-12T00:16:18.000Z
|
2018-02-18T11:12:35.000Z
|
/* * * * * * * * * * * * * Author's note * * * * * * * * * * * *\
* _ _ _ _ _ _ _ _ _ _ _ _ *
* |_| |_| |_| |_| |_|_ _|_| |_| |_| _|_|_|_|_| *
* |_|_ _ _|_| |_| |_| |_|_|_|_|_| |_| |_| |_|_ _ _ *
* |_|_|_|_|_| |_| |_| |_| |_| |_| |_| |_| |_|_|_|_ *
* |_| |_| |_|_ _ _|_| |_| |_| |_|_ _ _|_| _ _ _ _|_| *
* |_| |_| |_|_|_| |_| |_| |_|_|_| |_|_|_|_| *
* *
* http://www.humus.name *
* *
* This file is a part of the work done by Humus. You are free to *
* use the code in any way you like, modified, unmodified or copied *
* into your own work. However, I expect you to respect these points: *
* - If you use this file and its contents unmodified, or use a major *
* part of this file, please credit the author and leave this note. *
* - For use in anything commercial, please request my approval. *
* - Share your work and ideas too as much as you can. *
* *
\* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#include "Scissor.h"
/*
bool getScissorRectangle(const mat4 &projection, const mat4 &modelview, const vec3 &camPos, const vec3 &lightPos, const float radius, const int width, const int height, int *x, int *y, int *w, int *h){
float d = distance(camPos, lightPos);
float p = d * radius / sqrtf(d * d - radius * radius);
vec3 dx = modelview.rows[0].xyz();
vec3 dy = modelview.rows[1].xyz();
// vec3 dz = normalize(lightPos - camPos);
// dx = cross(dy, dz);
// dy = cross(dz, dx);
vec3 dz = normalize(lightPos - camPos);
vec3 dx = normalize(vec3(dz.z, 0, -dz.x));
vec3 dy = normalize(cross(dz, dx));
vec4 leftPos = vec4(lightPos - p * dx, 1.0f);
vec4 rightPos = vec4(lightPos + p * dx, 1.0f);
mat4 mvp = projection * modelview;
leftPos = mvp * leftPos;
rightPos = mvp * rightPos;
int left = int(width * (leftPos.x / leftPos.z * 0.5f + 0.5f));
int right = int(width * (rightPos.x / rightPos.z * 0.5f + 0.5f));
*x = left;
*w = right - left;
*y = 0;
*h = height;
return true;
}
*/
#define EPSILON 0.0005f
bool getScissorRectangle(const mat4 &modelview, const vec3 &pos, const float radius, const float fov, const int width, const int height, int *x, int *y, int *w, int *h){
vec4 lightPos = modelview * vec4(pos, 1.0f);
float ex = tanf(fov / 2);
float ey = ex * height / width;
float Lxz = (lightPos.x * lightPos.x + lightPos.z * lightPos.z);
float a = -radius * lightPos.x / Lxz;
float b = (radius * radius - lightPos.z * lightPos.z) / Lxz;
float f = -b + a * a;
float lp = 0;
float rp = 1;
float bp = 0;
float tp = 1;
// if (f > EPSILON){
if (f > 0){
float Nx0 = -a + sqrtf(f);
float Nx1 = -a - sqrtf(f);
float Nz0 = (radius - Nx0 * lightPos.x) / lightPos.z;
float Nz1 = (radius - Nx1 * lightPos.x) / lightPos.z;
float x0 = 0.5f * (1 - Nz0 / (Nx0 * ex));
float x1 = 0.5f * (1 - Nz1 / (Nx1 * ex));
float Pz0 = (Lxz - radius * radius) / (lightPos.z - lightPos.x * Nz0 / Nx0);
float Pz1 = (Lxz - radius * radius) / (lightPos.z - lightPos.x * Nz1 / Nx1);
float Px0 = -(Pz0 * Nz0) / Nx0;
float Px1 = -(Pz1 * Nz1) / Nx1;
if (Px0 > lightPos.x) rp = x0;
if (Px0 < lightPos.x) lp = x0;
if (Px1 > lightPos.x && x1 < rp) rp = x1;
if (Px1 < lightPos.x && x1 > lp) lp = x1;
}
float Lyz = (lightPos.y * lightPos.y + lightPos.z * lightPos.z);
a = -radius * lightPos.y / Lyz;
b = (radius * radius - lightPos.z * lightPos.z) / Lyz;
f = -b + a * a;
// if (f > EPSILON){
if (f > 0){
float Ny0 = -a + sqrtf(f);
float Ny1 = -a - sqrtf(f);
float Nz0 = (radius - Ny0 * lightPos.y) / lightPos.z;
float Nz1 = (radius - Ny1 * lightPos.y) / lightPos.z;
float y0 = 0.5f * (1 - Nz0 / (Ny0 * ey));
float y1 = 0.5f * (1 - Nz1 / (Ny1 * ey));
float Pz0 = (Lyz - radius * radius) / (lightPos.z - lightPos.y * Nz0 / Ny0);
float Pz1 = (Lyz - radius * radius) / (lightPos.z - lightPos.y * Nz1 / Ny1);
float Py0 = -(Pz0 * Nz0) / Ny0;
float Py1 = -(Pz1 * Nz1) / Ny1;
if (Py0 > lightPos.y) tp = y0;
if (Py0 < lightPos.y) bp = y0;
if (Py1 > lightPos.y && y1 < tp) tp = y1;
if (Py1 < lightPos.y && y1 > bp) bp = y1;
}
lp *= width;
rp *= width;
tp *= height;
bp *= height;
int left = int(lp);
int right = int(rp);
int top = int(tp);
int bottom = int(bp);
if (right <= left || top <= bottom) return false;
*x = min(max(int(left), 0), width - 1);
*y = min(max(int(bottom), 0), height - 1);
*w = min(int(right) - *x, width - *x);
*h = min(int(top) - *y, height - *y);
return (*w > 0 && *h > 0);
}
| 32.418919
| 201
| 0.516048
|
dengwenyi88
|
8c402ea7a19d66f47675ff19cdb33761cb9c5fe1
| 10,767
|
cpp
|
C++
|
app/src/main/jni/comitton/PdfCrypt.cpp
|
mryp/ComittoNxA
|
9b46c267bff22c2090d75ac70b589f9a12d61457
|
[
"Unlicense"
] | 14
|
2020-08-05T09:36:01.000Z
|
2022-02-23T01:48:18.000Z
|
app/src/main/jni/comitton/PdfCrypt.cpp
|
yuma2a/ComittoNxA-Continued
|
9d85c4f5753e534c3ff0cf83fe53df588872c8ff
|
[
"Unlicense"
] | 1
|
2021-11-13T14:23:07.000Z
|
2021-11-13T14:23:07.000Z
|
app/src/main/jni/comitton/PdfCrypt.cpp
|
mryp/ComittoNxA
|
9b46c267bff22c2090d75ac70b589f9a12d61457
|
[
"Unlicense"
] | 4
|
2021-04-21T02:56:50.000Z
|
2021-11-08T12:02:32.000Z
|
/*
MD5C.C - RSA Data Security, Inc., MD5 message-digest algorithm
Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991.
All rights reserved.
License to copy and use this software is granted provided that it
is identified as the "RSA Data Security, Inc. MD5 Message-Digest
Algorithm" in all material mentioning or referencing this software
or this function.
License is also granted to make and use derivative works provided
that such works are identified as "derived from the RSA Data
Security, Inc. MD5 Message-Digest Algorithm" in all material
mentioning or referencing the derived work.
RSA Data Security, Inc. makes no representations concerning either
the merchantability of this software or the suitability of this
software for any particular purpose. It is provided "as is"
without express or implied warranty of any kind.
These notices must be retained in any copies of any part of this
documentation and/or software.
*/
//#include "fitz-internal.h"
#include <string.h>
#include <android/log.h>
#include "PdfCrypt.h"
//#define DEBUG
/*
* Compute an encryption key (PDF 1.7 algorithm 3.2)
*/
static const unsigned char padding[32] =
{
0x28, 0xbf, 0x4e, 0x5e, 0x4e, 0x75, 0x8a, 0x41,
0x64, 0x00, 0x4e, 0x56, 0xff, 0xfa, 0x01, 0x08,
0x2e, 0x2e, 0x00, 0xb6, 0xd0, 0x68, 0x3e, 0x80,
0x2f, 0x0c, 0xa9, 0xfe, 0x64, 0x53, 0x69, 0x7a
};
/*
* PDF 1.7 algorithm 3.1 and ExtensionLevel 3 algorithm 3.1a
*
* Using the global encryption key that was generated from the
* password, create a new key that is used to decrypt individual
* objects and streams. This key is based on the object and
* generation numbers.
*/
int computeObjectKey(int method, BYTE *crypt_key, int crypt_len, int num, int gen, BYTE *res_key)
{
fz_md5 md5;
unsigned char message[5];
if (method == PDF_CRYPT_AESV3) {
memcpy(res_key, crypt_key, crypt_len / 8);
return crypt_len / 8;
}
fz_md5_init(&md5);
fz_md5_update(&md5, crypt_key, crypt_len / 8);
message[0] = (num) & 0xFF;
message[1] = (num >> 8) & 0xFF;
message[2] = (num >> 16) & 0xFF;
message[3] = (gen) & 0xFF;
message[4] = (gen >> 8) & 0xFF;
fz_md5_update(&md5, message, 5);
if (method == PDF_CRYPT_AESV2) {
fz_md5_update(&md5, (unsigned char *)"sAlT", 4);
}
fz_md5_final(&md5, res_key);
if (crypt_len / 8 + 5 > 16) {
return 16;
}
return crypt_len / 8 + 5;
}
static void
pdf_compute_encryption_key(pdf_crypt *crypt, unsigned char *password, int pwlen, unsigned char *key)
{
#ifdef DEBUG
LOGD("pdf_compute_encryption_key");
#endif
unsigned char buf[32];
unsigned int p;
int i, n;
fz_md5 md5;
n = crypt->length / 8;
/* Step 1 - copy and pad password string */
if (pwlen > 32)
pwlen = 32;
memcpy(buf, password, pwlen);
memcpy(buf + pwlen, padding, 32 - pwlen);
#ifdef DEBUG
LOGD("pdf_compute_encryption_key: 1-buf=%d,%d,%d,%d,%d,%d..., n=%d", (int)buf[0], (int)buf[1], (int)buf[2], (int)buf[3], (int)buf[4], (int)buf[5], n);
#endif
/* Step 2 - init md5 and pass value of step 1 */
fz_md5_init(&md5);
fz_md5_update(&md5, buf, 32);
#ifdef DEBUG
LOGD("pdf_compute_encryption_key: 2-buf=%d,%d,%d,%d,%d,%d..., n=%d", (int)buf[0], (int)buf[1], (int)buf[2], (int)buf[3], (int)buf[4], (int)buf[5], n);
#endif
/* Step 3 - pass O value */
fz_md5_update(&md5, crypt->o, 32);
/* Step 4 - pass P value as unsigned int, low-order byte first */
p = (unsigned int) crypt->p;
buf[0] = (p) & 0xFF;
buf[1] = (p >> 8) & 0xFF;
buf[2] = (p >> 16) & 0xFF;
buf[3] = (p >> 24) & 0xFF;
fz_md5_update(&md5, buf, 4);
#ifdef DEBUG
LOGD("pdf_compute_encryption_key: 3-buf=%d,%d,%d,%d,%d,%d..., n=%d", (int)buf[0], (int)buf[1], (int)buf[2], (int)buf[3], (int)buf[4], (int)buf[5], n);
#endif
/* Step 5 - pass first element of ID array */
fz_md5_update(&md5, crypt->id, crypt->id_len);
#ifdef DEBUG
LOGD("pdf_compute_encryption_key: id=%s,%d", crypt->id, crypt->id_len);
#endif
/* Step 6 (revision 4 or greater) - if metadata is not encrypted pass 0xFFFFFFFF */
if (crypt->r >= 4)
{
if (!crypt->encrypt_metadata)
{
buf[0] = 0xFF;
buf[1] = 0xFF;
buf[2] = 0xFF;
buf[3] = 0xFF;
fz_md5_update(&md5, buf, 4);
}
}
/* Step 7 - finish the hash */
fz_md5_final(&md5, buf);
#ifdef DEBUG
LOGD("pdf_compute_encryption_key: 4-buf=%d,%d,%d,%d,%d,%d..., n=%d", (int)buf[0], (int)buf[1], (int)buf[2], (int)buf[3], (int)buf[4], (int)buf[5], n);
#endif
/* Step 8 (revision 3 or greater) - do some voodoo 50 times */
if (crypt->r >= 3)
{
for (i = 0; i < 50; i++)
{
fz_md5_init(&md5);
fz_md5_update(&md5, buf, n);
fz_md5_final(&md5, buf);
}
}
/* Step 9 - the key is the first 'n' bytes of the result */
#ifdef DEBUG
LOGD("pdf_compute_encryption_key: 5-buf=%d,%d,%d,%d,%d,%d..., n=%d", (int)buf[0], (int)buf[1], (int)buf[2], (int)buf[3], (int)buf[4], (int)buf[5], n);
#endif
memcpy(key, buf, n);
}
/*
* Compute an encryption key (PDF 1.7 ExtensionLevel 3 algorithm 3.2a)
*/
static void
pdf_compute_encryption_key_r5(pdf_crypt *crypt, unsigned char *password, int pwlen, int ownerkey, unsigned char *validationkey)
{
unsigned char buffer[128 + 8 + 48];
fz_sha256 sha256;
fz_aes aes;
/* Step 2 - truncate UTF-8 password to 127 characters */
if (pwlen > 127)
pwlen = 127;
/* Step 3/4 - test password against owner/user key and compute encryption key */
memcpy(buffer, password, pwlen);
if (ownerkey)
{
memcpy(buffer + pwlen, crypt->o + 32, 8);
memcpy(buffer + pwlen + 8, crypt->u, 48);
}
else
memcpy(buffer + pwlen, crypt->u + 32, 8);
fz_sha256_init(&sha256);
fz_sha256_update(&sha256, buffer, pwlen + 8 + (ownerkey ? 48 : 0));
fz_sha256_final(&sha256, validationkey);
/* Step 3.5/4.5 - compute file encryption key from OE/UE */
memcpy(buffer + pwlen, crypt->u + 40, 8);
fz_sha256_init(&sha256);
fz_sha256_update(&sha256, buffer, pwlen + 8);
fz_sha256_final(&sha256, buffer);
/* clear password buffer and use it as iv */
memset(buffer + 32, 0, sizeof(buffer) - 32);
aes_setkey_dec(&aes, buffer, crypt->length);
aes_crypt_cbc(&aes, AES_DECRYPT, 32, buffer + 32, ownerkey ? crypt->oe : crypt->ue, crypt->key);
}
/*
* Computing the user password (PDF 1.7 algorithm 3.4 and 3.5)
* Also save the generated key for decrypting objects and streams in crypt->key.
*/
static void
pdf_compute_user_password(pdf_crypt *crypt, unsigned char *password, int pwlen, unsigned char *output)
{
#ifdef DEBUG
LOGD("pdf_compute_user_password: r=%d", crypt->r);
#endif
if (crypt->r == 2)
{
fz_arc4 arc4;
#ifdef DEBUG
LOGD("r==2", crypt->r);
#endif
pdf_compute_encryption_key(crypt, password, pwlen, crypt->key);
fz_arc4_init(&arc4, crypt->key, crypt->length / 8);
fz_arc4_encrypt(&arc4, output, padding, 32);
}
if (crypt->r == 3 || crypt->r == 4)
{
unsigned char xors[32];
unsigned char digest[16];
fz_md5 md5;
fz_arc4 arc4;
int i, x, n;
n = crypt->length / 8;
pdf_compute_encryption_key(crypt, password, pwlen, crypt->key);
fz_md5_init(&md5);
fz_md5_update(&md5, padding, 32);
fz_md5_update(&md5, crypt->id, crypt->id_len);
fz_md5_final(&md5, digest);
fz_arc4_init(&arc4, crypt->key, n);
fz_arc4_encrypt(&arc4, output, digest, 16);
for (x = 1; x <= 19; x++)
{
for (i = 0; i < n; i++)
xors[i] = crypt->key[i] ^ x;
fz_arc4_init(&arc4, xors, n);
fz_arc4_encrypt(&arc4, output, output, 16);
}
memcpy(output + 16, padding, 16);
}
if (crypt->r == 5)
{
pdf_compute_encryption_key_r5(crypt, password, pwlen, 0, output);
}
}
/*
* Authenticating the user password (PDF 1.7 algorithm 3.6
* and ExtensionLevel 3 algorithm 3.11)
* This also has the side effect of saving a key generated
* from the password for decrypting objects and streams.
*/
static int
pdf_authenticate_user_password(pdf_crypt *crypt, unsigned char *password, int pwlen)
{
#ifdef DEBUG
LOGD("pdf_authenticate_user_password");
#endif
unsigned char output[32];
pdf_compute_user_password(crypt, password, pwlen, output);
if (crypt->r == 2 || crypt->r == 5)
return memcmp(output, crypt->u, 32) == 0;
if (crypt->r == 3 || crypt->r == 4)
return memcmp(output, crypt->u, 16) == 0;
return 0;
}
/*
* Authenticating the owner password (PDF 1.7 algorithm 3.7
* and ExtensionLevel 3 algorithm 3.12)
* Generates the user password from the owner password
* and calls pdf_authenticate_user_password.
*/
static int
pdf_authenticate_owner_password(pdf_crypt *crypt, unsigned char *ownerpass, int pwlen)
{
unsigned char pwbuf[32];
unsigned char key[32];
unsigned char xors[32];
unsigned char userpass[32];
int i, n, x;
fz_md5 md5;
fz_arc4 arc4;
if (crypt->r == 5)
{
/* PDF 1.7 ExtensionLevel 3 algorithm 3.12 */
pdf_compute_encryption_key_r5(crypt, ownerpass, pwlen, 1, key);
return !memcmp(key, crypt->o, 32);
}
n = crypt->length / 8;
/* Step 1 -- steps 1 to 4 of PDF 1.7 algorithm 3.3 */
/* copy and pad password string */
if (pwlen > 32)
pwlen = 32;
memcpy(pwbuf, ownerpass, pwlen);
memcpy(pwbuf + pwlen, padding, 32 - pwlen);
/* take md5 hash of padded password */
fz_md5_init(&md5);
fz_md5_update(&md5, pwbuf, 32);
fz_md5_final(&md5, key);
/* do some voodoo 50 times (Revision 3 or greater) */
if (crypt->r >= 3)
{
for (i = 0; i < 50; i++)
{
fz_md5_init(&md5);
fz_md5_update(&md5, key, 16);
fz_md5_final(&md5, key);
}
}
/* Step 2 (Revision 2) */
if (crypt->r == 2)
{
fz_arc4_init(&arc4, key, n);
fz_arc4_encrypt(&arc4, userpass, crypt->o, 32);
}
/* Step 2 (Revision 3 or greater) */
if (crypt->r >= 3)
{
memcpy(userpass, crypt->o, 32);
for (x = 0; x < 20; x++)
{
for (i = 0; i < n; i++)
xors[i] = key[i] ^ (19 - x);
fz_arc4_init(&arc4, xors, n);
fz_arc4_encrypt(&arc4, userpass, userpass, 32);
}
}
return pdf_authenticate_user_password(crypt, userpass, 32);
}
int
pdf_authenticate_password(pdf_crypt *crypt, char *password)
{
#ifdef DEBUG
LOGD("pdf_authenticate_password");
#endif
if (crypt)
{
if (!password)
password = (char*)"";
if (pdf_authenticate_user_password(crypt, (unsigned char *)password, strlen(password)))
return 1;
if (pdf_authenticate_owner_password(crypt, (unsigned char *)password, strlen(password)))
return 1;
return 0;
}
return 1;
}
int
pdf_needs_password(pdf_crypt *crypt)
{
if (!crypt)
return 0;
if (pdf_authenticate_password(crypt, (char*)""))
return 0;
return 1;
}
int
pdf_has_permission(pdf_crypt *crypt, int p)
{
if (!crypt)
return 1;
return crypt->p & p;
}
unsigned char *
pdf_crypt_key(pdf_crypt *crypt)
{
if (crypt)
return crypt->key;
return NULL;
}
int
pdf_crypt_version(pdf_crypt *crypt)
{
if (crypt)
return crypt->v;
return 0;
}
int pdf_crypt_revision(pdf_crypt *crypt)
{
if (crypt)
return crypt->r;
return 0;
}
int
pdf_crypt_length(pdf_crypt *crypt)
{
if (crypt)
return crypt->length;
return 0;
}
| 24.414966
| 151
| 0.665181
|
mryp
|
8c4362e959450f80b6bf82e2f1ed5afb88ab06c5
| 13,332
|
cpp
|
C++
|
src/ui/inspectMode.cpp
|
averrin/lss
|
c2aa0486641fba15daceab3241122e387720c898
|
[
"MIT"
] | 4
|
2018-07-09T20:53:06.000Z
|
2018-07-12T07:10:19.000Z
|
src/ui/inspectMode.cpp
|
averrin/lss
|
c2aa0486641fba15daceab3241122e387720c898
|
[
"MIT"
] | null | null | null |
src/ui/inspectMode.cpp
|
averrin/lss
|
c2aa0486641fba15daceab3241122e387720c898
|
[
"MIT"
] | null | null | null |
#include "ui/inspectMode.hpp"
#include "ui/LSSApp.hpp"
#include "ui/fragment.hpp"
#include "lss/generator/room.hpp"
#include "lss/utils.hpp"
#include "ui/utils.hpp"
auto F = [](std::string c) { return std::make_shared<Fragment>(c); };
bool InspectMode::processKey(KeyEvent event) {
switch (event.getCode()) {
case SDL_SCANCODE_S:
highlightWhoCanSee = !highlightWhoCanSee;
app->state->invalidateSelection("change view mode");
render();
return true;
case SDL_SCANCODE_R:
showRooms = !showRooms;
app->state->invalidateSelection("change view mode");
render();
return true;
case SDL_SCANCODE_J:
case SDL_SCANCODE_H:
case SDL_SCANCODE_L:
if (event.isShiftDown()) {
showLightSources = !showLightSources;
app->state->invalidateSelection("change view mode");
render();
return true;
}
case SDL_SCANCODE_K:
case SDL_SCANCODE_Y:
case SDL_SCANCODE_U:
case SDL_SCANCODE_B:
case SDL_SCANCODE_N: {
auto d = ui_utils::getDir(event.getCode());
if (d == std::nullopt)
break;
auto nc = app->hero->currentLocation->getCell(
app->hero->currentLocation
->cells[app->state->cursor.y][app->state->cursor.x],
*utils::getDirectionByName(*d));
if (!nc)
break;
app->state->selectionClear();
app->state->setCursor({(*nc)->x, (*nc)->y});
render();
return true;
} break;
}
return false;
}
void InspectMode::render() {
auto location = app->hero->currentLocation;
auto cell = location->cells[app->state->cursor.y][app->state->cursor.x];
auto objects = location->getObjects(cell);
auto cc = app->hero->currentCell;
auto check = "<span color='green'>✔</span>";
app->state->selection.clear();
auto line = location->getLine(app->hero->currentCell, cell);
for (auto c : line) {
app->state->setSelection({{c->x, c->y}, COLORS::CURSOR_TRACE});
}
app->inspectState->setContent(
{F(fmt::format("Selected cell: <b>{}.{}</b>", cell->x, cell->y))});
app->inspectState->appendContent(State::END_LINE);
auto vs = "UNKNOWN";
if (cell->visibilityState == VisibilityState::SEEN) {
vs = "SEEN";
} else if (cell->visibilityState == VisibilityState::VISIBLE) {
vs = "VISISBLE";
}
app->inspectState->appendContent(
{F(fmt::format("Visibility state: <b>{}</b>", vs))});
app->inspectState->appendContent(State::END_LINE);
if (!app->debug && !app->hero->canSee(cell)) {
app->inspectState->appendContent(
{F(fmt::format("You cannot see this cell"))});
app->inspectState->appendContent(State::END_LINE);
return;
}
app->inspectState->appendContent(
{F(fmt::format("Type: <b>{}</b>", cell->type.name))});
app->inspectState->appendContent(State::END_LINE);
if (cell->type == CellType::UNKNOWN)
return;
app->inspectState->appendContent(
{F(fmt::format("Type <b>PASS</b>THROUGH: [<b>{}</b>]",
cell->type.passThrough ? check : " "))});
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent(
{F(fmt::format("Type <b>SEE</b>THROUGH: [<b>{}</b>]",
cell->type.passThrough ? check : " "))});
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent({F(fmt::format(
"<b>PASS</b>THROUGH: [<b>{}</b>]", cell->passThrough ? check : " "))});
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent({F(fmt::format(
"<b>SEE</b>THROUGH: [<b>{}</b>]", cell->passThrough ? check : " "))});
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent({F(fmt::format(
"Illuminated: [<b>{}</b>]", cell->illuminated ? check : " "))});
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent(
{F(fmt::format("Illumination: <b>{}</b>", cell->illumination))});
app->inspectState->appendContent(State::END_LINE);
auto f = app->state->fragments[cell->y * app->state->width + cell->x];
// app->inspectState->appendContent({F(fmt::format(
// "Cell Illumination: <b>{}</b>", f->alpha))});
// app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent({F(
fmt::format("Cell features count: <b>{}</b>", cell->features.size()))});
app->inspectState->appendContent(State::END_LINE);
if (cell->features.size() > 0) {
app->inspectState->appendContent({F("<b>Cell Features</b>")});
app->inspectState->appendContent(State::END_LINE);
}
for (auto f : cell->features) {
if (f == CellFeature::BLOOD) {
app->inspectState->appendContent(
{F(fmt::format("BLOOD: [<b>{}</b>]", check))});
}
if (f == CellFeature::CAVE) {
app->inspectState->appendContent(
{F(fmt::format("CAVE: [<b>{}</b>]", check))});
}
if (f == CellFeature::ACID) {
app->inspectState->appendContent(
{F(fmt::format("ACID: [<b>{}</b>]", check))});
}
if (f == CellFeature::FROST) {
app->inspectState->appendContent(
{F(fmt::format("FROST: [<b>{}</b>]", check))});
}
app->inspectState->appendContent(State::END_LINE);
}
app->inspectState->appendContent(State::END_LINE);
if (cell->room == nullptr) {
app->inspectState->appendContent(
{F(fmt::format("<b>Room is nullptr!</b>"))});
app->inspectState->appendContent(State::END_LINE);
} else {
app->inspectState->appendContent(
{F(fmt::format("Room @ <b>{}.{} [{}x{}]</b>", cell->room->x,
cell->room->y, cell->room->width, cell->room->height))});
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent(
{F(fmt::format("HALL: [<b>{}</b>]",
cell->room->type == RoomType::HALL ? check : " "))});
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent(
{F(fmt::format("PASSAGE: [<b>{}</b>]",
cell->room->type == RoomType::PASSAGE ? check : " "))});
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent({F(fmt::format(
"Room features count: <b>{}</b>", cell->room->features.size()))});
app->inspectState->appendContent(State::END_LINE);
if (app->debug && showRooms) {
for (auto c : cell->room->cells) {
app->state->selection.push_back({{c->x, c->y}, "#811"});
}
}
if (cell->room->features.size() > 0) {
app->inspectState->appendContent({F("<b>Room Features</b>")});
app->inspectState->appendContent(State::END_LINE);
}
for (auto f : cell->room->features) {
if (f == RoomFeature::DUNGEON) {
app->inspectState->appendContent(
{F(fmt::format("DUNGEON: [<b>{}</b>]", check))});
}
if (f == RoomFeature::CAVE) {
app->inspectState->appendContent(
{F(fmt::format("CAVE: [<b>{}</b>]", check))});
}
app->inspectState->appendContent(State::END_LINE);
}
app->inspectState->appendContent(State::END_LINE);
}
app->inspectState->appendContent(
{F(fmt::format("Light sources: <b>{}</b>", cell->lightSources.size()))});
if (showLightSources) {
for (auto ls : cell->lightSources) {
auto c = ls->currentCell;
app->state->selection.push_back({{c->x, c->y}, "#1f1"});
}
}
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent({F(fmt::format(
"Hero: [<b>{}</b>]", cell == app->hero->currentCell ? check : " "))});
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent(
{F(fmt::format("Hero can <b>pass</b>: [<b>{}</b>]",
cell->canPass(app->hero->traits) ? check : " "))});
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent(
{F(fmt::format("Hero can <b>see</b>: [<b>{}</b>]",
app->hero->canSee(cell) ? check : " "))});
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent({F(
fmt::format("Distance to hero: <b>{}</b>",
sqrt(pow(cc->x - cell->x, 2) + pow(cc->y - cell->y, 2))))});
app->inspectState->appendContent(State::END_LINE);
if (cell->type == CellType::WALL)
return;
auto allEnemies = utils::castObjects<Enemy>(location->objects);
for (auto e : allEnemies) {
if (e->canSee(cell) && highlightWhoCanSee) {
app->inspectState->appendContent(
{F(fmt::format("<b>{} @ {}.{}</b> can see: [<b>{}</b>]", e->type.name,
e->currentCell->x, e->currentCell->y,
e->canSee(cell) ? check : " "))});
app->state->selection.push_back(
{{e->currentCell->x, e->currentCell->y}, "#aaaa88"});
app->inspectState->appendContent(State::END_LINE);
}
}
app->inspectState->appendContent(
{F(fmt::format("Objects count: <b>{}</b>", objects.size()))});
app->inspectState->appendContent(State::END_LINE);
if (objects.size() > 0) {
auto isDoor = utils::castObjects<Door>(objects).size() > 0;
app->inspectState->appendContent(
{F(fmt::format("Door: [<b>{}</b>]", isDoor ? check : " "))});
app->inspectState->appendContent(State::END_LINE);
// auto isTorch = utils::castObjects<TorchStand>(objects).size() > 0;
// app->inspectState->appendContent(
// {F(fmt::format("Torch: [<b>{}</b>]", isTorch ? check : " "))});
// app->inspectState->appendContent(State::END_LINE);
// auto isStatue = utils::castObjects<Statue>(objects).size() > 0;
// app->inspectState->appendContent(
// {F(fmt::format("Statue: [<b>{}</b>]", isStatue ? check : " "))});
// app->inspectState->appendContent(State::END_LINE);
auto enemies = utils::castObjects<Enemy>(objects);
if (enemies.size() > 0) {
std::vector<std::string> enemyNames;
for (auto e : enemies) {
enemyNames.push_back(e->type.name);
app->inspectState->appendContent(
{F(fmt::format("<b>{} @ {}.{}</b> can see HERO: [<b>{}</b>]",
e->type.name, e->currentCell->x, e->currentCell->y,
e->canSee(cc) ? check : " "))});
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent({F(fmt::format(
"Has glow: [<b>{}</b>]", e->hasLight() ? check : " "))});
app->inspectState->appendContent(State::END_LINE);
auto glow = e->getGlow();
if (glow) {
app->inspectState->appendContent(
{F(fmt::format("Light: <b>{}</b>, stable: {}", (*glow).distance,
(*glow).stable))});
app->inspectState->appendContent(State::END_LINE);
}
app->inspectState->appendContent({F(fmt::format(
"<b>HP</b>: {:d}/{:d} ({:d})", int(e->HP(e.get())),
int(e->HP_MAX(e.get())), int(e->hp_max * e->strength)))});
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent(F(fmt::format(
"<b>MP</b>: {:d}/{:d} ({:d})", int(e->MP(e.get())),
int(e->MP_MAX(e.get())), int(e->mp_max * e->intelligence))));
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent(F(fmt::format("<b>Speed</b>: {} ({})",
e->SPEED(e.get()), e->speed)));
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent(F(fmt::format("<b>Defence</b>: {:d}",
int(e->DEF(e.get())))));
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent(
F(fmt::format("<b>Damage</b>: {}", e->getDmgDesc())));
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent({F("Traits:")});
app->inspectState->appendContent(State::END_LINE);
for (auto t : e->traits) {
app->inspectState->appendContent(
{F(fmt::format(" * {}", t.name))});
app->inspectState->appendContent(State::END_LINE);
}
app->inspectState->appendContent({F("Inventory:")});
app->inspectState->appendContent(State::END_LINE);
for (auto s : e->equipment->slots) {
app->inspectState->appendContent({F(fmt::format(
" * {} -- {}", s->name,
s->item != nullptr ? s->item->getTitle(true) : "empty"))});
app->inspectState->appendContent(State::END_LINE);
}
}
app->inspectState->appendContent({F(
fmt::format("Enemies: <b>{}</b>", LibLog::utils::join(enemyNames, ", ")))});
app->inspectState->appendContent(State::END_LINE);
}
auto items = utils::castObjects<Item>(objects);
if (items.size() > 0) {
std::vector<std::string> itemNames;
for (auto i : items) {
itemNames.push_back(i->getFullTitle(true));
}
app->inspectState->appendContent(
{F(fmt::format("Items: <b>{}</b>", LibLog::utils::join(itemNames, ", ")))});
app->inspectState->appendContent(State::END_LINE);
}
}
app->state->invalidateSelection("move inspect cursor");
}
| 41.6625
| 91
| 0.578533
|
averrin
|
8c43e0e106645fcd7d0bdf1e0d71a9925193356b
| 1,551
|
cc
|
C++
|
auxil/binpac/src/pac_datadep.cc
|
hugolin615/zeek-4.0.0-ele420520-spring2021
|
258e9b2ee1f2a4bd45c6332a75304793b7d44d40
|
[
"Apache-2.0"
] | 1
|
2021-03-06T19:51:07.000Z
|
2021-03-06T19:51:07.000Z
|
auxil/binpac/src/pac_datadep.cc
|
hugolin615/zeek-4.0.0-ele420520-spring2021
|
258e9b2ee1f2a4bd45c6332a75304793b7d44d40
|
[
"Apache-2.0"
] | null | null | null |
auxil/binpac/src/pac_datadep.cc
|
hugolin615/zeek-4.0.0-ele420520-spring2021
|
258e9b2ee1f2a4bd45c6332a75304793b7d44d40
|
[
"Apache-2.0"
] | null | null | null |
#include "pac_datadep.h"
#include "pac_expr.h"
#include "pac_id.h"
#include "pac_type.h"
DataDepElement::DataDepElement(DDE_Type type)
: dde_type_(type), in_traversal(false)
{
}
bool DataDepElement::Traverse(DataDepVisitor *visitor)
{
// Avoid infinite loop
if ( in_traversal )
return true;
if ( ! visitor->PreProcess(this) )
return false;
in_traversal = true;
bool cont = DoTraverse(visitor);
in_traversal = false;
if ( ! cont )
return false;
if ( ! visitor->PostProcess(this) )
return false;
return true;
}
Expr *DataDepElement::expr()
{
return static_cast<Expr *>(this);
}
Type *DataDepElement::type()
{
return static_cast<Type *>(this);
}
bool RequiresAnalyzerContext::PreProcess(DataDepElement *element)
{
switch ( element->dde_type() )
{
case DataDepElement::EXPR:
ProcessExpr(element->expr());
break;
default:
break;
}
// Continue traversal until we know the answer is 'yes'
return ! requires_analyzer_context_;
}
bool RequiresAnalyzerContext::PostProcess(DataDepElement *element)
{
return ! requires_analyzer_context_;
}
void RequiresAnalyzerContext::ProcessExpr(Expr *expr)
{
if ( expr->expr_type() == Expr::EXPR_ID )
{
requires_analyzer_context_ =
(requires_analyzer_context_ ||
*expr->id() == *analyzer_context_id ||
*expr->id() == *context_macro_id);
}
}
bool RequiresAnalyzerContext::compute(DataDepElement *element)
{
RequiresAnalyzerContext visitor;
element->Traverse(&visitor);
return visitor.requires_analyzer_context_;
}
| 20.142857
| 66
| 0.704707
|
hugolin615
|
8c44271c7bf0cc4c2dbd268a407221645e9f8866
| 1,296
|
cxx
|
C++
|
Libraries/QtVgCommon/vgSwatchCache.cxx
|
PinkDiamond1/vivia
|
70f7fbed4b33b14d34de35c69b2b14df3514d720
|
[
"BSD-3-Clause"
] | 14
|
2016-09-16T12:33:05.000Z
|
2021-02-14T02:16:33.000Z
|
Libraries/QtVgCommon/vgSwatchCache.cxx
|
PinkDiamond1/vivia
|
70f7fbed4b33b14d34de35c69b2b14df3514d720
|
[
"BSD-3-Clause"
] | 44
|
2016-10-06T22:12:57.000Z
|
2021-01-07T19:39:07.000Z
|
Libraries/QtVgCommon/vgSwatchCache.cxx
|
PinkDiamond1/vivia
|
70f7fbed4b33b14d34de35c69b2b14df3514d720
|
[
"BSD-3-Clause"
] | 17
|
2015-06-30T13:41:47.000Z
|
2021-11-22T17:38:48.000Z
|
// This file is part of ViViA, and is distributed under the
// OSI-approved BSD 3-Clause License. See top-level LICENSE file or
// https://github.com/Kitware/vivia/blob/master/LICENSE for details.
#include "vgSwatchCache.h"
#include <QCache>
#include <QColor>
#include <QPixmap>
QTE_IMPLEMENT_D_FUNC(vgSwatchCache)
//-----------------------------------------------------------------------------
class vgSwatchCachePrivate
{
public:
vgSwatchCachePrivate(int ssize, int csize) :
size(ssize), cache(csize > 0 ? csize : 100) {}
int size;
mutable QCache<quint32, QPixmap> cache;
};
//-----------------------------------------------------------------------------
vgSwatchCache::vgSwatchCache(int swatchSize, int cacheSize) :
d_ptr(new vgSwatchCachePrivate(swatchSize, cacheSize))
{
}
//-----------------------------------------------------------------------------
vgSwatchCache::~vgSwatchCache()
{
}
//-----------------------------------------------------------------------------
QPixmap vgSwatchCache::swatch(const QColor& color) const
{
QTE_D_CONST(vgSwatchCache);
quint32 key = color.rgba();
if (!d->cache.contains(key))
{
QPixmap* pixmap = new QPixmap(d->size, d->size);
pixmap->fill(color);
d->cache.insert(key, pixmap);
}
return *d->cache[key];
}
| 26.44898
| 79
| 0.536265
|
PinkDiamond1
|
8c443728e0b738837b7b6dab96af75f860b10cca
| 21,272
|
cc
|
C++
|
elang/compiler/analysis/method_analyzer_test.cc
|
eval1749/elang
|
5208b386ba3a3e866a5c0f0271280f79f9aac8c4
|
[
"Apache-2.0"
] | 1
|
2018-01-27T22:40:53.000Z
|
2018-01-27T22:40:53.000Z
|
elang/compiler/analysis/method_analyzer_test.cc
|
eval1749/elang
|
5208b386ba3a3e866a5c0f0271280f79f9aac8c4
|
[
"Apache-2.0"
] | 1
|
2016-01-29T00:54:49.000Z
|
2016-01-29T00:54:49.000Z
|
elang/compiler/analysis/method_analyzer_test.cc
|
eval1749/elang
|
5208b386ba3a3e866a5c0f0271280f79f9aac8c4
|
[
"Apache-2.0"
] | null | null | null |
// Copyright 2014-2015 Project Vogue. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <algorithm>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
#include "elang/compiler/analysis/analysis.h"
#include "elang/compiler/analysis/class_analyzer.h"
#include "elang/compiler/analysis/method_analyzer.h"
#include "elang/compiler/analysis/namespace_analyzer.h"
#include "elang/compiler/analysis/name_resolver.h"
#include "elang/compiler/ast/class.h"
#include "elang/compiler/ast/expressions.h"
#include "elang/compiler/ast/factory.h"
#include "elang/compiler/ast/method.h"
#include "elang/compiler/ast/namespace.h"
#include "elang/compiler/ast/query/node_queries.h"
#include "elang/compiler/ast/statements.h"
#include "elang/compiler/ast/visitor.h"
#include "elang/compiler/compilation_session.h"
#include "elang/compiler/modifiers.h"
#include "elang/compiler/namespace_builder.h"
#include "elang/compiler/parameter_kind.h"
#include "elang/compiler/predefined_names.h"
#include "elang/compiler/semantics/factory.h"
#include "elang/compiler/semantics/nodes.h"
#include "elang/compiler/testing/analyzer_test.h"
#include "elang/compiler/token_type.h"
namespace elang {
namespace compiler {
//////////////////////////////////////////////////////////////////////
//
// Collector
//
class Collector final : private ast::Visitor {
public:
explicit Collector(ast::Method* method);
Collector() = default;
const std::vector<ast::Call*>& calls() const { return calls_; }
const std::vector<ast::NamedNode*> variables() const { return variables_; }
private:
// ast::Visitor expressions
void VisitCall(ast::Call* node);
// ast::Visitor statements
void VisitForEachStatement(ast::ForEachStatement* node);
void VisitVarStatement(ast::VarStatement* node);
std::vector<ast::Call*> calls_;
std::vector<ast::NamedNode*> variables_;
DISALLOW_COPY_AND_ASSIGN(Collector);
};
Collector::Collector(ast::Method* method) {
for (auto const parameter : method->parameters())
variables_.push_back(parameter);
auto const body = method->body();
if (!body)
return;
Traverse(body);
}
// ast::Visitor statements
void Collector::VisitForEachStatement(ast::ForEachStatement* node) {
variables_.push_back(node->variable());
ast::Visitor::DoDefaultVisit(node);
}
void Collector::VisitVarStatement(ast::VarStatement* node) {
for (auto const variable : node->variables()) {
variables_.push_back(variable);
auto const value = variable->expression();
if (!value)
continue;
Traverse(value);
}
}
// ast::Visitor expressions
void Collector::VisitCall(ast::Call* node) {
ast::Visitor::DoDefaultVisit(node);
calls_.push_back(node);
}
//////////////////////////////////////////////////////////////////////
//
// MyNamespaceBuilder
// Installs classes and methods for testing.
//
class MyNamespaceBuilder final : public NamespaceBuilder {
public:
explicit MyNamespaceBuilder(NameResolver* name_resolver);
~MyNamespaceBuilder() = default;
void Build();
private:
DISALLOW_COPY_AND_ASSIGN(MyNamespaceBuilder);
};
MyNamespaceBuilder::MyNamespaceBuilder(NameResolver* name_resolver)
: NamespaceBuilder(name_resolver) {
}
void MyNamespaceBuilder::Build() {
// public class Console {
// public static void WriteLine(String string);
// public static void WriteLine(String string, Object object);
// }
auto const console_class = NewClass("Console", "Object");
auto const factory = session()->semantic_factory();
auto const write_line =
factory->NewMethodGroup(console_class, NewName("WriteLine"));
factory->NewMethod(
write_line,
Modifiers(Modifier::Extern, Modifier::Public, Modifier::Static),
factory->NewSignature(SemanticOf("System.Void")->as<sm::Type>(),
{NewParameter(ParameterKind::Required, 0,
"System.String", "string")}));
factory->NewMethod(
write_line,
Modifiers(Modifier::Extern, Modifier::Public, Modifier::Static),
factory->NewSignature(
SemanticOf("System.Void")->as<sm::Type>(),
{NewParameter(ParameterKind::Required, 0, "System.String", "string"),
NewParameter(ParameterKind::Required, 0, "System.Object",
"object")}));
}
//////////////////////////////////////////////////////////////////////
//
// MethodAnalyzerTest
//
class MethodAnalyzerTest : public testing::AnalyzerTest {
protected:
MethodAnalyzerTest() = default;
~MethodAnalyzerTest() override = default;
std::string DumpSemanticTree(ast::Node* node);
// Collect all semantics
std::string QuerySemantics(TokenType token_type);
// Collect calls in method |method_name|.
std::string GetCalls(base::StringPiece method_name);
// Collect variables used in method |method_name|.
std::string VariablesOf(base::StringPiece method_name);
// ::testing::Test
void SetUp() final;
private:
DISALLOW_COPY_AND_ASSIGN(MethodAnalyzerTest);
};
class PostOrderTraverse final : public ast::Visitor {
public:
explicit PostOrderTraverse(ast::Node* node) { Traverse(node); }
std::vector<ast::Node*>::iterator begin() { return nodes_.begin(); }
std::vector<ast::Node*>::iterator end() { return nodes_.end(); }
private:
// ast::Visitor
void DoDefaultVisit(ast::Node* node) final {
ast::Visitor::DoDefaultVisit(node);
nodes_.push_back(node);
}
std::vector<ast::Node*> nodes_;
DISALLOW_COPY_AND_ASSIGN(PostOrderTraverse);
};
std::string MethodAnalyzerTest::DumpSemanticTree(ast::Node* start_node) {
auto const analysis = session()->analysis();
std::ostringstream ostream;
for (auto node : PostOrderTraverse(start_node)) {
auto const semantic = analysis->SemanticOf(node);
if (!semantic)
continue;
ostream << node << " : " << ToString(semantic) << std::endl;
}
return ostream.str();
}
std::string MethodAnalyzerTest::QuerySemantics(TokenType token_type) {
typedef std::pair<ast::Node*, sm::Semantic*> KeyValue;
std::vector<KeyValue> key_values;
for (auto const key_value : analysis()->all()) {
if (!key_value.first->token()->location().start_offset())
continue;
if (key_value.first->token() != token_type)
continue;
key_values.push_back(key_value);
}
std::sort(key_values.begin(), key_values.end(),
[](const KeyValue& a, const KeyValue& b) {
return a.first->token()->location().start_offset() <
b.first->token()->location().start_offset();
});
std::ostringstream ostream;
for (auto const key_value : key_values)
ostream << *key_value.second << std::endl;
return ostream.str();
}
std::string MethodAnalyzerTest::GetCalls(base::StringPiece method_name) {
auto const method = FindMember(method_name)->as<ast::Method>();
if (!method)
return std::string("Not found: ") + method_name.as_string();
Collector collector(method);
std::ostringstream ostream;
for (auto const call : collector.calls()) {
if (auto const method = analysis()->SemanticOf(call->callee()))
ostream << *method;
else
ostream << "Not resolved: " << *call;
ostream << std::endl;
}
return ostream.str();
}
std::string MethodAnalyzerTest::VariablesOf(base::StringPiece method_name) {
auto const method = FindMember(method_name)->as<ast::Method>();
if (!method)
return std::string("Not found: ") + method_name.as_string();
Collector collector(method);
std::ostringstream ostream;
for (auto const variable : collector.variables())
ostream << *analysis()->SemanticOf(variable) << std::endl;
return ostream.str();
}
// Install methods for testing
void MethodAnalyzerTest::SetUp() {
MyNamespaceBuilder(name_resolver()).Build();
}
//////////////////////////////////////////////////////////////////////
//
// Test cases
//
// Array access
TEST_F(MethodAnalyzerTest, ArrayAccess) {
Prepare(
"using System;"
"class Sample {"
" static void Main(String[] args) {"
" Console.WriteLine(args[1]);"
" }"
"}");
ASSERT_EQ("", Analyze());
EXPECT_EQ("System.String[]\n", QuerySemantics(TokenType::LeftSquareBracket));
}
TEST_F(MethodAnalyzerTest, ArrayAccessErrorArray) {
Prepare(
"using System;"
"class Sample {"
" static void Main(int args) {"
" Console.WriteLine(args[1]);"
" }"
"}");
ASSERT_EQ("TypeResolver.ArrayAccess.Array(79) args\n", Analyze());
}
TEST_F(MethodAnalyzerTest, ArrayAccessErrorIndex) {
Prepare(
"using System;"
"class Sample {"
" static void Main(String[] args) {"
" Console.WriteLine(args[\"foo\"]);"
" }"
"}");
ASSERT_EQ("TypeResolver.ArrayAccess.Index(89) \"foo\"\n", Analyze());
}
TEST_F(MethodAnalyzerTest, ArrayAccessErrorRank) {
Prepare(
"using System;"
"class Sample {"
" static void Main(int[] args) {"
" Console.WriteLine(args[1, 2]);"
" }"
"}");
ASSERT_EQ("TypeResolver.ArrayAccess.Rank(85) [\n", Analyze());
}
// Assignment
TEST_F(MethodAnalyzerTest, AssignField) {
Prepare(
"class Sample {"
" int length_;"
" void SetLength(int new_length) { length_ = new_length; }"
"}");
ASSERT_EQ("", Analyze());
auto const method = FindMember("Sample.SetLength")->as<ast::Method>();
EXPECT_EQ(
"length_ : System.Int32 Sample.length_\n"
"new_length : ReadOnly System.Int32 new_length\n",
DumpSemanticTree(method->body()));
}
TEST_F(MethodAnalyzerTest, AssignErrorNoThis) {
Prepare(
"class Sample {"
" int length_;"
" static void SetLength(int n) { length_ = n; }"
"}");
ASSERT_EQ("TypeResolver.Field.NoThis(69) =\n", Analyze());
}
TEST_F(MethodAnalyzerTest, AssignErrorVoid) {
Prepare(
"class Sample {"
" static void Foo() { int x = 0; x = Bar(); }"
" static void Bar() {}"
"}");
// TODO(eval1749) We should have specific error code for void binding.
EXPECT_EQ("TypeResolver.Expression.Invalid(51) Bar\n", Analyze());
}
// Binary operations
TEST_F(MethodAnalyzerTest, BinaryOperationArithmeticFloat64) {
Prepare(
"class Sample {"
" void Foo(float64 f64, float32 f32,"
" int8 i8, int16 i16, int32 i32, int64 i64,"
" uint8 u8, uint16 u16, uint32 u32, uint64 u64) {"
" var f64_f32 = f64 + f32;"
" var f64_f64 = f64 + f64;"
""
" var f64_i8 = f64 + i8;"
" var f64_i16 = f64 + i16;"
" var f64_i32 = f64 + i32;"
" var f64_i64 = f64 + i64;"
""
" var f64_u8 = f64 + u8;"
" var f64_u16 = f64 + u16;"
" var f64_u32 = f64 + u32;"
" var f64_u64 = f64 + u64;"
" }"
"}");
ASSERT_EQ("", Analyze());
EXPECT_EQ(
"System.Float64\n"
"System.Float64\n"
"System.Float64\n"
"System.Float64\n"
"System.Float64\n"
"System.Float64\n"
"System.Float64\n"
"System.Float64\n"
"System.Float64\n"
"System.Float64\n",
QuerySemantics(TokenType::Add));
}
TEST_F(MethodAnalyzerTest, BinaryOperationArithmeticFloat32) {
Prepare(
"class Sample {"
" void Foo(float64 f64, float32 f32,"
" int8 i8, int16 i16, int32 i32, int64 i64,"
" uint8 u8, uint16 u16, uint32 u32, uint64 u64) {"
" var f32_f32 = f32 + f32;"
" var f32_f64 = f32 + f64;"
""
" var f32_i8 = f32 + i8;"
" var f32_i16 = f32 + i16;"
" var f32_i32 = f32 + i32;"
" var f32_i64 = f32 + i64;"
""
" var f32_u8 = f32 + u8;"
" var f32_u16 = f32 + u16;"
" var f32_u32 = f32 + u32;"
" var f32_u64 = f32 + u64;"
" }"
"}");
ASSERT_EQ("", Analyze());
EXPECT_EQ(
"System.Float32\n"
"System.Float64\n"
"System.Float32\n"
"System.Float32\n"
"System.Float32\n"
"System.Float32\n"
"System.Float32\n"
"System.Float32\n"
"System.Float32\n"
"System.Float32\n",
QuerySemantics(TokenType::Add));
}
TEST_F(MethodAnalyzerTest, Comparison) {
Prepare(
"class Sample {"
" static bool Use(bool x) { return x; }"
" static void Foo(int x, int y) {"
" Use(x == y);"
" Use(x != y);"
" Use(x < y);"
" Use(x <= y);"
" Use(x > y);"
" Use(x >= y);"
" }"
"}");
ASSERT_EQ("", Analyze());
auto const method = FindMember("Sample.Foo")->as<ast::Method>();
EXPECT_EQ(
"Use : System.Bool Sample.Use(System.Bool)\n"
"x : ReadOnly System.Int32 x\n"
"y : ReadOnly System.Int32 y\n"
"operator==(x, y) : System.Int32\n"
"Use : System.Bool Sample.Use(System.Bool)\n"
"x : ReadOnly System.Int32 x\n"
"y : ReadOnly System.Int32 y\n"
"operator!=(x, y) : System.Int32\n"
"Use : System.Bool Sample.Use(System.Bool)\n"
"x : ReadOnly System.Int32 x\n"
"y : ReadOnly System.Int32 y\n"
"operator<(x, y) : System.Int32\n"
"Use : System.Bool Sample.Use(System.Bool)\n"
"x : ReadOnly System.Int32 x\n"
"y : ReadOnly System.Int32 y\n"
"operator<=(x, y) : System.Int32\n"
"Use : System.Bool Sample.Use(System.Bool)\n"
"x : ReadOnly System.Int32 x\n"
"y : ReadOnly System.Int32 y\n"
"operator>(x, y) : System.Int32\n"
"Use : System.Bool Sample.Use(System.Bool)\n"
"x : ReadOnly System.Int32 x\n"
"y : ReadOnly System.Int32 y\n"
"operator>=(x, y) : System.Int32\n",
DumpSemanticTree(method->body()));
}
// Conditional expression
TEST_F(MethodAnalyzerTest, Conditional) {
Prepare(
"class Sample {"
" void Main() { Foo(Cond() ? 12 : 34); }"
" bool Cond() { return true; }"
" int Foo(int x) { return x; }"
" }");
ASSERT_EQ("", Analyze());
}
TEST_F(MethodAnalyzerTest, ConditionalErrorBool) {
Prepare(
"class Sample {"
" void Main() { Foo(Cond() ? 12 : 34); }"
" int Cond() { return 12; }"
" int Foo(int x) { return x; }"
" }");
EXPECT_EQ("TypeResolver.Expression.NotBool(36) Cond\n", Analyze());
}
TEST_F(MethodAnalyzerTest, ConditionalErrorResult) {
Prepare(
"class Sample {"
" void Main() { Cond() ? 12 : 34.0; }"
" bool Cond() { return true; }"
" }");
EXPECT_EQ("TypeResolver.Conditional.NotMatch(41) 12 34\n", Analyze());
}
// 'do' statement
TEST_F(MethodAnalyzerTest, Do) {
Prepare(
"class Sample {"
" void Main() { do { Foo(12); } while (Cond()); }"
" bool Cond() { return true; }"
" int Foo(int x) { return x; }"
" }");
ASSERT_EQ("", Analyze());
}
TEST_F(MethodAnalyzerTest, DoErrorCondition) {
Prepare(
"class Sample {"
" void Main() { do { Foo(0); } while (Foo(1)); }"
" abstract Sample Foo(int x);"
" }");
EXPECT_EQ("TypeResolver.Expression.NotBool(54) Foo\n", Analyze());
}
// field
TEST_F(MethodAnalyzerTest, Field) {
Prepare(
"class Point {"
" int x_;"
" int y_;"
" int X() { return x_; }"
"}");
ASSERT_EQ("", Analyze());
auto const method = FindMember("Point.X")->as<ast::Method>();
EXPECT_EQ("x_ : System.Int32 Point.x_\n", DumpSemanticTree(method->body()));
}
TEST_F(MethodAnalyzerTest, FieldError) {
Prepare(
"class Sample {"
" int length_;"
" static int Length() { return length_; }"
"}");
EXPECT_EQ("TypeResolver.Field.NoThis(59) length_\n", Analyze());
}
// 'for' statement
TEST_F(MethodAnalyzerTest, For) {
Prepare(
"class Sample {"
" void Main() { for (Foo(3); Cond(); Foo(4)) { Foo(12); } }"
" bool Cond() { return true; }"
" int Foo(int x) { return x; }"
" }");
ASSERT_EQ("", Analyze());
}
TEST_F(MethodAnalyzerTest, ForErrorCondition) {
Prepare(
"class Sample {"
" void Main() { for (;Foo(1);) { Foo(0); } }"
" abstract Sample Foo(int x);"
" }");
EXPECT_EQ("TypeResolver.Expression.NotBool(38) Foo\n", Analyze());
}
// for each statement
TEST_F(MethodAnalyzerTest, ForEach) {
Prepare(
"using System;"
"class Sample {"
" static void Main(String[] args) {"
" for (var arg : args)"
" Console.WriteLine(arg);"
" }"
"}");
ASSERT_EQ("", Analyze());
EXPECT_EQ(
"ReadOnly System.String[] args\n"
"ReadOnly System.String arg\n",
VariablesOf("Sample.Main"));
}
TEST_F(MethodAnalyzerTest, ForEachError) {
Prepare(
"using System;"
"class Sample {"
" static void Main(String[] args) {"
" for (int arg : args)"
" Console.WriteLine(arg);"
" }"
"}");
EXPECT_EQ(
"TypeResolver.ForEach.ElementType(75) arg\n"
"TypeResolver.Expression.Invalid(110) arg\n",
Analyze());
}
// 'if' statement
TEST_F(MethodAnalyzerTest, If) {
Prepare(
"class Sample {"
" void Main() { if (Cond()) Foo(12); }"
" void Other() { if (Cond()) Foo(12); else Foo(34); }"
" bool Cond() { return true; }"
" int Foo(int x) { return x; }"
" }");
ASSERT_EQ("", Analyze());
}
TEST_F(MethodAnalyzerTest, IfErrorCondition) {
Prepare(
"class Sample {"
" void Main() { if (Foo(0)) Foo(12); else Foo(34); }"
" abstract Sample Foo(int x);"
" }");
EXPECT_EQ("TypeResolver.Expression.NotBool(36) Foo\n", Analyze());
}
// Increment
TEST_F(MethodAnalyzerTest, Increment) {
Prepare(
"class Sample {"
" void Foo() { var x = 0; ++x; x++; }"
"}");
ASSERT_EQ("", Analyze());
EXPECT_EQ("System.Int32\n", QuerySemantics(TokenType::Increment));
EXPECT_EQ("System.Int32\n", QuerySemantics(TokenType::PostIncrement));
}
// Method resolution
TEST_F(MethodAnalyzerTest, Method) {
Prepare(
"using System;"
"class Sample {"
" void Main() { Console.WriteLine(\"Hello world!\"); }"
" }");
ASSERT_EQ("", Analyze());
EXPECT_EQ("System.Void System.Console.WriteLine(System.String)\n",
GetCalls("Sample.Main"));
}
TEST_F(MethodAnalyzerTest, Method2) {
Prepare(
"class Sample {"
" static void Foo(char x) {}"
" static void Foo(int x) {}"
" static void Foo(float32 x) {}"
" static void Foo(float64 x) {}"
" void Main() { Foo('a'); Foo(123); Foo(12.3); }"
" }");
ASSERT_EQ("", Analyze());
EXPECT_EQ(
"System.Void Sample.Foo(System.Char)\n"
"System.Void Sample.Foo(System.Int32)\n"
"System.Void Sample.Foo(System.Float64)\n",
GetCalls("Sample.Main"));
}
TEST_F(MethodAnalyzerTest, Parameter) {
Prepare(
"class Sample {"
" int Foo(int ival) { return ival; }" // ReadOnly
" char Foo(char ch) { ch = 'a'; return ch; }" // Local
" void Foo(float32 f32) {}" // Void == no references
" }");
ASSERT_EQ("", Analyze());
ast::NameQuery query(session()->NewAtomicString(L"Foo"));
auto const nodes = session()->QueryAstNodes(query);
std::ostringstream ostream;
for (auto node : nodes) {
auto const method = node->as<ast::Method>();
for (auto const parameter : method->parameters()) {
auto const variable =
analysis()->SemanticOf(parameter)->as<sm::Variable>();
if (!variable)
continue;
ostream << *parameter->name() << " " << variable->storage() << std::endl;
}
}
EXPECT_EQ("ival ReadOnly\nch Local\nf32 Void\n", ostream.str());
}
TEST_F(MethodAnalyzerTest, ReturnError) {
Prepare(
"class Sample {"
" int Foo() { return; }"
" void Bar() { return 42; }"
" }");
EXPECT_EQ(
"Method.Return.Void(30) return\n"
"Method.Return.NotVoid(56) return\n",
Analyze());
}
TEST_F(MethodAnalyzerTest, TypeVariable) {
Prepare(
"using System;"
"class Sample {"
" static char Foo(char x) { return x; }"
" static int Foo(int x) {}"
" void Main() { var x = Foo('a'); Foo(x); }"
" }");
ASSERT_EQ("", Analyze());
EXPECT_EQ(
"System.Char Sample.Foo(System.Char)\n"
"System.Char Sample.Foo(System.Char)\n",
GetCalls("Sample.Main"));
}
// 'var' statement
TEST_F(MethodAnalyzerTest, VarVoid) {
Prepare(
"class Sample {"
" static void Foo() { int x = Bar(); }"
" static void Bar() {}"
"}");
// TODO(eval1749) We should have specific error code for void binding.
EXPECT_EQ("TypeResolver.Expression.Invalid(44) Bar\n", Analyze());
}
// 'while' statement
TEST_F(MethodAnalyzerTest, While) {
Prepare(
"class Sample {"
" void Main() { while (Cond()) { Foo(12); } }"
" bool Cond() { return true; }"
" int Foo(int x) { return x; }"
" }");
ASSERT_EQ("", Analyze());
}
TEST_F(MethodAnalyzerTest, WhileErrorCondition) {
Prepare(
"class Sample {"
" void Main() { while (Foo(1)) { Foo(0); } }"
" abstract Sample Foo(int x);"
" }");
EXPECT_EQ("TypeResolver.Expression.NotBool(39) Foo\n", Analyze());
}
} // namespace compiler
} // namespace elang
| 29.421853
| 80
| 0.599144
|
eval1749
|
8c4761fc6234aa0a84b2b3511d7fb746f566f793
| 9,649
|
cpp
|
C++
|
experiments/src/globimap_test_polygons_mask.cpp
|
mlaass/globimap
|
6bbcbf33cc39ed343662e6b98871dc6dfbc4648f
|
[
"MIT"
] | null | null | null |
experiments/src/globimap_test_polygons_mask.cpp
|
mlaass/globimap
|
6bbcbf33cc39ed343662e6b98871dc6dfbc4648f
|
[
"MIT"
] | null | null | null |
experiments/src/globimap_test_polygons_mask.cpp
|
mlaass/globimap
|
6bbcbf33cc39ed343662e6b98871dc6dfbc4648f
|
[
"MIT"
] | null | null | null |
#include "globimap/counting_globimap.hpp"
#include "globimap_test_config.hpp"
#include <algorithm>
#include <chrono>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <limits>
#include <math.h>
#include <string>
#include <highfive/H5File.hpp>
#include <tqdm.hpp>
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point.hpp>
#include <boost/geometry/geometries/polygon.hpp>
#include "archive.h"
#include "loc.hpp"
#include "rasterizer.hpp"
#include "shapefile.hpp"
#include <H5Cpp.h>
namespace fs = std::filesystem;
namespace bg = boost::geometry;
namespace bgi = boost::geometry::index;
namespace bgt = boost::geometry::strategy::transform;
typedef bg::model::point<double, 2, bg::cs::cartesian> point_t;
typedef bg::model::box<point_t> box_t;
typedef bg::model::polygon<point_t> polygon_t;
typedef std::vector<polygon_t> poly_collection_t;
#ifndef TUM1_ICAML_ORG
const std::string base_path = "/mnt/G/datasets/atlas/";
const std::string vector_base_path = "/mnt/G/datasets/vector/";
const std::string experiments_path =
"/home/moritz/workspace/bgdm/globimap/experiments/";
#else
const std::string base_path = "/home/moritz/tf/pointclouds_2d/data/";
const std::string experiments_path = "/home/moritz/tf/globimap/experiments/";
const std::string vector_base_path = "/home/moritz/tf/vector/";
#endif
std::vector<std::string> datasets{"twitter_1mio_coords.h5",
"twitter_10mio_coords.h5",
"twitter_100mio_coords.h5"};
// std::vector<std::string> datasets{"twitter_200mio_coords.h5",
// "asia_200mio_coords.h5"};
std::vector<std::string> polygon_sets{"tl_2017_us_zcta510",
"Global_LSIB_Polygons_Detailed"};
template <typename T> std::string render_hist(std::vector<T> hist) {
std::stringstream ss;
ss << "[";
for (auto i = 0; i < hist.size(); ++i) {
ss << hist[i] << ((i < (hist.size() - 1)) ? ", " : "");
}
ss << "]";
return ss.str();
}
template <typename T>
std::string render_stat(const std::string &name, std::vector<T> stat) {
double stat_min = FLT_MAX;
double stat_max = 0;
double stat_mean = 0;
double stat_std = 0;
for (double v : stat) {
stat_min = std::min(stat_min, v);
stat_max = std::max(stat_max, v);
stat_mean += v;
}
stat_mean /= stat.size();
for (double v : stat) {
stat_std += pow((stat_mean - v), 2);
}
stat_std /= stat.size();
stat_std = sqrt(stat_std);
std::stringstream ss;
ss << "\"" << name << "\": {\n";
ss << "\"min\": " << stat_min << ",\n";
ss << "\"max\": " << stat_max << ",\n";
ss << "\"mean\": " << stat_mean << ",\n";
ss << "\"std\": " << stat_std << ",\n";
ss << "\"hist\": " << render_hist(globimap::make_histogram(stat, 1000))
<< "\n";
ss << "}";
return ss.str();
}
std::string
test_polys_mask(globimap::CountingGloBiMap<> &g, size_t poly_size,
std::function<std::vector<uint64_t>(size_t)> poly_gen) {
std::vector<uint32_t> errors_mask;
std::vector<uint32_t> errors_hash;
std::vector<uint32_t> diff_mask_hash;
std::vector<uint32_t> sizes;
std::vector<uint32_t> sums_mask;
std::vector<uint32_t> sums_hash;
std::vector<uint32_t> sums;
std::vector<double> errors_mask_pc;
std::vector<double> errors_hash_pc;
int n = 0;
std::cout << "polygons: " << poly_size << " ..." << std::endl;
auto P = tq::trange(poly_size);
P.set_prefix("mask for polygons ");
for (const auto &idx : P) {
auto raster = poly_gen(idx);
if (raster.size() > 0) {
auto hsfn = g.to_hashfn(raster);
auto mask_conf = globimap::FilterConfig{
g.config.hash_k, {{1, g.config.layers[0].logsize}}};
auto mask = globimap::CountingGloBiMap(mask_conf, false);
mask.put_all(raster);
auto res_raster = g.get_sum_raster_collected(raster);
auto res_mask = g.get_sum_masked(mask);
auto res_hashfn = g.get_sum_hashfn(raster);
sums.push_back(res_raster);
sums_mask.push_back(res_mask);
sums_hash.push_back(res_hashfn);
uint64_t err_mask = std::abs((int64_t)res_mask - (int64_t)res_raster);
uint64_t err_hash = std::abs((int64_t)res_hashfn - (int64_t)res_raster);
uint64_t hash_mask_diff =
std::abs((int64_t)res_mask - (int64_t)res_hashfn);
errors_mask.push_back(err_mask);
errors_hash.push_back(err_hash);
double div = (double)res_raster;
double err_mask_pc = ((double)err_mask) / div;
double err_hash_pc = ((double)err_hash) / div;
if (div == 0) {
err_mask_pc = (err_mask > 0 ? 1 : 0);
err_hash_pc = (err_hash > 0 ? 1 : 0);
}
errors_mask_pc.push_back(err_mask_pc);
errors_hash_pc.push_back(err_hash_pc);
sizes.push_back(raster.size() / 2);
n++;
}
}
std::stringstream ss;
ss << "{\n";
ss << "\"summary\": " << g.summary() << ",\n";
ss << "\"polygons\": " << n << ",\n";
ss << render_stat("errors_mask_pc", errors_mask_pc) << ",\n";
ss << render_stat("errors_hash_pc", errors_hash_pc) << ",\n";
ss << render_stat("errors_mask", errors_mask) << ",\n";
ss << render_stat("errors_hash", errors_hash) << ",\n";
ss << render_stat("sums", sums) << ",\n";
ss << render_stat("sums_mask", sums_mask) << ",\n";
ss << render_stat("sums_hash", sums_hash) << ",\n";
ss << render_stat("sizes", sizes) << "\n";
ss << "\n}" << std::endl;
// std::cout << ss.str();
return ss.str();
}
static void encode_dataset(globimap::CountingGloBiMap<> &g,
const std::string &name, const std::string &ds,
uint width, uint height) {
auto filename = base_path + ds;
auto batch_size = 4096;
std::cout << "Encode \"" << filename << "\" \nwith cfg: " << name
<< std::endl;
using namespace HighFive;
// we create a new hdf5 file
auto file = File(filename, File::ReadWrite);
std::vector<std::vector<double>> read_data;
// we get the dataset
DataSet dataset = file.getDataSet("coords");
using std::chrono::duration;
using std::chrono::duration_cast;
using std::chrono::high_resolution_clock;
using std::chrono::milliseconds;
auto t1 = high_resolution_clock::now();
std::vector<std::vector<double>> result;
auto shape = dataset.getDimensions();
int batches = std::floor(shape[0] / batch_size);
auto R = tq::trange(batches);
R.set_prefix("encoding batches ");
for (auto i : R) {
dataset.select({i * batch_size, 0}, {batch_size, 2}).read(result);
for (auto p : result) {
double x = (double)width * (((double)p[0] + 180.0) / 360.0);
double y = (double)height * (((double)p[0] + 90.0) / 180.0);
g.put({(uint64_t)x, (uint64_t)y});
}
}
auto t2 = high_resolution_clock::now();
duration<double, std::milli> insert_time = t2 - t1;
}
int main() {
std::vector<std::vector<globimap::LayerConfig>> cfgs;
get_configurations(cfgs, {16, 20, 24}, {8, 16, 32});
{
uint k = 8;
auto x = 0;
uint width = 2 * 8192, height = 2 * 8192;
std::string exp_name = "test_polygons_mask1";
save_configs(experiments_path + std::string("config_") + exp_name, cfgs);
mkdir((experiments_path + exp_name).c_str(), 0777);
for (auto c : cfgs) {
globimap::FilterConfig fc{k, c};
std::cout << "\n******************************************"
<< "\n******************************************" << std::endl;
std::cout << x << " / " << cfgs.size() << " fc: " << fc.to_string()
<< std::endl;
auto y = 0;
for (auto shp : polygon_sets) {
std::stringstream ss1;
ss1 << shp << "-" << width << "x" << height;
auto polyset_name = ss1.str();
std::stringstream ss;
ss << vector_base_path << polyset_name;
auto poly_path = ss.str();
int poly_count = 0;
for (auto e : fs::directory_iterator(poly_path))
poly_count += (e.is_regular_file() ? 1 : 0);
for (auto ds : datasets) {
std::stringstream fss;
fss << experiments_path << exp_name << "/" << exp_name << ".w"
<< width << "h" << height << "." << fc.to_string() << ds << "."
<< polyset_name << ".json";
if (file_exists(fss.str())) {
std::cout << "file already exists: " << fss.str() << std::endl;
} else {
std::cout << "run: " << fss.str() << std::endl;
std::ofstream out(fss.str());
auto g = globimap::CountingGloBiMap(fc, true);
encode_dataset(g, fc.to_string(), ds, width, height);
// g.detect_errors(0, 0, width, height);
std::cout << " COUNTER SIZE: " << g.counter.size() << std::endl;
std::cout << "test: " << polyset_name << std::endl;
out << test_polys_mask(g, poly_count, [&](int idx) {
std::vector<uint64_t> raster;
std::stringstream ss;
ss << poly_path << "/" << std::setw(8) << std::setfill('0')
<< idx;
auto filename = ss.str();
std::ifstream ifile(filename, std::ios::binary);
if (!ifile.is_open()) {
std::cout << "ERROR file doesn't exist: " << filename
<< std::endl;
return raster;
}
Archive<std::ifstream> a(ifile);
a >> raster;
ifile.close();
return raster;
});
out.close();
std::cout << "\n" << std::endl;
}
}
y++;
}
x++;
}
}
};
| 33.272414
| 79
| 0.5755
|
mlaass
|
8c4956b38e3a7b096e13e7c412ec0207db3912e4
| 58
|
cpp
|
C++
|
project/LogsLiteViewerCLI/ManageChannelsDialog.cpp
|
afronski/LogsLiteViewerCLI
|
cf95481b59b5e354e9f1d78e3168a91330c1210c
|
[
"MIT"
] | null | null | null |
project/LogsLiteViewerCLI/ManageChannelsDialog.cpp
|
afronski/LogsLiteViewerCLI
|
cf95481b59b5e354e9f1d78e3168a91330c1210c
|
[
"MIT"
] | null | null | null |
project/LogsLiteViewerCLI/ManageChannelsDialog.cpp
|
afronski/LogsLiteViewerCLI
|
cf95481b59b5e354e9f1d78e3168a91330c1210c
|
[
"MIT"
] | null | null | null |
#include "StdAfx.h"
#include "ManageChannelsDialog.h"
| 14.5
| 34
| 0.724138
|
afronski
|
8c4ae2f09ee13bd0829af2f0432da5c2187d79cf
| 267
|
hpp
|
C++
|
include/boomhs/game_config.hpp
|
bjadamson/BoomHS
|
60b5d8ddc2490ec57e8f530ba7ce3135221e2ec4
|
[
"MIT"
] | 2
|
2016-07-22T10:09:21.000Z
|
2017-09-16T06:50:01.000Z
|
include/boomhs/game_config.hpp
|
bjadamson/BoomHS
|
60b5d8ddc2490ec57e8f530ba7ce3135221e2ec4
|
[
"MIT"
] | 14
|
2016-08-13T22:45:56.000Z
|
2018-12-16T03:56:36.000Z
|
include/boomhs/game_config.hpp
|
bjadamson/BoomHS
|
60b5d8ddc2490ec57e8f530ba7ce3135221e2ec4
|
[
"MIT"
] | null | null | null |
#pragma once
namespace boomhs
{
enum class GameGraphicsMode
{
Basic = 0,
Medium,
Advanced
};
struct GameGraphicsSettings
{
GameGraphicsMode mode = GameGraphicsMode::Basic;
bool disable_sunshafts = true;
};
} // namespace boomhs
| 13.35
| 63
| 0.662921
|
bjadamson
|
8c5328e5fdeb3c8b024ba1539ad80c1d7ae43227
| 1,256
|
cpp
|
C++
|
day16/part1.cpp
|
Moremar/advent_of_code_2016
|
dea264671fc2c31baa42b1282751dfd1ae071a7d
|
[
"Apache-2.0"
] | null | null | null |
day16/part1.cpp
|
Moremar/advent_of_code_2016
|
dea264671fc2c31baa42b1282751dfd1ae071a7d
|
[
"Apache-2.0"
] | null | null | null |
day16/part1.cpp
|
Moremar/advent_of_code_2016
|
dea264671fc2c31baa42b1282751dfd1ae071a7d
|
[
"Apache-2.0"
] | null | null | null |
#include "part1.hpp"
using namespace std;
vector<char> Part1::parse(const string &fileName) {
const string line = getFileLines(fileName)[0];
return { line.begin(), line.end() };
}
vector<char> checksum(const vector<char> &input, size_t targetSize) {
vector<char> res;
res.reserve(targetSize / 2);
for (size_t i = 0; i < targetSize/2; ++i) {
res.push_back(input.at(2 * i) == input.at(2 * i + 1) ? '1' : '0');
}
return (res.size() % 2 == 0) ? checksum(res, res.size()) : res;
}
string Part1::solveForDiscSpace(const vector<char> &initialKey, size_t discSpace) {
auto curr = initialKey;
// get a long enough data sequence by dragon curve
while (curr.size() < discSpace) {
vector<char> next;
next.reserve(curr.size() * 2 + 1);
copy(curr.begin(), curr.end(), back_inserter(next));
next.push_back('0');
transform(curr.rbegin(), curr.rend(), back_inserter(next), [](const char &c) {
return c == '0' ? '1' : '0';
});
curr = next;
}
const auto check = checksum(curr, discSpace);
return string(check.begin(), check.end());
}
string Part1::solve(const vector<char> &initialKey) {
return solveForDiscSpace(initialKey, 272);
}
| 28.545455
| 86
| 0.602707
|
Moremar
|
8c57260b688499deeb446882123cfda02314f283
| 2,941
|
cpp
|
C++
|
source/app/gui.cpp
|
emiyl/dumpling
|
48d76f5a4c035585683e1b414df2b66d5bb12e15
|
[
"MIT"
] | 53
|
2020-04-11T15:49:21.000Z
|
2022-03-20T03:47:33.000Z
|
source/app/gui.cpp
|
emiyl/dumpling
|
48d76f5a4c035585683e1b414df2b66d5bb12e15
|
[
"MIT"
] | 22
|
2020-08-14T19:45:13.000Z
|
2022-03-30T00:49:27.000Z
|
source/app/gui.cpp
|
emiyl/dumpling
|
48d76f5a4c035585683e1b414df2b66d5bb12e15
|
[
"MIT"
] | 11
|
2020-04-19T09:19:08.000Z
|
2022-03-21T20:16:54.000Z
|
#include "gui.h"
#define NUM_LINES (16)
#define LINE_LENGTH (128)
#define MEMORY_HEAP_TAG (0x0002B2B2)
static char textBuffer[NUM_LINES][LINE_LENGTH];
static uint32_t currLineNumber = 0;
static uint8_t* frameBufferTVFrontPtr = nullptr;
static uint8_t* frameBufferTVBackPtr = nullptr;
static uint32_t frameBufferTVSize = 0;
static uint8_t* frameBufferDRCFrontPtr = nullptr;
static uint8_t* frameBufferDRCBackPtr = nullptr;
static uint32_t frameBufferDRCSize = 0;
static uint32_t* currTVFrameBuffer = nullptr;
static uint32_t* currDRCFrameBuffer = nullptr;
static uint32_t backgroundColor = 0x0b5d5e00;
bool initializeGUI() {
// Prepare rendering and framebuffers
OSScreenInit();
frameBufferTVSize = OSScreenGetBufferSizeEx(SCREEN_TV);
frameBufferDRCSize = OSScreenGetBufferSizeEx(SCREEN_DRC);
OSScreenEnableEx(SCREEN_TV, TRUE);
OSScreenEnableEx(SCREEN_DRC, TRUE);
MEMHeapHandle framebufferHeap = MEMGetBaseHeapHandle(MEM_BASE_HEAP_MEM1);
frameBufferTVFrontPtr = (uint8_t*)MEMAllocFromFrmHeapEx(framebufferHeap, frameBufferTVSize, 100);
frameBufferDRCFrontPtr = (uint8_t*)MEMAllocFromFrmHeapEx(framebufferHeap, frameBufferDRCSize, 100);
frameBufferTVBackPtr = frameBufferTVFrontPtr+(1280*720*4);
frameBufferDRCBackPtr = frameBufferDRCFrontPtr+(896*480*4);
currTVFrameBuffer = (uint32_t*)frameBufferTVFrontPtr;
currDRCFrameBuffer = (uint32_t*)frameBufferDRCFrontPtr;
OSScreenSetBufferEx(SCREEN_TV, currTVFrameBuffer);
OSScreenSetBufferEx(SCREEN_DRC, currDRCFrameBuffer);
WHBAddLogHandler(printLine);
return true;
}
void shutdownGUI() {
OSScreenShutdown();
MEMHeapHandle framebufferHeap = MEMGetBaseHeapHandle(MEM_BASE_HEAP_MEM1);
MEMFreeByStateToFrmHeap(framebufferHeap, MEMORY_HEAP_TAG);
}
void WHBLogConsoleDraw() {
OSScreenClearBufferEx(SCREEN_TV, backgroundColor);
OSScreenClearBufferEx(SCREEN_DRC, backgroundColor);
for (int32_t i=0; i<NUM_LINES; i++) {
OSScreenPutFontEx(SCREEN_TV, 0, i, textBuffer[i]);
OSScreenPutFontEx(SCREEN_DRC, 0, i, textBuffer[i]);
}
DCFlushRange(currTVFrameBuffer, frameBufferTVSize);
DCFlushRange(currTVFrameBuffer, frameBufferDRCSize);
OSScreenFlipBuffersEx(SCREEN_TV);
OSScreenFlipBuffersEx(SCREEN_DRC);
}
void printLine(const char* message) {
int32_t length = strlen(message);
if (length > LINE_LENGTH) {
length = LINE_LENGTH - 1;
}
if (currLineNumber == NUM_LINES) {
for (int i=0; i<NUM_LINES-1; i++) {
memcpy(textBuffer[i], textBuffer[i + 1], LINE_LENGTH);
}
memcpy(textBuffer[currLineNumber - 1], message, length);
textBuffer[currLineNumber - 1][length] = 0;
}
else {
memcpy(textBuffer[currLineNumber], message, length);
textBuffer[currLineNumber][length] = 0;
currLineNumber++;
}
}
void setBackgroundColor(uint32_t color) {
backgroundColor = color;
}
| 32.318681
| 103
| 0.743285
|
emiyl
|
8c57cdf94eb7b2e42d37e44f18e63a7b93c55d6b
| 146
|
cpp
|
C++
|
C03_ClassStructure/Main.cpp
|
Nolukdi/IGME309-2201
|
988d8bcae34613e5d88cb2cc92dafe0c1e8ff05a
|
[
"MIT"
] | 2
|
2020-08-20T14:54:45.000Z
|
2020-09-13T17:37:34.000Z
|
C03_ClassStructure/Main.cpp
|
Nolukdi/IGME309-2201
|
988d8bcae34613e5d88cb2cc92dafe0c1e8ff05a
|
[
"MIT"
] | null | null | null |
C03_ClassStructure/Main.cpp
|
Nolukdi/IGME309-2201
|
988d8bcae34613e5d88cb2cc92dafe0c1e8ff05a
|
[
"MIT"
] | 26
|
2020-08-20T17:39:34.000Z
|
2021-02-27T16:27:06.000Z
|
#include "Main.h"
int main(void)
{
AppClass* pApp = new AppClass();
pApp->Run();
if (pApp)
{
delete pApp;
pApp = nullptr;
}
return 0;
}
| 11.230769
| 33
| 0.59589
|
Nolukdi
|
8c58bcb88b8c8533858b93b5b5226d86efd5d4b7
| 11,114
|
cpp
|
C++
|
Lecture9/visualizer/theCamera.cpp
|
Zenologos/IDS6938-SimulationTechniques
|
b3630852b2edb3ec4e176b26f0de56b77b460a2a
|
[
"Apache-2.0"
] | null | null | null |
Lecture9/visualizer/theCamera.cpp
|
Zenologos/IDS6938-SimulationTechniques
|
b3630852b2edb3ec4e176b26f0de56b77b460a2a
|
[
"Apache-2.0"
] | null | null | null |
Lecture9/visualizer/theCamera.cpp
|
Zenologos/IDS6938-SimulationTechniques
|
b3630852b2edb3ec4e176b26f0de56b77b460a2a
|
[
"Apache-2.0"
] | null | null | null |
#include "theCamera.h"
/** @brief Constructs a camera
*
* Constructs a camera object by setting the position, look at position, up vector.
* Puts together a model matrix, and projection matrix.
*
* @param width - float - width of window
* @param height - float - height of window
* @return void.
*/
Visualizer::theCamera::theCamera()
{
mIdenityMatrix = glm::mat4(1.0f);
mOrthoProjection = mIdenityMatrix * glm::ortho(-1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f);
}
void Visualizer::theCamera::settheCamera(float width, float height)
{
screenWidth = width;
screenHeight = height;
setCameraPosition(40.0f, 40.0f, 40.0f);
setLookAtPosition(0.0f, 0.0f, 0.0f);
setupVector(0.0f, 0.0f, 1.0f);
//setModelMatrix(glm::vec3(1.0f, 0.0f, 0.0f), 0.0f, glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(1.0f, 1.0f, 1.0f));
mModelMatrix = glm::mat4(1.0f);
mProjectionMatrix = glm::mat4(1.0f);
//setProjectionMatrix(45.0f, width / height, 0.1f, 100000.0f);
setViewMatrix(getCameraPosition(), getLookAtPosition(), getupVector());
setName("myCamera");
realdiv = float(width + height);
roty = 0.0f;
rotx = 0.0f;
}
/** @brief Deconstructor a camera
*
* This function deconstructs the camera object
*/
Visualizer::theCamera::~theCamera(void)
{
}
/** @brief Translates the camera
*
* This function translates the camera in space.
*
* @param diffx - float - change in x
* @param diffy - float - change in y
* @return void.
*/
void Visualizer::theCamera::translate(float diffx, float diffy)
{
glm::vec3 c = getCameraPosition() - getLookAtPosition();
float change = sqrt(c.x*c.x + c.y*c.y + c.z*c.z);
//get the the view vector and then the right vector
glm::vec3 cameraW = glm::normalize(getLookAtPosition() - getCameraPosition());
glm::vec3 cameraU = glm::normalize(glm::cross(getupVector(), cameraW));
//TODO: need to add - Translate based on the magnitude
float magnitude = sqrt((cameraU.x*cameraU.x) + (cameraU.y*cameraU.y) + (cameraU.z*cameraU.z));
//x_changep/=magnitude;
//y_changep/=magnitude;
//z_changep/=magnitude;
//Do the actual translation lookatPosition
glm::vec3 changel = getLookAtPosition() + getupVector() * (35.5f*diffy / screenWidth);
changel += cameraU * (16.0f*diffx / screenHeight);
//Do the actual translation cameraPosition
glm::vec3 changec = getCameraPosition() + getupVector() * (35.5f*diffy / screenWidth);
changec += cameraU * (16.0f*diffx / screenHeight);
//set the camera
setCameraPosition(changec.x, changec.y, changec.z);
setLookAtPosition(changel.x, changel.y, changel.z);
setViewMatrix(getCameraPosition(), getLookAtPosition(), getupVector());
}
/** @brief Rotates the camera
*
* This function rotates the camera in space.
*
* @param diffx - float - change in x
* @param diffy - float - change in y
* @return void.
*/
void Visualizer::theCamera::rotate(float diffx, float diffy)
{
roty = -(float) 0.025f * diffx;
rotx = -(float) 0.025f * diffy;
float phi = (rotx);
float theta = (roty);
//get the view vector and the right vector
glm::vec3 cameraW = glm::normalize(getLookAtPosition() - getCameraPosition());
glm::vec3 cameraU = glm::normalize(glm::cross(cameraW, getupVector()));
//Get the quaterion rotate about the x and y axis: but fix the up axis to be constant
glm::quat myQuat = glm::normalize(glm::angleAxis(theta, glm::vec3(0.0f, 0.0f, 1.0f)) * glm::angleAxis(phi, glm::vec3(cameraU.x, cameraU.y, cameraU.z)));
glm::mat4 rotmat = glm::toMat4(myQuat); //make a rotation matrix
//Get the Camera position and vector to be rotated
//(remember to translate back, rotate, then translate)
glm::vec4 myPoint(getCameraPosition().x - getLookAtPosition().x, getCameraPosition().y - getLookAtPosition().y, getCameraPosition().z - getLookAtPosition().z, 1.0f);
glm::vec4 myVector(getupVector().x, getupVector().y, getupVector().z, 0.0f);
//Do the rotation
glm::vec4 newPosition = rotmat * myPoint;
glm::vec4 newUpVector = rotmat * myVector;
//glm::vec4 newUpVector = myQuat * myVector* glm::conjugate(myQuat); //not sure why this did not work
newUpVector = glm::normalize(newUpVector);
//translate back
newPosition.x += getLookAtPosition().x;
newPosition.y += getLookAtPosition().y;
newPosition.z += getLookAtPosition().z;
//set the camera
setCameraPosition(newPosition.x, newPosition.y, newPosition.z);
setupVector(newUpVector.x, newUpVector.y, newUpVector.z);
setViewMatrix(getCameraPosition(), getLookAtPosition(), getupVector());
}
/** @brief Zooms the camera
*
* This function zooms the camera in space.
*
* @param realdiff- float - total diff moved in both directions
* @return void.
*/
void Visualizer::theCamera::zoom(float realdiff)
{
//find the view vector, and move the camera on it
glm::vec3 change = getCameraPosition() - getLookAtPosition();
glm::vec3 change2 = getLookAtPosition() + change * (1 + 9.0f*realdiff / realdiv);
//set the camera
setCameraPosition(change2.x, change2.y, change2.z);
setViewMatrix(getCameraPosition(), getLookAtPosition(), getupVector());
}
/** @brief Update the MVP Matrix
*
* This function updates the MVP matrix : P * V * M
*
* @return glm::mat4 - MVP matrix.
*/
glm::mat4 Visualizer::theCamera::updateMVP()
{
return mProjectionMatrix * (mViewMatrix * mModelMatrix);
}
/** @brief Update the MV Matrix -Ortho
*
* This function updates the MV Ortho matrix : V * M
*
* @return glm::mat4 - MV matrix.
*/
glm::mat4 Visualizer::theCamera::updateMVP_ORTHO()
{
return mOrthoProjection;
}
/** @brief Gets the camera position
*
* This function returns the camera position in 3D space.
*
* @return glm::vec3 - camera position.
*/
glm::vec3 Visualizer::theCamera::getCameraPosition()
{
return mCameraPosition;
}
/** @brief Gets the look at position
*
* This function returns the camera look at position in 3D space.
*
* @return glm::vec3 - look at position.
*/
glm::vec3 Visualizer::theCamera::getLookAtPosition()
{
return mLookAtPosition;
}
/** @brief Gets the camera up vector
*
* This function returns the camera up vector.
*
* @return glm::vec3 - camera up vector.
*/
glm::vec3 Visualizer::theCamera::getupVector()
{
return mCameraUpVector;
}
/** @brief Sets the camera position
*
* This function sets the camera position in 3D space.
*
* @param x - float- x position
* @param y - float- y position
* @param z - float- z position
* @return void.
*/
void Visualizer::theCamera::setCameraPosition(float x, float y, float z)
{
mCameraPosition.x = x;
mCameraPosition.y = y;
mCameraPosition.z = z;
}
/** @brief Sets the look at position
*
* This function sets the camera looks at position in 3D space.
*
* @param x - float- x position
* @param y - float- y position
* @param z - float- z position
* @return void.
*/
void Visualizer::theCamera::setLookAtPosition(float x, float y, float z)
{
mLookAtPosition.x = x;
mLookAtPosition.y = y;
mLookAtPosition.z = z;
}
/** @brief Sets the camera up vectir
*
* This function sets the camera up vector.
*
* @param x - float- x direction
* @param y - float- y direction
* @param z - float- z direction
* @return void.
*/
void Visualizer::theCamera::setupVector(float x, float y, float z)
{
mCameraUpVector.x = x;
mCameraUpVector.y = y;
mCameraUpVector.z = z;
}
/** @brief Returns Projection Matrix
*
* This function returns the camera Projection Matrix.
*
* @return glm::mat4 - camera projection matrix.
*/
glm::mat4 Visualizer::theCamera::getProjectionMatrix()
{
return mProjectionMatrix;
}
/** @brief Returns View Matrix
*
* This function returns the camera View Matrix.
*
* @return glm::mat4 - camera view matrix.
*/
glm::mat4 Visualizer::theCamera::getViewMatrix()
{
return mViewMatrix;
}
/** @brief Returns Model Matrix
*
* This function returns the camera Model Matrix.
*
* @return glm::mat4 - camera model matrix.
*/
glm::mat4 Visualizer::theCamera::getModelMatrix()
{
return mModelMatrix;
}
/** @brief Process mouse event.
*
* This function processes mouse events.
*
* @return void.
*/
void Visualizer::theCamera::process_mouse_event()
{
}
/** @brief Returns the camera name
*
* This function returns the camera name.
*
* @return std::string - camera name.
*/
std::string Visualizer::theCamera::getName()
{
return mName;
}
/** @brief Sets teh camera name
*
* This function sets the camera name.
*
* @param - name - std::string - camera name
* @return void.
*/
void Visualizer::theCamera::setName(std::string name)
{
mName = name;
}
/** @brief Sets the Model Matrix
*
* This function sets the Model Matrix.
*
* @param rotate - glm::vec3 - rotate
* @param rotateaxis - float - axis to rotate
* @aram translate - glm::vec3 - translate
* @param scale - glm::vec3 - scale
* @return void.
*/
void Visualizer::theCamera::setModelMatrix(glm::vec3 rotate, float rotateaxis, glm::vec3 translate, glm::vec3 scale)
{
mModelMatrix = glm::mat4(1.0f);
mModelMatrix = glm::rotate(mModelMatrix, rotateaxis, rotate);
mModelMatrix = glm::translate(mModelMatrix, translate);
mModelMatrix = glm::scale(mModelMatrix, scale);
}
/** @brief Sets the projection matrix
*
* This function sets the projection matrix for a projective transform.
*
* @param fovy - float - field of view y
* @param aspect - float - aspect ration
* @param zNear - float - zNear plane
* @param zFar - float - zFar plane
* @return void.
*/
void Visualizer::theCamera::setProjectionMatrix(float fovy, float aspect, float zNear, float zFar)
{
mProjectionMatrix = glm::mat4(1.0f);
mProjectionMatrix *= glm::perspective(fovy, aspect, zNear, zFar);
}
/** @brief Sets the projection matrix for orthographic mode
*
* This function sets the projection matrix for a orthographic transform.
*
* @param left - float - left position
* @param right - float - right position
* @param bottom - float - bottom position
* @param top - float - top position
* @param zNear - float - zNear plane
* @param zFar - float - zFar plane
* @return void.
*/
void Visualizer::theCamera::setProjectionMatrix(float left, float right, float bottom, float top, float zNear, float zFar)
{
mProjectionMatrix = glm::mat4(1.0f);
mProjectionMatrix *= glm::ortho(left, right, bottom, top, zNear, zFar);
}
/** @brief Sets the view matrix
*
* This function sets the view matrix for the camera
*
* @param position - glm::vec3 - camera position
* @param lookat - glm::vec3 - look at position
* @param up - glm::vec3 - up vector
* @return void.
*/
void Visualizer::theCamera::setViewMatrix(glm::vec3 &position, glm::vec3 &lookat, glm::vec3 &up)
{
mViewMatrix = glm::mat4(1.0f);
mViewMatrix *= glm::lookAt(
position, // The eye's position in 3d space
lookat, // What the eye is looking at
up); // The eye's orientation vector (which way is up)
}
void Visualizer::theCamera::setViewMatrixY(glm::vec3 &position, glm::vec3 &lookat, glm::vec3 &up)
{
mViewMatrix = glm::mat4(1.0f);
mViewMatrix *= glm::lookAt(
position, // The eye's position in 3d space
lookat, // What the eye is looking at
up); // The eye's orientation vector (which way is up)
mViewMatrix[1][0] *= -1.0f;
mViewMatrix[1][1] *= -1.0f;
mViewMatrix[1][2] *= -1.0f;
mViewMatrix[1][3] *= -1.0f;
}
| 26.089202
| 166
| 0.699028
|
Zenologos
|
8c5946d276ae225928ba41370ad04228e7d08352
| 2,506
|
cc
|
C++
|
src/structured-interface/detail/debug.cc
|
project-arcana/structured-interface
|
56054310e08a3ae98f8065a90b454e23a36d60d9
|
[
"MIT"
] | 1
|
2020-12-09T13:55:07.000Z
|
2020-12-09T13:55:07.000Z
|
src/structured-interface/detail/debug.cc
|
project-arcana/structured-interface
|
56054310e08a3ae98f8065a90b454e23a36d60d9
|
[
"MIT"
] | 1
|
2019-09-29T09:02:03.000Z
|
2019-09-29T09:02:03.000Z
|
src/structured-interface/detail/debug.cc
|
project-arcana/structured-interface
|
56054310e08a3ae98f8065a90b454e23a36d60d9
|
[
"MIT"
] | null | null | null |
#include "debug.hh"
#include <iomanip>
#include <iostream>
#include <clean-core/string.hh>
#include <structured-interface/element_tree.hh>
#include <structured-interface/properties.hh>
#include <structured-interface/recorded_ui.hh>
namespace
{
void print_property(cc::string_view prefix, size_t prop_id, cc::span<std::byte const> value)
{
auto name = si::detail::get_property_name_from_id(prop_id);
auto type = si::detail::get_property_type_from_id(prop_id);
std::cout << cc::string(prefix).c_str() << "- " << std::string_view(name.data(), name.size()) << ": ";
if (type == cc::type_id<cc::string_view>())
{
std::cout << "\"";
std::cout << std::string_view(reinterpret_cast<char const*>(value.data()), value.size());
std::cout << "\"";
}
else
{
std::cout << std::hex;
for (auto v : value)
std::cout << " " << std::setw(2) << std::setfill('0') << unsigned(v);
std::cout << std::dec;
}
std::cout << std::endl;
}
}
void si::debug::print(recorded_ui const& r)
{
struct printer
{
int indent = 0;
cc::vector<size_t> id_stack;
std::string indent_str() const { return std::string(indent * 2, ' '); }
void start_element(size_t id, element_type type)
{
std::cout << indent_str() << "[" << cc::string(to_string(type)).c_str() << "] id: " << id << std::endl;
++indent;
id_stack.push_back(id);
}
void property(size_t prop_id, cc::span<std::byte const> value) { print_property(indent_str(), prop_id, value); }
void end_element()
{
--indent;
id_stack.pop_back();
}
};
r.visit(printer{});
}
namespace
{
void debug_print(cc::string prefix, si::element_tree const& t, si::element_tree::element const& e)
{
std::cout << prefix.c_str() << "[" << cc::string(to_string(e.type)).c_str() << "] id: " << e.id.id() << " (" << e.children_count << " c, "
<< e.properties_count << " p)" << std::endl;
auto cprefix = prefix + " ";
// TODO: properly print all properties
// for (auto const& p : t.packed_properties_of(e))
// print_property(cprefix, p.id.id(), p.value);
for (auto const& c : t.children_of(e))
debug_print(cprefix, t, c);
}
}
void si::debug::print(const si::element_tree& t)
{
std::cout << t.roots().size() << " roots" << std::endl;
for (auto const& e : t.roots())
debug_print(" ", t, e);
}
| 31.325
| 142
| 0.570231
|
project-arcana
|
8c5f17b009c88df2381cc99e3110295474d7802e
| 1,699
|
cpp
|
C++
|
src/graph/src/FlowEdge.cpp
|
karz0n/algorithms
|
b2a08ba990c7e4f078eb7bf3c90d050eb38de9d8
|
[
"MIT"
] | 1
|
2020-04-18T14:34:16.000Z
|
2020-04-18T14:34:16.000Z
|
src/graph/src/FlowEdge.cpp
|
karz0n/algorithms
|
b2a08ba990c7e4f078eb7bf3c90d050eb38de9d8
|
[
"MIT"
] | null | null | null |
src/graph/src/FlowEdge.cpp
|
karz0n/algorithms
|
b2a08ba990c7e4f078eb7bf3c90d050eb38de9d8
|
[
"MIT"
] | null | null | null |
/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT WARRANTY OF ANY KIND; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* MIT License for more details.
*/
/**
* @file FlowEdge.cpp
*
* @brief Flow edge graph data type implementation
*
* @author Denys Asauliak
* Contact: d.asauliak@gmail.com
*/
#include "FlowEdge.hpp"
#include <stdexcept>
namespace algorithms {
FlowEdge::FlowEdge(std::size_t v, std::size_t w, double capacity)
: _v{v}
, _w{w}
, _capacity{capacity}
, _flow{0.0}
{
}
std::size_t
FlowEdge::from() const
{
return _v;
}
std::size_t
FlowEdge::to() const
{
return _w;
}
std::size_t
FlowEdge::other(std::size_t v) const
{
if (v == _v) {
return _w;
}
if (v == _w) {
return _v;
}
throw std::logic_error{"Invalid input argument"};
}
double
FlowEdge::capacity() const
{
return _capacity;
}
double
FlowEdge::flow() const
{
return _flow;
}
double
FlowEdge::residualCapacityTo(std::size_t v) const
{
if (v == _w) { // Forward edge
return _capacity - _flow;
}
if (v == _v) { // Backward edge
return _flow;
}
throw std::logic_error{"Invalid input argument"};
}
void
FlowEdge::addResidualFlowTo(std::size_t v, double delta)
{
if (v == _w) { // Forward Edge
_flow += delta;
return;
}
if (v == _v) { // Backward edge
_flow -= delta;
return;
}
throw std::logic_error{"Invalid input argument"};
}
} // namespace algorithms
| 17.515464
| 73
| 0.626839
|
karz0n
|
8c5fb83452c076d7e7240ae989fb6e1cc6e3ee1c
| 6,783
|
cpp
|
C++
|
NoFTL_v1.0/shoreMT-KIT/src/workload/ssb/qpipe/qpipe_qsupplier.cpp
|
DBlabRT/NoFTL
|
cba8b5a6d9c422bdd39b01575244e557cbd12e43
|
[
"Unlicense"
] | 4
|
2019-01-24T02:00:23.000Z
|
2021-03-17T11:56:59.000Z
|
NoFTL_v1.0/shoreMT-KIT/src/workload/ssb/qpipe/qpipe_qsupplier.cpp
|
DBlabRT/NoFTL
|
cba8b5a6d9c422bdd39b01575244e557cbd12e43
|
[
"Unlicense"
] | null | null | null |
NoFTL_v1.0/shoreMT-KIT/src/workload/ssb/qpipe/qpipe_qsupplier.cpp
|
DBlabRT/NoFTL
|
cba8b5a6d9c422bdd39b01575244e557cbd12e43
|
[
"Unlicense"
] | 4
|
2019-01-22T10:35:55.000Z
|
2021-03-17T11:57:23.000Z
|
/* -*- mode:C++; c-basic-offset:4 -*-
Shore-kits -- Benchmark implementations for Shore-MT
Copyright (c) 2007-2009
Data Intensive Applications and Systems Labaratory (DIAS)
Ecole Polytechnique Federale de Lausanne
All Rights Reserved.
Permission to use, copy, modify and distribute this software and
its documentation is hereby granted, provided that both the
copyright notice and this permission notice appear in all copies of
the software, derivative works or modified versions, and any
portions thereof, and that both notices appear in supporting
documentation.
This code 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. THE AUTHORS
DISCLAIM ANY LIABILITY OF ANY KIND FOR ANY DAMAGES WHATSOEVER
RESULTING FROM THE USE OF THIS SOFTWARE.
*/
/** @file: qpipe_qsupplier.cpp
*
* @brief: Implementation of simple QPIPE SSB tablescans over Shore-MT
*
* @author: Manos Athanassoulis
* @date: July 2010
*/
#include "workload/ssb/shore_ssb_env.h"
#include "qpipe.h"
using namespace shore;
using namespace qpipe;
ENTER_NAMESPACE(ssb);
/********************************************************************
*
* QPIPE qsupplier - Structures needed by operators
*
********************************************************************/
// the tuples after tablescan projection
typedef struct ssb_supplier_tuple projected_tuple;
struct count_tuple
{
int COUNT;
};
class supplier_tscan_filter_t : public tuple_filter_t
{
private:
ShoreSSBEnv* _ssbdb;
table_row_t* _prsupp;
rep_row_t _rr;
ssb_supplier_tuple _supplier;
public:
supplier_tscan_filter_t(ShoreSSBEnv* ssbdb, qsupplier_input_t &in)
: tuple_filter_t(ssbdb->supplier_desc()->maxsize()), _ssbdb(ssbdb)
{
// Get a supplier tupple from the tuple cache and allocate space
_prsupp = _ssbdb->supplier_man()->get_tuple();
_rr.set_ts(_ssbdb->supplier_man()->ts(),
_ssbdb->supplier_desc()->maxsize());
_prsupp->_rep = &_rr;
}
~supplier_tscan_filter_t()
{
// Give back the supplier tuple
_ssbdb->supplier_man()->give_tuple(_prsupp);
}
// Predication
bool select(const tuple_t &input) {
// Get next supplier and read its shipdate
if (!_ssbdb->supplier_man()->load(_prsupp, input.data)) {
assert(false); // RC(se_WRONG_DISK_DATA)
}
return (true);
}
// Projection
void project(tuple_t &d, const tuple_t &s) {
projected_tuple *dest;
dest = aligned_cast<projected_tuple>(d.data);
_prsupp->get_value(0, _supplier.S_SUPPKEY);
_prsupp->get_value(1, _supplier.S_NAME,25);
TRACE( TRACE_RECORD_FLOW, "%d|%s --d\n",
_supplier.S_SUPPKEY,
_supplier.S_NAME);
dest->S_SUPPKEY = _supplier.S_SUPPKEY;
strcpy(dest->S_NAME,_supplier.S_NAME);
}
supplier_tscan_filter_t* clone() const {
return new supplier_tscan_filter_t(*this);
}
c_str to_string() const {
return c_str("supplier_tscan_filter_t()");
}
};
struct count_aggregate_t : public tuple_aggregate_t {
default_key_extractor_t _extractor;
count_aggregate_t()
: tuple_aggregate_t(sizeof(projected_tuple))
{
}
virtual key_extractor_t* key_extractor() { return &_extractor; }
virtual void aggregate(char* agg_data, const tuple_t &) {
count_tuple* agg = aligned_cast<count_tuple>(agg_data);
agg->COUNT++;
}
virtual void finish(tuple_t &d, const char* agg_data) {
memcpy(d.data, agg_data, tuple_size());
}
virtual count_aggregate_t* clone() const {
return new count_aggregate_t(*this);
}
virtual c_str to_string() const {
return "count_aggregate_t";
}
};
class ssb_qsupplier_process_tuple_t : public process_tuple_t
{
public:
void begin() {
TRACE(TRACE_QUERY_RESULTS, "*** qsupplier ANSWER ...\n");
TRACE(TRACE_QUERY_RESULTS, "*** SUM_QTY\tSUM_BASE\tSUM_DISC...\n");
}
virtual void process(const tuple_t& output) {
projected_tuple *tuple;
tuple = aligned_cast<projected_tuple>(output.data);
TRACE( TRACE_QUERY_RESULTS, "%d|%s --d\n",
tuple->S_SUPPKEY,
tuple->S_NAME);
}
};
/********************************************************************
*
* QPIPE qsupplier - Packet creation and submission
*
********************************************************************/
w_rc_t ShoreSSBEnv::xct_qpipe_qsupplier(const int xct_id,
qsupplier_input_t& in)
{
TRACE( TRACE_ALWAYS, "********** qsupplier *********\n");
policy_t* dp = this->get_sched_policy();
xct_t* pxct = smthread_t::me()->xct();
// TSCAN PACKET
tuple_fifo* tscan_out_buffer =
new tuple_fifo(sizeof(projected_tuple));
tscan_packet_t* supplier_tscan_packet =
new tscan_packet_t("TSCAN SUPPLIER",
tscan_out_buffer,
new supplier_tscan_filter_t(this,in),
this->db(),
_psupplier_desc.get(),
pxct
//, SH
);
/* tuple_fifo* agg_output = new tuple_fifo(sizeof(count_tuple));
aggregate_packet_t* agg_packet =
new aggregate_packet_t(c_str("COUNT_AGGREGATE"),
agg_output,
new trivial_filter_t(agg_output->tuple_size()),
new count_aggregate_t(),
new int_key_extractor_t(),
date_tscan_packet);
new partial_aggregate_packet_t(c_str("COUNT_AGGREGATE"),
agg_output,
new trivial_filter_t(agg_output->tuple_size()),
qsupplier_tscan_packet,
new count_aggregate_t(),
new default_key_extractor_t(),
new int_key_compare_t());
*/
qpipe::query_state_t* qs = dp->query_state_create();
supplier_tscan_packet->assign_query_state(qs);
//agg_packet->assign_query_state(qs);
// Dispatch packet
ssb_qsupplier_process_tuple_t pt;
process_query(supplier_tscan_packet, pt);
dp->query_state_destroy(qs);
return (RCOK);
}
EXIT_NAMESPACE(ssb);
| 28.2625
| 78
| 0.579685
|
DBlabRT
|
8c669eaca48d5321dcbb261122b229507e08e344
| 358
|
cpp
|
C++
|
src/geoarrow.cpp
|
paleolimbot/geoarrow
|
45033ffe9cd9e0d21ee223361f0ac5eaf1f4330a
|
[
"MIT"
] | 42
|
2021-11-26T01:17:46.000Z
|
2022-03-26T21:00:28.000Z
|
src/geoarrow.cpp
|
paleolimbot/geoarrow
|
45033ffe9cd9e0d21ee223361f0ac5eaf1f4330a
|
[
"MIT"
] | 3
|
2022-03-02T18:18:38.000Z
|
2022-03-23T20:06:22.000Z
|
src/geoarrow.cpp
|
paleolimbot/geoarrow
|
45033ffe9cd9e0d21ee223361f0ac5eaf1f4330a
|
[
"MIT"
] | null | null | null |
#include "port.h"
#ifdef IS_LITTLE_ENDIAN
#define GEOARROW_ENDIAN 0x01
#else
#define GEOARROW_ENDIAN 0x00
#endif
#define FASTFLOAT_ASSERT(x)
#include "internal/fast_float/fast_float.h"
#include "ryu/ryu.h"
#define geoarrow_d2s_fixed_n geoarrow_d2sfixed_buffered_n
// For implementations of release callbacks
#define ARROW_HPP_IMPL
#include "geoarrow.h"
| 18.842105
| 57
| 0.812849
|
paleolimbot
|
8c6dfa01b68b414515c098f39383abadd82a6003
| 822
|
cc
|
C++
|
courses/algos/main_project/balgosrbkw/04-graphs/undirected/cycle.cc
|
obs145628/ml-notebooks
|
08a64962e106ec569039ab204a7ae4c900783b6b
|
[
"MIT"
] | 1
|
2020-10-29T11:26:00.000Z
|
2020-10-29T11:26:00.000Z
|
courses/algos/main_project/balgosrbkw/04-graphs/undirected/cycle.cc
|
obs145628/ml-notebooks
|
08a64962e106ec569039ab204a7ae4c900783b6b
|
[
"MIT"
] | 5
|
2021-03-18T21:33:45.000Z
|
2022-03-11T23:34:50.000Z
|
courses/algos/main_project/balgosrbkw/04-graphs/undirected/cycle.cc
|
obs145628/ml-notebooks
|
08a64962e106ec569039ab204a7ae4c900783b6b
|
[
"MIT"
] | 1
|
2019-12-23T21:50:02.000Z
|
2019-12-23T21:50:02.000Z
|
#include "cycle.hh"
Cycle::Cycle(const Graph &g) : _marked(g.vcount(), false), _cycle(false) {
for (std::size_t v = 0; v < g.vcount(); ++v)
if (!_marked[v])
dfs(g, v, v);
}
// v is the vertex we want to visit, and u it's predecessor
// Use a boolean array to keep track of visited vertices
// Before visiting a new vertex, mark it as visited.
// For all unvisited adjacent vertices, do a recursive call
// If already visted, and that's not it's predecessor, there is a cycle
// Undirected graph, we have a->b, b->a, so we need to check if that's not just
// the other link
void Cycle::dfs(const Graph &g, std::size_t v, std::size_t u) {
_marked[v] = true;
for (auto it = g.adj_begin(v); it != g.adj_end(v); ++it)
if (!_marked[*it])
dfs(g, *it, v);
else if (*it != u)
_cycle = true;
}
| 34.25
| 79
| 0.63382
|
obs145628
|
8c705db0081bed8fcbb08d2420152574960a6d18
| 424
|
cpp
|
C++
|
target_teensy3/src/blink.cpp
|
tulth/diy-acura-bluetooth
|
8fe9d99ef1c6860a092cb7e17240ba1436d06a3d
|
[
"MIT"
] | null | null | null |
target_teensy3/src/blink.cpp
|
tulth/diy-acura-bluetooth
|
8fe9d99ef1c6860a092cb7e17240ba1436d06a3d
|
[
"MIT"
] | null | null | null |
target_teensy3/src/blink.cpp
|
tulth/diy-acura-bluetooth
|
8fe9d99ef1c6860a092cb7e17240ba1436d06a3d
|
[
"MIT"
] | null | null | null |
#include <stdbool.h>
#include <stdint.h>
#include <WProgram.h>
// #include <core_pins.h>
#define LED_PIN 13
extern "C" int main(void)
{
setup();
while (1) {
loop();
}
}
void setup() {
// initialize the digital pin as an output.
pinMode(LED_PIN, OUTPUT);
}
void loop() {
digitalWrite(LED_PIN, HIGH); // set the LED on
delay(200);
digitalWrite(LED_PIN, LOW); // set the LED off
delay(200);
}
| 14.62069
| 51
| 0.622642
|
tulth
|
8c70c08d30aff00462e2d8455b0c8417e7ad4fd2
| 1,204
|
hpp
|
C++
|
include/rt1w/integrator.hpp
|
guerarda/rt1w
|
2fa13326e0a745214fb1a9fdc49a345c1407b6f3
|
[
"MIT"
] | null | null | null |
include/rt1w/integrator.hpp
|
guerarda/rt1w
|
2fa13326e0a745214fb1a9fdc49a345c1407b6f3
|
[
"MIT"
] | null | null | null |
include/rt1w/integrator.hpp
|
guerarda/rt1w
|
2fa13326e0a745214fb1a9fdc49a345c1407b6f3
|
[
"MIT"
] | null | null | null |
#pragma once
#include "rt1w/geometry.hpp"
#include "rt1w/spectrum.hpp"
#include "rt1w/sptr.hpp"
#include "rt1w/task.hpp"
#include <string>
struct Interaction;
struct Ray;
struct Sampler;
struct Scene;
Spectrum UniformSampleOneLight(const Interaction &isect,
const sptr<Scene> &scene,
const sptr<Sampler> &sampler);
struct Integrator : Object {
static sptr<Integrator> create(const std::string &type,
const sptr<Sampler> &sampler,
size_t maxDepth);
virtual sptr<const Sampler> sampler() const = 0;
virtual Spectrum Li(const Ray &ray,
const sptr<Scene> &scene,
const sptr<Sampler> &sampler,
size_t depth,
v3f *N = nullptr,
Spectrum *A = nullptr) const = 0;
};
struct IntegratorAsync : Integrator {
using Integrator::Li;
virtual sptr<Batch<Spectrum>> Li(const std::vector<Ray> &rays,
const sptr<Scene> &scene,
const sptr<Sampler> &sampler) const = 0;
};
| 30.871795
| 77
| 0.532392
|
guerarda
|
8c70ed625e9b363370c6115a733c78d4243393d5
| 5,925
|
cpp
|
C++
|
src/HAL/gpio.cpp
|
QIU1995NONAME/Q20161106_Project0
|
f321c52496996e94bc8bd52805721e922da4151c
|
[
"MIT"
] | 4
|
2016-11-11T04:47:05.000Z
|
2019-01-23T14:14:00.000Z
|
src/HAL/gpio.cpp
|
QIU1995NONAME/Q20161106_Project0
|
f321c52496996e94bc8bd52805721e922da4151c
|
[
"MIT"
] | null | null | null |
src/HAL/gpio.cpp
|
QIU1995NONAME/Q20161106_Project0
|
f321c52496996e94bc8bd52805721e922da4151c
|
[
"MIT"
] | null | null | null |
#include "gpio.h"
namespace QIU {
namespace PJ0 {
// 目前已经被初始化的GPIO口
// 12 8 4 0
// GPIO_A 0001-1110 1110-0001
// GPIO_B 1111-0101 1110-0000
// GPIO_C 0000-0000 1111-1111
// GPIO_D 1111-1111 1111-0011
// GPIO_E 1111-1111 1001-1111
// GPIO_F 1111-0000 0011-1111
// GPIO_G 0111-0100 0011-1111
//
GPIO_InitTypeDef gpio_init;
// 按键
inline void gpio_config_key(void) {
// PA0
gpio_init.GPIO_Speed = GPIO_Speed_50MHz;
gpio_init.GPIO_Mode = GPIO_Mode_IPD;
gpio_init.GPIO_Pin = GPIO_Pin_0;
GPIO_Init(GPIOA, &gpio_init);
// PE2 PE3 PE4
gpio_init.GPIO_Speed = GPIO_Speed_50MHz;
gpio_init.GPIO_Mode = GPIO_Mode_IPU;
gpio_init.GPIO_Pin = GPIO_Pin_2 | GPIO_Pin_3 | GPIO_Pin_4;
GPIO_Init(GPIOA, &gpio_init);
}
// LED 数码管
inline void gpio_config_led(void) {
// PC7 ~ PC0
gpio_init.GPIO_Speed = GPIO_Speed_50MHz;
gpio_init.GPIO_Mode = GPIO_Mode_Out_PP;
gpio_init.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1 | GPIO_Pin_2 | GPIO_Pin_3
| GPIO_Pin_4 | GPIO_Pin_5 | GPIO_Pin_6 | GPIO_Pin_7;
GPIO_Init(GPIOC, &gpio_init);
}
// 蜂鸣器PWM输出
inline void gpio_config_beep_pwm(void) {
// PB5 使用PWM驱动
gpio_init.GPIO_Speed = GPIO_Speed_50MHz;
gpio_init.GPIO_Mode = GPIO_Mode_AF_PP;
gpio_init.GPIO_Pin = GPIO_Pin_5;
GPIO_Init(GPIOB, &gpio_init);
}
// 风扇PWM输出
inline void gpio_config_fan_pwm(void) {
// PB8 使用PWM驱动
gpio_init.GPIO_Speed = GPIO_Speed_50MHz;
gpio_init.GPIO_Mode = GPIO_Mode_AF_PP;
gpio_init.GPIO_Pin = GPIO_Pin_8;
GPIO_Init(GPIOB, &gpio_init);
}
// E6A2 光电编码器
inline void gpio_config_e6a2(void) {
gpio_init.GPIO_Speed = GPIO_Speed_50MHz;
gpio_init.GPIO_Mode = GPIO_Mode_IPU;
gpio_init.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7;
GPIO_Init(GPIOB, &gpio_init);
}
// TB6560 步进电机驱动板
inline void gpio_config_tb6560(void) {
// 3根线 EN+ CW+ CLK+ PB10 PA11 PA12
gpio_init.GPIO_Speed = GPIO_Speed_50MHz;
gpio_init.GPIO_Mode = GPIO_Mode_Out_PP;
gpio_init.GPIO_Pin = GPIO_Pin_11 | GPIO_Pin_12;
GPIO_Init(GPIOA, &gpio_init);
gpio_init.GPIO_Pin = GPIO_Pin_10;
GPIO_Init(GPIOB, &gpio_init);
}
// 串口1
inline void gpio_config_usart1(void) {
// 初始化 USART1使用的GPIO PA9输出(TX) PA10 输入(RX)
gpio_init.GPIO_Speed = GPIO_Speed_50MHz;
gpio_init.GPIO_Mode = GPIO_Mode_AF_PP; // 复用推挽输出
gpio_init.GPIO_Pin = GPIO_Pin_9; // TX
GPIO_Init(GPIOA, &gpio_init);
gpio_init.GPIO_Mode = GPIO_Mode_IN_FLOATING; // 浮空输入
gpio_init.GPIO_Pin = GPIO_Pin_10; // RX
GPIO_Init(GPIOA, &gpio_init);
}
// 触摸屏 用来检测是否触摸的信号线
inline void gpio_config_touch_pen(void) {
// TOUCH_PEN PD7
gpio_init.GPIO_Speed = GPIO_Speed_50MHz;
gpio_init.GPIO_Mode = GPIO_Mode_IPU; // 上拉输入
gpio_init.GPIO_Pin = GPIO_Pin_7;
GPIO_Init(GPIOD, &gpio_init);
}
// SPI 1 2 总线初始化
inline void gpio_config_spi(void) {
// SPI1 PA5 PA6 PA7
gpio_init.GPIO_Speed = GPIO_Speed_50MHz;
gpio_init.GPIO_Mode = GPIO_Mode_AF_PP; // 复用推挽输出
gpio_init.GPIO_Pin = GPIO_Pin_5 | GPIO_Pin_6 | GPIO_Pin_7;
GPIO_Init(GPIOA, &gpio_init);
GPIO_SetBits(GPIOA, GPIO_Pin_5 | GPIO_Pin_6 | GPIO_Pin_7);
// SPI2 PB13 PB14 PB15
gpio_init.GPIO_Speed = GPIO_Speed_50MHz;
gpio_init.GPIO_Mode = GPIO_Mode_AF_PP; // 复用推挽输出
gpio_init.GPIO_Pin = GPIO_Pin_13 | GPIO_Pin_14 | GPIO_Pin_15;
GPIO_Init(GPIOB, &gpio_init);
// 使用SPI1的模块信号线
// TOUCH_CS PD6
gpio_init.GPIO_Mode = GPIO_Mode_Out_PP; // 推挽输出
gpio_init.GPIO_Pin = GPIO_Pin_6;
GPIO_Init(GPIOD, &gpio_init);
GPIO_SetBits(GPIOD, GPIO_Pin_6);
// 使用SPI2的模块信号线
// SD_CS PG14
// FLASH_CS PG13
gpio_init.GPIO_Mode = GPIO_Mode_Out_PP; // 推挽输出
gpio_init.GPIO_Pin = GPIO_Pin_14 | GPIO_Pin_13;
GPIO_Init(GPIOG, &gpio_init);
GPIO_SetBits(GPIOG, GPIO_Pin_13);
GPIO_SetBits(GPIOG, GPIO_Pin_14);
// ENC28J60_CS PB12
gpio_init.GPIO_Pin = GPIO_Pin_12;
GPIO_Init(GPIOB, &gpio_init);
GPIO_SetBits(GPIOB, GPIO_Pin_12);
}
// FSMC模块
inline void gpio_config_fsmc(void) {
gpio_init.GPIO_Speed = GPIO_Speed_50MHz;
gpio_init.GPIO_Mode = GPIO_Mode_AF_PP;
// PD0 FSMC_D2
// PD1 FSMC_D3
// PD4 FSMC_NOE
// PD5 FSMC_NWE
// PD8 FSMC_D13
// PD9 FSMC_D14
// PD10 FSMC_D15
// PD11 FSMC_A16
// PD12 FSMC_A17
// PD13 FSMC_A18
// PD14 FSMC_D0
// PD15 FSMC_D1
gpio_init.GPIO_Pin = GPIO_Pin_All
& ~(GPIO_Pin_2 | GPIO_Pin_3 | GPIO_Pin_6 | GPIO_Pin_7);
GPIO_Init(GPIOD, &gpio_init);
// PE0 FSMC_NBL0
// PE1 FSMC_NBL1
// PE7 FSMC_D4
// PE8 FSMC_D5
// PE9 FSMC_D6
// PE10 FSMC_D7
// PE11 FSMC_D8
// PE12 FSMC_D9
// PE13 FSMC_D10
// PE14 FSMC_D11
// PE15 FSMC_D12
gpio_init.GPIO_Pin = GPIO_Pin_All & ~( GPIO_Pin_2 | GPIO_Pin_3)
& ~(GPIO_Pin_4 | GPIO_Pin_5 | GPIO_Pin_6);
GPIO_Init(GPIOE, &gpio_init);
// PF0 FSMC_A0
// PF1 FSMC_A1
// PF2 FSMC_A2
// PF3 FSMC_A3
// PF4 FSMC_A4
// PF5 FSMC_A5
// PF12 FSMC_A6
// PF13 FSMC_A7
// PF14 FSMC_A8
// PF15 FSMC_A9
gpio_init.GPIO_Pin = GPIO_Pin_All & ~( GPIO_Pin_6 | GPIO_Pin_7)
& ~(GPIO_Pin_8 | GPIO_Pin_9 | GPIO_Pin_10 | GPIO_Pin_11);
GPIO_Init(GPIOF, &gpio_init);
// PG0 FSMC_A10
// PG1 FSMC_A11
// PG2 FSMC_A12
// PG3 FSMC_A13
// PG4 FSMC_A14
// PG5 FSMC_A15
// PG10 FSMC_NE3
// PG12 FSMC_NE4
gpio_init.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1 | GPIO_Pin_2 | GPIO_Pin_3
| GPIO_Pin_4 | GPIO_Pin_5 | GPIO_Pin_10 | GPIO_Pin_12;
GPIO_Init(GPIOG, &gpio_init);
}
// 初始化
extern void gpio_config(void) {
// GPIO 时钟使能
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOD, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOE, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOF, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOG, ENABLE);
//各项外设GPIO初始化
gpio_config_key();
gpio_config_led();
gpio_config_beep_pwm();
gpio_config_fan_pwm();
gpio_config_usart1();
gpio_config_touch_pen();
gpio_config_spi();
gpio_config_fsmc();
gpio_config_e6a2();
gpio_config_tb6560();
}
}
}
| 28.349282
| 71
| 0.741941
|
QIU1995NONAME
|
8c77496126f518e77faa8e0bdc5bdb90393f9d1e
| 545
|
cpp
|
C++
|
uri-online-judge/1457/main.cpp
|
olegon/online-judges
|
4ec27c8940ae492ce71aec0cc9ed944b094bce55
|
[
"MIT"
] | 12
|
2017-11-30T11:10:45.000Z
|
2022-01-26T23:49:19.000Z
|
uri-online-judge/1457/main.cpp
|
olegon/online-judges
|
4ec27c8940ae492ce71aec0cc9ed944b094bce55
|
[
"MIT"
] | null | null | null |
uri-online-judge/1457/main.cpp
|
olegon/online-judges
|
4ec27c8940ae492ce71aec0cc9ed944b094bce55
|
[
"MIT"
] | 4
|
2017-11-25T03:13:32.000Z
|
2019-08-16T08:08:10.000Z
|
/*
Oráculo de Alexandria
https://www.urionlinejudge.com.br/judge/pt/problems/view/1457
*/
#include <cstdio>
using namespace std;
typedef unsigned long long int uint64;
uint64 k_fat(int N, int K);
int main(void) {
int T;
scanf("%d\n", &T);
while (T-- > 0) {
int N, K = 0;
char C;
scanf("%d", &N);
while (scanf("%c", &C), C == '!') K++;
printf("%llu\n", k_fat(N, K));
}
return 0;
}
uint64 k_fat(int N, int K) {
if (N < 2) return 1;
else return N * k_fat(N - K, K);
}
| 14.72973
| 61
| 0.522936
|
olegon
|
8c79eddf42d2b47d20743277e8f32b5375aa0671
| 35,329
|
cpp
|
C++
|
source/main.cpp
|
LiquidFenrir/MinesweeperFPS
|
63f52b9c0e2ee6c9e9d6a489535fd2411df17637
|
[
"MIT"
] | 8
|
2020-08-25T19:30:41.000Z
|
2021-12-10T20:11:28.000Z
|
source/main.cpp
|
LiquidFenrir/MinesweeeperFPS
|
63f52b9c0e2ee6c9e9d6a489535fd2411df17637
|
[
"MIT"
] | 1
|
2020-08-28T14:52:51.000Z
|
2020-08-29T12:28:33.000Z
|
source/main.cpp
|
LiquidFenrir/MinesweeeperFPS
|
63f52b9c0e2ee6c9e9d6a489535fd2411df17637
|
[
"MIT"
] | 2
|
2020-08-26T18:07:28.000Z
|
2021-12-10T20:11:24.000Z
|
#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS
#ifdef __SWITCH__
#include <switch.h>
#endif
#include <enet/enet.h>
#include <glm/gtc/matrix_transform.hpp>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <memory>
#include <tuple>
#include <array>
#include <algorithm>
extern "C" {
#include <sys/stat.h>
}
#ifdef __MINGW32__
#include "mingw.thread.h"
#else
#include <thread>
#endif
#include <chrono>
#include "graphics_includes.h"
#include "globjects.h"
#include "focus.h"
#include "game_limits.h"
#include "server.h"
#include "client.h"
#include "globjects.h"
#include "icon.png.h"
#include "base_skin.png.h"
#include "spritesheet.png.h"
#include "shader.h"
#include "shader_fsh.glsl.h"
#include "flat_shader_vsh.glsl.h"
#include "world_shader_vsh.glsl.h"
inline constexpr std::string_view CONFIG_VERSION = "v02";
void glCheckError_(const char *file, int line)
{
int errorCode;
while ((errorCode = glGetError()) != GL_NO_ERROR)
{
switch (errorCode)
{
case GL_INVALID_ENUM: fprintf(stderr, "%s", "INVALID_ENUM"); break;
case GL_INVALID_VALUE: fprintf(stderr, "%s", "INVALID_VALUE"); break;
case GL_INVALID_OPERATION: fprintf(stderr, "%s", "INVALID_OPERATION"); break;
case GL_STACK_OVERFLOW: fprintf(stderr, "%s", "STACK_OVERFLOW"); break;
case GL_STACK_UNDERFLOW: fprintf(stderr, "%s", "STACK_UNDERFLOW"); break;
case GL_OUT_OF_MEMORY: fprintf(stderr, "%s", "OUT_OF_MEMORY"); break;
case GL_INVALID_FRAMEBUFFER_OPERATION: fprintf(stderr, "%s", "INVALID_FRAMEBUFFER_OPERATION"); break;
}
fprintf(stderr, " | %s (%d)\n", file, line);
}
}
static void glfw_error_callback(int error, const char* description)
{
fprintf(stderr, "Glfw Error %d: %s\n", error, description);
}
static bool check_username_char_valid(const char c)
{
return (c == '_' || c== ' ' || (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'));
}
static int username_callback(ImGuiInputTextCallbackData* data)
{
if(auto c = data->EventChar; !check_username_char_valid(c))
{
return 1;
}
return 0;
}
static void server_thread_func(std::unique_ptr<MineServer>&& srv_ptr)
{
std::unique_ptr<MineServer> server = std::move(srv_ptr);
const auto first_upd = std::chrono::steady_clock::now();
auto last_upd = first_upd;
bool first_tick = true;
while(!server->should_shutdown())
{
if(server->is_all_set) {
auto now = std::chrono::steady_clock::now();
if(first_tick)
{
last_upd = now;
first_tick = false;
}
if(const float deltaTime = std::chrono::duration<float>{now - last_upd}.count(); deltaTime >= TIME_PER_TICK * 2.0f)
{
server->update(deltaTime);
server->send_update();
last_upd = now;
}
}
server->receive();
}
}
struct WindowDeleter {
void operator()(GLFWwindow* w)
{
glfwDestroyWindow(w);
}
};
using WindowPtr = std::unique_ptr<GLFWwindow, WindowDeleter>;
static void do_graphical(std::string filepath, const char* skinpath)
{
GLFWmonitor* primary = glfwGetPrimaryMonitor();
int total_resolutions;
const GLFWvidmode* m = glfwGetVideoModes(primary, &total_resolutions);
std::vector<std::pair<int, int>> resolution_results;
for(auto mp = m; mp != m + total_resolutions; ++mp)
{
const auto& m = *mp;
auto p = std::make_pair(m.width, m.height);
if(std::find(resolution_results.cbegin(), resolution_results.cend(), p) == resolution_results.cend())
{
resolution_results.push_back(std::move(p));
}
}
total_resolutions = resolution_results.size();
std::sort(resolution_results.begin(), resolution_results.end());
const std::string possible_resolutions_str = [&]() {
std::string s;
for(const auto& [w, h] : resolution_results)
{
s += std::to_string(w) + "x" + std::to_string(h) + '\0';
}
return s;
}();
const std::vector<const char*> possible_resolutions = [&]() {
std::vector<const char*> v;
std::string_view sv{possible_resolutions_str};
for(int i = 0; i < total_resolutions; ++i)
{
v.push_back(sv.data());
sv.remove_prefix(sv.find('\0', 3) + 1);
}
return v;
}();
int current_resolution = 0;
// Decide GL+GLSL versions
// GL 3.0 + GLSL 330
#ifndef __SWITCH__
const char* glsl_version = "#version 330 core";
#else
const char* glsl_version = "#version 300 es";
#endif
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // 3.2+ only
glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE);
const auto [initial_w, initial_h] = resolution_results[current_resolution];
// Create window with graphics context
WindowPtr window_holder(glfwCreateWindow(initial_w, initial_h, "MinesweeperFPS v1.2", nullptr, nullptr));
if(!window_holder)
return;
auto window = window_holder.get();
glfwMakeContextCurrent(window);
// Initialize OpenGL loader
bool err = gladLoadGLLoader((GLADloadproc)glfwGetProcAddress) == 0;
if(err)
{
fprintf(stderr, "Failed to initialize OpenGL loader!\n");
return;
}
glfwSwapInterval(1); // Enable vsync
GLFWimage icon_image;
const auto& [icon_image_width, icon_image_height, icon_image_pixels] = Images::icon;
auto icon_pixels = std::make_unique<unsigned char[]>(icon_image_pixels.size());
memcpy(icon_pixels.get(), icon_image_pixels.data(), icon_image_pixels.size());
std::tie(icon_image.width, icon_image.height, icon_image.pixels) = std::tuple(icon_image_width, icon_image_height, icon_pixels.get());
glfwSetWindowIcon(window, 1, &icon_image);
glfwSetWindowFocusCallback(window, Focus::callback);
glfwSetInputMode(window, GLFW_STICKY_KEYS, GLFW_TRUE);
glfwSetInputMode(window, GLFW_STICKY_MOUSE_BUTTONS, GLFW_TRUE);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// Setup Dear ImGui context
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
io.IniFilename = nullptr;
io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
// Setup Dear ImGui style
ImGui::StyleColorsDark();
// Setup Platform/Renderer bindings
ImGui_ImplGlfw_InitForOpenGL(window, true);
ImGui_ImplOpenGL3_Init(glsl_version);
// Our state
{
constexpr std::string_view world_vsh_shader(Shaders::world_shader_vsh.data(), Shaders::world_shader_vsh.size());
constexpr std::string_view flat_vsh_shader(Shaders::flat_shader_vsh.data(), Shaders::flat_shader_vsh.size());
constexpr std::string_view fsh_shader(Shaders::shader_fsh.data(), Shaders::shader_fsh.size());
Shader worldShader(world_vsh_shader, fsh_shader);
Shader flatShader(flat_vsh_shader, fsh_shader);
const auto& [tex_width, tex_height, tex_data] = Images::spritesheet;
glActiveTexture(GL_TEXTURE0);
Texture spritesheet(tex_width, tex_height, tex_data.data());
const auto& [skin_width, skin_height, skin_data] = Images::base_skin;
Texture default_skin(skin_width, skin_height, skin_data.data());
flatShader.use();
flatShader.setInt("texture1", 0);
worldShader.use();
worldShader.setInt("texture1", 0);
char username[MAX_NAME_LEN + 1] = {0};
const auto set_username = [](char* usr) {
#ifdef __SWITCH__
Result rc = accountInitialize(AccountServiceType_Application);
if(R_FAILED(rc)) return;
AccountUid userID={0};
AccountProfile profile;
AccountUserData userdata;
AccountProfileBase profilebase;
rc = accountGetPreselectedUser(&userID);
if(R_SUCCEEDED(rc))
{
rc = accountGetProfile(&profile, userID);
if(R_SUCCEEDED(rc))
{
rc = accountProfileGet(&profile, &userdata, &profilebase);//userdata is otional, see libnx acc.h.
if(R_SUCCEEDED(rc))
{
for(size_t i = 0, o = 0; i < MAX_NAME_LEN; ++i)
{
const char c = profilebase.nickname[i];
if(c & 0x80) // remove all utf-8 characters, only ascii here
{
if(c & 0x40)
{
++i;
if(c & 0x20)
{
++i;
if(c & 0x10)
{
++i;
}
}
}
}
else if(check_username_char_valid(c)) // and even then, only a subset of ascii (alphanumeric + _ + space)
{
usr[o] = c;
++o;
}
}
}
accountProfileClose(&profile);
}
}
accountExit();
#endif
if(usr[0] == 0) strncpy(usr, "Player", MAX_NAME_LEN);
};
set_username(username);
char server_address[2048] = {0};
std::array<float, 4> crosshair_color{{
0.25f, 0.25f, 0.25f, 0.75f
}};
std::thread server_thread;
std::unique_ptr<MineClient> client;
enum class MenuScreen {
Main,
Settings,
Server,
CoOpClient,
SPClient,
StartingServer,
StartingLocalServer,
StartingClient,
InGame,
AfterGame,
};
MenuScreen screen = MenuScreen::Main;
const auto main_window_flags = ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoCollapse;
const auto extra_window_flags = ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoCollapse;
bool closed_extra_window = true;
bool in_esc_menu = false;
bool is_typing = false;
bool released_esc = false;
bool first_frame = false;
bool start_client = false, start_server = false;
bool fullscreen = false;
std::vector<std::unique_ptr<char[]>> out_chat;
float mouse_sensitivity = 3.5f;
int fov = 60;
int crosshair_distance = 5;
int crosshair_width = 8;
int crosshair_length = 20;
int minimap_scale = 10;
int overlay_w = 25;
int overlay_h = 50;
int map_width = 15, map_height = 15, bombs_percent = 10, player_amount = 2;
int window_x = 0, window_y = 0;
float client_start_time = 0.0f;
bool modified_config = false;
const auto load_config = [&]() {
fprintf(stderr, "Attempting to load config from: '%s'\n", filepath.c_str());
struct stat s;
if(stat(filepath.c_str(), &s) < 0)
{
modified_config = true;
}
else if(FILE* fh = fopen(filepath.c_str(), "r"); fh != nullptr)
{
auto buf = std::make_unique<char[]>(s.st_size);
size_t rsize = fread(buf.get(), 1, s.st_size, fh);
fclose(fh);
std::string_view sv(buf.get(), rsize);
if(sv.compare(0, CONFIG_VERSION.size(), CONFIG_VERSION) == 0)
{
sv = sv.substr(CONFIG_VERSION.size() + 1); // + 1 for ';'
while(sv.size() > 0)
{
const char front = sv.front();
sv = sv.substr(2);
const size_t len = sv.find_first_of(';');
const auto val = sv.substr(0, len);
constexpr auto convert_to_float = [](auto val) { return std::stof(std::string(val)); };
constexpr auto convert_to_int = [](auto val) { return std::stoi(std::string(val)); };
switch(front)
{
case 'n':
memset(username, 0, MAX_NAME_LEN);
strncpy(username, val.data(), std::min(MAX_NAME_LEN, len));
break;
#define MAP_TO(constant, out, conv) case constant: out = conv(val); break;
MAP_TO('r', crosshair_color[0], convert_to_float)
MAP_TO('g', crosshair_color[1], convert_to_float)
MAP_TO('b', crosshair_color[2], convert_to_float)
MAP_TO('a', crosshair_color[3], convert_to_float)
MAP_TO('S', mouse_sensitivity, convert_to_float)
MAP_TO('d', crosshair_distance, convert_to_int)
MAP_TO('w', crosshair_width, convert_to_int)
MAP_TO('l', crosshair_length, convert_to_int)
MAP_TO('W', overlay_w, convert_to_int)
MAP_TO('H', overlay_h, convert_to_int)
MAP_TO('Z', minimap_scale, convert_to_int)
MAP_TO('F', fov, convert_to_int)
#undef MAP_TO
default:
break;
}
sv = sv.substr(len + 1);
}
}
}
else
{
modified_config = true;
}
};
load_config();
std::string typed_text;
auto last_int_upd = std::chrono::steady_clock::now();
auto last_ext_upd = last_int_upd;
// Main loop
while(!glfwWindowShouldClose(window))
{
// Poll and handle events (inputs, window resize, etc.)
// You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
// Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
glfwPollEvents();
int display_w, display_h;
glfwGetFramebufferSize(window, &display_w, &display_h);
// Start the Dear ImGui frame
auto start_imgui_frame = [](){
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
ImVec2 center(ImGui::GetIO().DisplaySize.x * 0.5f, ImGui::GetIO().DisplaySize.y * 0.5f);
ImVec2 sz(ImGui::GetIO().DisplaySize.x * 0.75f, ImGui::GetIO().DisplaySize.y * 0.75f);
ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));
ImGui::SetNextWindowSize(center);
};
const MineClient::State st = client ? client->get_state() : MineClient::State::NotConnected;
const auto now = std::chrono::steady_clock::now();
const auto lastComm = std::chrono::duration<float>{now - last_ext_upd}.count();
const auto deltaTime = std::chrono::duration<float>{now - last_int_upd}.count();
const auto prev_screen = screen;
if(screen == MenuScreen::InGame)
{
if(st != MineClient::State::Playing || lastComm >= TIME_PER_TICK)
{
ENetEvent event;
if(client->host && enet_host_service(client->host.get(), &event, 1))
{
switch(event.type)
{
case ENET_EVENT_TYPE_CONNECT:
// connection succeeded
break;
case ENET_EVENT_TYPE_RECEIVE:
client->receive_packet(event.packet->data, event.packet->dataLength, out_chat);
// Clean up the packet now that we're done using it.
enet_packet_destroy(event.packet);
break;
case ENET_EVENT_TYPE_DISCONNECT:
client->disconnect(true);
break;
}
}
}
if(st == MineClient::State::NotConnected)
{
start_imgui_frame();
int timeout = 5 - int(glfwGetTime() - client_start_time);
if(timeout == 0) client->cancel();
ImGui::Begin("Waiting for server", nullptr, extra_window_flags);
ImGui::Text("Please wait for the connection to the server to complete.");
ImGui::Text("Timeout in %d second%s.", timeout, timeout == 1 ? "" : "s");
ImGui::End();
}
else if(st == MineClient::State::Waiting)
{
start_imgui_frame();
ImGui::Begin("Waiting for players", nullptr, extra_window_flags);
ImGui::Text("Please wait for the other players to join.");
ImGui::End();
}
else if(st == MineClient::State::Playing)
{
auto set_controls_for_game = [&]() -> void {
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
};
if(first_frame)
{
first_frame = false;
set_controls_for_game();
}
if(in_esc_menu)
{
start_imgui_frame();
ImGui::Begin("Pause menu", &closed_extra_window, extra_window_flags);
if(ImGui::SliderInt("HUD width", &overlay_w, 5, 45)) modified_config = true;
if(ImGui::SliderInt("HUD height", &overlay_h, 10, 90)) modified_config = true;
if(ImGui::SliderInt("Minimap zoom", &minimap_scale, 0, 20)) modified_config = true;
ImGui::Spacing();
if(ImGui::SliderInt("Field of View", &fov, 30, 90)) modified_config = true;
ImGui::Spacing();
if(ImGui::SliderFloat("Mouse sensitivity", &mouse_sensitivity, 0.5f, 5.0f)) modified_config = true;
if(ImGui::SliderInt("Crosshair thickness", &crosshair_width, 4, 16)) modified_config = true;
if(ImGui::SliderInt("Crosshair size", &crosshair_length, 8, 35)) modified_config = true;
if(ImGui::SliderInt("Crosshair space", &crosshair_distance, 4, 12)) modified_config = true;
ImGui::Separator();
if(ImGui::Button("Back to game")) in_esc_menu = false;
ImGui::SameLine();
if(ImGui::Button("Back to main menu")) client->disconnect(true);
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
ImGui::End();
if(!closed_extra_window)
{
closed_extra_window = true;
in_esc_menu = false;
}
if(glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
{
if(released_esc)
{
in_esc_menu = false;
released_esc = false;
}
}
else
{
released_esc = true;
}
if(!in_esc_menu) set_controls_for_game();
}
if(deltaTime >= 1.0f/60.0f)
{
client->handle_events(window, mouse_sensitivity/20.0f, display_w, display_h, in_esc_menu, released_esc, is_typing, deltaTime);
if(in_esc_menu)
{
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
}
last_int_upd = now;
}
}
else
{
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
if(client->host) client->disconnect(false);
screen = MenuScreen::AfterGame;
}
}
else if(screen == MenuScreen::AfterGame)
{
auto exit_lambda = [&]() {
screen = MenuScreen::Main;
client = nullptr;
if(server_thread.joinable()) server_thread.join();
};
start_imgui_frame();
if(st == MineClient::State::Cancelled)
{
ImGui::Begin("Your connection was cancelled.", &closed_extra_window, extra_window_flags);
if(ImGui::Button("Back to main menu")) exit_lambda();
ImGui::SameLine();
if(ImGui::Button("Quit game")) glfwSetWindowShouldClose(window, true);
ImGui::End();
}
if(st == MineClient::State::Lost)
{
ImGui::Begin("You lost to the mines!", &closed_extra_window, extra_window_flags);
ImGui::Text("What a shame, you didn't win this time! Better luck on the next one.");
ImGui::Text("Loss in %02d min%s %02d second%s",
client->sc_packet.minutes, client->sc_packet.minutes == 1 ? "" : "s",
client->sc_packet.seconds, client->sc_packet.seconds == 1 ? "" : "s");
ImGui::Separator();
if(ImGui::Button("Back to main menu")) exit_lambda();
ImGui::SameLine();
if(ImGui::Button("Quit game")) glfwSetWindowShouldClose(window, true);
ImGui::End();
}
else if(st == MineClient::State::Won)
{
ImGui::Begin("You won!", &closed_extra_window, extra_window_flags);
ImGui::Text("Congratulations! Maybe challenge yourself with a bigger field?");
ImGui::Text("Victory in %02d min%s %02d second%s",
client->sc_packet.minutes, client->sc_packet.minutes == 1 ? "" : "s",
client->sc_packet.seconds, client->sc_packet.seconds == 1 ? "" : "s");
ImGui::Separator();
if(ImGui::Button("Back to main menu")) exit_lambda();
ImGui::SameLine();
if(ImGui::Button("Quit game")) glfwSetWindowShouldClose(window, true);
ImGui::End();
}
else if(st == MineClient::State::Disconnected)
{
ImGui::Begin("You were disconnected.", &closed_extra_window, extra_window_flags);
ImGui::Text("You were disconnected from the server.");
ImGui::Separator();
if(ImGui::Button("Back to main menu")) exit_lambda();
ImGui::SameLine();
if(ImGui::Button("Quit game")) glfwSetWindowShouldClose(window, true);
ImGui::End();
}
if(!closed_extra_window)
{
closed_extra_window = true;
client = nullptr;
exit_lambda();
}
}
else
{
if(start_client)
{
size_t l = strnlen(username, MAX_NAME_LEN);
if(l < MAX_NAME_LEN) memset(username + l, 0, MAX_NAME_LEN - l);
client = std::make_unique<MineClient>(server_address, skinpath, default_skin, crosshair_color, username);
client_start_time = glfwGetTime();
start_client = false;
in_esc_menu = false;
first_frame = true;
screen = MenuScreen::InGame;
}
if(start_server)
{
server_thread = std::thread(server_thread_func, std::make_unique<MineServer>(map_width, map_height, bombs_percent, player_amount));
std::this_thread::sleep_for(std::chrono::milliseconds(250));
std::fill(std::begin(server_address), std::end(server_address), '\0');
player_amount = player_amount == 1 ? 2 : player_amount;
start_server = false;
screen = MenuScreen::StartingClient;
}
if(screen != MenuScreen::InGame) start_imgui_frame();
if(screen == MenuScreen::Main)
{
ImGui::Begin("Welcome to MinesweeperFPS v1.1!", nullptr, main_window_flags);
ImGui::Text("This is a clone of Minesweeper, where you play in a first person view!");
ImGui::Text("It also supports playing with friends, to make large maps easier.");
ImGui::Separator();
if(ImGui::Button("Edit settings")) screen = MenuScreen::Settings;
if(ImGui::Button("Play singleplayer")) screen = MenuScreen::SPClient;
if(ImGui::Button("Host coop server")) screen = MenuScreen::Server;
if(ImGui::Button("Join coop server")) screen = MenuScreen::CoOpClient;
ImGui::Separator();
if(ImGui::Button("Quit game")) glfwSetWindowShouldClose(window, true);
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
ImGui::End();
}
else if(screen == MenuScreen::Settings)
{
ImGui::Begin("Settings", &closed_extra_window, extra_window_flags);
ImGui::Text("Player settings");
if(ImGui::InputText("Player name", username, MAX_NAME_LEN, ImGuiInputTextFlags_CallbackCharFilter, username_callback))
{
modified_config = true;
}
if(ImGui::ColorEdit4("Crosshair color", crosshair_color.data(), ImGuiColorEditFlags_AlphaBar | ImGuiColorEditFlags_AlphaPreview))
{
modified_config = true;
}
if(total_resolutions > 1)
{
ImGui::Spacing();
ImGui::Text("Graphics settings");
if(ImGui::Checkbox("Fullscreen", &fullscreen))
{
if(fullscreen)
{
GLFWmonitor* monitor = glfwGetPrimaryMonitor();
const GLFWvidmode* mode = glfwGetVideoMode(monitor);
glfwGetWindowPos(window, &window_x, &window_y);
glfwSetWindowMonitor(window, monitor, 0, 0, mode->width, mode->height, 60);
}
else
{
const auto& [resolution_x, resolution_y] = resolution_results[current_resolution];
glfwSetWindowMonitor(window, nullptr, window_x, window_y, resolution_x, resolution_y, 60);
}
}
if(!fullscreen)
{
if(ImGui::Combo("Resolution", ¤t_resolution, possible_resolutions.data(), total_resolutions))
{
const auto& [resolution_x, resolution_y] = resolution_results[current_resolution];
glfwSetWindowSize(window, resolution_x, resolution_y);
}
}
}
ImGui::Separator();
if(ImGui::Button("Back")) screen = MenuScreen::Main;
ImGui::End();
}
else if(screen == MenuScreen::Server)
{
ImGui::Begin("Host", &closed_extra_window, extra_window_flags);
ImGui::SliderInt("Map width", &map_width, Limits::Min::Width, Limits::Max::Width);
ImGui::SliderInt("Map height", &map_height, Limits::Min::Height, Limits::Max::Height);
ImGui::SliderInt("Bomb %", &bombs_percent, Limits::Min::BombPercent, Limits::Max::BombPercent);
ImGui::Spacing();
ImGui::SliderInt("Players", &player_amount, Limits::Min::Players, Limits::Max::Players);
ImGui::Separator();
if(ImGui::Button("Start")) screen = MenuScreen::StartingServer;
ImGui::SameLine();
if(ImGui::Button("Back")) screen = MenuScreen::Main;
ImGui::End();
}
else if(screen == MenuScreen::CoOpClient)
{
ImGui::Begin("Join", &closed_extra_window, extra_window_flags);
ImGui::InputText("Server address", server_address, IM_ARRAYSIZE(server_address));
ImGui::Separator();
if(ImGui::Button("Join")) screen = MenuScreen::StartingClient;
ImGui::SameLine();
if(ImGui::Button("Back")) screen = MenuScreen::Main;
ImGui::End();
}
else if(screen == MenuScreen::SPClient)
{
ImGui::Begin("Singleplayer", &closed_extra_window, extra_window_flags);
ImGui::SliderInt("Map width", &map_width, Limits::Min::Width, Limits::Max::Width);
ImGui::SliderInt("Map height", &map_height, Limits::Min::Height, Limits::Max::Height);
ImGui::SliderInt("Bomb %", &bombs_percent, Limits::Min::BombPercent, Limits::Max::BombPercent);
ImGui::Separator();
if(ImGui::Button("Start")) screen = MenuScreen::StartingLocalServer;
ImGui::SameLine();
if(ImGui::Button("Back")) screen = MenuScreen::Main;
ImGui::End();
}
else if(screen == MenuScreen::StartingServer)
{
ImGui::Begin("Starting co-op server", nullptr, main_window_flags);
ImGui::Text("Please wait...");
ImGui::End();
start_server = true;
}
else if(screen == MenuScreen::StartingLocalServer)
{
ImGui::Begin("Starting local server", nullptr, main_window_flags);
ImGui::Text("Please wait...");
ImGui::End();
player_amount = 1;
start_server = true;
}
else if(screen == MenuScreen::StartingClient)
{
ImGui::Begin("Starting client", nullptr, main_window_flags);
ImGui::Text("Please wait...");
ImGui::End();
start_client = true;
}
if(!closed_extra_window)
{
screen = MenuScreen::Main;
closed_extra_window = true;
}
}
glViewport(0, 0, display_w, display_h);
glClearColor(0.0f, 148.0f/255.0f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if(client && st == MineClient::State::Playing)
{
MineClient::RenderInfo info{
worldShader, flatShader, spritesheet, display_w, display_h,
crosshair_distance, crosshair_width, crosshair_length,
minimap_scale,
overlay_w, overlay_h,
fov
};
client->render(info);
if(lastComm >= (TIME_PER_TICK * 2.0f))
{
client->send();
last_ext_upd = now;
}
}
if((screen == MenuScreen::AfterGame && prev_screen == screen) || (screen != MenuScreen::InGame && screen != MenuScreen::AfterGame) || st != MineClient::State::Playing || in_esc_menu)
{
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
}
glfwSwapBuffers(window);
}
if(server_thread.joinable()) server_thread.join();
if(modified_config)
{
if(FILE* fh = fopen(filepath.c_str(), "w"); fh != nullptr)
{
std::string to_write(CONFIG_VERSION.data(), CONFIG_VERSION.size());
to_write += ';';
#define ADD(constant, in) { \
to_write += constant; \
to_write += ':'; \
to_write += in; \
to_write += ';'; \
}
#define MAP_TO(constant, in) ADD(constant, std::to_string(in))
ADD('n', username)
MAP_TO('r', crosshair_color[0])
MAP_TO('g', crosshair_color[1])
MAP_TO('b', crosshair_color[2])
MAP_TO('a', crosshair_color[3])
MAP_TO('S', mouse_sensitivity)
MAP_TO('d', crosshair_distance)
MAP_TO('w', crosshair_width)
MAP_TO('l', crosshair_length)
MAP_TO('W', overlay_w)
MAP_TO('H', overlay_h)
MAP_TO('Z', minimap_scale)
MAP_TO('F', fov)
#undef MAP_TO
#undef ADD
fwrite(to_write.c_str(), 1, to_write.size(), fh);
fclose(fh);
}
}
}
// Cleanup
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
}
#ifndef __SWITCH__
static void do_server_alone(char** args)
{
const char* width_a = args[0];
const int width = atoi(width_a);
if(Limits::Max::Width < width || width < Limits::Min::Width) return;
const char* height_a = args[1];
const int height = atoi(height_a);
if(Limits::Max::Height < height || height < Limits::Min::Height) return;
const char* bombs_a = args[2];
const int bombs = atoi(bombs_a);
if(Limits::Max::BombPercent < bombs || bombs < Limits::Min::BombPercent) return;
const char* players_a = args[3];
const int players = atoi(players_a);
if(Limits::Max::Players < players || players < Limits::Min::Players) return;
printf("Starting server\n - width: %d\n - height: %d\n - bombs %%: %d\n - players: %d\n", width, height, bombs, players);
server_thread_func(std::make_unique<MineServer>(width, height, bombs, players));
printf("Server stopped.\n");
}
#endif
int main(int argc, char** argv)
{
if(enet_initialize () != 0)
{
fprintf(stderr, "An error occurred while initializing ENet.\n");
return 1;
}
#ifndef __SWITCH__
if(argc == 6)
{
const char* server_indicator = argv[1];
if(strcmp(server_indicator, "srv") == 0) do_server_alone(argv + 2);
}
else if(argc <= 2)
#endif
{
glfwSetErrorCallback(glfw_error_callback);
if(glfwInit())
{
std::string confpath = argv[0];
do_graphical(confpath + ".cfg", argv[1]);
glfwTerminate();
}
}
enet_deinitialize();
}
| 37.664179
| 190
| 0.538651
|
LiquidFenrir
|
8c7a128f7d22b05646abc7b8cd63a65e7e15b2d8
| 1,403
|
hpp
|
C++
|
include/wav.hpp
|
hackner-security/swd
|
52376221afbe1968cf269ab5d08d18ffad41fba1
|
[
"MIT"
] | 4
|
2020-09-26T12:35:28.000Z
|
2021-06-13T12:22:03.000Z
|
include/wav.hpp
|
hackner-security/swd
|
52376221afbe1968cf269ab5d08d18ffad41fba1
|
[
"MIT"
] | null | null | null |
include/wav.hpp
|
hackner-security/swd
|
52376221afbe1968cf269ab5d08d18ffad41fba1
|
[
"MIT"
] | 1
|
2020-10-27T12:11:46.000Z
|
2020-10-27T12:11:46.000Z
|
// Copyright 2020 Barger M., Knoll M., Kofler L.
#ifndef INCLUDE_WAV_HPP_
#define INCLUDE_WAV_HPP_
#include <string>
#include <iostream>
#include <vector>
#include <fstream>
#include <iterator>
#include "log.hpp"
// WAV Header
#define WAV_HEADER_SIZE 44
struct WAV_HEADER {
// RIFF Header
char riff_magic_num[4];
uint32_t file_size;
char wav_magic_num[4];
// FMT Header
char fmt_magic_num[4];
uint32_t fmt_hdr_len;
uint16_t format_tag;
uint16_t channels;
uint32_t sample_rate;
uint32_t bytes_per_second;
uint16_t block_align;
uint16_t bits_per_sample;
// Chunk Header
char chunk_magic_num[4];
uint32_t data_block_len;
};
class Wav {
public:
// Constructor
//
// file_path: path to the wav file
Wav();
// Extracts information from a wav file
//
// return: was extraction successful
bool Read(std::string file_path);
bool Read(std::vector<int8_t> alaw_samples);
// return: samples in the file
std::vector<int16_t> GetSamples();
// return: sample rate
uint GetSampleRate();
// Prints all header information to the console
void PrintHeaderInfo();
bool IsWavFile();
double GetDuration();
private:
int16_t DecodeAlawSample(int8_t number);
void DecodeAlaw(std::vector<int8_t> alaw_samples);
std::vector<int16_t> samples;
std::string file_name;
WAV_HEADER wav_hdr;
double duration;
};
#endif // INCLUDE_WAV_HPP_
| 18.460526
| 52
| 0.71846
|
hackner-security
|
8c7e18ec40572d542a476ed7a78fb3aeec471826
| 1,862
|
cpp
|
C++
|
CSES/RangeQueries/forest_queries.cpp
|
PranavReddyP16/DSA-Templates
|
cb68b1ced5fd4990a413ce88cdb741fdcaa6e89b
|
[
"MIT"
] | null | null | null |
CSES/RangeQueries/forest_queries.cpp
|
PranavReddyP16/DSA-Templates
|
cb68b1ced5fd4990a413ce88cdb741fdcaa6e89b
|
[
"MIT"
] | null | null | null |
CSES/RangeQueries/forest_queries.cpp
|
PranavReddyP16/DSA-Templates
|
cb68b1ced5fd4990a413ce88cdb741fdcaa6e89b
|
[
"MIT"
] | null | null | null |
#include "bits/stdc++.h"
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
using namespace std::chrono;
#define ll long long
#define ld long double
#define sz(c) ((ll)c.size())
#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
#define int ll
const ll inf = 1e18;
const int mod = 1e9 + 7;
const int mod2 = 998244353;
high_resolution_clock::time_point curTime() { return high_resolution_clock::now(); }
#define rep(i,n) for(int i=0;i<n;i++)
signed main()
{
ios_base :: sync_with_stdio(false);
cin.tie(NULL);
auto startTime = curTime();
int n;
cin>>n;
int q;
cin>>q;
vector<string> a(n);
for(int i=0;i<n;i++)
{
cin>>a[i];
}
vector<vector<int>> dp(n, vector<int> (n));
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(i==0 && j==0)
{
dp[i][j] = (a[i][j]=='*'? 1 : 0);
continue;
}
if(i==0) dp[i][j] = dp[i][j-1]+(a[i][j]=='*'? 1 : 0);
if(j==0) dp[i][j] = dp[i-1][j]+(a[i][j]=='*'? 1 : 0);
if(i>0&&j>0)
{
dp[i][j] = dp[i-1][j]+dp[i][j-1]-dp[i-1][j-1] + (a[i][j]=='*'?1:0);
}
}
}
while(q--)
{
int x1,x2,y1,y2;
cin>>x1>>y1>>x2>>y2;
y1--;
x1--;
y2--;
x2--;
int ans=0;
ans += dp[x2][y2];
if(x1>0) ans -= dp[x1-1][y2];
if(y1>0) ans -= dp[x2][y1-1];
if(x1*y1>0) ans += dp[x1-1][y1-1];
cout<<ans<<endl;
}
auto stopTime = curTime();
auto duration = duration_cast<microseconds>(stopTime - startTime);
//cout<<"Program ran for "<<(ld)duration.count()/1e6<<" "<<"seconds"<<endl;
}
| 21.905882
| 97
| 0.489259
|
PranavReddyP16
|
8c7fa0ba5640be3d5bedf217754da3122904a68d
| 6,484
|
cpp
|
C++
|
test/accumulator_test.cpp
|
4paradigm/prpc
|
2d264b696dd08191346535b852bb2b5391506a20
|
[
"Apache-2.0"
] | 2
|
2021-08-24T03:35:11.000Z
|
2021-09-08T15:17:07.000Z
|
test/accumulator_test.cpp
|
4paradigm/prpc
|
2d264b696dd08191346535b852bb2b5391506a20
|
[
"Apache-2.0"
] | null | null | null |
test/accumulator_test.cpp
|
4paradigm/prpc
|
2d264b696dd08191346535b852bb2b5391506a20
|
[
"Apache-2.0"
] | null | null | null |
#include <cstdlib>
#include <cstdio>
#include <glog/logging.h>
#include <gtest/gtest.h>
#include <sys/prctl.h>
#include "macro.h"
#include "Aggregator.h"
#include "SumAggregator.h"
#include "AvgAggregator.h"
#include "ArithmeticMaxAggregator.h"
#include "ArithmeticMinAggregator.h"
#include "TimerAggregator.h"
#include "Accumulator.h"
#include "MultiProcess.h"
namespace paradigm4 {
namespace pico {
namespace core {
class AccumulatorMultiProcess {
public:
AccumulatorMultiProcess(size_t num): _num(num) {
_master = std::make_unique<Master>("127.0.0.1");
_master->initialize();
p = std::make_unique<MultiProcess>(num);
_mc = std::make_unique<TcpMasterClient>(_master->endpoint());
_mc->initialize();
RpcConfig rpc_config;
rpc_config.protocol = "tcp";
rpc_config.bind_ip = "127.0.0.1";
rpc_config.io_thread_num = 1;
_rpc = std::make_unique<RpcService>();
_rpc->initialize(_mc.get(), rpc_config);
if (_rpc->global_rank() == 0) {
AccumulatorServer::singleton().initialize(_rpc.get());
}
AccumulatorClient::singleton().initialize(_rpc.get());
}
~AccumulatorMultiProcess() {
if (comm_rank() == 0) {
AccumulatorClient::singleton().erase_all();
}
AccumulatorClient::singleton().finalize();
_mc->barrier("XXXXX", _num);
if (comm_rank() == 0) {
AccumulatorServer::singleton().finalize();
}
_rpc->finalize();
_mc->finalize();
p.reset();
_master->exit();
_master->finalize();
}
comm_rank_t comm_rank() {
return _rpc->global_rank();
}
comm_rank_t comm_size() {
return _num;
}
void wait_empty() {
AccumulatorClient::singleton().wait_empty();
AccumulatorServer::singleton().wait_empty();
_mc->barrier("XXXX", _num);
}
size_t _num;
std::unique_ptr<Master> _master;
std::unique_ptr<TcpMasterClient> _mc;
std::unique_ptr<RpcService> _rpc;
std::unique_ptr<MultiProcess> p;
};
void AccumulatorTest_single_thread_per_rank_sum_int_check_ok(size_t num) {
AccumulatorMultiProcess mp(num);
Accumulator<SumAggregator<int64_t>> counter("sum_int_counter_single_ok", 10);
const int count_max = 1000;
for (int i = 0; i < count_max; i++) {
ASSERT_TRUE(counter.write((i+1) * (mp.comm_rank()+1)));
}
mp.wait_empty();
if (mp.comm_rank() == 0) {
Accumulator<SumAggregator<int64_t>> counter("sum_int_counter_single_ok");
std::string cnt_res;
ASSERT_TRUE(counter.try_read_to_string(cnt_res));
std::string right_res = boost::lexical_cast<std::string>((1+count_max)*count_max/2
* mp.comm_size() * (mp.comm_size() + 1) / 2);
EXPECT_STREQ(right_res.c_str(), cnt_res.c_str());
}
}
void AccumulatorTest_multi_thread_per_rank_sum_int_check_ok(size_t num) {
AccumulatorMultiProcess mp(num);
const int64_t thread_num = 101;
const int64_t count_max = 1000;
std::thread thr[thread_num];
for (int64_t tid = 0; tid < thread_num; tid++) {
thr[tid] = std::thread([&mp, tid]() {
Accumulator<SumAggregator<int64_t>> counter("sum_int_counter_multi_ok", 10);
for (int64_t i = 0; i < count_max; i++) {
ASSERT_TRUE(counter.write((i+1) * (tid+1) * (mp.comm_rank()+1)));
}
});
}
for (int64_t tid = 0; tid < thread_num; tid++) {
thr[tid].join();
}
mp.wait_empty();
if (mp.comm_rank() == 0) {
for (int64_t i = 0; i < mp.comm_size(); i++) {
Accumulator<SumAggregator<int64_t>> counter("sum_int_counter_multi_ok");
std::string cnt_res;
ASSERT_TRUE(counter.try_read_to_string(cnt_res));
std::string right_res = boost::lexical_cast<std::string>( (1+count_max)*count_max/2
* thread_num * (thread_num + 1) / 2
* mp.comm_size() * (mp.comm_size() + 1) / 2);
EXPECT_STREQ(right_res.c_str(), cnt_res.c_str());
}
}
}
void AccumulatorTest_single_thread_per_rank_maxmin_int_check_ok(size_t num) {
AccumulatorMultiProcess mp(num);
Accumulator<ArithmeticMaxAggregator<int>> counter_max("max_int_counter_single_ok", 10);
Accumulator<ArithmeticMinAggregator<int>> counter_min("min_int_counter_single_ok", 10);
const int64_t count_max = 10000;
for (int64_t i = 0; i < count_max; i++) {
ASSERT_TRUE(counter_max.write((i+1) * (mp.comm_rank()+1)));
ASSERT_TRUE(counter_min.write((i+1) * (mp.comm_rank()+1)));
}
mp.wait_empty();
Accumulator<AvgAggregator<float>> dummy1("dummy1");
Accumulator<TimerAggregator<float>> dummy2("dummy2");
if (mp.comm_rank() == 0) {
Accumulator<ArithmeticMaxAggregator<int>> counter_max("max_int_counter_single_ok", 10);
Accumulator<ArithmeticMinAggregator<int>> counter_min("min_int_counter_single_ok", 10);
std::string cnt_res;
ASSERT_TRUE(counter_max.try_read_to_string(cnt_res));
std::string right_res = boost::lexical_cast<std::string>(count_max * mp.comm_size());
EXPECT_STREQ(right_res.c_str(), cnt_res.c_str());
ASSERT_TRUE(counter_min.try_read_to_string(cnt_res));
right_res = boost::lexical_cast<std::string>(1);
EXPECT_STREQ(right_res.c_str(), cnt_res.c_str());
}
}
static constexpr size_t REPEAT_TIME = 10;
std::vector<size_t> NUM_PROCESS = {1, 3, 5, 8};
TEST(AccumulatorTest, single_thread_per_rank_sum_int_check_ok) {
for (size_t i = 0; i < REPEAT_TIME; ++i) {
for (size_t np: NUM_PROCESS) {
AccumulatorTest_single_thread_per_rank_sum_int_check_ok(np);
}
}
}
TEST(AccumulatorTest, multi_thread_per_rank_sum_int_check_ok) {
for (size_t i = 0; i < REPEAT_TIME; ++i) {
for (size_t np: NUM_PROCESS) {
AccumulatorTest_multi_thread_per_rank_sum_int_check_ok(np);
}
}
}
TEST(AccumulatorTest, single_thread_per_rank_maxmin_int_check_ok) {
for (size_t i = 0; i < REPEAT_TIME; ++i) {
for (size_t np: NUM_PROCESS) {
AccumulatorTest_single_thread_per_rank_maxmin_int_check_ok(np);
}
}
}
}
} // namespace pico
} // namespace paradigm4
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc, argv);
int ret = RUN_ALL_TESTS();
return ret;
}
| 33.251282
| 95
| 0.633251
|
4paradigm
|
8c853586a6deb2cf6b298b53ca4c42d13471719f
| 492
|
cpp
|
C++
|
coding_blocks/source/blocks_example.cpp
|
koobonil/CodingStudy
|
5a727bbcf30f30e04075ba9f86cbb9b0463a6f96
|
[
"MIT"
] | 2
|
2018-03-05T03:08:40.000Z
|
2020-09-13T21:57:05.000Z
|
coding_blocks/source/blocks_example.cpp
|
koobonil/CodingStudy
|
5a727bbcf30f30e04075ba9f86cbb9b0463a6f96
|
[
"MIT"
] | null | null | null |
coding_blocks/source/blocks_example.cpp
|
koobonil/CodingStudy
|
5a727bbcf30f30e04075ba9f86cbb9b0463a6f96
|
[
"MIT"
] | null | null | null |
#include <boss.hpp>
#include "blocks_example.hpp"
#include <resource.hpp>
////////////////////////////////////////////////////////////////////////////////
#define LEVEL_NUMBER LEVEL_USER
////////////////////////////////////////////////////////////////////////////////
#define STEP_NUMBER 0
MISSION_DECLARE("STEP_0")
String BlocksExample::OnInit(int& xcount, int& ycount)
{
return "";
}
void BlocksExample::OnClick(int& id)
{
}
void BlocksExample::OnRender(ZayPanel& panel, int id)
{
}
| 20.5
| 80
| 0.495935
|
koobonil
|
8c857129f7642d7c420a4cc4ebadfc5cc2e64258
| 7,901
|
cpp
|
C++
|
src/source_v4l.cpp
|
folkertvanheusden/constatus
|
7b0c42a5017bf96afcb0f34c0d4987bdc40ef2e6
|
[
"Apache-2.0"
] | 5
|
2021-07-15T11:39:25.000Z
|
2022-02-25T06:14:58.000Z
|
src/source_v4l.cpp
|
folkertvanheusden/constatus
|
7b0c42a5017bf96afcb0f34c0d4987bdc40ef2e6
|
[
"Apache-2.0"
] | 2
|
2021-09-27T11:13:42.000Z
|
2021-10-10T01:02:39.000Z
|
src/source_v4l.cpp
|
folkertvanheusden/constatus
|
7b0c42a5017bf96afcb0f34c0d4987bdc40ef2e6
|
[
"Apache-2.0"
] | 2
|
2021-06-11T09:19:47.000Z
|
2022-02-18T22:22:01.000Z
|
// (C) 2017-2021 by folkert van heusden, released under Apache License v2.0
// some code from https://01.org/linuxgraphics/gfx-docs/drm/media/uapi/v4l/v4l2grab.c.html
#include "config.h"
#if HAVE_LIBV4L2 == 1
#include <fcntl.h>
#include <libv4l2.h>
#include <math.h>
#include <poll.h>
#include <cstring>
#include <unistd.h>
#include <linux/videodev2.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include "error.h"
#include "source.h"
#include "source_v4l.h"
#include "picio.h"
#include "log.h"
#include "utils.h"
#include "ptz_v4l.h"
#include "controls_v4l.h"
static bool xioctl(int fh, long unsigned int request, void *arg, const char *const name)
{
int r;
do {
r = v4l2_ioctl(fh, request, arg);
} while (r == -1 && (errno == EINTR || errno == EAGAIN));
if (r == -1) {
log(LL_WARNING, "ioctl %s: error %d, %s\n", name, errno, strerror(errno));
return false;
}
return true;
}
source_v4l::source_v4l(const std::string & id, const std::string & descr, const std::string & exec_failure, const std::string & dev, const int jpeg_quality, const double max_fps, const int w_override, const int h_override, resize *const r, const int resize_w, const int resize_h, const int loglevel, const double timeout, std::vector<filter *> *const filters, const failure_t & failure, const bool prefer_jpeg, const bool use_controls) : source(id, descr, exec_failure, max_fps, r, resize_w, resize_h, loglevel, timeout, filters, failure, nullptr, jpeg_quality), dev(dev), prefer_jpeg(prefer_jpeg), w_override(w_override), h_override(h_override), use_controls(use_controls)
{
fd = -1;
vw = vh = -1;
pixelformat = 0;
n_buffers = 0;
}
source_v4l::~source_v4l()
{
stop();
}
bool try_format(int fd, struct v4l2_format *const fmt, int codec)
{
fmt->fmt.pix.pixelformat = codec;
if (xioctl(fd, VIDIOC_S_FMT, fmt, "VIDIOC_S_FMT (try_format)") == false)
return false;
return fmt->fmt.pix.pixelformat == codec;
}
void source_v4l::operator()()
{
log(id, LL_INFO, "source v4l2 thread started");
set_thread_name("src_v4l2");
fd = v4l2_open(dev.c_str(), O_RDWR, 0);
if (fd == -1) {
set_error(myformat("Cannot access video4linux device \"%s\"", dev.c_str()), true);
do_exec_failure();
return;
}
struct v4l2_format fmt { 0 };
struct v4l2_buffer buf { 0 };
struct v4l2_requestbuffers req { 0 };
enum v4l2_buf_type type;
fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
fmt.fmt.pix.width = w_override;
fmt.fmt.pix.height = h_override;
if (prefer_jpeg) {
if (try_format(fd, &fmt, V4L2_PIX_FMT_JPEG))
log(id, LL_INFO, "JPEG codec chosen");
else if (try_format(fd, &fmt, V4L2_PIX_FMT_MJPEG))
log(id, LL_INFO, "MJPEG codec chosen");
else {
log(id, LL_INFO, "Cannot use (M)JPEG mode, using RGB24 instead");
fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_RGB24;
xioctl(fd, VIDIOC_S_FMT, &fmt, "VIDIOC_S_FMT");
}
}
else {
fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_RGB24;
xioctl(fd, VIDIOC_S_FMT, &fmt, "VIDIOC_S_FMT");
}
fmt.fmt.pix.field = V4L2_FIELD_INTERLACED;
if (fmt.fmt.pix.width != w_override || fmt.fmt.pix.height != h_override)
log(id, LL_WARNING, "Note: driver is sending image at %dx%d (requested: %dx%d)", fmt.fmt.pix.width, fmt.fmt.pix.height, w_override, h_override);
std::unique_lock<std::mutex> lck(lock);
width = fmt.fmt.pix.width;
height = fmt.fmt.pix.height;
pixelformat = fmt.fmt.pix.pixelformat;
v4l2_jpegcompression ctrl{ jpeg_quality };
ioctl(fd, VIDIOC_G_JPEGCOMP, &ctrl);
memset(&req, 0x00, sizeof req);
req.count = 2;
req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
req.memory = V4L2_MEMORY_MMAP;
xioctl(fd, VIDIOC_REQBUFS, &req, "VIDIOC_REQBUFS");
bool fail = false;
buffers = (buffer *)calloc(req.count, sizeof(*buffers));
n_buffers = 0;
for(; !fail && n_buffers < req.count; ++n_buffers) {
memset(&buf, 0x00, sizeof(buf));
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
buf.index = n_buffers;
xioctl(fd, VIDIOC_QUERYBUF, &buf, "VIDIOC_QUERYBUF");
buffers[n_buffers].length = buf.length;
buffers[n_buffers].start = v4l2_mmap(NULL, buf.length, PROT_READ | PROT_WRITE, MAP_SHARED, fd, buf.m.offset);
if (MAP_FAILED == buffers[n_buffers].start) {
set_error(myformat("Cannot map video4linux device \"%s\" buffers", dev.c_str()), true);
do_exec_failure();
fail = true;
}
}
log(id, LL_INFO, "v4l: n_buffers: %d", n_buffers);
for (int i = 0; !fail && i < n_buffers; ++i) {
memset(&buf, 0x00, sizeof(buf));
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
buf.index = i;
xioctl(fd, VIDIOC_QBUF, &buf, "VIDIOC_QBUF");
}
type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
xioctl(fd, VIDIOC_STREAMON, &type, "VIDIOC_STREAMON");
vw = width;
vh = height;
if (need_scale()) {
width = resize_w;
height = resize_h;
}
lck.unlock();
track = ptz::check_is_supported(fd);
controls_lock.lock();
if (!fail && use_controls)
this->c = new controls_v4l(fd);
controls_lock.unlock();
int bytes = vw * vh * 3;
unsigned char *conv_buffer = static_cast<unsigned char *>(malloc(bytes));
const uint64_t interval = max_fps > 0.0 ? 1.0 / max_fps * 1000.0 * 1000.0 : 0;
struct pollfd fds[] = { { fd, POLLIN, 0 } };
for(;!fail && !local_stop_flag;) {
uint64_t start_ts = get_us();
fds[0].revents = 0;
if (poll(fds, 1, 100) == 0)
continue;
struct v4l2_buffer buf { 0 };
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
if (v4l2_ioctl(fd, VIDIOC_DQBUF, &buf) == -1) {
set_error(myformat("VIDIOC_DQBUF failed: %s", strerror(errno)), true);
do_exec_failure();
break;
}
if (work_required() && !is_paused()) {
unsigned char *io_buffer = (unsigned char *)buffers[buf.index].start;
if (pixelformat == V4L2_PIX_FMT_JPEG || pixelformat == V4L2_PIX_FMT_MJPEG) {
int cur_n_bytes = buf.bytesused;
if (resize_h != -1 || resize_w != -1) {
int dw = -1, dh = -1;
unsigned char *temp = NULL;
if (my_jpeg.read_JPEG_memory(io_buffer, cur_n_bytes, &dw, &dh, &temp))
set_scaled_frame(temp, dw, dh);
free(temp);
}
else {
set_frame(E_JPEG, io_buffer, cur_n_bytes);
}
}
else {
const size_t n = IMS(vw, vh, 3);
memcpy(conv_buffer, io_buffer, n);
if (need_scale())
set_scaled_frame(conv_buffer, vw, vh);
else
set_frame(E_RGB, conv_buffer, n);
}
clear_error();
}
if (v4l2_ioctl(fd, VIDIOC_QBUF, &buf) == -1) {
set_error("ioctl(VIDIOC_QBUF) failed", true);
do_exec_failure();
break;
}
uint64_t end_ts = get_us();
int64_t left = interval - (end_ts - start_ts);
//printf("total took %d, left %d, interval %ld\n", int(end_ts - start_ts), int(left), int(interval));
st->track_cpu_usage();
if (interval > 0 && left > 0)
myusleep(left);
}
free(conv_buffer);
controls_lock.lock();
delete c;
c = nullptr;
controls_lock.unlock();
type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
xioctl(fd, VIDIOC_STREAMOFF, &type, "VIDIOC_STREAMOFF");
for(int i = 0; i < n_buffers; ++i)
v4l2_munmap(buffers[i].start, buffers[i].length);
v4l2_close(fd);
free(buffers);
delete track;
register_thread_end("source v4l2");
}
void source_v4l::pan_tilt(const double abs_pan, const double abs_tilt)
{
if (track) {
track->pan(abs_pan);
track->tilt(abs_tilt);
}
}
void source_v4l::get_pan_tilt(double *const pan, double *const tilt) const
{
if (track) {
*pan = track->get_pan();
*tilt = track->get_tilt();
}
}
#endif
| 27.625874
| 673
| 0.638021
|
folkertvanheusden
|
8c868b5c7c47d77d06ac8bfde89b5964fefb96b7
| 998
|
cc
|
C++
|
codeforces/1305/b.cc
|
Ashindustry007/competitive-programming
|
2eabd3975c029d235abb7854569593d334acae2f
|
[
"WTFPL"
] | 506
|
2018-08-22T10:30:38.000Z
|
2022-03-31T10:01:49.000Z
|
codeforces/1305/b.cc
|
Ashindustry007/competitive-programming
|
2eabd3975c029d235abb7854569593d334acae2f
|
[
"WTFPL"
] | 13
|
2019-08-07T18:31:18.000Z
|
2020-12-15T21:54:41.000Z
|
codeforces/1305/b.cc
|
Ashindustry007/competitive-programming
|
2eabd3975c029d235abb7854569593d334acae2f
|
[
"WTFPL"
] | 234
|
2018-08-06T17:11:41.000Z
|
2022-03-26T10:56:42.000Z
|
// https://codeforces.com/contest/1305/problem/B
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ii = tuple<int, int>;
using vi = vector<ll>;
using vii = vector<ii>;
using vvi = vector<vi>;
using si = set<ll>;
int main() {
cin.tie(0), ios::sync_with_stdio(0);
string s;
cin >> s;
int n = s.size();
vi c(n);
vvi r;
while (1) {
int i = 0, j = n-1;
vi a;
while (i < j) {
if (c[i] && c[j]) i++, j--;
else if (c[i]) i++;
else if (c[j]) j--;
else if (s[i] == '(' && s[j] == ')')
c[i] = 1, c[j] = 1, a.push_back(i+1), a.push_back(j+1), i++, j--;
else if (s[i] == '(') j--;
else if (s[j] == ')') i++;
else i++, j--;
}
if (!a.size()) break;
sort(a.begin(), a.end());
r.push_back(a);
}
cout << r.size() << '\n';
for (int i = 0; i < r.size(); i++) {
cout << r[i].size() << '\n';
for (int j = 0; j < r[i].size(); j++)
cout << r[i][j] << " \n"[j == r[i].size()-1];
}
}
| 23.209302
| 73
| 0.44489
|
Ashindustry007
|
8c8b6e448037068d45c3c82817fdb283584b6487
| 1,703
|
cpp
|
C++
|
src/States/CharacterCreatorState.cpp
|
Miguel-EpicJS/state-rpg-tutorial
|
c909fe7ffee2cad4d3aac88afef9c5dc21b965ce
|
[
"MIT"
] | null | null | null |
src/States/CharacterCreatorState.cpp
|
Miguel-EpicJS/state-rpg-tutorial
|
c909fe7ffee2cad4d3aac88afef9c5dc21b965ce
|
[
"MIT"
] | null | null | null |
src/States/CharacterCreatorState.cpp
|
Miguel-EpicJS/state-rpg-tutorial
|
c909fe7ffee2cad4d3aac88afef9c5dc21b965ce
|
[
"MIT"
] | null | null | null |
#include "../../includes/CharacterCreatorState.h"
CharacterCreatorState::CharacterCreatorState(std::vector<Character *> *characterList, unsigned &activeCharacter, std::stack<State *> *states) : activeCharacter(activeCharacter), State(), maxCharacter(5)
{
this->characterList = characterList;
this->states = states;
}
CharacterCreatorState::~CharacterCreatorState()
{
}
void CharacterCreatorState::createCharacter()
{
if (this->characterList->size() < this->maxCharacter)
{
/* code */
std::string name = "";
std::string bio = "";
std::getline(std::cin, name);
std::cout << "Name: ";
std::getline(std::cin, name);
std::cout << "Bio: ";
std::getline(std::cin, bio);
this->characterList->push_back(new Character(name, bio));
std::cout << "Character " << name << " created.\n\n";
}else
{
std::cout << "Max number of characters reached!" << "\n";
}
}
void CharacterCreatorState::printMenu()
{
std::cout << "=== Character Creator === \n\n"
<< " Characterr: " << std::to_string(this->characterList->size()) << " / " << std::to_string(this->maxCharacter) << "\n\n"
<< " (-1) Back To Menu\n"
<< " (1) New Character\n\n";
}
void CharacterCreatorState::updateMenu()
{
switch (this->getChoice())
{
case -1:
this->setQuit(true);
std::cout << "\n\n Quitting main menu state \n\n";
break;
case 1:
createCharacter();
break;
default:
std::cout << "Not a valid option! \n\n";
break;
}
}
void CharacterCreatorState::update()
{
this->printMenu();
this->updateMenu();
}
| 24.328571
| 202
| 0.574868
|
Miguel-EpicJS
|
8c8c6c8c4c976dd83dd54907346ddc4fb781091d
| 318
|
hpp
|
C++
|
include/graphics/ITexture.hpp
|
icebreakersentertainment/ice_engine
|
52a8313bc266c053366bdf554b5dc27a54ddcb25
|
[
"MIT"
] | null | null | null |
include/graphics/ITexture.hpp
|
icebreakersentertainment/ice_engine
|
52a8313bc266c053366bdf554b5dc27a54ddcb25
|
[
"MIT"
] | null | null | null |
include/graphics/ITexture.hpp
|
icebreakersentertainment/ice_engine
|
52a8313bc266c053366bdf554b5dc27a54ddcb25
|
[
"MIT"
] | 1
|
2019-06-11T03:41:48.000Z
|
2019-06-11T03:41:48.000Z
|
#ifndef ITEXTURE_H_
#define ITEXTURE_H_
#include <string>
#include "graphics/IImage.hpp"
namespace ice_engine
{
namespace graphics
{
class ITexture
{
public:
virtual ~ITexture() = default;
virtual const std::string& name() const = 0;
virtual const IImage* image() const = 0;
};
}
}
#endif /* ITEXTURE_H_ */
| 12.230769
| 45
| 0.704403
|
icebreakersentertainment
|
8c8d01d8f0d937d872aa1f5c7cdd8b2f0154c847
| 789
|
cpp
|
C++
|
bzoj/1002.cpp
|
swwind/code
|
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
|
[
"WTFPL"
] | 3
|
2017-09-17T09:12:50.000Z
|
2018-04-06T01:18:17.000Z
|
bzoj/1002.cpp
|
swwind/code
|
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
|
[
"WTFPL"
] | null | null | null |
bzoj/1002.cpp
|
swwind/code
|
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
|
[
"WTFPL"
] | null | null | null |
#include <iostream>
#include <cstdio>
using namespace std;
struct data{
int a[101],len;
};
int n;
data mul(data a,int k){
for(int i = 1; i <= a.len; i++)
a.a[i] *= k;
for(int i = 1; i <= a.len; i++)
a.a[i+1] += a.a[i] / 10,
a.a[i] %= 10;
if(a.a[a.len+1]) a.len++;
return a;
}
data sub(data a, data b){
a.a[1] += 2;
int j = 1;
while(a.a[j] >= 10)
a.a[j] %= 10,
a.a[++j]++;
for(int i = 1; i <= a.len; i++){
a.a[i] -= b.a[i];
if(a.a[i] < 0)
a.a[i] += 10,
a.a[i+1]--;
}
while(!a.a[a.len]) a.len--;
return a;
}
int main(){
data f[101];
f[1].a[1] = 1;
f[2].a[1] = 5;
f[1].len = f[2].len = 1;
scanf("%d",&n);
for(int i = 3; i <= n; i++)
f[i] = sub(mul(f[i-1], 3), f[i-2]);
for(int i = f[n].len; i; i--)
printf("%d", f[n].a[i]);
puts("");
return 0;
}
| 17.533333
| 37
| 0.452471
|
swwind
|
8c8d1f9abdb9515ef3093631370b47555314a638
| 3,808
|
cc
|
C++
|
src/input/KeyboardSettings.cc
|
lutris/openmsx
|
91ed35400c7b4c8c460004710736af9abc4dde29
|
[
"Naumen",
"Condor-1.1",
"MS-PL"
] | 5
|
2015-02-27T21:42:28.000Z
|
2021-10-10T23:36:08.000Z
|
src/input/KeyboardSettings.cc
|
lutris/openmsx
|
91ed35400c7b4c8c460004710736af9abc4dde29
|
[
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null |
src/input/KeyboardSettings.cc
|
lutris/openmsx
|
91ed35400c7b4c8c460004710736af9abc4dde29
|
[
"Naumen",
"Condor-1.1",
"MS-PL"
] | 2
|
2015-06-15T09:57:56.000Z
|
2017-05-14T01:11:48.000Z
|
#include "KeyboardSettings.hh"
#include "EnumSetting.hh"
#include "BooleanSetting.hh"
#include "memory.hh"
#include <cassert>
namespace openmsx {
KeyboardSettings::KeyboardSettings(CommandController& commandController)
: alwaysEnableKeypad(make_unique<BooleanSetting>(
commandController, "kbd_numkeypad_always_enabled",
"Numeric keypad is always enabled, even on an MSX that does not have one",
false))
, traceKeyPresses(make_unique<BooleanSetting>(
commandController, "kbd_trace_key_presses",
"Trace key presses (show SDL key code, SDL modifiers and Unicode code-point value)",
false, Setting::DONT_SAVE))
, autoToggleCodeKanaLock(make_unique<BooleanSetting>(commandController,
"kbd_auto_toggle_code_kana_lock",
"Automatically toggle the CODE/KANA lock, based on the characters entered on the host keyboard",
true))
{
EnumSetting<Keys::KeyCode>::Map allowedKeys = {
{ "RALT", Keys::K_RALT },
{ "MENU", Keys::K_MENU },
{ "RCTRL", Keys::K_RCTRL },
{ "HENKAN_MODE", Keys::K_HENKAN_MODE },
{ "RSHIFT", Keys::K_RSHIFT },
{ "RMETA", Keys::K_RMETA },
{ "LMETA", Keys::K_LMETA },
{ "LSUPER", Keys::K_LSUPER },
{ "RSUPER", Keys::K_RSUPER },
{ "HELP", Keys::K_HELP },
{ "UNDO", Keys::K_UNDO },
{ "END", Keys::K_END },
{ "PAGEUP", Keys::K_PAGEUP },
{ "PAGEDOWN", Keys::K_PAGEDOWN } };
codeKanaHostKey = make_unique<EnumSetting<Keys::KeyCode>>(
commandController, "kbd_code_kana_host_key",
"Host key that maps to the MSX CODE/KANA key. Please note that the HENKAN_MODE key only exists on Japanese host keyboards)",
Keys::K_RALT, allowedKeys);
deadkeyHostKey[0] = make_unique<EnumSetting<Keys::KeyCode>>(
commandController, "kbd_deadkey1_host_key",
"Host key that maps to deadkey 1. Not applicable to Japanese and Korean MSX models",
Keys::K_RCTRL, allowedKeys);
deadkeyHostKey[1] = make_unique<EnumSetting<Keys::KeyCode>>(
commandController, "kbd_deadkey2_host_key",
"Host key that maps to deadkey 2. Only applicable to Brazilian MSX models (Sharp Hotbit and Gradiente)",
Keys::K_PAGEUP, allowedKeys);
deadkeyHostKey[2] = make_unique<EnumSetting<Keys::KeyCode>>(
commandController, "kbd_deadkey3_host_key",
"Host key that maps to deadkey 3. Only applicable to Brazilian Sharp Hotbit MSX models",
Keys::K_PAGEDOWN, allowedKeys);
EnumSetting<KpEnterMode>::Map kpEnterModeMap = {
{ "KEYPAD_COMMA", MSX_KP_COMMA },
{ "ENTER", MSX_ENTER } };
kpEnterMode = make_unique<EnumSetting<KpEnterMode>>(
commandController, "kbd_numkeypad_enter_key",
"MSX key that the enter key on the host numeric keypad must map to",
MSX_KP_COMMA, kpEnterModeMap);
EnumSetting<MappingMode>::Map mappingModeMap = {
{ "KEY", KEY_MAPPING },
{ "CHARACTER", CHARACTER_MAPPING } };
mappingMode = make_unique<EnumSetting<MappingMode>>(
commandController, "kbd_mapping_mode",
"Keyboard mapping mode",
CHARACTER_MAPPING, mappingModeMap);
}
KeyboardSettings::~KeyboardSettings()
{
}
EnumSetting<Keys::KeyCode>& KeyboardSettings::getCodeKanaHostKey() const
{
return *codeKanaHostKey;
}
Keys::KeyCode KeyboardSettings::getDeadkeyHostKey(unsigned n) const
{
assert(n < 3);
return deadkeyHostKey[n]->getEnum();
}
EnumSetting<KeyboardSettings::KpEnterMode>& KeyboardSettings::getKpEnterMode() const
{
return *kpEnterMode;
}
EnumSetting<KeyboardSettings::MappingMode>& KeyboardSettings::getMappingMode() const
{
return *mappingMode;
}
BooleanSetting& KeyboardSettings::getAlwaysEnableKeypad() const
{
return *alwaysEnableKeypad;
}
BooleanSetting& KeyboardSettings::getTraceKeyPresses() const
{
return *traceKeyPresses;
}
BooleanSetting& KeyboardSettings::getAutoToggleCodeKanaLock() const
{
return *autoToggleCodeKanaLock;
}
} // namespace openmsx
| 32.827586
| 126
| 0.731618
|
lutris
|
8c908a13dfbcf49908db3a036d4f761ad506ee19
| 17,731
|
cc
|
C++
|
src/core/cachedshardsimpl.cc
|
aching/Clusterlib
|
da81a653e9630b61214dbf7c37c75196300cf606
|
[
"Apache-2.0"
] | 2
|
2015-03-31T17:57:46.000Z
|
2019-06-18T17:29:46.000Z
|
src/core/cachedshardsimpl.cc
|
aching/Clusterlib
|
da81a653e9630b61214dbf7c37c75196300cf606
|
[
"Apache-2.0"
] | null | null | null |
src/core/cachedshardsimpl.cc
|
aching/Clusterlib
|
da81a653e9630b61214dbf7c37c75196300cf606
|
[
"Apache-2.0"
] | 1
|
2020-04-24T05:23:25.000Z
|
2020-04-24T05:23:25.000Z
|
/*
* Copyright (c) 2010 Yahoo! Inc. 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. See accompanying
* LICENSE file.
*
* $Id$
*/
#include "clusterlibinternal.h"
using namespace std;
using namespace boost;
using namespace json;
namespace clusterlib {
/**
* Given 2 shards, compare them based on priority. Used to sort shard
* containers.
*
* @param a the first shard
* @param b the second shard
* @return true if a < b
*/
static bool shardPriorityCompare(Shard a, Shard b)
{
if (a.getPriority() < b.getPriority()) {
return true;
}
else {
return false;
}
}
CachedShardsImpl::CachedShardsImpl(NotifyableImpl *notifyable)
: CachedDataImpl(notifyable),
m_shardTree(NULL),
m_shardTreeCount(0),
m_hashRange(NULL)
{
/*
* Start with the UnknownHashRange and initialize to the correct
* one later.
*/
m_hashRange = &(getOps()->getHashRange(UnknownHashRange::name()));
/*
* Do this for consistency.
*/
m_shardTree = new IntervalTree<HashRange &, ShardTreeData>(
*m_hashRange, ShardTreeData());
}
CachedShardsImpl::~CachedShardsImpl()
{
Locker l(&getCachedDataLock());
/*
* Cannot simply call "clear()" since the repository object may have
* been removed.
*/
IntervalTreeNode<HashRange &, ShardTreeData> *node = NULL;
while (m_shardTree->empty() == false) {
node = m_shardTree->getTreeHead();
node = m_shardTree->deleteNode(node);
delete &(node->getStartRange());
delete &(node->getEndRange());
delete &(node->getEndRangeMax());
delete node;
}
delete m_shardTree;
m_shardTree = NULL;
m_shardTreeCount = 0;
delete m_hashRange;
m_hashRange = NULL;
}
int32_t
CachedShardsImpl::publish(bool unconditional)
{
TRACE(CL_LOG, "publish");
getNotifyable()->throwIfRemoved();
string shardsKey = DataDistributionImpl::createShardJsonObjectKey(
getNotifyable()->getKey());
Locker l(&getCachedDataLock());
string encodedJsonObject = JSONCodec::encode(marshalShards());
LOG_DEBUG(CL_LOG,
"Tried to publish shards for notifyable %s to %s "
"with current version %d, unconditional %d\n",
getNotifyable()->getKey().c_str(),
encodedJsonObject.c_str(),
getVersion(),
unconditional);
Stat stat;
try {
SAFE_CALL_ZK(getOps()->getRepository()->setNodeData(
shardsKey,
encodedJsonObject,
((unconditional == false) ? getVersion(): -1),
&stat),
"Setting of %s failed: %s",
shardsKey.c_str(),
false,
true);
} catch (const zk::BadVersionException &e) {
throw PublishVersionException(e.what());
}
/*
* Since we should have the lock, the data should be identical to
* the zk data. When the lock is released, clusterlib events will
* try to push this change again.
*/
setStat(stat);
return stat.version;
}
void
CachedShardsImpl::loadDataFromRepository(bool setWatchesOnly)
{
TRACE(CL_LOG, "loadDataFromRepository");
string shardsKey = DataDistributionImpl::createShardJsonObjectKey(
getNotifyable()->getKey());
string encodedJsonValue;
Stat stat;
Locker l(&getCachedDataLock());
SAFE_CALLBACK_ZK(
getOps()->getRepository()->getNodeData(
shardsKey,
encodedJsonValue,
getOps()->getZooKeeperEventAdapter(),
getOps()->getCachedObjectChangeHandlers()->
getChangeHandler(
CachedObjectChangeHandlers::SHARDS_CHANGE),
&stat),
getOps()->getRepository()->getNodeData(
shardsKey, encodedJsonValue, NULL, NULL, &stat),
CachedObjectChangeHandlers::SHARDS_CHANGE,
shardsKey,
"Loading shardsKey %s failed: %s",
shardsKey.c_str(),
false,
true);
if (setWatchesOnly) {
return;
}
if (!updateStat(stat)) {
return;
}
/*
* Default values from the constructor are used when there are
* empty nodes
*/
if (encodedJsonValue.empty()) {
return;
}
unmarshalShards(encodedJsonValue);
}
string
CachedShardsImpl::getHashRangeName()
{
Locker l(&getCachedDataLock());
return m_hashRange->getName();
}
NotifyableList
CachedShardsImpl::getNotifyables(const HashRange &hashPoint)
{
TRACE(CL_LOG, "getNotifyables");
getNotifyable()->throwIfRemoved();
/* This is a slow implementation, will be optimized later. */
vector<Shard> shardVec = getAllShards(shared_ptr<Notifyable>(), -1);
NotifyableList ntList;
/* Allow this to success if nothing exists */
if (shardVec.empty()) {
return ntList;
}
throwIfUnknownHashRange();
/* Sort the shard by priority */
sort(shardVec.begin(), shardVec.end(), shardPriorityCompare);
vector<Shard>::iterator shardVecIt;
for (shardVecIt = shardVec.begin(); shardVecIt != shardVec.end();
++shardVecIt) {
if ((shardVecIt->getStartRange() <= hashPoint) &&
(shardVecIt->getEndRange() >= hashPoint)) {
ntList.push_back(shardVecIt->getNotifyable());
}
}
return ntList;
}
uint32_t
CachedShardsImpl::getCount()
{
TRACE(CL_LOG, "getCount");
getNotifyable()->throwIfRemoved();
Locker l(&getCachedDataLock());
return m_shardTreeCount;
}
bool
CachedShardsImpl::isCovered()
{
TRACE(CL_LOG, "isCovered");
getNotifyable()->throwIfRemoved();
throwIfUnknownHashRange();
Locker l(&getCachedDataLock());
IntervalTree<HashRange &, ShardTreeData>::iterator it
= m_shardTree->begin();
if (it->getStartRange().isBegin() == false) {
return false;
}
HashRange &end = m_hashRange->create();
end = it->getStartRange();
for (; it != m_shardTree->end(); ++it) {
LOG_DEBUG(
CL_LOG,
"isCovered: end=%s startRange=%s endRange=%s",
JSONCodec::encode(end.toJSONValue()).c_str(),
JSONCodec::encode(it->getStartRange().toJSONValue()).c_str(),
JSONCodec::encode(it->getEndRange().toJSONValue()).c_str());
if (it->getStartRange() > end) {
delete &end;
return false;
}
else if (it->getEndRange() >= end) {
if (it->getEndRange().isEnd()) {
delete &end;
return true;
}
else {
end = it->getEndRange();
++end;
}
}
}
delete &end;
return false;
}
void
CachedShardsImpl::insert(const HashRange &start,
const HashRange &end,
const shared_ptr<Notifyable> ¬ifyableSP,
int32_t priority)
{
TRACE(CL_LOG, "insert");
getNotifyable()->throwIfRemoved();
Locker l(&getCachedDataLock());
/*
* Ensure that the HashRange objects are the same type and not
* UnknownHashRange. The only time they need not be the same as
* the m_hashRange is if m_shardTreeCount == 0. Then m_hashRange
* is set to this type.
*/
if ((start.getName() == UnknownHashRange::name()) ||
(end.getName() == UnknownHashRange::name())) {
throw InvalidArgumentsException(
"insert: Either start or end has HashRange == UnknownHashRange");
}
if ((m_shardTreeCount == 0) &&
(start.getName() != getHashRangeName())) {
clear();
delete m_hashRange;
m_hashRange = &(start.create());
delete m_shardTree;
m_shardTree = new IntervalTree<HashRange &, ShardTreeData>(
*m_hashRange, ShardTreeData());
}
if ((typeid(start) != typeid(*m_hashRange)) ||
(typeid(start) != typeid(end))) {
throw InvalidArgumentsException(
"insert: The types of start, end and "
"the set hash range are not in agreement.");
}
/* Alllocate the data that will be put into the tree. */
HashRange &finalStart = m_hashRange->create();
HashRange &finalEnd = m_hashRange->create();
HashRange &finalEndMax = m_hashRange->create();
finalStart = start;
finalEnd = end;
m_shardTree->insertNode(
finalStart,
finalEnd,
finalEndMax,
ShardTreeData(
priority,
(notifyableSP == NULL) ? string() : notifyableSP->getKey()));
++m_shardTreeCount;
}
vector<Shard>
CachedShardsImpl::getAllShards(
const shared_ptr<Notifyable> ¬ifyableSP, int32_t priority)
{
TRACE(CL_LOG, "getAllShards");
getNotifyable()->throwIfRemoved();
/*
* Get all the shards and then filter based on the notifyable and/or
* priority.
*/
vector<Shard> res;
IntervalTree<HashRange &, ShardTreeData>::iterator treeIt;
Locker l(&getCachedDataLock());
if (getHashRangeName() == UnknownHashRange::name()) {
res = m_unknownShardArr;
}
else {
for (treeIt = m_shardTree->begin();
treeIt != m_shardTree->end();
++treeIt) {
res.push_back(
Shard(dynamic_pointer_cast<Root>(
getOps()->getNotifyable(
shared_ptr<NotifyableImpl>(),
CLString::REGISTERED_ROOT_NAME,
CLStringInternal::ROOT_NAME,
CACHED_ONLY)),
treeIt->getStartRange(),
treeIt->getEndRange(),
treeIt->getData().getNotifyableKey(),
treeIt->getData().getPriority()));
}
}
vector<Shard>::iterator resIt;
vector<Shard> finalRes;
for (resIt = res.begin(); resIt != res.end(); ++resIt) {
/* Filter by notifyable if not NULL */
if ((notifyableSP == NULL) ||
(notifyableSP->getKey() == resIt->getNotifyableKey())) {
finalRes.push_back(*resIt);
}
/* Filter by priority if not -1 */
if ((priority != -1) || (priority == resIt->getPriority())) {
finalRes.push_back(*resIt);
}
}
return finalRes;
}
bool
CachedShardsImpl::remove(Shard &shard)
{
TRACE(CL_LOG, "remove");
getNotifyable()->throwIfRemoved();
throwIfUnknownHashRange();
Locker l(&getCachedDataLock());
//AC-debug
m_shardTree->printDepthFirstSearch();
IntervalTreeNode<HashRange &, ShardTreeData> *node =
m_shardTree->nodeSearch(shard.getStartRange(),
shard.getEndRange(),
ShardTreeData(shard.getPriority(),
shard.getNotifyableKey()));
if (node != NULL) {
node = m_shardTree->deleteNode(node);
delete &(node->getStartRange());
delete &(node->getEndRange());
delete &(node->getEndRangeMax());
delete node;
m_shardTreeCount--;
return true;
}
return false;
}
void
CachedShardsImpl::clear()
{
TRACE(CL_LOG, "clear");
getNotifyable()->throwIfRemoved();
Locker l(&getCachedDataLock());
IntervalTreeNode<HashRange &, ShardTreeData> *node = NULL;
while (m_shardTree->empty() == false) {
node = m_shardTree->getTreeHead();
node = m_shardTree->deleteNode(node);
delete &(node->getStartRange());
delete &(node->getEndRange());
delete &(node->getEndRangeMax());
delete node;
}
m_shardTreeCount = 0;
m_unknownShardArr.clear();
}
JSONValue::JSONArray
CachedShardsImpl::marshalShards()
{
TRACE(CL_LOG, "marshalShards");
getNotifyable()->throwIfRemoved();
Locker l(&getCachedDataLock());
IntervalTree<HashRange &, ShardTreeData>::iterator it;
JSONValue::JSONArray shardArr;
JSONValue::JSONArray shardMetadataArr;
/* Shard format: [ "<HashRange name>",[<shard0],[shard1],...] */
if (m_shardTreeCount != 0) {
if (m_hashRange->getName() == UnknownHashRange::name()) {
throw InvalidMethodException(
"marshalShards: Cannot marshal shards if the HashRange is "
"UnknownHashRange and the number of elements is > 0");
}
shardArr.push_back(m_hashRange->getName());
for (it = m_shardTree->begin(); it != m_shardTree->end(); it++) {
shardMetadataArr.clear();
shardMetadataArr.push_back(it->getStartRange().toJSONValue());
shardMetadataArr.push_back(it->getEndRange().toJSONValue());
shardMetadataArr.push_back(it->getData().getNotifyableKey());
shardMetadataArr.push_back(it->getData().getPriority());
shardArr.push_back(shardMetadataArr);
}
}
LOG_DEBUG(CL_LOG,
"marshalShards: Generated string (%s)",
JSONCodec::encode(shardArr).c_str());
return shardArr;
}
void
CachedShardsImpl::unmarshalShards(const string &encodedJsonArr)
{
TRACE(CL_LOG, "unmarshalShards");
getNotifyable()->throwIfRemoved();
vector<string> components;
vector<string> shardComponents;
vector<string>::iterator sIt;
LOG_DEBUG(CL_LOG,
"unmarshalShards: Got encodedJsonArr '%s'",
encodedJsonArr.c_str());
Locker l(&getCachedDataLock());
clear();
m_shardTreeCount = 0;
if (encodedJsonArr.empty()) {
return;
}
JSONValue::JSONArray jsonArr =
JSONCodec::decode(encodedJsonArr).get<JSONValue::JSONArray>();
if (jsonArr.empty()) {
return;
}
JSONValue::JSONArray shardMetadataArr;
JSONValue::JSONArray::const_iterator jsonArrIt;
/*
* First array element should be the HashRange name and should
* match the *m_hashRange.
*/
JSONValue::JSONString hashRangeName =
jsonArr.front().get<JSONValue::JSONString>();
jsonArr.pop_front();
delete m_hashRange;
m_hashRange = &(getOps()->getHashRange(hashRangeName));
delete m_shardTree;
m_shardTree = new IntervalTree<HashRange &, ShardTreeData>(
*m_hashRange, ShardTreeData());
bool unknownHashRange = false;
if (m_hashRange->getName() == UnknownHashRange::name()) {
unknownHashRange = true;
}
/*
* If this is UnknownHashRange data, put in m_shardArr, otherwise
* put in m_shardTree.
*/
for (jsonArrIt = jsonArr.begin();
jsonArrIt != jsonArr.end();
++jsonArrIt) {
shardMetadataArr.clear();
shardMetadataArr = jsonArrIt->get<JSONValue::JSONArray>();
if (shardMetadataArr.size() != 4) {
throw InconsistentInternalStateException(
"unmarshalShards: Impossible that the size of the "
"shardMetadataArr != 4");
}
JSONValue::JSONString ntpKey =
shardMetadataArr[2].get<JSONValue::JSONString>();
if (unknownHashRange) {
m_unknownShardArr.push_back(
Shard(dynamic_pointer_cast<Root>(
getOps()->getNotifyable(
shared_ptr<NotifyableImpl>(),
CLString::REGISTERED_ROOT_NAME,
CLStringInternal::ROOT_NAME,
CACHED_ONLY)),
UnknownHashRange(shardMetadataArr[0]),
UnknownHashRange(shardMetadataArr[1]),
ntpKey,
shardMetadataArr[3].get<JSONValue::JSONInteger>()));
}
else {
HashRange &start = m_hashRange->create();
HashRange &end = m_hashRange->create();
HashRange &endMax = m_hashRange->create();
start.set(shardMetadataArr[0]);
end.set(shardMetadataArr[1]);
m_shardTree->insertNode(
start,
end,
endMax,
ShardTreeData(
shardMetadataArr[3].get<JSONValue::JSONInteger>(),
ntpKey));
}
LOG_DEBUG(CL_LOG,
"unmarshalShards: Found shard with HashRange name %s: "
"start=%s end=%s, notifyable key=%s, priority=%" PRId64,
m_hashRange->getName().c_str(),
JSONCodec::encode(shardMetadataArr[0]).c_str(),
JSONCodec::encode(shardMetadataArr[1]).c_str(),
ntpKey.c_str(),
shardMetadataArr[3].get<JSONValue::JSONInteger>());
++m_shardTreeCount;
}
}
void
CachedShardsImpl::throwIfUnknownHashRange()
{
Locker l(&getCachedDataLock());
if (getHashRangeName() == UnknownHashRange::name()) {
throw InvalidMethodException("throwIfUnknownHashRange: This method is "
"not available for UnknownHashRange");
}
}
} /* End of 'namespace clusterlib' */
| 29.067213
| 79
| 0.585246
|
aching
|
8c93edd04204894383ab9063c5318815054dd273
| 83,478
|
cpp
|
C++
|
src/toldialoghump.cpp
|
JoaoQPereira/motion_manager
|
de853e9341c482a0c13e0ba7b78429c019890507
|
[
"MIT"
] | null | null | null |
src/toldialoghump.cpp
|
JoaoQPereira/motion_manager
|
de853e9341c482a0c13e0ba7b78429c019890507
|
[
"MIT"
] | null | null | null |
src/toldialoghump.cpp
|
JoaoQPereira/motion_manager
|
de853e9341c482a0c13e0ba7b78429c019890507
|
[
"MIT"
] | null | null | null |
#include "../include/motion_manager/toldialoghump.hpp"
namespace motion_manager {
using namespace Qt;
TolDialogHUMP::TolDialogHUMP(QWidget *parent) :
QDialog(parent),
ui(new Ui::TolDialogHUMP)
{
ui->setupUi(this);
QObject::connect(ui->checkBox_approach, SIGNAL(stateChanged(int)), this, SLOT(checkApproach(int)));
QObject::connect(ui->checkBox_retreat, SIGNAL(stateChanged(int)), this, SLOT(checkRetreat(int)));
QObject::connect(ui->checkBox_sel_final_posture, SIGNAL(stateChanged(int)), this, SLOT(checkFinalPosture(int)));
QObject::connect(ui->checkBox_add_plane, SIGNAL(stateChanged(int)), this, SLOT(checkAddPlane(int)));
if(ui->checkBox_approach->isChecked())
{
ui->groupBox_pre_grasp->setEnabled(false);
ui->groupBox_pre_place->setEnabled(false);
ui->label_pick->setEnabled(false);
}
if(ui->checkBox_retreat->isChecked())
{
ui->groupBox_post_grasp->setEnabled(false);
ui->groupBox_post_place->setEnabled(false);
ui->label_pick->setEnabled(false);
}
#if HAND == 1
adaptationElectricGripper();
#elif HAND == 0
ui->lineEdit_w_max_gripper->setText(QString::number(0));
ui->lineEdit_w_max_gripper->setEnabled(false);
ui->lineEdit_alpha_max_gripper->setText(QString::number(0));
ui->lineEdit_alpha_max_gripper->setEnabled(false);
#elif HAND == 2
adaptationElectricGripper();
ui->lineEdit_w_max_gripper->setText(QString::number(0));
ui->lineEdit_w_max_gripper->setEnabled(false);
ui->lineEdit_alpha_max_gripper->setText(QString::number(0));
ui->lineEdit_alpha_max_gripper->setEnabled(false);
#endif
}
void TolDialogHUMP::adaptationElectricGripper()
{
//******Disable the joints that aren't used to this type of hand
//Points of the hand
ui->lineEdit_hand_1_3->setText(QString::number(0));
ui->lineEdit_hand_1_3->setEnabled(false);
ui->lineEdit_hand_2_1->setText(QString::number(0));
ui->lineEdit_hand_2_1->setEnabled(false);
ui->lineEdit_hand_2_2->setText(QString::number(0));
ui->lineEdit_hand_2_2->setEnabled(false);
ui->lineEdit_hand_2_3->setText(QString::number(0));
ui->lineEdit_hand_2_3->setEnabled(false);
ui->lineEdit_hand_3_1->setText(QString::number(0));
ui->lineEdit_hand_3_1->setEnabled(false);
ui->lineEdit_hand_3_2->setText(QString::number(0));
ui->lineEdit_hand_3_2->setEnabled(false);
ui->lineEdit_hand_3_3->setText(QString::number(0));
ui->lineEdit_hand_3_3->setEnabled(false);
ui->lineEdit_hand_tip_3->setText(QString::number(0));
ui->lineEdit_hand_tip_3->setEnabled(false);
// Joint Expense Factors
ui->lineEdit_lambda_9->setText(QString::number(0));
ui->lineEdit_lambda_9->setEnabled(false);
ui->lineEdit_lambda_10->setText(QString::number(0));
ui->lineEdit_lambda_10->setEnabled(false);
ui->lineEdit_lambda_11->setText(QString::number(0));
ui->lineEdit_lambda_11->setEnabled(false);
//Boundary conditions
//init vel
ui->lineEdit_init_vel_9->setText(QString::number(0));
ui->lineEdit_init_vel_9->setEnabled(false);
ui->lineEdit_init_vel_10->setText(QString::number(0));
ui->lineEdit_init_vel_10->setEnabled(false);
ui->lineEdit_init_vel_11->setText(QString::number(0));
ui->lineEdit_init_vel_11->setEnabled(false);
//final vel
ui->lineEdit_final_vel_9->setText(QString::number(0));
ui->lineEdit_final_vel_9->setEnabled(false);
ui->lineEdit_final_vel_10->setText(QString::number(0));
ui->lineEdit_final_vel_10->setEnabled(false);
ui->lineEdit_final_vel_11->setText(QString::number(0));
ui->lineEdit_final_vel_11->setEnabled(false);
//init acc
ui->lineEdit_init_acc_9->setText(QString::number(0));
ui->lineEdit_init_acc_9->setEnabled(false);
ui->lineEdit_init_acc_10->setText(QString::number(0));
ui->lineEdit_init_acc_10->setEnabled(false);
ui->lineEdit_init_acc_11->setText(QString::number(0));
ui->lineEdit_init_acc_11->setEnabled(false);
//final acc
ui->lineEdit_final_acc_9->setText(QString::number(0));
ui->lineEdit_final_acc_9->setEnabled(false);
ui->lineEdit_final_acc_10->setText(QString::number(0));
ui->lineEdit_final_acc_10->setEnabled(false);
ui->lineEdit_final_acc_11->setText(QString::number(0));
ui->lineEdit_final_acc_11->setEnabled(false);
//Final Hand Posture
ui->lineEdit_final_hand_2->setText(QString::number(0));
ui->lineEdit_final_hand_2->setEnabled(false);
ui->lineEdit_final_hand_3->setText(QString::number(0));
ui->lineEdit_final_hand_3->setEnabled(false);
ui->lineEdit_final_hand_4->setText(QString::number(0));
ui->lineEdit_final_hand_4->setEnabled(false);
//Max vel and max acceleration of joints
ui->label_w_max_barrett->setEnabled(false);
ui->label_alpha_max_barrett->setEnabled(false);
}
TolDialogHUMP::~TolDialogHUMP()
{
delete ui;
}
void TolDialogHUMP::getTolsHand(MatrixXd &tols)
{
tols = MatrixXd::Constant(4,3,1);
tols(0,0) = ui->lineEdit_hand_1_1->text().toDouble();
tols(0,1) = ui->lineEdit_hand_1_2->text().toDouble();
tols(0,2) = ui->lineEdit_hand_1_3->text().toDouble();
tols(1,0) = ui->lineEdit_hand_2_1->text().toDouble();
tols(1,1) = ui->lineEdit_hand_2_2->text().toDouble();
tols(1,2) = ui->lineEdit_hand_2_3->text().toDouble();
tols(2,0) = ui->lineEdit_hand_3_1->text().toDouble();
tols(2,1) = ui->lineEdit_hand_3_2->text().toDouble();
tols(2,2) = ui->lineEdit_hand_3_3->text().toDouble();
tols(3,0) = ui->lineEdit_hand_tip_1->text().toDouble();
tols(3,1) = ui->lineEdit_hand_tip_2->text().toDouble();
tols(3,2) = ui->lineEdit_hand_tip_3->text().toDouble();
}
void TolDialogHUMP::getTolsArm(vector<double> &tols)
{
tols.clear();
tols.push_back(ui->lineEdit_sphere1_r->text().toDouble());
tols.push_back(ui->lineEdit_sphere2_r->text().toDouble());
tols.push_back(ui->lineEdit_sphere3_r->text().toDouble());
tols.push_back(ui->lineEdit_sphere4_r->text().toDouble());
tols.push_back(ui->lineEdit_sphere5_r->text().toDouble());
tols.push_back(ui->lineEdit_sphere6_r->text().toDouble());
tols.push_back(ui->lineEdit_sphere7_r->text().toDouble());
tols.push_back(ui->lineEdit_sphere8_r->text().toDouble());
tols.push_back(ui->lineEdit_sphere9_r->text().toDouble());
tols.push_back(ui->lineEdit_sphere10_r->text().toDouble());
tols.push_back(ui->lineEdit_sphere11_r->text().toDouble());
tols.push_back(ui->lineEdit_sphere12_r->text().toDouble());
tols.push_back(ui->lineEdit_sphere13_r->text().toDouble());
tols.push_back(ui->lineEdit_sphere14_r->text().toDouble());
}
void TolDialogHUMP::getLambda(std::vector<double> &lambda)
{
lambda.clear();
lambda.push_back(ui->lineEdit_lambda_1->text().toDouble());
lambda.push_back(ui->lineEdit_lambda_2->text().toDouble());
lambda.push_back(ui->lineEdit_lambda_3->text().toDouble());
lambda.push_back(ui->lineEdit_lambda_4->text().toDouble());
lambda.push_back(ui->lineEdit_lambda_5->text().toDouble());
lambda.push_back(ui->lineEdit_lambda_6->text().toDouble());
lambda.push_back(ui->lineEdit_lambda_7->text().toDouble());
lambda.push_back(ui->lineEdit_lambda_8->text().toDouble());
#if HAND == 0
lambda.push_back(ui->lineEdit_lambda_9->text().toDouble());
lambda.push_back(ui->lineEdit_lambda_10->text().toDouble());
lambda.push_back(ui->lineEdit_lambda_11->text().toDouble());
#endif
}
void TolDialogHUMP::getTolsObstacles(MatrixXd &tols)
{
tols = MatrixXd::Constant(3,6,1);
tols(0,0)=ui->lineEdit_obs_xx_1->text().toDouble(); tols(0,1)=ui->lineEdit_obs_yy_1->text().toDouble(); tols(0,2)=ui->lineEdit_obs_zz_1->text().toDouble(); tols(0,3)=ui->lineEdit_obs_xy_1->text().toDouble(); tols(0,4)=ui->lineEdit_obs_xz_1->text().toDouble(); tols(0,5)=ui->lineEdit_obs_yz_1->text().toDouble();
tols(1,0)=ui->lineEdit_obs_xx_2->text().toDouble(); tols(1,1)=ui->lineEdit_obs_yy_2->text().toDouble(); tols(1,2)=ui->lineEdit_obs_zz_2->text().toDouble(); tols(1,3)=ui->lineEdit_obs_xy_2->text().toDouble(); tols(1,4)=ui->lineEdit_obs_xz_2->text().toDouble(); tols(1,5)=ui->lineEdit_obs_yz_2->text().toDouble();
tols(2,0)=ui->lineEdit_obs_xx_3->text().toDouble(); tols(2,1)=ui->lineEdit_obs_yy_3->text().toDouble(); tols(2,2)=ui->lineEdit_obs_zz_3->text().toDouble(); tols(2,3)=ui->lineEdit_obs_xy_3->text().toDouble(); tols(2,4)=ui->lineEdit_obs_xz_3->text().toDouble(); tols(2,5)=ui->lineEdit_obs_yz_3->text().toDouble();
}
void TolDialogHUMP::getTolsTarget(MatrixXd &tols)
{
tols = MatrixXd::Constant(3,6,1);
tols(0,0)=ui->lineEdit_tar_xx_1->text().toDouble(); tols(0,1)=ui->lineEdit_tar_yy_1->text().toDouble(); tols(0,2)=ui->lineEdit_tar_zz_1->text().toDouble(); tols(0,3)=ui->lineEdit_tar_xy_1->text().toDouble(); tols(0,4)=ui->lineEdit_tar_xz_1->text().toDouble(); tols(0,5)=ui->lineEdit_tar_yz_1->text().toDouble();
tols(1,0)=ui->lineEdit_tar_xx_2->text().toDouble(); tols(1,1)=ui->lineEdit_tar_yy_2->text().toDouble(); tols(1,2)=ui->lineEdit_tar_zz_2->text().toDouble(); tols(1,3)=ui->lineEdit_tar_xy_2->text().toDouble(); tols(1,4)=ui->lineEdit_tar_xz_2->text().toDouble(); tols(1,5)=ui->lineEdit_tar_yz_2->text().toDouble();
tols(2,0)=ui->lineEdit_tar_xx_3->text().toDouble(); tols(2,1)=ui->lineEdit_tar_yy_3->text().toDouble(); tols(2,2)=ui->lineEdit_tar_zz_3->text().toDouble(); tols(2,3)=ui->lineEdit_tar_xy_3->text().toDouble(); tols(2,4)=ui->lineEdit_tar_xz_3->text().toDouble(); tols(2,5)=ui->lineEdit_tar_yz_3->text().toDouble();
}
double TolDialogHUMP::getWMax()
{
return ui->lineEdit_w_max->text().toDouble();
}
double TolDialogHUMP::getAlphaMax()
{
return ui->lineEdit_alpha_max->text().toDouble();
}
double TolDialogHUMP::getWMaxUR()
{
return ui->lineEdit_w_max_ur->text().toDouble();
}
double TolDialogHUMP::getAlphaMaxUR()
{
return ui->lineEdit_alpha_max_ur->text().toDouble();
}
void TolDialogHUMP::setWMax(double w)
{
ui->lineEdit_w_max->setText(QString::number(w));
}
#if HAND == 1
double TolDialogHUMP::getWMaxGripper()
{
return ui->lineEdit_w_max_gripper->text().toDouble();
}
double TolDialogHUMP::getAlphaMaxGripper()
{
return ui->lineEdit_alpha_max_gripper->text().toDouble();
}
void TolDialogHUMP::setWMaxGripper(double w)
{
ui->lineEdit_w_max_gripper->setText(QString::number(w));
}
#endif
double TolDialogHUMP::getTolTarPos()
{
return ui->lineEdit_tar_pos->text().toDouble();
}
double TolDialogHUMP::getTolTarOr()
{
return ui->lineEdit_tar_or->text().toDouble();
}
void TolDialogHUMP::setInfo(string info)
{
this->infoLine = info;
}
bool TolDialogHUMP::getTargetAvoidance()
{
return !ui->checkBox_tar_av->isChecked();
}
bool TolDialogHUMP::getObstacleAvoidance()
{
return !ui->checkBox_ob_av->isChecked();
}
bool TolDialogHUMP::getApproach()
{
return !ui->checkBox_approach->isChecked();
}
bool TolDialogHUMP::getRetreat()
{
return !ui->checkBox_retreat->isChecked();
}
void TolDialogHUMP::getInitVel(std::vector<double> &init_vel)
{
init_vel.clear();
init_vel.push_back(ui->lineEdit_init_vel_1->text().toDouble());
init_vel.push_back(ui->lineEdit_init_vel_2->text().toDouble());
init_vel.push_back(ui->lineEdit_init_vel_3->text().toDouble());
init_vel.push_back(ui->lineEdit_init_vel_4->text().toDouble());
init_vel.push_back(ui->lineEdit_init_vel_5->text().toDouble());
init_vel.push_back(ui->lineEdit_init_vel_6->text().toDouble());
init_vel.push_back(ui->lineEdit_init_vel_7->text().toDouble());
init_vel.push_back(ui->lineEdit_init_vel_8->text().toDouble());
init_vel.push_back(ui->lineEdit_init_vel_9->text().toDouble());
init_vel.push_back(ui->lineEdit_init_vel_10->text().toDouble());
init_vel.push_back(ui->lineEdit_init_vel_11->text().toDouble());
}
void TolDialogHUMP::getFinalVel(std::vector<double> &final_vel)
{
final_vel.clear();
final_vel.push_back(ui->lineEdit_final_vel_1->text().toDouble());
final_vel.push_back(ui->lineEdit_final_vel_2->text().toDouble());
final_vel.push_back(ui->lineEdit_final_vel_3->text().toDouble());
final_vel.push_back(ui->lineEdit_final_vel_4->text().toDouble());
final_vel.push_back(ui->lineEdit_final_vel_5->text().toDouble());
final_vel.push_back(ui->lineEdit_final_vel_6->text().toDouble());
final_vel.push_back(ui->lineEdit_final_vel_7->text().toDouble());
final_vel.push_back(ui->lineEdit_final_vel_8->text().toDouble());
final_vel.push_back(ui->lineEdit_final_vel_9->text().toDouble());
final_vel.push_back(ui->lineEdit_final_vel_10->text().toDouble());
final_vel.push_back(ui->lineEdit_final_vel_11->text().toDouble());
}
void TolDialogHUMP::getInitAcc(std::vector<double> &init_acc)
{
init_acc.clear();
init_acc.push_back(ui->lineEdit_init_acc_1->text().toDouble());
init_acc.push_back(ui->lineEdit_init_acc_2->text().toDouble());
init_acc.push_back(ui->lineEdit_init_acc_3->text().toDouble());
init_acc.push_back(ui->lineEdit_init_acc_4->text().toDouble());
init_acc.push_back(ui->lineEdit_init_acc_5->text().toDouble());
init_acc.push_back(ui->lineEdit_init_acc_6->text().toDouble());
init_acc.push_back(ui->lineEdit_init_acc_7->text().toDouble());
init_acc.push_back(ui->lineEdit_init_acc_8->text().toDouble());
init_acc.push_back(ui->lineEdit_init_acc_9->text().toDouble());
init_acc.push_back(ui->lineEdit_init_acc_10->text().toDouble());
init_acc.push_back(ui->lineEdit_init_acc_11->text().toDouble());
}
void TolDialogHUMP::getFinalAcc(std::vector<double> &final_acc)
{
final_acc.clear();
final_acc.push_back(ui->lineEdit_final_acc_1->text().toDouble());
final_acc.push_back(ui->lineEdit_final_acc_2->text().toDouble());
final_acc.push_back(ui->lineEdit_final_acc_3->text().toDouble());
final_acc.push_back(ui->lineEdit_final_acc_4->text().toDouble());
final_acc.push_back(ui->lineEdit_final_acc_5->text().toDouble());
final_acc.push_back(ui->lineEdit_final_acc_6->text().toDouble());
final_acc.push_back(ui->lineEdit_final_acc_7->text().toDouble());
final_acc.push_back(ui->lineEdit_final_acc_8->text().toDouble());
final_acc.push_back(ui->lineEdit_final_acc_9->text().toDouble());
final_acc.push_back(ui->lineEdit_final_acc_10->text().toDouble());
final_acc.push_back(ui->lineEdit_final_acc_11->text().toDouble());
}
void TolDialogHUMP::getPreGraspApproach(std::vector<double> &pre_grasp)
{
pre_grasp.clear();
pre_grasp.push_back(ui->lineEdit_pre_grasp_x->text().toDouble());
pre_grasp.push_back(ui->lineEdit_pre_grasp_y->text().toDouble());
pre_grasp.push_back(ui->lineEdit_pre_grasp_z->text().toDouble());
pre_grasp.push_back(ui->lineEdit_pre_grasp_dist->text().toDouble());
}
void TolDialogHUMP::getPostGraspRetreat(std::vector<double> &post_grasp)
{
post_grasp.clear();
post_grasp.push_back(ui->lineEdit_post_grasp_x->text().toDouble());
post_grasp.push_back(ui->lineEdit_post_grasp_y->text().toDouble());
post_grasp.push_back(ui->lineEdit_post_grasp_z->text().toDouble());
post_grasp.push_back(ui->lineEdit_post_grasp_dist->text().toDouble());
}
void TolDialogHUMP::getPrePlaceApproach(std::vector<double> &pre_place)
{
pre_place.clear();
pre_place.push_back(ui->lineEdit_pre_place_x->text().toDouble());
pre_place.push_back(ui->lineEdit_pre_place_y->text().toDouble());
pre_place.push_back(ui->lineEdit_pre_place_z->text().toDouble());
pre_place.push_back(ui->lineEdit_pre_place_dist->text().toDouble());
}
void TolDialogHUMP::getPostPlaceRetreat(std::vector<double> &post_place)
{
post_place.clear();
post_place.push_back(ui->lineEdit_post_place_x->text().toDouble());
post_place.push_back(ui->lineEdit_post_place_y->text().toDouble());
post_place.push_back(ui->lineEdit_post_place_z->text().toDouble());
post_place.push_back(ui->lineEdit_post_place_dist->text().toDouble());
}
double TolDialogHUMP::getW_red_app()
{
return ui->lineEdit_w_red_app->text().toDouble();
}
double TolDialogHUMP::getW_red_ret()
{
return ui->lineEdit_w_red_ret->text().toDouble();
}
void TolDialogHUMP::getTargetMove(std::vector<double> &target)
{
target.clear();
target.push_back(ui->lineEdit_target_x->text().toDouble());
target.push_back(ui->lineEdit_target_y->text().toDouble());
target.push_back(ui->lineEdit_target_z->text().toDouble());
target.push_back((ui->lineEdit_target_roll->text().toDouble()*M_PI)/180);
target.push_back((ui->lineEdit_target_pitch->text().toDouble()*M_PI)/ 180);
target.push_back((ui->lineEdit_target_yaw->text().toDouble()*M_PI)/180);
}
void TolDialogHUMP::setTargetMove(std::vector<double> &target)
{
ui->lineEdit_target_x->setText(QString::number(target.at(0)));
ui->lineEdit_target_y->setText(QString::number(target.at(1)));
ui->lineEdit_target_z->setText(QString::number(target.at(2)));
ui->lineEdit_target_roll->setText(QString::number(target.at(3)));
ui->lineEdit_target_pitch->setText(QString::number(target.at(4)));
ui->lineEdit_target_yaw->setText(QString::number(target.at(5)));
}
void TolDialogHUMP::getFinalArm(std::vector<double> &finalArm)
{
finalArm.clear();
finalArm.push_back((ui->lineEdit_final_arm_1->text().toDouble()*M_PI)/180);
finalArm.push_back((ui->lineEdit_final_arm_2->text().toDouble()*M_PI)/180);
finalArm.push_back((ui->lineEdit_final_arm_3->text().toDouble()*M_PI)/180);
finalArm.push_back((ui->lineEdit_final_arm_4->text().toDouble()*M_PI)/180);
finalArm.push_back((ui->lineEdit_final_arm_5->text().toDouble()*M_PI)/180);
finalArm.push_back((ui->lineEdit_final_arm_6->text().toDouble()*M_PI)/180);
finalArm.push_back((ui->lineEdit_final_arm_7->text().toDouble()*M_PI)/180);
}
void TolDialogHUMP::getFinalHand(std::vector<double> &finalHand)
{
finalHand.clear();
finalHand.push_back((ui->lineEdit_final_hand_1->text().toDouble()*M_PI)/180);
finalHand.push_back((ui->lineEdit_final_hand_2->text().toDouble()*M_PI)/180);
finalHand.push_back((ui->lineEdit_final_hand_3->text().toDouble()*M_PI)/180);
finalHand.push_back((ui->lineEdit_final_hand_4->text().toDouble()*M_PI)/180);
}
void TolDialogHUMP::setPlaneParameters(std::vector<double> &point1,std::vector<double> &point2,std::vector<double> &point3)
{
if(!point1.empty() && !point2.empty() && !point3.empty())
{
ui->lineEdit_point_1_x->setText(QString::number(point1.at(0)));
ui->lineEdit_point_1_y->setText(QString::number(point1.at(1)));
ui->lineEdit_point_1_z->setText(QString::number(point1.at(2)));
ui->lineEdit_point_2_x->setText(QString::number(point2.at(0)));
ui->lineEdit_point_2_y->setText(QString::number(point2.at(1)));
ui->lineEdit_point_2_z->setText(QString::number(point2.at(2)));
ui->lineEdit_point_3_x->setText(QString::number(point3.at(0)));
ui->lineEdit_point_3_y->setText(QString::number(point3.at(1)));
ui->lineEdit_point_3_z->setText(QString::number(point3.at(2)));
}
}
void TolDialogHUMP::setInitJointsVel(std::vector<double>& init_vel)
{
if(!init_vel.empty())
{
ui->lineEdit_init_vel_1->setText(QString::number(init_vel.at(0)));
ui->lineEdit_init_vel_2->setText(QString::number(init_vel.at(1)));
ui->lineEdit_init_vel_3->setText(QString::number(init_vel.at(2)));
ui->lineEdit_init_vel_4->setText(QString::number(init_vel.at(3)));
ui->lineEdit_init_vel_5->setText(QString::number(init_vel.at(4)));
ui->lineEdit_init_vel_6->setText(QString::number(init_vel.at(5)));
ui->lineEdit_init_vel_7->setText(QString::number(init_vel.at(6)));
ui->lineEdit_init_vel_8->setText(QString::number(init_vel.at(7)));
#if HAND == 0
ui->lineEdit_init_vel_9->setText(QString::number(init_vel.at(8)));
ui->lineEdit_init_vel_10->setText(QString::number(init_vel.at(9)));
ui->lineEdit_init_vel_11->setText(QString::number(init_vel.at(10)));
#endif
}
}
void TolDialogHUMP::setInitJointsAcc(std::vector<double>& init_acc)
{
if(!init_acc.empty())
{
ui->lineEdit_init_acc_1->setText(QString::number(init_acc.at(0)));
ui->lineEdit_init_acc_2->setText(QString::number(init_acc.at(1)));
ui->lineEdit_init_acc_3->setText(QString::number(init_acc.at(2)));
ui->lineEdit_init_acc_4->setText(QString::number(init_acc.at(3)));
ui->lineEdit_init_acc_5->setText(QString::number(init_acc.at(4)));
ui->lineEdit_init_acc_6->setText(QString::number(init_acc.at(5)));
ui->lineEdit_init_acc_7->setText(QString::number(init_acc.at(6)));
ui->lineEdit_init_acc_8->setText(QString::number(init_acc.at(7)));
#if HAND == 0
ui->lineEdit_init_acc_9->setText(QString::number(init_acc.at(8)));
ui->lineEdit_init_acc_10->setText(QString::number(init_acc.at(9)));
ui->lineEdit_init_acc_11->setText(QString::number(init_acc.at(10)));
#endif
}
}
void TolDialogHUMP::setPointsOfArm(DHparams m_DH_rightArm, string name)
{
double D_LENGHT_TOL = 350; //Max Length of the link
int npoints_arm = 0;
#if HAND == 0
int npoints_finger = 9;
#elif HAND == 1
int npoints_finger = 4;
#elif HAND == 2
int npoints_finger = 0;
#endif
ui->lineEdit_sphere1_r->setText(QString::number(0));
ui->lineEdit_sphere1_r->setEnabled(false);
ui->lineEdit_sphere2_r->setText(QString::number(0));
ui->lineEdit_sphere2_r->setEnabled(false);
ui->lineEdit_sphere3_r->setText(QString::number(0));
ui->lineEdit_sphere3_r->setEnabled(false);
ui->lineEdit_sphere4_r->setText(QString::number(0));
ui->lineEdit_sphere4_r->setEnabled(false);
ui->lineEdit_sphere5_r->setText(QString::number(0));
ui->lineEdit_sphere5_r->setEnabled(false);
ui->lineEdit_sphere6_r->setText(QString::number(0));
ui->lineEdit_sphere6_r->setEnabled(false);
ui->lineEdit_sphere7_r->setText(QString::number(0));
ui->lineEdit_sphere7_r->setEnabled(false);
ui->lineEdit_sphere8_r->setText(QString::number(0));
ui->lineEdit_sphere8_r->setEnabled(false);
ui->lineEdit_sphere9_r->setText(QString::number(0));
ui->lineEdit_sphere9_r->setEnabled(false);
ui->lineEdit_sphere10_r->setText(QString::number(0));
ui->lineEdit_sphere10_r->setEnabled(false);
ui->lineEdit_sphere11_r->setText(QString::number(0));
ui->lineEdit_sphere11_r->setEnabled(false);
//Manipulator with shoulder offset
if(m_DH_rightArm.d.at(1)!=0)
{
npoints_arm = npoints_arm + 2;
ui->lineEdit_sphere2_r->setEnabled(true);
ui->lineEdit_sphere4_r->setEnabled(true);
if(m_DH_rightArm.d.at(0)>=D_LENGHT_TOL)
{
npoints_arm++;
ui->lineEdit_sphere1_r->setEnabled(true);
}
if(m_DH_rightArm.d.at(1)>=D_LENGHT_TOL)
{
npoints_arm++;
ui->lineEdit_sphere3_r->setEnabled(true);
}
}
//Manipulator without shoulder offset
else
{
npoints_arm++;
ui->lineEdit_sphere4_r->setEnabled(true);
if(m_DH_rightArm.d.at(0)>=D_LENGHT_TOL)
{
npoints_arm++;
ui->lineEdit_sphere1_r->setEnabled(true);
}
}
//Manipulator with elbow offset
if(m_DH_rightArm.d.at(3)!=0)
{
npoints_arm = npoints_arm + 2;
ui->lineEdit_sphere6_r->setEnabled(true);
ui->lineEdit_sphere8_r->setEnabled(true);
if(m_DH_rightArm.d.at(2)>=D_LENGHT_TOL)
{
npoints_arm++;
ui->lineEdit_sphere5_r->setEnabled(true);
}
if(m_DH_rightArm.d.at(3)>=D_LENGHT_TOL)
{
npoints_arm++;
ui->lineEdit_sphere7_r->setEnabled(true);
}
}
//Manipulator without elbow offset
else
{
npoints_arm++;
ui->lineEdit_sphere8_r->setEnabled(true);
if(m_DH_rightArm.d.at(2)>=D_LENGHT_TOL)
{
npoints_arm++;
ui->lineEdit_sphere5_r->setEnabled(true);
}
}
//Manipulator with wrist offset
if(m_DH_rightArm.d.at(5)!=0)
{
npoints_arm = npoints_arm + 2;
ui->lineEdit_sphere10_r->setEnabled(true);
ui->lineEdit_sphere12_r->setEnabled(true);
if(m_DH_rightArm.d.at(4)>=D_LENGHT_TOL)
{
npoints_arm++;
ui->lineEdit_sphere9_r->setEnabled(true);
}
if(m_DH_rightArm.d.at(5)>=D_LENGHT_TOL)
{
npoints_arm++;
ui->lineEdit_sphere11_r->setEnabled(true);
}
}
//Manipulator without wrist offset
else
{
npoints_arm++;
ui->lineEdit_sphere12_r->setEnabled(true);
if(m_DH_rightArm.d.at(4)>=D_LENGHT_TOL)
{
npoints_arm++;
ui->lineEdit_sphere9_r->setEnabled(true);
}
}
//Sphere 13 and 14 are create for all manipulators
npoints_arm = npoints_arm + 2;
//Spheres used to model/represent the fingers (in BarrettHand)
npoints_arm = npoints_arm + npoints_finger;
//default values: defined based on the structure of the robot
if(!name.compare("ARoS"))
{
ui->lineEdit_sphere4_r->setText(QString::number(70.00));
ui->lineEdit_sphere5_r->setText(QString::number(60.00));
ui->lineEdit_sphere8_r->setText(QString::number(70.00));
ui->lineEdit_sphere9_r->setText(QString::number(60.00));
ui->lineEdit_sphere12_r->setText(QString::number(70.00));
ui->lineEdit_sphere13_r->setText(QString::number(70.00));
ui->lineEdit_sphere14_r->setText(QString::number(40.00));
}
if(!name.compare("Sawyer"))
{
ui->lineEdit_sphere2_r->setText(QString::number(60.00));
ui->lineEdit_sphere4_r->setText(QString::number(85.00));
ui->lineEdit_sphere5_r->setText(QString::number(65.00));
ui->lineEdit_sphere6_r->setText(QString::number(70.00));
ui->lineEdit_sphere8_r->setText(QString::number(70.00));
ui->lineEdit_sphere9_r->setText(QString::number(70.00));
ui->lineEdit_sphere10_r->setText(QString::number(60.00));
ui->lineEdit_sphere12_r->setText(QString::number(60.00));
ui->lineEdit_sphere13_r->setText(QString::number(80.00));
ui->lineEdit_sphere14_r->setText(QString::number(70.00));
}
ui->label_points_arm->setText(QString::number(npoints_arm));
}
void TolDialogHUMP::getPlaneParameters(std::vector<double> ¶ms)
{
params.clear(); double a,b,c,d;
std::vector<double> point1;
std::vector<double> point2;
std::vector<double> point3;
point1.push_back(ui->lineEdit_point_1_x->text().toDouble());
point1.push_back(ui->lineEdit_point_1_y->text().toDouble());
point1.push_back(ui->lineEdit_point_1_z->text().toDouble());
point2.push_back(ui->lineEdit_point_2_x->text().toDouble());
point2.push_back(ui->lineEdit_point_2_y->text().toDouble());
point2.push_back(ui->lineEdit_point_2_z->text().toDouble());
point3.push_back(ui->lineEdit_point_3_x->text().toDouble());
point3.push_back(ui->lineEdit_point_3_y->text().toDouble());
point3.push_back(ui->lineEdit_point_3_z->text().toDouble());
Matrix3d D; double det;
D << point1.at(0),point1.at(1),point1.at(2),
point2.at(0),point2.at(1),point2.at(2),
point3.at(0),point3.at(1),point3.at(2);
det = D.determinant();
//what does here?
//what does de matrix ABC?
if(det!=0)
{
d=1000;
Matrix3d A;
A << 1,point1.at(1),point1.at(2),
1,point2.at(1),point2.at(2),
1,point3.at(1),point3.at(2);
a = (-d/det)*A.determinant();
Matrix3d B;
B << point1.at(0),1,point1.at(2),
point2.at(0),1,point2.at(2),
point3.at(0),1,point3.at(2);
b = (-d/det)*B.determinant();
Matrix3d C;
C << point1.at(0),point1.at(1),1,
point2.at(0),point2.at(1),1,
point3.at(0),point3.at(1),1;
c = (-d/det)*C.determinant();
params.push_back(a);
params.push_back(b);
params.push_back(c);
params.push_back(d);
}
}
void TolDialogHUMP::on_pushButton_save_clicked()
{
QString filename = QFileDialog::getSaveFileName(this,
tr("Save the file of tolerances"),
QString(MAIN_PATH)+"/Tols",
"All Files (*.*);;Tol Files (*.tol)");
QFile f( filename );
if(f.open( QIODevice::WriteOnly ))
{
QTextStream stream( &f );
stream << "### Parameters of the Human-like Upper-limbs Motion Library ###" << endl;
stream << "# "<< this->infoLine.c_str() << endl;
stream << "# Geometric Dimensions of the arms and of the fingers" << endl;
stream << "Sphere1_radius=" << ui->lineEdit_sphere1_r->text().toStdString().c_str() << endl;
stream << "Sphere2_radius=" << ui->lineEdit_sphere2_r->text().toStdString().c_str() << endl;
stream << "Sphere3_radius=" << ui->lineEdit_sphere3_r->text().toStdString().c_str() << endl;
stream << "Sphere4_radius=" << ui->lineEdit_sphere4_r->text().toStdString().c_str() << endl;
stream << "Sphere5_radius=" << ui->lineEdit_sphere5_r->text().toStdString().c_str() << endl;
stream << "Sphere6_radius=" << ui->lineEdit_sphere6_r->text().toStdString().c_str() << endl;
stream << "Sphere7_radius=" << ui->lineEdit_sphere7_r->text().toStdString().c_str() << endl;
stream << "Sphere8_radius=" << ui->lineEdit_sphere8_r->text().toStdString().c_str() << endl;
stream << "Sphere9_radius=" << ui->lineEdit_sphere9_r->text().toStdString().c_str() << endl;
stream << "Sphere10_radius=" << ui->lineEdit_sphere10_r->text().toStdString().c_str() << endl;
stream << "Sphere11_radius=" << ui->lineEdit_sphere11_r->text().toStdString().c_str() << endl;
stream << "Sphere12_radius=" << ui->lineEdit_sphere12_r->text().toStdString().c_str() << endl;
stream << "Sphere13_radius=" << ui->lineEdit_sphere13_r->text().toStdString().c_str() << endl;
stream << "Sphere14_radius=" << ui->lineEdit_sphere14_r->text().toStdString().c_str() << endl;
stream << "Hand_1_1=" << ui->lineEdit_hand_1_1->text().toStdString().c_str() << endl;
stream << "Hand_1_2=" << ui->lineEdit_hand_1_2->text().toStdString().c_str() << endl;
stream << "Hand_1_3=" << ui->lineEdit_hand_1_3->text().toStdString().c_str() << endl;
stream << "Hand_2_1=" << ui->lineEdit_hand_2_1->text().toStdString().c_str() << endl;
stream << "Hand_2_2=" << ui->lineEdit_hand_2_2->text().toStdString().c_str() << endl;
stream << "Hand_2_3=" << ui->lineEdit_hand_2_3->text().toStdString().c_str() << endl;
stream << "Hand_3_1=" << ui->lineEdit_hand_3_1->text().toStdString().c_str() << endl;
stream << "Hand_3_2=" << ui->lineEdit_hand_3_2->text().toStdString().c_str() << endl;
stream << "Hand_3_3=" << ui->lineEdit_hand_3_3->text().toStdString().c_str() << endl;
stream << "Hand_tip_1=" << ui->lineEdit_hand_tip_1->text().toStdString().c_str() << endl;
stream << "Hand_tip_2=" << ui->lineEdit_hand_tip_2->text().toStdString().c_str() << endl;
stream << "Hand_tip_3=" << ui->lineEdit_hand_tip_3->text().toStdString().c_str() << endl;
stream << "# Joint Expanse factors" << endl;
stream << "lambda_1=" << ui->lineEdit_lambda_1->text().toStdString().c_str() << endl;
stream << "lambda_2=" << ui->lineEdit_lambda_2->text().toStdString().c_str() << endl;
stream << "lambda_3=" << ui->lineEdit_lambda_3->text().toStdString().c_str() << endl;
stream << "lambda_4=" << ui->lineEdit_lambda_4->text().toStdString().c_str() << endl;
stream << "lambda_5=" << ui->lineEdit_lambda_5->text().toStdString().c_str() << endl;
stream << "lambda_6=" << ui->lineEdit_lambda_6->text().toStdString().c_str() << endl;
stream << "lambda_7=" << ui->lineEdit_lambda_7->text().toStdString().c_str() << endl;
stream << "lambda_8=" << ui->lineEdit_lambda_8->text().toStdString().c_str() << endl;
stream << "lambda_9=" << ui->lineEdit_lambda_9->text().toStdString().c_str() << endl;
stream << "lambda_10=" << ui->lineEdit_lambda_10->text().toStdString().c_str() << endl;
stream << "lambda_11=" << ui->lineEdit_lambda_11->text().toStdString().c_str() << endl;
stream << "# Initial Velocity " << endl;
stream << "init_vel_1=" << ui->lineEdit_init_vel_1->text().toStdString().c_str() << endl;
stream << "init_vel_2=" << ui->lineEdit_init_vel_2->text().toStdString().c_str() << endl;
stream << "init_vel_3=" << ui->lineEdit_init_vel_3->text().toStdString().c_str() << endl;
stream << "init_vel_4=" << ui->lineEdit_init_vel_4->text().toStdString().c_str() << endl;
stream << "init_vel_5=" << ui->lineEdit_init_vel_5->text().toStdString().c_str() << endl;
stream << "init_vel_6=" << ui->lineEdit_init_vel_6->text().toStdString().c_str() << endl;
stream << "init_vel_7=" << ui->lineEdit_init_vel_7->text().toStdString().c_str() << endl;
stream << "init_vel_8=" << ui->lineEdit_init_vel_8->text().toStdString().c_str() << endl;
stream << "init_vel_9=" << ui->lineEdit_init_vel_9->text().toStdString().c_str() << endl;
stream << "init_vel_10=" << ui->lineEdit_init_vel_10->text().toStdString().c_str() << endl;
stream << "init_vel_11=" << ui->lineEdit_init_vel_11->text().toStdString().c_str() << endl;
stream << "# Final Velocity " << endl;
stream << "final_vel_1=" << ui->lineEdit_final_vel_1->text().toStdString().c_str() << endl;
stream << "final_vel_2=" << ui->lineEdit_final_vel_2->text().toStdString().c_str() << endl;
stream << "final_vel_3=" << ui->lineEdit_final_vel_3->text().toStdString().c_str() << endl;
stream << "final_vel_4=" << ui->lineEdit_final_vel_4->text().toStdString().c_str() << endl;
stream << "final_vel_5=" << ui->lineEdit_final_vel_5->text().toStdString().c_str() << endl;
stream << "final_vel_6=" << ui->lineEdit_final_vel_6->text().toStdString().c_str() << endl;
stream << "final_vel_7=" << ui->lineEdit_final_vel_7->text().toStdString().c_str() << endl;
stream << "final_vel_8=" << ui->lineEdit_final_vel_8->text().toStdString().c_str() << endl;
stream << "final_vel_9=" << ui->lineEdit_final_vel_9->text().toStdString().c_str() << endl;
stream << "final_vel_10=" << ui->lineEdit_final_vel_10->text().toStdString().c_str() << endl;
stream << "final_vel_11=" << ui->lineEdit_final_vel_11->text().toStdString().c_str() << endl;
stream << "# Initial Acceleration " << endl;
stream << "init_acc_1=" << ui->lineEdit_init_acc_1->text().toStdString().c_str() << endl;
stream << "init_acc_2=" << ui->lineEdit_init_acc_2->text().toStdString().c_str() << endl;
stream << "init_acc_3=" << ui->lineEdit_init_acc_3->text().toStdString().c_str() << endl;
stream << "init_acc_4=" << ui->lineEdit_init_acc_4->text().toStdString().c_str() << endl;
stream << "init_acc_5=" << ui->lineEdit_init_acc_5->text().toStdString().c_str() << endl;
stream << "init_acc_6=" << ui->lineEdit_init_acc_6->text().toStdString().c_str() << endl;
stream << "init_acc_7=" << ui->lineEdit_init_acc_7->text().toStdString().c_str() << endl;
stream << "init_acc_8=" << ui->lineEdit_init_acc_8->text().toStdString().c_str() << endl;
stream << "init_acc_9=" << ui->lineEdit_init_acc_9->text().toStdString().c_str() << endl;
stream << "init_acc_10=" << ui->lineEdit_init_acc_10->text().toStdString().c_str() << endl;
stream << "init_acc_11=" << ui->lineEdit_init_acc_11->text().toStdString().c_str() << endl;
stream << "# Final Acceleration " << endl;
stream << "final_acc_1=" << ui->lineEdit_final_acc_1->text().toStdString().c_str() << endl;
stream << "final_acc_2=" << ui->lineEdit_final_acc_2->text().toStdString().c_str() << endl;
stream << "final_acc_3=" << ui->lineEdit_final_acc_3->text().toStdString().c_str() << endl;
stream << "final_acc_4=" << ui->lineEdit_final_acc_4->text().toStdString().c_str() << endl;
stream << "final_acc_5=" << ui->lineEdit_final_acc_5->text().toStdString().c_str() << endl;
stream << "final_acc_6=" << ui->lineEdit_final_acc_6->text().toStdString().c_str() << endl;
stream << "final_acc_7=" << ui->lineEdit_final_acc_7->text().toStdString().c_str() << endl;
stream << "final_acc_8=" << ui->lineEdit_final_acc_8->text().toStdString().c_str() << endl;
stream << "final_acc_9=" << ui->lineEdit_final_acc_9->text().toStdString().c_str() << endl;
stream << "final_acc_10=" << ui->lineEdit_final_acc_10->text().toStdString().c_str() << endl;
stream << "final_acc_11=" << ui->lineEdit_final_acc_11->text().toStdString().c_str() << endl;
stream << "# Tolerances with the target [mm]" << endl;
stream << "tar_xx_1=" << ui->lineEdit_tar_xx_1->text().toStdString().c_str()<< endl;
stream << "tar_xx_2=" << ui->lineEdit_tar_xx_2->text().toStdString().c_str()<< endl;
stream << "tar_xx_3=" << ui->lineEdit_tar_xx_3->text().toStdString().c_str()<< endl;
stream << "tar_yy_1=" << ui->lineEdit_tar_yy_1->text().toStdString().c_str()<< endl;
stream << "tar_yy_2=" << ui->lineEdit_tar_yy_2->text().toStdString().c_str()<< endl;
stream << "tar_yy_3=" << ui->lineEdit_tar_yy_3->text().toStdString().c_str()<< endl;
stream << "tar_zz_1=" << ui->lineEdit_tar_zz_1->text().toStdString().c_str()<< endl;
stream << "tar_zz_2=" << ui->lineEdit_tar_zz_2->text().toStdString().c_str()<< endl;
stream << "tar_zz_3=" << ui->lineEdit_tar_zz_3->text().toStdString().c_str()<< endl;
stream << "tar_xy_1=" << ui->lineEdit_tar_xy_1->text().toStdString().c_str()<< endl;
stream << "tar_xy_2=" << ui->lineEdit_tar_xy_2->text().toStdString().c_str()<< endl;
stream << "tar_xy_3=" << ui->lineEdit_tar_xy_3->text().toStdString().c_str()<< endl;
stream << "tar_xz_1=" << ui->lineEdit_tar_xz_1->text().toStdString().c_str()<< endl;
stream << "tar_xz_2=" << ui->lineEdit_tar_xz_2->text().toStdString().c_str()<< endl;
stream << "tar_xz_3=" << ui->lineEdit_tar_xz_3->text().toStdString().c_str()<< endl;
stream << "tar_yz_1=" << ui->lineEdit_tar_yz_1->text().toStdString().c_str()<< endl;
stream << "tar_yz_2=" << ui->lineEdit_tar_yz_2->text().toStdString().c_str()<< endl;
stream << "tar_yz_3=" << ui->lineEdit_tar_yz_3->text().toStdString().c_str()<< endl;
stream << "# Tolerances with the obstacles [mm]" << endl;
stream << "obs_xx_1=" << ui->lineEdit_obs_xx_1->text().toStdString().c_str()<< endl;
stream << "obs_xx_2=" << ui->lineEdit_obs_xx_2->text().toStdString().c_str()<< endl;
stream << "obs_xx_3=" << ui->lineEdit_obs_xx_3->text().toStdString().c_str()<< endl;
stream << "obs_yy_1=" << ui->lineEdit_obs_yy_1->text().toStdString().c_str()<< endl;
stream << "obs_yy_2=" << ui->lineEdit_obs_yy_2->text().toStdString().c_str()<< endl;
stream << "obs_yy_3=" << ui->lineEdit_obs_yy_3->text().toStdString().c_str()<< endl;
stream << "obs_zz_1=" << ui->lineEdit_obs_zz_1->text().toStdString().c_str()<< endl;
stream << "obs_zz_2=" << ui->lineEdit_obs_zz_2->text().toStdString().c_str()<< endl;
stream << "obs_zz_3=" << ui->lineEdit_obs_zz_3->text().toStdString().c_str()<< endl;
stream << "obs_xy_1=" << ui->lineEdit_obs_xy_1->text().toStdString().c_str()<< endl;
stream << "obs_xy_2=" << ui->lineEdit_obs_xy_2->text().toStdString().c_str()<< endl;
stream << "obs_xy_3=" << ui->lineEdit_obs_xy_3->text().toStdString().c_str()<< endl;
stream << "obs_xz_1=" << ui->lineEdit_obs_xz_1->text().toStdString().c_str()<< endl;
stream << "obs_xz_2=" << ui->lineEdit_obs_xz_2->text().toStdString().c_str()<< endl;
stream << "obs_xz_3=" << ui->lineEdit_obs_xz_3->text().toStdString().c_str()<< endl;
stream << "obs_yz_1=" << ui->lineEdit_obs_yz_1->text().toStdString().c_str()<< endl;
stream << "obs_yz_2=" << ui->lineEdit_obs_yz_2->text().toStdString().c_str()<< endl;
stream << "obs_yz_3=" << ui->lineEdit_obs_yz_3->text().toStdString().c_str()<< endl;
stream << "# Tolerances for the final posture" << endl;
stream << "tar_pos=" << ui->lineEdit_tar_pos->text().toStdString().c_str()<< endl;
stream << "tar_or="<< ui->lineEdit_tar_or->text().toStdString().c_str() << endl;
stream << "# Pick settings" << endl;
stream << "pre_grasp_x="<< ui->lineEdit_pre_grasp_x->text().toStdString().c_str() << endl;
stream << "pre_grasp_y="<< ui->lineEdit_pre_grasp_y->text().toStdString().c_str() << endl;
stream << "pre_grasp_z="<< ui->lineEdit_pre_grasp_z->text().toStdString().c_str() << endl;
stream << "pre_grasp_dist="<< ui->lineEdit_pre_grasp_dist->text().toStdString().c_str() << endl;
stream << "post_grasp_x="<< ui->lineEdit_post_grasp_x->text().toStdString().c_str() << endl;
stream << "post_grasp_y="<< ui->lineEdit_post_grasp_y->text().toStdString().c_str() << endl;
stream << "post_grasp_z="<< ui->lineEdit_post_grasp_z->text().toStdString().c_str() << endl;
stream << "post_grasp_dist="<< ui->lineEdit_post_grasp_dist->text().toStdString().c_str() << endl;
stream << "# Place settings" << endl;
stream << "pre_place_x="<< ui->lineEdit_pre_place_x->text().toStdString().c_str() << endl;
stream << "pre_place_y="<< ui->lineEdit_pre_place_y->text().toStdString().c_str() << endl;
stream << "pre_place_z="<< ui->lineEdit_pre_place_z->text().toStdString().c_str() << endl;
stream << "pre_place_dist="<< ui->lineEdit_pre_place_dist->text().toStdString().c_str() << endl;
stream << "post_place_x="<< ui->lineEdit_post_place_x->text().toStdString().c_str() << endl;
stream << "post_place_y="<< ui->lineEdit_post_place_y->text().toStdString().c_str() << endl;
stream << "post_place_z="<< ui->lineEdit_post_place_z->text().toStdString().c_str() << endl;
stream << "post_place_dist="<< ui->lineEdit_post_place_dist->text().toStdString().c_str() << endl;
stream << "w_red_app=" << ui->lineEdit_w_red_app->text().toStdString().c_str() << endl;
stream << "w_red_ret=" << ui->lineEdit_w_red_ret->text().toStdString().c_str() << endl;
stream << "# Move settings" << endl;
stream << "target_x=" << ui->lineEdit_target_x->text().toStdString().c_str() << endl;
stream << "target_y=" << ui->lineEdit_target_y->text().toStdString().c_str() << endl;
stream << "target_z=" << ui->lineEdit_target_z->text().toStdString().c_str() << endl;
stream << "target_roll=" << ui->lineEdit_target_roll->text().toStdString().c_str() << endl;
stream << "target_pitch=" << ui->lineEdit_target_pitch->text().toStdString().c_str() << endl;
stream << "target_yaw=" << ui->lineEdit_target_yaw->text().toStdString().c_str() << endl;
stream << "final_arm_1=" << ui->lineEdit_final_arm_1->text().toStdString().c_str() << endl;
stream << "final_arm_2=" << ui->lineEdit_final_arm_2->text().toStdString().c_str() << endl;
stream << "final_arm_3=" << ui->lineEdit_final_arm_3->text().toStdString().c_str() << endl;
stream << "final_arm_4=" << ui->lineEdit_final_arm_4->text().toStdString().c_str() << endl;
stream << "final_arm_5=" << ui->lineEdit_final_arm_5->text().toStdString().c_str() << endl;
stream << "final_arm_6=" << ui->lineEdit_final_arm_6->text().toStdString().c_str() << endl;
stream << "final_arm_7=" << ui->lineEdit_final_arm_7->text().toStdString().c_str() << endl;
stream << "final_hand_1=" << ui->lineEdit_final_hand_1->text().toStdString().c_str() << endl;
stream << "final_hand_2=" << ui->lineEdit_final_hand_2->text().toStdString().c_str() << endl;
stream << "final_hand_3=" << ui->lineEdit_final_hand_3->text().toStdString().c_str() << endl;
stream << "final_hand_4=" << ui->lineEdit_final_hand_4->text().toStdString().c_str() << endl;
if (ui->checkBox_sel_final_posture->isChecked())
stream << "sel_final=true"<< endl;
else
stream << "sel_final=false"<< endl;
stream << "plane_point1_x=" << ui->lineEdit_point_1_x->text().toStdString().c_str() << endl;
stream << "plane_point1_y=" << ui->lineEdit_point_1_y->text().toStdString().c_str() << endl;
stream << "plane_point1_z=" << ui->lineEdit_point_1_z->text().toStdString().c_str() << endl;
stream << "plane_point2_x=" << ui->lineEdit_point_2_x->text().toStdString().c_str() << endl;
stream << "plane_point2_y=" << ui->lineEdit_point_2_y->text().toStdString().c_str() << endl;
stream << "plane_point2_z=" << ui->lineEdit_point_2_z->text().toStdString().c_str() << endl;
stream << "plane_point3_x=" << ui->lineEdit_point_3_x->text().toStdString().c_str() << endl;
stream << "plane_point3_y=" << ui->lineEdit_point_3_y->text().toStdString().c_str() << endl;
stream << "plane_point3_z=" << ui->lineEdit_point_3_z->text().toStdString().c_str() << endl;
if (ui->checkBox_add_plane->isChecked())
stream << "add_plane=true"<< endl;
else
stream << "add_plane=false"<< endl;
stream << "# Others" << endl;
stream << "max_velocity="<< ui->lineEdit_w_max->text().toStdString().c_str() <<endl;
stream << "max_alpha="<< ui->lineEdit_alpha_max->text().toStdString().c_str() <<endl;
#if HAND == 1
stream << "max_velocity_gripper="<< ui->lineEdit_w_max_gripper->text().toStdString().c_str() <<endl;
stream << "max_alpha_gripper="<< ui->lineEdit_alpha_max_gripper->text().toStdString().c_str() <<endl;
#endif
if (ui->checkBox_tar_av->isChecked())
stream << "tar_av=false"<< endl;
else
stream << "tar_av=true"<< endl;
if (ui->checkBox_ob_av->isChecked())
stream << "ob_av=false"<< endl;
else
stream << "ob_av=true"<< endl;
if(ui->checkBox_approach->isChecked())
stream << "approach=false"<<endl;
else
stream << "approach=true"<<endl;
if(ui->checkBox_retreat->isChecked())
stream << "retreat=false"<<endl;
else
stream << "retreat=true"<<endl;
if(ui->checkBox_rand_init->isChecked())
stream << "rand_init=true"<<endl;
else
stream << "rand_init=false"<<endl;
if(ui->checkBox_coll->isChecked())
stream << "coll=false"<<endl;
else
stream << "coll=true"<<endl;
if(ui->checkBox_straight_line->isChecked())
stream << "straight_line=true"<<endl;
else
stream << "straight_line=false"<<endl;
f.close();
}
}
void TolDialogHUMP::on_pushButton_load_clicked()
{
QString filename = QFileDialog::getOpenFileName(this,
tr("Load the file of tolerances"),
QString(MAIN_PATH)+"/Tols",
"All Files (*.*);; Tol Files (*.tol)");
QFile f(filename);
//if(f.open( QIODevice::ReadOnly )) //with this line i get the error: QIODevice::write: ReadOnly device
if(f.open( QIODevice::ReadOnly))
{
QTextStream stream( &f );
QString line;
while(!stream.atEnd())
{
line = f.readLine();
if(line.at(0)!=QChar('#'))
{ //get the error QIODevice::write: ReadOnly device when enter here
QStringList fields = line.split("=");
stream << "Sphere1_radius=" << ui->lineEdit_sphere1_r->text().toStdString().c_str() << endl;
stream << "Sphere2_radius=" << ui->lineEdit_sphere2_r->text().toStdString().c_str() << endl;
stream << "Sphere3_radius=" << ui->lineEdit_sphere3_r->text().toStdString().c_str() << endl;
stream << "Sphere4_radius=" << ui->lineEdit_sphere4_r->text().toStdString().c_str() << endl;
stream << "Sphere5_radius=" << ui->lineEdit_sphere5_r->text().toStdString().c_str() << endl;
stream << "Sphere6_radius=" << ui->lineEdit_sphere6_r->text().toStdString().c_str() << endl;
stream << "Sphere7_radius=" << ui->lineEdit_sphere7_r->text().toStdString().c_str() << endl;
stream << "Sphere8_radius=" << ui->lineEdit_sphere8_r->text().toStdString().c_str() << endl;
stream << "Sphere9_radius=" << ui->lineEdit_sphere9_r->text().toStdString().c_str() << endl;
stream << "Sphere10_radius=" << ui->lineEdit_sphere10_r->text().toStdString().c_str() << endl;
stream << "Sphere11_radius=" << ui->lineEdit_sphere11_r->text().toStdString().c_str() << endl;
stream << "Sphere12_radius=" << ui->lineEdit_sphere12_r->text().toStdString().c_str() << endl;
stream << "Sphere13_radius=" << ui->lineEdit_sphere13_r->text().toStdString().c_str() << endl;
stream << "Sphere14_radius=" << ui->lineEdit_sphere14_r->text().toStdString().c_str() << endl;
if (QString::compare(fields.at(0),QString("Sphere1_radius"),Qt::CaseInsensitive)==0)
ui->lineEdit_sphere1_r->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("Sphere2_radius"),Qt::CaseInsensitive)==0)
ui->lineEdit_sphere2_r->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("Sphere3_radius"),Qt::CaseInsensitive)==0)
ui->lineEdit_sphere3_r->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("Sphere4_radius"),Qt::CaseInsensitive)==0)
ui->lineEdit_sphere4_r->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("Sphere5_radius"),Qt::CaseInsensitive)==0)
ui->lineEdit_sphere5_r->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("Sphere6_radius"),Qt::CaseInsensitive)==0)
ui->lineEdit_sphere6_r->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("Sphere7_radius"),Qt::CaseInsensitive)==0)
ui->lineEdit_sphere7_r->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("Sphere8_radius"),Qt::CaseInsensitive)==0)
ui->lineEdit_sphere8_r->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("Sphere9_radius"),Qt::CaseInsensitive)==0)
ui->lineEdit_sphere9_r->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("Sphere10_radius"),Qt::CaseInsensitive)==0)
ui->lineEdit_sphere10_r->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("Sphere11_radius"),Qt::CaseInsensitive)==0)
ui->lineEdit_sphere11_r->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("Sphere12_radius"),Qt::CaseInsensitive)==0)
ui->lineEdit_sphere12_r->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("Sphere13_radius"),Qt::CaseInsensitive)==0)
ui->lineEdit_sphere13_r->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("Sphere14_radius"),Qt::CaseInsensitive)==0)
ui->lineEdit_sphere14_r->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("Hand_1_1"),Qt::CaseInsensitive)==0)
ui->lineEdit_hand_1_1->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("Hand_1_2"),Qt::CaseInsensitive)==0)
ui->lineEdit_hand_1_2->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("Hand_1_3"),Qt::CaseInsensitive)==0)
ui->lineEdit_hand_1_3->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("Hand_2_1"),Qt::CaseInsensitive)==0)
ui->lineEdit_hand_2_1->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("Hand_2_2"),Qt::CaseInsensitive)==0)
ui->lineEdit_hand_2_2->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("Hand_2_3"),Qt::CaseInsensitive)==0)
ui->lineEdit_hand_2_3->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("Hand_3_1"),Qt::CaseInsensitive)==0)
ui->lineEdit_hand_3_1->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("Hand_3_2"),Qt::CaseInsensitive)==0)
ui->lineEdit_hand_3_2->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("Hand_3_3"),Qt::CaseInsensitive)==0)
ui->lineEdit_hand_3_3->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("Hand_tip_1"),Qt::CaseInsensitive)==0)
ui->lineEdit_hand_tip_1->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("Hand_tip_2"),Qt::CaseInsensitive)==0)
ui->lineEdit_hand_tip_2->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("Hand_tip_3"),Qt::CaseInsensitive)==0)
ui->lineEdit_hand_tip_3->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("lambda_1"),Qt::CaseInsensitive)==0)
ui->lineEdit_lambda_1->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("lambda_2"),Qt::CaseInsensitive)==0)
ui->lineEdit_lambda_2->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("lambda_3"),Qt::CaseInsensitive)==0)
ui->lineEdit_lambda_3->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("lambda_4"),Qt::CaseInsensitive)==0)
ui->lineEdit_lambda_4->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("lambda_5"),Qt::CaseInsensitive)==0)
ui->lineEdit_lambda_5->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("lambda_6"),Qt::CaseInsensitive)==0)
ui->lineEdit_lambda_6->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("lambda_7"),Qt::CaseInsensitive)==0)
ui->lineEdit_lambda_7->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("lambda_8"),Qt::CaseInsensitive)==0)
ui->lineEdit_lambda_8->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("lambda_9"),Qt::CaseInsensitive)==0)
ui->lineEdit_lambda_9->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("lambda_10"),Qt::CaseInsensitive)==0)
ui->lineEdit_lambda_10->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("lambda_11"),Qt::CaseInsensitive)==0)
ui->lineEdit_lambda_11->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("init_vel_1"),Qt::CaseInsensitive)==0)
ui->lineEdit_init_vel_1->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("init_vel_2"),Qt::CaseInsensitive)==0)
ui->lineEdit_init_vel_2->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("init_vel_3"),Qt::CaseInsensitive)==0)
ui->lineEdit_init_vel_3->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("init_vel_4"),Qt::CaseInsensitive)==0)
ui->lineEdit_init_vel_4->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("init_vel_5"),Qt::CaseInsensitive)==0)
ui->lineEdit_init_vel_5->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("init_vel_6"),Qt::CaseInsensitive)==0)
ui->lineEdit_init_vel_6->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("init_vel_7"),Qt::CaseInsensitive)==0)
ui->lineEdit_init_vel_7->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("init_vel_8"),Qt::CaseInsensitive)==0)
ui->lineEdit_init_vel_8->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("init_vel_9"),Qt::CaseInsensitive)==0)
ui->lineEdit_init_vel_9->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("init_vel_10"),Qt::CaseInsensitive)==0)
ui->lineEdit_init_vel_10->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("init_vel_11"),Qt::CaseInsensitive)==0)
ui->lineEdit_init_vel_11->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("final_vel_1"),Qt::CaseInsensitive)==0)
ui->lineEdit_final_vel_1->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("final_vel_2"),Qt::CaseInsensitive)==0)
ui->lineEdit_final_vel_2->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("final_vel_3"),Qt::CaseInsensitive)==0)
ui->lineEdit_final_vel_3->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("final_vel_4"),Qt::CaseInsensitive)==0)
ui->lineEdit_final_vel_4->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("final_vel_5"),Qt::CaseInsensitive)==0)
ui->lineEdit_final_vel_5->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("final_vel_6"),Qt::CaseInsensitive)==0)
ui->lineEdit_final_vel_6->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("final_vel_7"),Qt::CaseInsensitive)==0)
ui->lineEdit_final_vel_7->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("final_vel_8"),Qt::CaseInsensitive)==0)
ui->lineEdit_final_vel_8->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("final_vel_9"),Qt::CaseInsensitive)==0)
ui->lineEdit_final_vel_9->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("final_vel_10"),Qt::CaseInsensitive)==0)
ui->lineEdit_final_vel_10->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("final_vel_11"),Qt::CaseInsensitive)==0)
ui->lineEdit_final_vel_11->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("init_acc_1"),Qt::CaseInsensitive)==0)
ui->lineEdit_init_acc_1->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("init_acc_2"),Qt::CaseInsensitive)==0)
ui->lineEdit_init_acc_2->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("init_acc_3"),Qt::CaseInsensitive)==0)
ui->lineEdit_init_acc_3->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("init_acc_4"),Qt::CaseInsensitive)==0)
ui->lineEdit_init_acc_4->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("init_acc_5"),Qt::CaseInsensitive)==0)
ui->lineEdit_init_acc_5->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("init_acc_6"),Qt::CaseInsensitive)==0)
ui->lineEdit_init_acc_6->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("init_acc_7"),Qt::CaseInsensitive)==0)
ui->lineEdit_init_acc_7->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("init_acc_8"),Qt::CaseInsensitive)==0)
ui->lineEdit_init_acc_8->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("init_acc_9"),Qt::CaseInsensitive)==0)
ui->lineEdit_init_acc_9->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("init_acc_10"),Qt::CaseInsensitive)==0)
ui->lineEdit_init_acc_10->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("init_acc_11"),Qt::CaseInsensitive)==0)
ui->lineEdit_init_acc_11->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("final_acc_1"),Qt::CaseInsensitive)==0)
ui->lineEdit_final_acc_1->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("final_acc_2"),Qt::CaseInsensitive)==0)
ui->lineEdit_final_acc_2->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("final_acc_3"),Qt::CaseInsensitive)==0)
ui->lineEdit_final_acc_3->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("final_acc_4"),Qt::CaseInsensitive)==0)
ui->lineEdit_final_acc_4->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("final_acc_5"),Qt::CaseInsensitive)==0)
ui->lineEdit_final_acc_5->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("final_acc_6"),Qt::CaseInsensitive)==0)
ui->lineEdit_final_acc_6->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("final_acc_7"),Qt::CaseInsensitive)==0)
ui->lineEdit_final_acc_7->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("final_acc_8"),Qt::CaseInsensitive)==0)
ui->lineEdit_final_acc_8->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("final_acc_9"),Qt::CaseInsensitive)==0)
ui->lineEdit_final_acc_9->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("final_acc_10"),Qt::CaseInsensitive)==0)
ui->lineEdit_final_acc_10->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("final_acc_11"),Qt::CaseInsensitive)==0)
ui->lineEdit_final_acc_11->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("tar_xx_1"),Qt::CaseInsensitive)==0)
ui->lineEdit_tar_xx_1->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("tar_xx_2"),Qt::CaseInsensitive)==0)
ui->lineEdit_tar_xx_2->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("tar_xx_3"),Qt::CaseInsensitive)==0)
ui->lineEdit_tar_xx_3->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("tar_yy_1"),Qt::CaseInsensitive)==0)
ui->lineEdit_tar_yy_1->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("tar_yy_2"),Qt::CaseInsensitive)==0)
ui->lineEdit_tar_yy_2->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("tar_yy_3"),Qt::CaseInsensitive)==0)
ui->lineEdit_tar_yy_3->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("tar_zz_1"),Qt::CaseInsensitive)==0)
ui->lineEdit_tar_zz_1->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("tar_zz_2"),Qt::CaseInsensitive)==0)
ui->lineEdit_tar_zz_2->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("tar_zz_3"),Qt::CaseInsensitive)==0)
ui->lineEdit_tar_zz_3->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("tar_xy_1"),Qt::CaseInsensitive)==0)
ui->lineEdit_tar_xy_1->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("tar_xy_2"),Qt::CaseInsensitive)==0)
ui->lineEdit_tar_xy_2->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("tar_xy_3"),Qt::CaseInsensitive)==0)
ui->lineEdit_tar_xy_3->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("tar_xz_1"),Qt::CaseInsensitive)==0)
ui->lineEdit_tar_xz_1->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("tar_xz_2"),Qt::CaseInsensitive)==0)
ui->lineEdit_tar_xz_2->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("tar_xz_3"),Qt::CaseInsensitive)==0)
ui->lineEdit_tar_xz_3->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("tar_yz_1"),Qt::CaseInsensitive)==0)
ui->lineEdit_tar_yz_1->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("tar_yz_2"),Qt::CaseInsensitive)==0)
ui->lineEdit_tar_yz_2->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("tar_yz_3"),Qt::CaseInsensitive)==0)
ui->lineEdit_tar_yz_3->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("obs_xx_1"),Qt::CaseInsensitive)==0)
ui->lineEdit_obs_xx_1->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("obs_xx_2"),Qt::CaseInsensitive)==0)
ui->lineEdit_obs_xx_2->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("obs_xx_3"),Qt::CaseInsensitive)==0)
ui->lineEdit_obs_xx_3->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("obs_yy_1"),Qt::CaseInsensitive)==0)
ui->lineEdit_obs_yy_1->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("obs_yy_2"),Qt::CaseInsensitive)==0)
ui->lineEdit_obs_yy_2->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("obs_yy_3"),Qt::CaseInsensitive)==0)
ui->lineEdit_obs_yy_3->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("obs_zz_1"),Qt::CaseInsensitive)==0)
ui->lineEdit_obs_zz_1->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("obs_zz_2"),Qt::CaseInsensitive)==0)
ui->lineEdit_obs_zz_2->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("obs_zz_3"),Qt::CaseInsensitive)==0)
ui->lineEdit_obs_zz_3->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("obs_xy_1"),Qt::CaseInsensitive)==0)
ui->lineEdit_obs_xy_1->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("obs_xy_2"),Qt::CaseInsensitive)==0)
ui->lineEdit_obs_xy_2->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("obs_xy_3"),Qt::CaseInsensitive)==0)
ui->lineEdit_obs_xy_3->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("obs_xz_1"),Qt::CaseInsensitive)==0)
ui->lineEdit_obs_xz_1->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("obs_xz_2"),Qt::CaseInsensitive)==0)
ui->lineEdit_obs_xz_2->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("obs_xz_3"),Qt::CaseInsensitive)==0)
ui->lineEdit_obs_xz_3->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("obs_yz_1"),Qt::CaseInsensitive)==0)
ui->lineEdit_obs_yz_1->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("obs_yz_2"),Qt::CaseInsensitive)==0)
ui->lineEdit_obs_yz_2->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("obs_yz_3"),Qt::CaseInsensitive)==0)
ui->lineEdit_obs_yz_3->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("tar_pos"),Qt::CaseInsensitive)==0)
ui->lineEdit_tar_pos->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("tar_or"),Qt::CaseInsensitive)==0)
ui->lineEdit_tar_or->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("pre_grasp_x"),Qt::CaseInsensitive)==0)
ui->lineEdit_pre_grasp_x->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("pre_grasp_y"),Qt::CaseInsensitive)==0)
ui->lineEdit_pre_grasp_y->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("pre_grasp_z"),Qt::CaseInsensitive)==0)
ui->lineEdit_pre_grasp_z->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("pre_grasp_dist"),Qt::CaseInsensitive)==0)
ui->lineEdit_pre_grasp_dist->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("post_grasp_x"),Qt::CaseInsensitive)==0)
ui->lineEdit_post_grasp_x->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("post_grasp_y"),Qt::CaseInsensitive)==0)
ui->lineEdit_post_grasp_y->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("post_grasp_z"),Qt::CaseInsensitive)==0)
ui->lineEdit_post_grasp_z->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("post_grasp_dist"),Qt::CaseInsensitive)==0)
ui->lineEdit_post_grasp_dist->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("pre_place_x"),Qt::CaseInsensitive)==0)
ui->lineEdit_pre_place_x->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("pre_place_y"),Qt::CaseInsensitive)==0)
ui->lineEdit_pre_place_y->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("pre_place_z"),Qt::CaseInsensitive)==0)
ui->lineEdit_pre_place_z->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("pre_place_dist"),Qt::CaseInsensitive)==0)
ui->lineEdit_pre_place_dist->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("post_place_x"),Qt::CaseInsensitive)==0)
ui->lineEdit_post_place_x->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("post_place_y"),Qt::CaseInsensitive)==0)
ui->lineEdit_post_place_y->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("post_place_z"),Qt::CaseInsensitive)==0)
ui->lineEdit_post_place_z->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("post_place_dist"),Qt::CaseInsensitive)==0)
ui->lineEdit_post_place_dist->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("w_red_app"),Qt::CaseInsensitive)==0)
ui->lineEdit_w_red_app->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("w_red_ret"),Qt::CaseInsensitive)==0)
ui->lineEdit_w_red_ret->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("target_x"),Qt::CaseInsensitive)==0)
ui->lineEdit_target_x->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("target_y"),Qt::CaseInsensitive)==0)
ui->lineEdit_target_y->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("target_z"),Qt::CaseInsensitive)==0)
ui->lineEdit_target_z->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("target_roll"),Qt::CaseInsensitive)==0)
ui->lineEdit_target_roll->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("target_pitch"),Qt::CaseInsensitive)==0)
ui->lineEdit_target_pitch->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("target_yaw"),Qt::CaseInsensitive)==0)
ui->lineEdit_target_yaw->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("final_arm_1"),Qt::CaseInsensitive)==0)
ui->lineEdit_final_arm_1->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("final_arm_2"),Qt::CaseInsensitive)==0)
ui->lineEdit_final_arm_2->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("final_arm_3"),Qt::CaseInsensitive)==0)
ui->lineEdit_final_arm_3->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("final_arm_4"),Qt::CaseInsensitive)==0)
ui->lineEdit_final_arm_4->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("final_arm_5"),Qt::CaseInsensitive)==0)
ui->lineEdit_final_arm_5->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("final_arm_6"),Qt::CaseInsensitive)==0)
ui->lineEdit_final_arm_6->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("final_arm_7"),Qt::CaseInsensitive)==0)
ui->lineEdit_final_arm_7->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("final_hand_1"),Qt::CaseInsensitive)==0)
ui->lineEdit_final_hand_1->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("final_hand_2"),Qt::CaseInsensitive)==0)
ui->lineEdit_final_hand_2->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("final_hand_3"),Qt::CaseInsensitive)==0)
ui->lineEdit_final_hand_3->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("final_hand_4"),Qt::CaseInsensitive)==0)
ui->lineEdit_final_hand_4->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("sel_final"),Qt::CaseInsensitive)==0)
{
if(QString::compare(fields.at(1),QString("false\n"),Qt::CaseInsensitive)==0)
ui->checkBox_sel_final_posture->setChecked(false);
else
ui->checkBox_sel_final_posture->setChecked(true);
}
else if(QString::compare(fields.at(0),QString("plane_point1_x"),Qt::CaseInsensitive)==0)
ui->lineEdit_point_1_x->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("plane_point1_y"),Qt::CaseInsensitive)==0)
ui->lineEdit_point_1_y->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("plane_point1_z"),Qt::CaseInsensitive)==0)
ui->lineEdit_point_1_z->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("plane_point2_x"),Qt::CaseInsensitive)==0)
ui->lineEdit_point_2_x->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("plane_point2_y"),Qt::CaseInsensitive)==0)
ui->lineEdit_point_2_y->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("plane_point2_z"),Qt::CaseInsensitive)==0)
ui->lineEdit_point_2_z->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("plane_point3_x"),Qt::CaseInsensitive)==0)
ui->lineEdit_point_3_x->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("plane_point3_y"),Qt::CaseInsensitive)==0)
ui->lineEdit_point_3_y->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("plane_point3_z"),Qt::CaseInsensitive)==0)
ui->lineEdit_point_3_z->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("add_plane"),Qt::CaseInsensitive)==0)
{
if(QString::compare(fields.at(1),QString("false\n"),Qt::CaseInsensitive)==0)
ui->checkBox_add_plane->setChecked(false);
else
ui->checkBox_add_plane->setChecked(true);
}
else if(QString::compare(fields.at(0),QString("max_velocity"),Qt::CaseInsensitive)==0)
ui->lineEdit_w_max->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("max_alpha"),Qt::CaseInsensitive)==0)
ui->lineEdit_alpha_max->setText(fields.at(1));
#if HAND == 1
else if(QString::compare(fields.at(0),QString("max_velocity_gripper"),Qt::CaseInsensitive)==0)
ui->lineEdit_w_max_gripper->setText(fields.at(1));
else if(QString::compare(fields.at(0),QString("max_alpha_gripper"),Qt::CaseInsensitive)==0)
ui->lineEdit_alpha_max_gripper->setText(fields.at(1));
#endif
else if(QString::compare(fields.at(0),QString("tar_av"),Qt::CaseInsensitive)==0)
{
if(QString::compare(fields.at(1),QString("false\n"),Qt::CaseInsensitive)==0)
ui->checkBox_tar_av->setChecked(true);
else
ui->checkBox_tar_av->setChecked(false);
}
else if(QString::compare(fields.at(0),QString("ob_av"),Qt::CaseInsensitive)==0)
{
if(QString::compare(fields.at(1),QString("false\n"),Qt::CaseInsensitive)==0)
ui->checkBox_ob_av->setChecked(true);
else
ui->checkBox_ob_av->setChecked(false);
}
else if(QString::compare(fields.at(0),QString("approach"),Qt::CaseInsensitive)==0)
{
if(QString::compare(fields.at(1),QString("false\n"),Qt::CaseInsensitive)==0)
ui->checkBox_approach->setChecked(true);
else
ui->checkBox_approach->setChecked(false);
}
else if(QString::compare(fields.at(0),QString("retreat"),Qt::CaseInsensitive)==0)
{
if(QString::compare(fields.at(1),QString("false\n"),Qt::CaseInsensitive)==0)
ui->checkBox_retreat->setChecked(true);
else
ui->checkBox_retreat->setChecked(false);
}
else if(QString::compare(fields.at(0),QString("rand_init"),Qt::CaseInsensitive)==0)
{
if(QString::compare(fields.at(1),QString("false\n"),Qt::CaseInsensitive)==0)
ui->checkBox_rand_init->setChecked(false);
else
ui->checkBox_rand_init->setChecked(true);
}
else if(QString::compare(fields.at(0),QString("coll"),Qt::CaseInsensitive)==0)
{
if(QString::compare(fields.at(1),QString("false\n"),Qt::CaseInsensitive)==0)
ui->checkBox_coll->setChecked(true);
else
ui->checkBox_coll->setChecked(false);
}
else if(QString::compare(fields.at(0),QString("straight_line"),Qt::CaseInsensitive)==0)
{
if(QString::compare(fields.at(1),QString("false\n"),Qt::CaseInsensitive)==0)
ui->checkBox_straight_line->setChecked(false);
else
ui->checkBox_straight_line->setChecked(true);
}
}
}
f.close();
}
}
void TolDialogHUMP::checkApproach(int state)
{
if(state==0)
{
// unchecked
ui->groupBox_pre_grasp->setEnabled(true);
ui->groupBox_pre_place->setEnabled(true);
ui->label_pick->setEnabled(true);
}
else
{
//checked
ui->groupBox_pre_grasp->setEnabled(false);
ui->groupBox_pre_place->setEnabled(false);
ui->label_pick->setEnabled(false);
}
}
void TolDialogHUMP::checkRetreat(int state)
{
if(state==0)
{
// unchecked
ui->groupBox_post_grasp->setEnabled(true);
ui->groupBox_post_place->setEnabled(true);
ui->label_pick->setEnabled(true);
}
else
{
//checked
ui->groupBox_post_grasp->setEnabled(false);
ui->groupBox_post_place->setEnabled(false);
ui->label_pick->setEnabled(false);
}
}
void TolDialogHUMP::checkFinalPosture(int state)
{
if(state==0)
{
// unchecked
ui->groupBox_target->setEnabled(true);
ui->groupBox_final_arm->setEnabled(false);
}
else
{
//checked
ui->groupBox_target->setEnabled(false);
ui->groupBox_final_arm->setEnabled(true);
}
}
void TolDialogHUMP::checkAddPlane(int state)
{
if(state==0)
//unchecked
ui->groupBox_plane->setEnabled(false);
else
//checked
ui->groupBox_plane->setEnabled(true);
}
bool TolDialogHUMP::getRandInit()
{
return ui->checkBox_rand_init->isChecked();
}
void TolDialogHUMP::setRandInit(bool rand)
{
ui->checkBox_rand_init->setChecked(rand);
}
bool TolDialogHUMP::getColl()
{
return !ui->checkBox_coll->isChecked();
}
void TolDialogHUMP::setColl(bool coll)
{
ui->checkBox_coll->setChecked(!coll);
}
bool TolDialogHUMP::get_use_final_posture()
{
return ui->checkBox_sel_final_posture->isChecked();
}
bool TolDialogHUMP::get_add_plane()
{
return ui->checkBox_add_plane->isChecked();
}
bool TolDialogHUMP::get_straight_line()
{
return ui->checkBox_straight_line->isChecked();
}
void TolDialogHUMP::setStraightLine(bool straight)
{
ui->checkBox_straight_line->setChecked(straight);
}
void TolDialogHUMP::set_add_plane(bool plane)
{
ui->checkBox_add_plane->setChecked(plane);
}
} // namespace motion_manager
| 54.066062
| 315
| 0.628788
|
JoaoQPereira
|
8c995366b02402a232627d44ea3ff64138e1a6db
| 4,413
|
cpp
|
C++
|
repos/plywood/src/reflect/ply-reflect/TypeSynthesizer.cpp
|
boldsort/plywood
|
ab85a187e9e9d42d55cd3bd24be000898fd50234
|
[
"MIT"
] | 742
|
2020-05-26T12:34:24.000Z
|
2022-03-14T07:22:36.000Z
|
repos/plywood/src/reflect/ply-reflect/TypeSynthesizer.cpp
|
boldsort/plywood
|
ab85a187e9e9d42d55cd3bd24be000898fd50234
|
[
"MIT"
] | 18
|
2020-05-27T20:29:15.000Z
|
2022-01-17T00:19:45.000Z
|
repos/plywood/src/reflect/ply-reflect/TypeSynthesizer.cpp
|
boldsort/plywood
|
ab85a187e9e9d42d55cd3bd24be000898fd50234
|
[
"MIT"
] | 51
|
2020-05-26T15:30:00.000Z
|
2021-12-15T01:02:25.000Z
|
/*------------------------------------
///\ Plywood C++ Framework
\\\/ https://plywood.arc80.com/
------------------------------------*/
#include <ply-reflect/Core.h>
#include <ply-reflect/TypeSynthesizer.h>
#include <ply-reflect/FormatDescriptor.h>
#include <ply-reflect/SynthTypeDeduplicator.h>
namespace ply {
struct BuiltInPair {
FormatKey key;
TypeDescriptor* type;
};
extern Array<BuiltInPair> BuiltInTypeDescs;
// Currently, we just use a global hook for the app to install custom type synthesizers.
// If needed, we could use a more flexible approach in the future:
std::map<String, SynthFunc> g_TypeSynthRegistry;
struct TypeSynthesizer {
TypeDescriptorOwner* m_typeDescOwner = nullptr;
std::map<FormatDescriptor*, TypeDescriptor*> m_formatToType;
};
TypeDescriptor* synthesize(TypeSynthesizer* synth, FormatDescriptor* formatDesc) {
PLY_ASSERT(formatDesc);
// Handle primitive built-in types
if (formatDesc->formatKey < (u8) FormatKey::StartUserKeyRange) {
BuiltInPair& pair = BuiltInTypeDescs[formatDesc->formatKey];
PLY_ASSERT(pair.type);
PLY_ASSERT(pair.key == (FormatKey) formatDesc->formatKey);
return pair.type;
}
// See if a TypeDescriptor was already synthesized for this FormatDescriptor
auto iter = synth->m_formatToType.find(formatDesc);
if (iter != synth->m_formatToType.end())
return iter->second;
// Synthesize a new TypeDescriptor
TypeDescriptor* typeDesc = nullptr;
switch ((FormatKey) formatDesc->formatKey) {
case FormatKey::FixedArray: {
FormatDescriptor_FixedArray* fixedFormat = (FormatDescriptor_FixedArray*) formatDesc;
TypeDescriptor* itemType = synthesize(synth, fixedFormat->itemFormat);
typeDesc = new TypeDescriptor_FixedArray{itemType, fixedFormat->numItems};
synth->m_typeDescOwner->adoptType(typeDesc);
break;
}
case FormatKey::Array: {
FormatDescriptor_Array* arrayFormat = (FormatDescriptor_Array*) formatDesc;
TypeDescriptor* itemType = synthesize(synth, arrayFormat->itemFormat);
typeDesc = new TypeDescriptor_Array{itemType};
synth->m_typeDescOwner->adoptType(typeDesc);
break;
}
case FormatKey::Struct: {
FormatDescriptor_Struct* structFormat = (FormatDescriptor_Struct*) formatDesc;
auto iter = g_TypeSynthRegistry.find(structFormat->name);
if (iter != g_TypeSynthRegistry.end()) {
// Currently, we just use a global hook for the app to install custom type
// synthesizers. If needed, we could use a more flexible approach in the
// future:
typeDesc = iter->second(synth, formatDesc);
} else {
// Synthesize a struct
TypeDescriptor_Struct* structType =
new TypeDescriptor_Struct{0, structFormat->name};
u32 memberOffset = 0;
for (const FormatDescriptor_Struct::Member& member : structFormat->members) {
TypeDescriptor* memberType = synthesize(synth, member.formatDesc);
structType->members.append({member.name, memberOffset, memberType});
// FIXME: Deal with alignment here
memberOffset += memberType->fixedSize;
}
// FIXME: Deal with alignment here
structType->fixedSize = memberOffset;
typeDesc = structType;
synth->m_typeDescOwner->adoptType(typeDesc);
}
break;
}
default: {
// Shouldn't get here
PLY_ASSERT(0);
break;
}
}
// Add it to owner and lookup table
PLY_ASSERT(typeDesc);
synth->m_formatToType[formatDesc] = typeDesc;
return typeDesc;
}
void append(TypeSynthesizer* synth, TypeDescriptor* typeDesc) {
synth->m_typeDescOwner->adoptType(typeDesc);
}
Reference<TypeDescriptorOwner> synthesizeType(FormatDescriptor* formatDesc) {
Reference<TypeDescriptorOwner> typeDescOwner = new TypeDescriptorOwner;
TypeSynthesizer synth;
synth.m_typeDescOwner = typeDescOwner;
typeDescOwner->setRootType(synthesize(&synth, formatDesc));
return getUniqueType(&g_typeDedup, typeDescOwner);
}
} // namespace ply
| 38.373913
| 97
| 0.640834
|
boldsort
|
8ca3e44fb3afb84b0ade55a42d2758e71f2d1b2e
| 1,910
|
cpp
|
C++
|
Paperworks/src/Platform/OpenGL/OpenGLRendererAPI.cpp
|
codenobacon4u/paperworks
|
0e96cd2fb6070a2387ddd36aaa327b04733234fa
|
[
"MIT"
] | 1
|
2019-08-15T18:58:54.000Z
|
2019-08-15T18:58:54.000Z
|
Paperworks/src/Platform/OpenGL/OpenGLRendererAPI.cpp
|
codenobacon4u/paperworks
|
0e96cd2fb6070a2387ddd36aaa327b04733234fa
|
[
"MIT"
] | null | null | null |
Paperworks/src/Platform/OpenGL/OpenGLRendererAPI.cpp
|
codenobacon4u/paperworks
|
0e96cd2fb6070a2387ddd36aaa327b04733234fa
|
[
"MIT"
] | null | null | null |
#include "pwpch.h"
#include "OpenGLRendererAPI.h"
#include <glad/glad.h>
namespace Paperworks {
void OpenGLMessageCallback(
unsigned source,
unsigned type,
unsigned id,
unsigned severity,
int length,
const char* message,
const void* userParam)
{
switch (severity)
{
case GL_DEBUG_SEVERITY_HIGH: PW_CORE_CRITICAL("{0} Source: {1}", message, source); return;
case GL_DEBUG_SEVERITY_MEDIUM: PW_CORE_ERROR("{0} Source: {1}", message, source); return;
case GL_DEBUG_SEVERITY_LOW: PW_CORE_WARN("{0} Source: {1}", message, source); return;
case GL_DEBUG_SEVERITY_NOTIFICATION: PW_CORE_TRACE(message); return;
}
PW_CORE_ASSERT(false, "Unknown severity level!");
}
void OpenGLRendererAPI::Init()
{
#ifdef PW_DEBUG
glEnable(GL_DEBUG_OUTPUT);
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
glDebugMessageCallback(OpenGLMessageCallback, nullptr);
glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_NOTIFICATION, 0, NULL, GL_FALSE);
#endif
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_DEPTH_TEST);
}
void OpenGLRendererAPI::SetViewport(uint32_t x, uint32_t y, uint32_t width, uint32_t height)
{
glViewport(x, y, width, height);
}
void OpenGLRendererAPI::SetClearColor(const glm::vec4& color)
{
glClearColor(color.r, color.g, color.b, color.a);
}
void OpenGLRendererAPI::Clear()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
std::pair<int, int> OpenGLRendererAPI::GetViewport()
{
int viewport[4];
glGetIntegerv(GL_VIEWPORT, viewport);
return std::pair<int, int>(viewport[2], viewport[3]);
}
void OpenGLRendererAPI::DrawIndexed(const Shared<VertexArray>& vertexArray, uint32_t indexCount)
{
glDrawElements(GL_TRIANGLES, indexCount ? vertexArray->GetIndexBuffer()->GetCount() : indexCount, GL_UNSIGNED_INT, nullptr);
glBindTexture(GL_TEXTURE_2D, 0);
}
}
| 27.285714
| 126
| 0.742932
|
codenobacon4u
|
8ca44f36d5ebacb5cef0d8b9e03e7f90c366e5f5
| 763
|
cpp
|
C++
|
src/hexview/view/player.cpp
|
ejrh/hex
|
3c063ce142e6b62fb0f92f71bc94280305b53322
|
[
"MIT"
] | 7
|
2015-09-15T13:20:23.000Z
|
2020-12-07T10:14:57.000Z
|
src/hexview/view/player.cpp
|
ejrh/hex
|
3c063ce142e6b62fb0f92f71bc94280305b53322
|
[
"MIT"
] | null | null | null |
src/hexview/view/player.cpp
|
ejrh/hex
|
3c063ce142e6b62fb0f92f71bc94280305b53322
|
[
"MIT"
] | 1
|
2018-09-07T00:54:35.000Z
|
2018-09-07T00:54:35.000Z
|
#include "common.h"
#include "hexview/view/player.h"
namespace hex {
Player::Player(int id, const std::string& name): id(id), name(name) {
}
void Player::grant_view(Faction::pointer faction, bool allow) {
if (allow)
faction_view.insert(faction->id);
else
faction_view.erase(faction->id);
}
void Player::grant_control(Faction::pointer faction, bool allow) {
if (allow)
faction_control.insert(faction->id);
else
faction_control.erase(faction->id);
}
bool Player::has_view(Faction::pointer faction) const {
return faction_view.find(faction->id) != faction_view.end();
}
bool Player::has_control(Faction::pointer faction) const {
return faction_control.find(faction->id) != faction_control.end();
}
};
| 22.441176
| 70
| 0.686763
|
ejrh
|
8ca50759f3edb895b34ce913275ee93732491906
| 8,473
|
cpp
|
C++
|
Softrast/src/SoftwareRasterizer/texture_load.cpp
|
RickvanMiltenburg/SoftRast
|
e14b74804c052bb448058808cbb6dd06616ba585
|
[
"MIT"
] | null | null | null |
Softrast/src/SoftwareRasterizer/texture_load.cpp
|
RickvanMiltenburg/SoftRast
|
e14b74804c052bb448058808cbb6dd06616ba585
|
[
"MIT"
] | null | null | null |
Softrast/src/SoftwareRasterizer/texture_load.cpp
|
RickvanMiltenburg/SoftRast
|
e14b74804c052bb448058808cbb6dd06616ba585
|
[
"MIT"
] | null | null | null |
/*
SoftRast software rasterizer, by Rick van Miltenburg
Software rasterizer created for fun and educational purposes.
---
Copyright (c) 2015 Rick van Miltenburg
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 "softrast.h"
#include "../MemoryMappedFile.h"
#include <assert.h>
#include <math.h>
#define STB_IMAGE_IMPLEMENTATION
#define STB_IMAGE_RESIZE_IMPLEMENTATION
#include <stb_image.h>
#include <stb_image_resize.h>
extern "C" {
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
extern buddy_allocator* _softrastAllocator;
extern DEBUG_SETTINGS Debug;
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
uint32_t softrast_texture_load ( softrast_texture* tex, const char* path )
{
//--------------------------------
// Load file
//--------------------------------
MemoryMappedFile file ( path );
if ( !file.IsValid ( ) )
return -1; // File not found (probably)
//--------------------------------
// Load as texture
//--------------------------------
int width, height, components;
unsigned char* data = stbi_load_from_memory ( (const stbi_uc*)file.GetData ( ), (int)file.GetSize ( ), &width, &height, &components, 4 );
if ( data == nullptr )
return -2; // Could not load image
//--------------------------------
// Check parameters
//--------------------------------
if ( width != height )
return (stbi_image_free ( data ), -5); // Only square textures are supported
if ( width & (width-1) )
return (stbi_image_free ( data ), -6); // Only power-of-two textures are supported
if ( width > 0xFFFF )
return (stbi_image_free ( data ), -7); // Only power-of-two sizes that fit in 16 bits are supported
//--------------------------------
// Allocate memory for all mips
//--------------------------------
const uint32_t mipLevels = 1 + (uint32_t)floorf ( 0.5f + log2f ( (float)width ) );
size_t allocSize;
switch ( Debug.textureAddressingMode )
{
case TEXTURE_ADDRESSING_LINEAR:
allocSize = mipLevels * sizeof ( uint32_t* )
+ (width * height + (width * height)/3) * sizeof ( uint32_t );
break;
case TEXTURE_ADDRESSING_TILED:
{
size_t mippedPixCount = (width * height + (width * height)/3);
mippedPixCount += (16 - 1*1); // Pad mip 1x1
if ( mipLevels > 1 )
mippedPixCount += (16 - 2*2); // Pad mip 2x2
allocSize = mipLevels * sizeof ( uint32_t* )
+ mippedPixCount * sizeof ( uint32_t );
}
break;
case TEXTURE_ADDRESSING_SWIZZLED:
allocSize = mipLevels * sizeof ( uint32_t* )
+ (width * height + (width * height)/3+3) * sizeof ( uint32_t );
break;
default:
assert ( false );
break;
}
void* tempMipData = (void*)miltyalloc_buddy_allocator_alloc ( _softrastAllocator, (width/2 + width/4) * (height/2 + height/4) * sizeof ( uint32_t ) );
void* memory = (void*)miltyalloc_buddy_allocator_alloc ( _softrastAllocator, allocSize );
if ( memory == nullptr || tempMipData == nullptr )
return (miltyalloc_buddy_allocator_free ( _softrastAllocator, memory ), miltyalloc_buddy_allocator_free ( _softrastAllocator, tempMipData ), stbi_image_free ( data ), -8); // Could not allocate enough memory
//--------------------------------
// Fill texture data
//--------------------------------
tex->mipData = (uint32_t**)memory;
tex->mipLevels = (uint32_t)mipLevels;
tex->width = (uint16_t)width;
tex->height = (uint16_t)height;
//--------------------------------
// Mip data for swapping
//--------------------------------
uint32_t* mipData[2] = { (uint32_t*)tempMipData, ((uint32_t*)tempMipData) + ((width/2) * (height/2)) };
//--------------------------------
// Fill mips
//--------------------------------
uint32_t* memPtr = (uint32_t*)((uintptr_t)memory + tex->mipLevels * sizeof ( uint32_t* ));
uint32_t mipSize = (uint32_t)width;
uint32_t* imgpixels = (uint32_t*)data;
for ( uint32_t i = 0; i < mipLevels; i++, mipSize /= 2 )
{
uint32_t rowPitch = mipSize * sizeof ( uint32_t );
uintptr_t imgaddr = (uintptr_t)imgpixels;
tex->mipData[i] = memPtr;
if ( Debug.textureAddressingMode == TEXTURE_ADDRESSING_LINEAR )
{
for ( uint32_t r = 0; r < mipSize; r++, imgaddr += rowPitch, memPtr += mipSize )
memcpy ( memPtr, (void*)imgaddr, mipSize * sizeof ( uint32_t ) );
}
else if ( Debug.textureAddressingMode == TEXTURE_ADDRESSING_TILED )
{
const uint32_t tileCols = (mipSize + 3)/4;
const uint32_t tileRows = (mipSize + 3)/4;
uint32_t* dptr = tex->mipData[i];
for ( uint32_t r = 0; r < tileRows; r++ )
{
for ( uint32_t c = 0; c < tileCols; c++, memPtr += 16 )
{
const uint32_t startSrcX = c * 4;
const uint32_t startSrcY = r * 4;
const uint32_t pixCols = (mipSize > 4 ? 4 : mipSize);
const uint32_t pixRows = (mipSize > 4 ? 4 : mipSize);
uint32_t* dptr = memPtr;
for ( uint32_t pr = 0; pr < pixRows; pr++, dptr += 4 )
{
const uint32_t* src = (uint32_t*)(imgpixels + ((startSrcY+pr) * rowPitch)) + startSrcX;
uint32_t* dst = dptr;
for ( uint32_t pc = 0; pc < pixCols; pc++, src++, dst++ )
{
*dst = *src;
}
}
}
}
}
else if ( Debug.textureAddressingMode == TEXTURE_ADDRESSING_SWIZZLED )
{
uint32_t idx = 0;
uint32_t* dptr = tex->mipData[i];
const uint32_t* eptr = dptr + mipSize * mipSize;
for ( ; dptr != eptr; idx++, dptr++ )
{
// yxyx yxyx yxyx yxyx yxyx yxyx yxyx yxyx
// x = 0x55555555
// y = 0xAAAAAAAA
uint32_t srcXPadded = idx & 0x55555555;
uint32_t srcYPadded = (idx & 0xAAAAAAAA) >> 1;
// 0x0x 0x0x 0x0x 0x0x 0x0x 0x0x 0x0x 0x0x
// => 0000 0000 0000 0000 xxxx xxxx xxxx xxxx
uint32_t srcX = 0, srcY = 0;
for ( uint32_t i = 0; i < 16; i++ )
{
srcX |= ((srcXPadded & (1<<(2*i))) >> i);
srcY |= ((srcYPadded & (1<<(2*i))) >> i);
}
*dptr = ((uint32_t*)(imgpixels + srcY * rowPitch))[srcX];
}
memPtr += mipSize * mipSize;
}
else
assert ( false );
//--------------------------------
// Swap mips
//--------------------------------
stbir_resize_uint8_srgb_edgemode ( (const unsigned char*)imgpixels, mipSize, mipSize, mipSize * sizeof ( uint32_t ), (unsigned char*)mipData[i&1], mipSize/2, mipSize/2, mipSize/2 * sizeof ( uint32_t ), 4, 3, 0, STBIR_EDGE_WRAP );
imgpixels = mipData[i&1];
}
if ( Debug.textureAddressingMode == TEXTURE_ADDRESSING_SWIZZLED )
{
*(memPtr++) = 0xFF00FF;
*(memPtr++) = 0xFF00FF;
*(memPtr++) = 0xFF00FF;
}
//--------------------------------
// Memory checks
//--------------------------------
assert ( (uintptr_t)memPtr == (uintptr_t)memory + allocSize );
//--------------------------------
// Cleanup
//--------------------------------
miltyalloc_buddy_allocator_free ( _softrastAllocator, tempMipData );
stbi_image_free ( data );
//--------------------------------
// We're done here!
//--------------------------------
return 0;
}
uint32_t softrast_texture_free ( softrast_texture* tex )
{
if ( miltyalloc_buddy_allocator_free ( _softrastAllocator, tex->mipData ) == MILTYALLOC_SUCCESS )
return 0;
else
return -1; // Could not free memory
}
};
| 36.83913
| 461
| 0.571698
|
RickvanMiltenburg
|
8cb1b9ffa9f5b3e7ec621aefc9ed6a2a16422d91
| 2,888
|
hpp
|
C++
|
network/configuration.hpp
|
agnesnatasya/Be-Tree
|
516c97c1a4ee68346e301277cfc318bb07a0c1b7
|
[
"BSD-2-Clause"
] | null | null | null |
network/configuration.hpp
|
agnesnatasya/Be-Tree
|
516c97c1a4ee68346e301277cfc318bb07a0c1b7
|
[
"BSD-2-Clause"
] | null | null | null |
network/configuration.hpp
|
agnesnatasya/Be-Tree
|
516c97c1a4ee68346e301277cfc318bb07a0c1b7
|
[
"BSD-2-Clause"
] | null | null | null |
// -*- mode: c++; c-file-style: "k&r"; c-basic-offset: 4 -*-
#ifndef _NETWORK_CONFIGURATION_H_
#define _NETWORK_CONFIGURATION_H_
//#include "replication/common/viewstamp.h"
#include <fstream>
#include <stdbool.h>
#include <string>
#include <vector>
using std::string;
namespace network {
struct ServerAddress
{
string host;
string port;
ServerAddress(const string &host, const string &port);
bool operator==(const ServerAddress &other) const;
inline bool operator!=(const ServerAddress &other) const {
return !(*this == other);
}
bool operator<(const ServerAddress &other) const;
bool operator<=(const ServerAddress &other) const {
return *this < other || *this == other;
}
bool operator>(const ServerAddress &other) const {
return !(*this <= other);
}
bool operator>=(const ServerAddress &other) const {
return !(*this < other);
}
};
class Configuration
{
public:
Configuration(const Configuration &c);
Configuration(int n,
// int f,
std::vector<ServerAddress> servers,
ServerAddress *multicastAddress = nullptr);
Configuration(std::ifstream &file);
virtual ~Configuration();
ServerAddress GetServerAddress(int idx) const;
const ServerAddress *multicast() const;
// int GetLeaderIndex(view_t view) const;
// int QuorumSize() const;
// int FastQuorumSize() const;
bool operator==(const Configuration &other) const;
inline bool operator!=(const Configuration &other) const {
return !(*this == other);
}
bool operator<(const Configuration &other) const;
bool operator<=(const Configuration &other) const {
return *this < other || *this == other;
}
bool operator>(const Configuration &other) const {
return !(*this <= other);
}
bool operator>=(const Configuration &other) const {
return !(*this < other);
}
public:
int n; // number of servers
// int f; // number of failures tolerated
private:
std::vector<ServerAddress> servers;
ServerAddress *multicastAddress;
bool hasMulticast;
};
} // namespace network
namespace std {
template <> struct hash<network::ServerAddress>
{
size_t operator()(const network::ServerAddress & x) const
{
return hash<string>()(x.host) * 37 + hash<string>()(x.port);
}
};
}
namespace std {
template <> struct hash<network::Configuration>
{
size_t operator()(const network::Configuration & x) const
{
size_t out = 0;
out = x.n * 37;
for (int i = 0; i < x.n; i++) {
out *= 37;
out += hash<network::ServerAddress>()(x.GetServerAddress(i));
}
return out;
}
};
}
#endif /* _NETWORK_CONFIGURATION_H_ */
| 26.990654
| 77
| 0.607341
|
agnesnatasya
|
8cb486af18aba5622fb729bbd92a89b3fd5aecd8
| 19,252
|
cpp
|
C++
|
falcon/src/main/c/src/haplotypecaller/com_falconcomputing_genomics_haplotypecaller_FalconSmithWaterman.cpp
|
FCS-holding/gatk4
|
6dd3c78c455980ccd67bb600f1f50660c9ae4365
|
[
"BSD-3-Clause"
] | null | null | null |
falcon/src/main/c/src/haplotypecaller/com_falconcomputing_genomics_haplotypecaller_FalconSmithWaterman.cpp
|
FCS-holding/gatk4
|
6dd3c78c455980ccd67bb600f1f50660c9ae4365
|
[
"BSD-3-Clause"
] | null | null | null |
falcon/src/main/c/src/haplotypecaller/com_falconcomputing_genomics_haplotypecaller_FalconSmithWaterman.cpp
|
FCS-holding/gatk4
|
6dd3c78c455980ccd67bb600f1f50660c9ae4365
|
[
"BSD-3-Clause"
] | null | null | null |
#include <jni.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <emmintrin.h>
#include <immintrin.h>
#include <xmmintrin.h>
#include "com_falconcomputing_genomics_haplotypecaller_FalconSmithWaterman.h"
#include "Common.h"
#include "smithwaterman/avx2_impl.h"
jfieldID state_list_fd;
jfieldID length_list_fd;
jfieldID cigar_list_size_fd;
jfieldID alignment_offset_fd;
jfieldID ret_code_fd;
struct SWPairJNIObj{
jclass results_class;
jobject ret_object;
jintArray length_list;
jintArray state_list;
};
std::mutex obj_map_mutex;
std::map<std::thread::id, struct SWPairJNIObj> SWPairJNIObj_map;
struct SWPairJNIObj init_JNI_obj(JNIEnv* env, jobject& obj){
std::thread::id this_id = std::this_thread::get_id();
std::map<std::thread::id, struct SWPairJNIObj>::iterator JNIObj_mapIter = SWPairJNIObj_map.find(this_id);
if(JNIObj_mapIter == SWPairJNIObj_map.end()){
struct SWPairJNIObj objs;
jintArray length_list_global = env->NewIntArray(MAX_SEQ_LENGTH);
if (env->ExceptionCheck()) {
throwAccError(env, "failed new jintArray length_list");
}
objs.length_list = (jintArray) env->NewGlobalRef(length_list_global);
jintArray state_list_global = env->NewIntArray(MAX_SEQ_LENGTH);
if (env->ExceptionCheck()) {
throwAccError(env, "failed new jintArray state_list");
}
objs.state_list = (jintArray) env->NewGlobalRef(state_list_global);
jclass results_class_global = env->FindClass("Lcom/falconcomputing/genomics/haplotypecaller/FalconSmithWaterman$FalconSWResultsNative;");
if(results_class_global == NULL){
throwAccError(env, "Failed to FindClass FalconSWResultsNative");
}
objs.results_class = (jclass) env->NewGlobalRef(results_class_global);
jmethodID results_class_cnstrctr = env->GetMethodID(results_class_global, "<init>", "(Lcom/falconcomputing/genomics/haplotypecaller/FalconSmithWaterman;[I[IIII)V");
if(results_class_cnstrctr == NULL){
throwAccError(env, "Failed to Get constructor of FalconSWResultsNative");
}
jobject ret_object_global = env->NewObject(results_class_global, results_class_cnstrctr, obj, state_list_global, length_list_global, 0, 0, (jint)0);
objs.ret_object = (jclass) env->NewGlobalRef(ret_object_global);
obj_map_mutex.lock();
SWPairJNIObj_map[this_id] = objs;
obj_map_mutex.unlock();
return objs;
}
else{
return JNIObj_mapIter->second;
}
}
JNIEXPORT void JNICALL Java_com_falconcomputing_genomics_haplotypecaller_FalconSmithWaterman_init_1native(JNIEnv *env, jobject obj){
struct SWPairJNIObj JNIObjs = init_JNI_obj(env, obj);
state_list_fd = env->GetFieldID(JNIObjs.results_class, "state_list", "[I");
length_list_fd = env->GetFieldID(JNIObjs.results_class, "length_list", "[I");
cigar_list_size_fd = env->GetFieldID(JNIObjs.results_class, "cigar_list_size", "I");
alignment_offset_fd = env->GetFieldID(JNIObjs.results_class, "alignment_offset", "I");
ret_code_fd = env->GetFieldID(JNIObjs.results_class, "ret_code", "I");
}
JNIEXPORT void JNICALL Java_com_falconcomputing_genomics_haplotypecaller_FalconSmithWaterman_done_1native(JNIEnv *env, jobject obj){
/*if(results_class != NULL){
env->NewGlobalRef(results_class);
}
if(Exception != NULL){
env->NewGlobalRef(Exception);
}*/
}
JNIEXPORT jobject JNICALL Java_com_falconcomputing_genomics_haplotypecaller_FalconSmithWaterman_align_1native(JNIEnv *env, jobject thisObj, jbyteArray reference, jbyteArray alternate, jint w_match, jint w_mismatch, jint w_open, jint w_extend, jint overhang_strategy){
struct SWPairJNIObj JNIObjs = init_JNI_obj(env, thisObj);
jobject ret_object = JNIObjs.ret_object;
jintArray length_list = JNIObjs.length_list;
jintArray state_list = JNIObjs.state_list;
int ret_code = 0;
int n = (int)(env->GetArrayLength(reference)) + 1;
int m = (int)(env->GetArrayLength(alternate)) + 1;
int overhang_strategy_native = (int)overhang_strategy; //0 is SOFT_CLIP, 1 is INDEL, 2 is LEADING_INDEL, 3 is IGNORE
if(overhang_strategy < 0 || overhang_strategy > 3){
//fprintf(stderr, "Wrong strategy\n");
ret_code = -1;
throwAccError(env, "Illegal overhang_strategy");
return NULL;
}
//now initialize the native reference and native alternate arrays
jboolean isCopy_reference;
jboolean isCopy_alternate;
char* reference_native = (char*)env->GetByteArrayElements(reference, &isCopy_reference);
if(!reference_native){
ret_code = -1;
throwAccError(env, "Failed to get native reference[]");
return NULL;
}
char* alternate_native = (char*)env->GetByteArrayElements(alternate, &isCopy_alternate);
if(!alternate_native){
ret_code = -1;
throwAccError(env, "Failed to get native alternate[]");
return NULL;
}
int w_match_native = (int)w_match;
int w_mismatch_native = (int)w_mismatch;
int w_open_native = (int)w_open;
int w_extend_native = (int)w_extend;
int* length_list_native = NULL;
int* state_list_native = NULL;
int Cigar_list_size;
int alignment_offset_native;
SWPairwiseAlignmentOnceGKL(reference_native, n - 1, alternate_native, m - 1, w_match_native, w_mismatch_native, w_open_native, w_extend_native, overhang_strategy_native, &length_list_native, &state_list_native, Cigar_list_size, alignment_offset_native);
/*calculate_matrix_ret = calculateMatrixRowWiseSIMDUnroll4x(reference_native, alternate_native, sw, m, n, btrack, overhang_strategy_native, cutoff_native, w_match_native, w_mismatch_native, w_open_native, w_extend_native);
if(calculate_matrix_ret < 0){
return NULL;
}
calculate_cigar_ret = calculateCigar(env, sw, btrack, n, m, overhang_strategy_native, &length_list_native, &state_list_native, &Cigar_list_size, &alignment_offset_native);
if(calculate_cigar_ret < 0){
return NULL;
}*/
///now covert the length_list_native and state_list_native and alignment_offset_native to java vars
env->SetIntArrayRegion(length_list, 0, Cigar_list_size, length_list_native);
if (env->ExceptionCheck()) {
throwAccError(env, "Failed to setIntArrayRegion length_list");
return NULL;
}
env->SetIntArrayRegion(state_list, 0, Cigar_list_size, state_list_native);
if (env->ExceptionCheck()) {
throwAccError(env, "Failed to setIntArrayRegion state_list");
return NULL;
}
jint alignment_offset = (jint)alignment_offset_native;
jint ret_code_java = (jint)ret_code;
env->SetObjectField(ret_object, state_list_fd, state_list);
env->SetObjectField(ret_object, length_list_fd, length_list);
env->SetIntField(ret_object, cigar_list_size_fd, Cigar_list_size);
env->SetIntField(ret_object, alignment_offset_fd, alignment_offset);
env->SetIntField(ret_object, ret_code_fd, ret_code_java);
if (env->ExceptionCheck()) {
throwAccError(env, "Failed to new return object");
return NULL;
}
free(length_list_native);
free(state_list_native);
return ret_object;
}
/*
int calculateMatrix(JNIEnv *env, char* reference, char* alternate, int** sw, int ncol, int nrow, int** btrack, int overhang_strategy_native, int cutoff, int w_match, int w_mismatch, int w_open, int w_extend){
int matrix_min_cutoff;
if(cutoff) matrix_min_cutoff = 0;
else matrix_min_cutoff = (int)(-1e8);
int i = 0;
signed int lowInitValue = -1073741824;
int* best_gap_v;
int* best_gap_h;
int* gap_size_v;
int* gap_size_h;
if(!(best_gap_v = (int*)_mm_malloc((ncol + 1) * sizeof(int), 64))){
throwAccError(env, "failed to malloc best_gap_v[]");
//env->ThrowNew(Exception_SWPair, "failed to malloc best_gap_v[]");
return -1;
}
if(!(best_gap_h = (int*)_mm_malloc((nrow + 1) * sizeof(int), 64))){
throwAccError(env, "failed to malloc best_gap_h[]");
//env->ThrowNew(Exception_SWPair, "failed to malloc best_gap_h[]");
return -1;
}
if(!(gap_size_v = (int*)_mm_malloc((ncol + 1) * sizeof(int), 64))){
throwAccError(env, "failed to malloc gap_size_v[]");
//env->ThrowNew(Exception_SWPair, "failed to malloc gap_size_v[]");
return -1;
}
if(!(gap_size_h = (int*)_mm_malloc((nrow + 1) * sizeof(int), 64))){
throwAccError(env, "failed to malloc gap_size_h[]");
//env->ThrowNew(Exception_SWPair, "failed to malloc gap_size_h[]");
return -1;
}
for(i = 0; i < ncol + 1; ++i){
best_gap_v[i] = lowInitValue;
gap_size_v[i] = 0;
}
for(i = 0; i < nrow + 1; ++i){
best_gap_h[i] = lowInitValue;
gap_size_h[i] = 0;
}
if(overhang_strategy_native == OVERHANG_STRATEGY_INDEL || overhang_strategy_native == OVERHANG_STRATEGY_LEADING_INDEL){
sw[0][1] = w_open;
int currentValue = w_open;
for(i = 2; i < ncol; i++){
currentValue += w_extend;
sw[0][i] = currentValue;
}
sw[1][0] = w_open;
currentValue = w_open;
for(i = 2; i < nrow; i++){
currentValue += w_extend;
sw[i][0] = currentValue;
}
}
//build smith-waterman matrix and keep backtrack info
int curRow_id = 0;
int lastRow_id = 0;
int curBackTrackRow_id = 0;
int j = 0;
char a_base = 0;
char b_base = 0;
int step_diag = 0;
int prev_gap = 0;
int step_down = 0;
int kd = 0;
int step_right = 0;
int ki = 0;
int diagHighestOrEqual = 0;
for(i = 1; i < nrow; ++i){
a_base = reference[i - 1];
lastRow_id = curRow_id;
curRow_id = i;
curBackTrackRow_id = i;
for(j = 1; j< ncol; ++j){
b_base = alternate[j - 1];
step_diag = sw[lastRow_id][j - 1] + wd(a_base, b_base, w_match, w_mismatch);
prev_gap = sw[lastRow_id][j] + w_open;
best_gap_v[j] += w_extend;
if(prev_gap > best_gap_v[j]){
best_gap_v[j] = prev_gap;
gap_size_v[j] = 1;
}
else{
gap_size_v[j]++;
}
step_down = best_gap_v[j];
kd = gap_size_v[j];
prev_gap = sw[curRow_id][j - 1] + w_open;
best_gap_h[i] += w_extend;
if(prev_gap > best_gap_h[i]){
best_gap_h[i] = prev_gap;
gap_size_h[i] = 1;
}
else{
gap_size_h[i]++;
}
step_right = best_gap_h[i];
ki = gap_size_h[i];
//priority here will be step diagonal, step righ, step down
diagHighestOrEqual = (step_diag >= step_down) && (step_diag >= step_right);
if(diagHighestOrEqual){
sw[curRow_id][j] = max(matrix_min_cutoff, step_diag);
btrack[curBackTrackRow_id][j] = 0;
}
else if(step_right >= step_down){
sw[curRow_id][j] = max(matrix_min_cutoff, step_right);
btrack[curBackTrackRow_id][j] = -ki;
}
else{
sw[curRow_id][j] = max(matrix_min_cutoff, step_down);
btrack[curBackTrackRow_id][j] = kd;
}
}
}
_mm_free(best_gap_h);
_mm_free(best_gap_v);
_mm_free(gap_size_h);
_mm_free(gap_size_v);
return 0;
}
int calculateCigar(JNIEnv *env, int** sw, int** btrack, int nrow, int ncol, int overhang_strategy, int** length_list_ptr, int** state_list_ptr, int* Cigar_list_length, int* alignment_offset_ptr){
int p1 = 0;
int p2 = 0;
int refLength = nrow - 1;
int altLength = ncol - 1;
int maxscore = -2147483648;
int segment_length = 0;
int i = 0;
int j = 0;
int curScore = 0;
if(overhang_strategy == OVERHANG_STRATEGY_INDEL){
p1 = refLength;
p2 = altLength;
}
else{
p2 = altLength;
for(i = 1; i < nrow; ++i){
curScore = sw[i][altLength];
if(curScore >= maxscore){
p1 = i;
maxscore = curScore;
}
}
//now look for a larger score on the bottom-most row
if(overhang_strategy != OVERHANG_STRATEGY_LEADING_INDEL){
for(j = 1; j < ncol; ++j){
curScore = sw[refLength][j];
if(curScore > maxscore || (curScore == maxscore && (abs(refLength - j) < abs(p1 - p2)))){
p1 = refLength;
p2 = j;
maxscore = curScore;
segment_length = altLength - j;
}
}
}
}
int lce_length = 0;
struct CigarList* lce_head_node = NULL;
if(segment_length > 0 && overhang_strategy == OVERHANG_STRATEGY_SOFTCLIP){
if(!(lce_head_node = (struct CigarList*) malloc(sizeof(struct CigarList)))){
throwAccError(env, "failed to malloc lce_head_node");
//env->ThrowNew(Exception_SWPair,"failed to malloc lce_head_node");
return -1;
}
lce_head_node->state = STATE_CLIP;
lce_head_node->length = segment_length;
lce_head_node->next = NULL;
lce_length++;
segment_length = 0;
}
int state = STATE_MATCH;
int btr = 0;
int new_state =0;
int step_length = 0;
struct CigarList* lce_new_node = NULL;
do{
btr = btrack[p1][p2];
step_length = 1;
if(btr > 0){
new_state = STATE_DELETION;
step_length = btr;
}
else if(btr < 0){
new_state = STATE_INSERTION;
step_length = (-btr);
}
else
new_state = STATE_MATCH;
switch(new_state){
case STATE_MATCH: p1--; p2--; break;
case STATE_INSERTION: p2 -= step_length; break;
case STATE_DELETION: p1 -= step_length; break;
}
if(new_state == state) segment_length += step_length;
else{
lce_new_node = NULL;
if(!(lce_new_node = (struct CigarList*) malloc(sizeof(struct CigarList)))){
throwAccError(env, "failed to malloc lce_new_node");
//env->ThrowNew(Exception_SWPair, "failed to malloc lce_new_node");
return -1;
}
lce_new_node->state = state;
lce_new_node->length = segment_length;
lce_new_node->next = lce_head_node;
lce_head_node = lce_new_node;
lce_length++;
segment_length = step_length;
state = new_state;
}
}while(p1 > 0 && p2 > 0);
if(overhang_strategy == OVERHANG_STRATEGY_SOFTCLIP){
if(!(lce_new_node = (struct CigarList*) malloc(sizeof(struct CigarList)))){
throwAccError(env, "failed to malloc lce_new_node");
//env->ThrowNew(Exception_SWPair, "failed to malloc lce_new_node");
return -1;
}
lce_new_node->state = state;
lce_new_node->length = segment_length;
lce_new_node->next = lce_head_node;
lce_head_node = lce_new_node;
lce_length++;
if(p2 > 0){
if(!(lce_new_node = (struct CigarList*) malloc(sizeof(struct CigarList)))){
//fprintf(stderr, "No mem space for CigarList node\n");
throwAccError(env, "failed to malloc lce_new_node");
//env->ThrowNew(Exception_SWPair, "failed to malloc lce_new_node");
return -1;
}
lce_new_node->state = STATE_CLIP;
lce_new_node->length = p2;
lce_new_node->next = lce_head_node;
lce_head_node = lce_new_node;
lce_length++;
}
*alignment_offset_ptr = p1;
}
else if(overhang_strategy == OVERHANG_STRATEGY_IGNORE){
if(!(lce_new_node = (struct CigarList*) malloc(sizeof(struct CigarList)))){
throwAccError(env, "failed to malloc lce_new_node");
//env->ThrowNew(Exception_SWPair, "failed to malloc lce_new_node");
return -1;
}
lce_new_node->state = state;
lce_new_node->length = segment_length + p2;
lce_new_node->next = lce_head_node;
lce_head_node = lce_new_node;
lce_length++;
*alignment_offset_ptr = p1 - p2;
}
else{
if(!(lce_new_node = (struct CigarList*) malloc(sizeof(struct CigarList)))){
throwAccError(env, "failed to malloc lce_new_node");
//env->ThrowNew(Exception_SWPair, "failed to malloc lce_new_node");
return -1;
}
lce_new_node->state = state;
lce_new_node->length = segment_length;
lce_new_node->next = lce_head_node;
lce_head_node = lce_new_node;
lce_length++;
if(p1 > 0){
if(!(lce_new_node = (struct CigarList*) malloc(sizeof(struct CigarList)))){
throwAccError(env, "failed to malloc lce_new_node");
//env->ThrowNew(Exception_SWPair, "failed to malloc lce_new_node");
return -1;
}
lce_new_node->state = STATE_DELETION;
lce_new_node->length = p1;
lce_new_node->next = lce_head_node;
lce_head_node = lce_new_node;
lce_length++;
}
else if(p2 > 0){
if(!(lce_new_node = (struct CigarList*) malloc(sizeof(struct CigarList)))){
throwAccError(env, "failed to malloc lce_new_node");
//env->ThrowNew(Exception_SWPair, "failed to malloc lce_new_node");
return -1;
}
lce_new_node->state = STATE_INSERTION;
lce_new_node->length = p2;
lce_new_node->next = lce_head_node;
lce_head_node = lce_new_node;
lce_length++;
}
*alignment_offset_ptr = 0;
}
//lce_new_node is already a reversed linked list
//now cast it into a int array
if(!(*length_list_ptr = (int*)malloc(lce_length*sizeof(int)))){
throwAccError(env, "failed to malloc length_list_ptr");
//env->ThrowNew(Exception_SWPair, "failed to malloc length_list_ptr");
return -1;
}
if(!(*state_list_ptr = (int*)malloc(lce_length*sizeof(int)))){
throwAccError(env, "failed to malloc state_list_ptr");
//env->ThrowNew(Exception_SWPair, "failed to malloc state_list_ptr");
return -1;
}
struct CigarList* lce_list_ptr = lce_head_node;
for(i = 0; i < lce_length; ++i){
(*length_list_ptr)[i] = lce_list_ptr->length;
(*state_list_ptr)[i] = lce_list_ptr->state;
lce_list_ptr = lce_list_ptr->next;
}
*Cigar_list_length = lce_length;
//free the lce list
struct CigarList* lce_list_cur = lce_head_node;
while(lce_list_cur){
lce_list_ptr = lce_list_cur->next;
free(lce_list_cur);
lce_list_cur = lce_list_ptr;
}
return 0;
}*/
| 37.094412
| 267
| 0.617806
|
FCS-holding
|
8cb6c29e8ae2ff198dabd14817f916210c9ad420
| 554
|
cpp
|
C++
|
Sid's Levels/Level - 2/Arrays/MissingNumber.cpp
|
Tiger-Team-01/DSA-A-Z-Practice
|
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
|
[
"MIT"
] | 14
|
2021-08-22T18:21:14.000Z
|
2022-03-08T12:04:23.000Z
|
Sid's Levels/Level - 2/Arrays/MissingNumber.cpp
|
Tiger-Team-01/DSA-A-Z-Practice
|
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
|
[
"MIT"
] | 1
|
2021-10-17T18:47:17.000Z
|
2021-10-17T18:47:17.000Z
|
Sid's Levels/Level - 2/Arrays/MissingNumber.cpp
|
Tiger-Team-01/DSA-A-Z-Practice
|
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
|
[
"MIT"
] | 5
|
2021-09-01T08:21:12.000Z
|
2022-03-09T12:13:39.000Z
|
class Solution {
public:
int missingNumber(vector<int>& nums) {
//OM GAN GANAPATHAYE NAMO NAMAH
//JAI SHRI RAM
//JAI BAJRANGBALI
//AMME NARAYANA, DEVI NARAYANA, LAKSHMI NARAYANA, BHADRE NARAYANA
int sumOfArray = 0;
int actualSum = 0;
for(int i = 0; i < nums.size(); i++)
{
sumOfArray += nums[i];
}
for(int i = 0; i <= nums.size(); i++)
{
actualSum += i;
}
int res = actualSum - sumOfArray;
return res;
}
};
| 25.181818
| 73
| 0.490975
|
Tiger-Team-01
|
8cbbcc9381916ada850f388d1f3e4995f1eec20a
| 29,023
|
cxx
|
C++
|
tools/bundle_adjust_tracks.cxx
|
dstoup/maptk
|
04e8b65147f147b833bf936e9c770fd52168100d
|
[
"BSD-3-Clause"
] | null | null | null |
tools/bundle_adjust_tracks.cxx
|
dstoup/maptk
|
04e8b65147f147b833bf936e9c770fd52168100d
|
[
"BSD-3-Clause"
] | null | null | null |
tools/bundle_adjust_tracks.cxx
|
dstoup/maptk
|
04e8b65147f147b833bf936e9c770fd52168100d
|
[
"BSD-3-Clause"
] | null | null | null |
/*ckwg +29
* Copyright 2014 by Kitware, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither name of Kitware, Inc. nor the names of any 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 AUTHORS 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.
*/
/**
* \file
* \brief Sparse Bungle Adjustment utility
*/
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <exception>
#include <string>
#include <vector>
#include <maptk/modules.h>
#include <maptk/core/algo/bundle_adjust.h>
#include <maptk/core/algo/initialize_cameras_landmarks.h>
#include <maptk/core/algo/estimate_similarity_transform.h>
#include <maptk/core/algo/triangulate_landmarks.h>
#include <maptk/core/algo/geo_map.h>
#include <maptk/core/camera_io.h>
#include <maptk/core/config_block.h>
#include <maptk/core/config_block_io.h>
#include <maptk/core/exceptions.h>
#include <maptk/core/geo_reference_points_io.h>
#include <maptk/core/ins_data_io.h>
#include <maptk/core/landmark_map_io.h>
#include <maptk/core/local_geo_cs.h>
#include <maptk/core/metrics.h>
#include <maptk/core/track_set.h>
#include <maptk/core/track_set_io.h>
#include <maptk/core/transform.h>
#include <maptk/core/types.h>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/value_semantic.hpp>
#include <boost/program_options/variables_map.hpp>
#include <boost/timer/timer.hpp>
namespace bfs = boost::filesystem;
namespace bpo = boost::program_options;
static maptk::config_block_sptr default_config()
{
using namespace maptk;
config_block_sptr config = config_block::empty_config("bundle_adjust_tracks_tool");
config->set_value("input_track_file", "",
"Path an input file containing feature tracks");
config->set_value("image_list_file", "",
"Path to the input image list file used to generated the "
"input tracks.");
config->set_value("input_pos_files", "",
"A directory containing the input POS files, or a text file"
"containing a newline-separated list of POS files. "
"This is optional, leave blank to ignore. This is "
"mutually exclusive with the input_reference_points "
"option when using an st_estimator.");
config->set_value("input_reference_points_file", "",
"File containing reference points to use for reprojection "
"of results into the geographic coordinate system. This "
"option is NOT mutually exclusive with input_pos_files "
"when using an st_estimator. When both are provided, "
"use of the reference file is given priority over the "
"POS files.\n"
"\n"
"Reference points file format (lm=landmark, tNsM=track N state M):\n"
"\tlm1.x lm1.y lm1.z t1s1.frame t1s1.x t1s1.y t1s2.frame t1s2.x t1s2.y ...\n"
"\tlm2.x lm2.y lm2.z t2s1.frame t2s1.x t2s1.y t2s2.frame t2s2.x t2s2.y ...\n"
"\t...\n"
"\n"
"At least 3 landmarks must be given, with at least 2 "
"track states recorded for each landmark, for "
"transformation estimation to converge, however more of "
"each is recommended.\n"
"\n"
"Landmark z position, or altitude, should be provided in meters.");
config->set_value("output_ply_file", "output/landmarks.ply",
"Path to the output PLY file in which to write "
"resulting 3D landmark points");
config->set_value("output_pos_dir", "output/pos",
"A directory in which to write the output POS files.");
config->set_value("output_krtd_dir", "output/krtd",
"A directory in which to write the output KRTD files.");
config->set_value("min_track_length", "50",
"Filter the input tracks keeping those covering "
"at least this many frames.");
config->set_value("camera_sample_rate", "1",
"Sub-sample the cameras for by this rate.\n"
"Set to 1 to use all cameras, "
"2 to use every other camera, etc.");
config->set_value("base_camera:focal_length", "1.0",
"focal length of the base camera model");
config->set_value("base_camera:principal_point", "640 480",
"The principal point of the base camera model \"x y\".\n"
"It is usually safe to assume this is the center of the "
"image.");
config->set_value("base_camera:aspect_ratio", "1.0",
"the pixel aspect ratio of the base camera model");
config->set_value("base_camera:skew", "0.0",
"The skew factor of the base camera model.\n"
"This is almost always zero in any real camera.");
config->set_value("ins:rotation_offset", "0 0 0 1",
"A quaternion used to offset rotation data from POS files "
"when updating cameras. This option is only relevent if a "
"value is give to the input_pos_files option.");
algo::bundle_adjust::get_nested_algo_configuration("bundle_adjuster", config,
algo::bundle_adjust_sptr());
algo::initialize_cameras_landmarks
::get_nested_algo_configuration("initializer", config,
algo::initialize_cameras_landmarks_sptr());
algo::triangulate_landmarks::get_nested_algo_configuration("triangulator", config,
algo::triangulate_landmarks_sptr());
algo::geo_map::get_nested_algo_configuration("geo_mapper", config,
algo::geo_map_sptr());
algo::estimate_similarity_transform::get_nested_algo_configuration("st_estimator", config,
algo::estimate_similarity_transform_sptr());
return config;
}
static bool check_config(maptk::config_block_sptr config)
{
bool config_valid = true;
#define MAPTK_CONFIG_FAIL(msg) \
std::cerr << "Config Check Fail: " << msg << std::endl; \
config_valid = false
if (!config->has_value("input_track_file"))
{
MAPTK_CONFIG_FAIL("Not given a tracks file path");
}
else if (!bfs::exists(config->get_value<std::string>("input_track_file")))
{
MAPTK_CONFIG_FAIL("Given tracks file path doesn't point to an existing file.");
}
if (!config->has_value("image_list_file"))
{
MAPTK_CONFIG_FAIL("Not given an image list file");
}
else if (!bfs::exists(config->get_value<std::string>("image_list_file")))
{
MAPTK_CONFIG_FAIL("Given image list file path doesn't point to an existing file.");
}
if (config->get_value<std::string>("input_pos_files", "") != "")
{
if(!bfs::exists(config->get_value<std::string>("input_pos_files")))
{
MAPTK_CONFIG_FAIL("POS input path given, but doesn't point to an existing location.");
}
}
if (config->get_value<std::string>("input_reference_points_file", "") != "")
{
if (!bfs::exists(config->get_value<std::string>("input_reference_points_file")))
{
MAPTK_CONFIG_FAIL("Path given for input reference points file does not exist.");
}
}
if (!maptk::algo::bundle_adjust::check_nested_algo_configuration("bundle_adjuster", config))
{
MAPTK_CONFIG_FAIL("Failed config check in bundle_adjuster algorithm.");
}
if (!maptk::algo::initialize_cameras_landmarks
::check_nested_algo_configuration("initializer", config))
{
MAPTK_CONFIG_FAIL("Failed config check in initializer algorithm.");
}
if (!maptk::algo::triangulate_landmarks::check_nested_algo_configuration("triangulator", config))
{
MAPTK_CONFIG_FAIL("Failed config check in triangulator algorithm.");
}
if (!maptk::algo::geo_map::check_nested_algo_configuration("geo_mapper", config))
{
MAPTK_CONFIG_FAIL("Failed config check in geo_mapper algorithm.");
}
if (config->has_value("st_estimator:type") && config->get_value<std::string>("st_estimator:type") != "")
{
if (!maptk::algo::estimate_similarity_transform::check_nested_algo_configuration("st_estimator", config))
{
MAPTK_CONFIG_FAIL("Failed config check in st_estimator algorithm.");
}
}
#undef MAPTK_CONFIG_FAIL
return config_valid;
}
/// create a base camera instance from config options
maptk::camera_d
base_camera_from_config(maptk::config_block_sptr config)
{
using namespace maptk;
camera_intrinsics_d K(config->get_value<double>("focal_length"),
config->get_value<vector_2d>("principal_point"),
config->get_value<double>("aspect_ratio"),
config->get_value<double>("skew"));
return camera_d(vector_3d(0,0,-1), rotation_d(), K);
}
/// filter track set by removing short tracks
maptk::track_set_sptr
filter_tracks(maptk::track_set_sptr tracks, size_t min_length)
{
using namespace maptk;
std::vector<track_sptr> trks = tracks->tracks();
std::vector<track_sptr> good_trks;
BOOST_FOREACH(track_sptr t, trks)
{
if( t->size() >= min_length )
{
good_trks.push_back(t);
}
}
return track_set_sptr(new simple_track_set(good_trks));
}
/// Subsample a every Nth camera, where N is specfied by factor
/**
* Uses camera frame numbers to determine subsample. This is fine when we
* assume the cameras given are sequential and always start with frame 0.
* This will behave in possibly undesired ways when the given cameras are not in
* sequential frame order, or the first camera's frame is not a multiple of
* \c factor.
*/
maptk::camera_map_sptr
subsample_cameras(maptk::camera_map_sptr cameras, unsigned factor)
{
using namespace maptk;
camera_map::map_camera_t cams = cameras->cameras();
camera_map::map_camera_t sub_cams;
BOOST_FOREACH(const camera_map::map_camera_t::value_type& p, cams)
{
if(p.first % factor == 0)
{
sub_cams.insert(p);
}
}
return camera_map_sptr(new simple_camera_map(sub_cams));
}
// return a sorted list of files in a directory
std::vector<bfs::path>
files_in_dir(const bfs::path& dir)
{
bfs::directory_iterator it(dir), eod;
std::vector<bfs::path> files;
BOOST_FOREACH(bfs::path const &p, std::make_pair(it, eod))
{
files.push_back(p);
}
std::sort(files.begin(), files.end());
return files;
}
#define print_config(config) \
do \
{ \
BOOST_FOREACH( maptk::config_block_key_t key, config->available_values() ) \
{ \
std::cerr << "\t" \
<< key << " = " << config->get_value<maptk::config_block_key_t>(key) \
<< std::endl; \
} \
} while (false)
static int maptk_main(int argc, char const* argv[])
{
// register the algorithms in the various modules for dynamic look-up
maptk::register_modules();
// define/parse CLI options
bpo::options_description opt_desc;
opt_desc.add_options()
("help,h", "output help message and exit")
("config,c",
bpo::value<maptk::path_t>(),
"Configuration file for the tool.")
("output-config,o",
bpo::value<maptk::path_t>(),
"Output a configuration.This may be seeded with"
" a configuration file from -c/--config.")
;
bpo::variables_map vm;
try
{
bpo::store(bpo::parse_command_line(argc, argv, opt_desc), vm);
}
catch (bpo::unknown_option const& e)
{
std::cerr << "Error: unknown option " << e.get_option_name() << std::endl;
return EXIT_FAILURE;
}
bpo::notify(vm);
if(vm.count("help"))
{
std::cerr << opt_desc << std::endl;
return EXIT_SUCCESS;
}
// Set config to algo chain
// Get config from algo chain after set
// Check config validity, store result
//
// If -o/--output-config given,
// output config result and notify of current (in)validity
// Else error if provided config not valid.
namespace algo = maptk::algo;
// Set up top level configuration w/ defaults where applicable.
maptk::config_block_sptr config = maptk::config_block::empty_config();
algo::bundle_adjust_sptr bundle_adjuster;
algo::initialize_cameras_landmarks_sptr initializer;
algo::triangulate_landmarks_sptr triangulator;
algo::geo_map_sptr geo_mapper;
algo::estimate_similarity_transform_sptr st_estimator;
// If -c/--config given, read in confg file, merge in with default just generated
if(vm.count("config"))
{
//std::cerr << "[DEBUG] Given config file: " << vm["config"].as<maptk::path_t>() << std::endl;
config->merge_config(maptk::read_config_file(vm["config"].as<maptk::path_t>()));
}
//std::cerr << "[DEBUG] Config BEFORE set:" << std::endl;
//print_config(config);
algo::bundle_adjust::set_nested_algo_configuration("bundle_adjuster", config, bundle_adjuster);
algo::triangulate_landmarks::set_nested_algo_configuration("triangulator", config, triangulator);
algo::initialize_cameras_landmarks::set_nested_algo_configuration("initializer", config, initializer);
algo::geo_map::set_nested_algo_configuration("geo_mapper", config, geo_mapper);
algo::estimate_similarity_transform::set_nested_algo_configuration("st_estimator", config, st_estimator);
//std::cerr << "[DEBUG] Config AFTER set:" << std::endl;
//print_config(config);
bool valid_config = check_config(config);
if(vm.count("output-config"))
{
maptk::config_block_sptr dflt_config = default_config();
dflt_config->merge_config(config);
config = dflt_config;
algo::bundle_adjust::get_nested_algo_configuration("bundle_adjuster", config, bundle_adjuster);
algo::triangulate_landmarks::get_nested_algo_configuration("triangulator", config, triangulator);
algo::initialize_cameras_landmarks::get_nested_algo_configuration("initializer", config, initializer);
algo::geo_map::get_nested_algo_configuration("geo_mapper", config, geo_mapper);
algo::estimate_similarity_transform::get_nested_algo_configuration("st_estimator", config, st_estimator);
//std::cerr << "[DEBUG] Given config output target: "
// << vm["output-config"].as<maptk::path_t>() << std::endl;
write_config_file(config, vm["output-config"].as<maptk::path_t>());
if(valid_config)
{
std::cerr << "INFO: Configuration file contained valid parameters"
<< " and may be used for running" << std::endl;
}
else
{
std::cerr << "WARNING: Configuration deemed not valid." << std::endl;
}
return EXIT_SUCCESS;
}
else if(!valid_config)
{
std::cerr << "ERROR: Configuration not valid." << std::endl;
return EXIT_FAILURE;
}
//
// Read the track file
//
std::string track_file = config->get_value<std::string>("input_track_file");
std::cout << "loading track file: " << track_file <<std::endl;
maptk::track_set_sptr tracks = maptk::read_track_file(track_file);
std::cout << "loaded "<<tracks->size()<<" tracks"<<std::endl;
size_t min_track_len = config->get_value<size_t>("min_track_length");
if( min_track_len > 1 )
{
boost::timer::auto_cpu_timer t("track filtering: %t sec CPU, %w sec wall\n");
tracks = filter_tracks(tracks, min_track_len);
std::cout << "filtered down to "<<tracks->size()<<" long tracks"<<std::endl;
}
//
// Read in image list file
//
// Also creating helper structures (i.e. frameID-to-filename and vise versa
// maps).
//
std::string image_list_file = config->get_value<std::string>("image_list_file");
std::ifstream image_list_ifs(image_list_file.c_str());
if (!image_list_ifs)
{
std::cerr << "Error: Could not open image list file!" << std::endl;
return EXIT_FAILURE;
}
std::vector<maptk::path_t> image_files;
for (std::string line; std::getline(image_list_ifs, line); )
{
image_files.push_back(line);
}
// Since input tracks were generated over these frames, we can assume that
// the frames are "in order" in that tracking followed this list in this given
// order. As this is a single list, we assume that there are no gaps (same
// assumptions as makde in tracking).
// Creating forward and revese mappings for frame to file stem-name.
std::vector<std::string> frame2filename; // valid since we are assuming no frame gaps
std::map<std::string, maptk::frame_id_t> filename2frame;
BOOST_FOREACH(maptk::path_t i_file, image_files)
{
std::string i_file_stem = i_file.stem().string();
filename2frame[i_file_stem] = static_cast<maptk::frame_id_t>(frame2filename.size());
frame2filename.push_back(i_file_stem);
}
//
// Create the local coordinate system
//
maptk::local_geo_cs local_cs(geo_mapper);
maptk::camera_d base_camera = base_camera_from_config(config->subblock("base_camera"));
//
// Initialize cameras
//
typedef std::map<maptk::frame_id_t, maptk::ins_data> ins_map_t;
ins_map_t ins_map;
maptk::camera_map::map_camera_t cameras;
// Vars that are used/populated when POS files are given.
maptk::camera_map::map_camera_t pos_cameras;
maptk::rotation_d ins_rot_offset = config->get_value<maptk::rotation_d>("ins:rotation_offset",
maptk::rotation_d());
// Vars that are used/populated if reference points file given.
maptk::landmark_map_sptr reference_landmarks(new maptk::simple_landmark_map());
maptk::track_set_sptr reference_tracks(new maptk::simple_track_set());
// if POS files are available, use them to initialize the cameras
if( config->get_value<std::string>("input_pos_files", "") != "" )
{
boost::timer::auto_cpu_timer t("Initializing cameras from POS files: %t sec CPU, %w sec wall\n");
std::string pos_files = config->get_value<std::string>("input_pos_files");
std::vector<bfs::path> files;
if( bfs::is_directory(pos_files) )
{
files = files_in_dir(pos_files);
}
else
{
std::ifstream ifs(pos_files.c_str());
if (!ifs)
{
std::cerr << "Error: Could not open POS file list "
<< "\"" <<pos_files << "\""
<< std::endl;
return EXIT_FAILURE;
}
for (std::string line; std::getline(ifs,line); )
{
files.push_back(line);
}
}
std::cout << "loading POS files" <<std::endl;
// Associating POS file to frame ID based on whether its filename stem is
// the same as an image in the given image list (map created above).
BOOST_FOREACH(maptk::path_t const& fpath, files)
{
std::string pos_file_stem = fpath.stem().string();
if (filename2frame.count(pos_file_stem))
{
ins_map[filename2frame[pos_file_stem]] = maptk::read_pos_file(fpath);
}
}
// Warn if the POS file set is sparse compared to input frames
if (!ins_map.empty())
{
// TODO: generated interpolated cameras for missing POS files.
if (filename2frame.size() != ins_map.size())
{
std::cerr << "Warning: Input POS file-set is sparse compared to input "
<< "imagery! (not as many input POS files as there were input "
<< "images)"
<< std::endl;
}
cameras = maptk::initialize_cameras_with_ins(ins_map, base_camera, local_cs,
ins_rot_offset);
// Creating duplicate cameras structure signifying POS files were input
BOOST_FOREACH(maptk::camera_map::map_camera_t::value_type &v, cameras)
{
pos_cameras[v.first] = v.second->clone();
}
}
else
{
std::cerr << "ERROR: No POS files from input set match input image "
<< "frames. Check POS files!"
<< std::endl;
return EXIT_FAILURE;
}
}
//
// Initialize cameras and landmarks
//
maptk::camera_map_sptr cam_map;
maptk::landmark_map_sptr lm_map;
if(!cameras.empty())
{
cam_map = maptk::camera_map_sptr(new maptk::simple_camera_map(cameras));
}
{
boost::timer::auto_cpu_timer t("Initializing cameras and landmarks: %t sec CPU, %w sec wall\n");
initializer->initialize(cam_map, lm_map, tracks);
}
if (config->get_value<std::string>("input_reference_points_file", "") != "")
{
maptk::path_t ref_file = config->get_value<maptk::path_t>("input_reference_points_file");
// Load up landmarks and assocaited tracks from file, (re)initializing local coordinate system object
maptk::load_reference_file(ref_file, local_cs, reference_landmarks, reference_tracks);
}
maptk::camera_map_sptr orig_cam_map(new maptk::simple_camera_map(pos_cameras));
std::cout << "initialized "<<cam_map->size()<<" cameras"<<std::endl;
unsigned int cam_samp_rate = config->get_value<unsigned int>("camera_sample_rate");
if(cam_samp_rate > 1)
{
boost::timer::auto_cpu_timer t("Tool-level sub-sampling: %t sec CPU, %w sec wall\n");
maptk::camera_map_sptr subsampled_cams = subsample_cameras(cam_map, cam_samp_rate);
// If we were given reference landmarks and tracks, make sure to include
// the cameras for frames reference track states land on. Required for
// sba-space landmark triangulation and correlation later.
if (reference_tracks->size() > 0)
{
maptk::camera_map::map_camera_t cams = cam_map->cameras(),
sub_cams = subsampled_cams->cameras();
// for each track state in each reference track, make sure that the
// state's frame's camera is in the sub-sampled set of cameras
BOOST_FOREACH(maptk::track_sptr const t, reference_tracks->tracks())
{
for (maptk::track::history_const_itr tsit = t->begin(); tsit != t->end(); ++tsit)
{
if (cams.count(tsit->frame_id) > 0)
{
sub_cams.insert(*cams.find(tsit->frame_id));
}
}
}
subsampled_cams = maptk::camera_map_sptr(new maptk::simple_camera_map(sub_cams));
}
cam_map = subsampled_cams;
std::cout << "subsampled down to "<<cam_map->size()<<" cameras"<<std::endl;
}
//
// Run bundle adjustment
//
{ // scope block
boost::timer::auto_cpu_timer t("Tool-level SBA algorithm: %t sec CPU, %w sec wall\n");
double init_rmse = maptk::reprojection_rmse(cam_map->cameras(),
lm_map->landmarks(),
tracks->tracks());
std::cout << "initial reprojection RMSE: " << init_rmse << std::endl;
bundle_adjuster->optimize(cam_map, lm_map, tracks);
double end_rmse = maptk::reprojection_rmse(cam_map->cameras(),
lm_map->landmarks(),
tracks->tracks());
std::cout << "final reprojection RMSE: " << end_rmse << std::endl;
}
//
// Adjust cameras/landmarks based on input cameras/reference points
//
// If we were given POS files / reference points as input, compute a
// similarity transform from the refined cameras to the POS file / reference
// point structures. Then, apply the estimated transform to the refined
// camera positions and landmarks.
//
if (st_estimator)
{
boost::timer::auto_cpu_timer t_1("st estimation and application: %t sec "
"CPU, %w sec wall\n");
// initialize identity transform
maptk::similarity_d sim_transform;
// Prioritize use of reference landmarks/tracks over use of POS files for
// transformation out of SBA-space.
if (reference_landmarks->size() > 0 && reference_tracks->size() > 0)
{
boost::timer::auto_cpu_timer t_2("similarity transform estimation from "
"ref file: %t sec CPU, %w sec wall\n");
// Generate corresponding landmarks in SBA-space based on transformed
// cameras and reference landmarks/tracks via triangulation.
maptk::landmark_map_sptr sba_space_landmarks(new maptk::simple_landmark_map(reference_landmarks->landmarks()));
triangulator->triangulate(cam_map, reference_tracks, sba_space_landmarks);
double post_tri_rmse = maptk::reprojection_rmse(cam_map->cameras(),
sba_space_landmarks->landmarks(),
reference_tracks->tracks());
std::cerr << "Post reference triangulation RMSE: " << post_tri_rmse << std::endl;
// Estimate ST from sba-space to reference space.
sim_transform = st_estimator->estimate_transform(sba_space_landmarks, reference_landmarks);
}
else if (pos_cameras.size() > 0)
{
boost::timer::auto_cpu_timer t_2("similarity transform estimation from "
"POS cams: %t sec CPU, %w sec wall\n");
std::cout << "Estimating and applying similarity transform to refined "
<< "cameras (from POS files)" << std::endl;
sim_transform = st_estimator->estimate_transform(cam_map, orig_cam_map);
}
else
{
// In the absence of other information, use a canonical transformation
sim_transform = canonical_transform(cam_map, lm_map);
}
std::cerr << "--> Estimated Transformation:" << std::endl
<< sim_transform << std::endl;
// apply to cameras
std::cout << "--> Applying to cameras..." << std::endl;
cam_map = maptk::transform(cam_map, sim_transform);
// apply to landmarks
std::cout << "--> Applying to landmarks..." << std::endl;
lm_map = maptk::transform(lm_map, sim_transform);
}
//
// Write the output PLY file
//
if( config->has_value("output_ply_file") )
{
boost::timer::auto_cpu_timer t("writing output PLY file: %t sec CPU, %w sec wall\n");
std::string ply_file = config->get_value<std::string>("output_ply_file");
write_ply_file(lm_map, ply_file);
}
//
// Write the output POS files
//
if( config->has_value("output_pos_dir") )
{
boost::timer::auto_cpu_timer t("writing output POS file(s): %t sec CPU, %w sec wall\n");
bfs::path pos_dir = config->get_value<std::string>("output_pos_dir");
// update ins_map with refined data. Its ok if ins map is empty.
maptk::update_ins_from_cameras(cam_map->cameras(), local_cs, ins_map);
BOOST_FOREACH(const ins_map_t::value_type& p, ins_map)
{
bfs::path out_pos_file = pos_dir / (frame2filename[p.first] + ".pos");
write_pos_file(p.second, out_pos_file);
}
}
//
// Write the output KRTD files
//
if( config->has_value("output_krtd_dir") )
{
boost::timer::auto_cpu_timer t("writing output KRTD file(s): %t sec CPU, %w sec wall\n");
bfs::path krtd_dir = config->get_value<std::string>("output_krtd_dir");
typedef maptk::camera_map::map_camera_t::value_type cam_map_val_t;
BOOST_FOREACH(const cam_map_val_t& p, cam_map->cameras())
{
bfs::path out_krtd_file = krtd_dir / (frame2filename[p.first] + ".krtd");
write_krtd_file(*p.second, out_krtd_file);
}
}
return EXIT_SUCCESS;
}
int main(int argc, char const* argv[])
{
try
{
return maptk_main(argc, argv);
}
catch (std::exception const& e)
{
std::cerr << "Exception caught: " << e.what() << std::endl;
return EXIT_FAILURE;
}
catch (...)
{
std::cerr << "Unknown exception caught" << std::endl;
return EXIT_FAILURE;
}
}
| 37.304627
| 117
| 0.654584
|
dstoup
|
8cc0a3bb1780fe3de0e882f2f10fc812d3c612b7
| 2,226
|
cc
|
C++
|
src/tests/cartoWeakptr_test/weakptr_test.cc
|
charbeljc/soma-io
|
17548eb8eafdcb82d20ea6fba760856f279d7424
|
[
"CECILL-B"
] | 3
|
2020-05-13T04:15:29.000Z
|
2021-08-28T18:13:35.000Z
|
src/tests/cartoWeakptr_test/weakptr_test.cc
|
charbeljc/soma-io
|
17548eb8eafdcb82d20ea6fba760856f279d7424
|
[
"CECILL-B"
] | 15
|
2018-10-30T16:52:14.000Z
|
2022-02-15T12:34:00.000Z
|
src/tests/cartoWeakptr_test/weakptr_test.cc
|
charbeljc/soma-io
|
17548eb8eafdcb82d20ea6fba760856f279d7424
|
[
"CECILL-B"
] | 3
|
2019-12-15T07:23:16.000Z
|
2021-10-05T14:09:09.000Z
|
/* This software and supporting documentation are distributed by
* Institut Federatif de Recherche 49
* CEA/NeuroSpin, Batiment 145,
* 91191 Gif-sur-Yvette cedex
* France
*
* This software is governed by the CeCILL-B license under
* French law and abiding by the rules of distribution of free software.
* You can use, modify and/or redistribute the software under the
* terms of the CeCILL-B license as circulated by CEA, CNRS
* and INRIA at the following URL "http://www.cecill.info".
*
* As a counterpart to the access to the source code and rights to copy,
* modify and redistribute granted by the license, users are provided only
* with a limited warranty and the software's author, the holder of the
* economic rights, and the successive licensors have only limited
* liability.
*
* In this respect, the user's attention is drawn to the risks associated
* with loading, using, modifying and/or developing or reproducing the
* software by the user in light of its specific status of free software,
* that may mean that it is complicated to manipulate, and that also
* therefore means that it is reserved for developers and experienced
* professionals having in-depth computer knowledge. Users are therefore
* encouraged to load and test the software's suitability as regards their
* requirements in conditions enabling the security of their systems and/or
* data to be ensured and, more generally, to use and operate it in the
* same conditions as regards security.
*
* The fact that you are presently reading this means that you have had
* knowledge of the CeCILL-B license and that you accept its terms.
*/
#include <cartobase/smart/weakptr.h>
#include <cartobase/smart/weakobject.h>
#include <cartobase/exception/assert.h>
class Foo : public carto::WeakObject
{
public:
~Foo();
};
Foo::~Foo()
{
}
int main()
{
Foo* p1 = new Foo;
carto::weak_ptr< Foo > x1( p1 );
ASSERT( x1 );
Foo* p2 = new Foo;
carto::weak_ptr< Foo > x2;
ASSERT( !x2 );
ASSERT( x1 != x2 );
x2.reset( p2 );
ASSERT( x2 );
x2.release();
ASSERT( !x2 );
x2 = x1;
ASSERT( x2 );
delete p2;
ASSERT( x2 );
delete p1;
ASSERT( !x1 );
ASSERT( !x2 );
}
| 31.352113
| 75
| 0.709344
|
charbeljc
|
8cc104b9be9c6db26cbebdc42f2c3a5075eeb286
| 521
|
cpp
|
C++
|
02-Arrays/OddOccurrencesInArray.cpp
|
hNrChVz/codility-lessons-solution
|
b76e802c97ed95feb69a1038736db6d494418777
|
[
"FSFAP"
] | null | null | null |
02-Arrays/OddOccurrencesInArray.cpp
|
hNrChVz/codility-lessons-solution
|
b76e802c97ed95feb69a1038736db6d494418777
|
[
"FSFAP"
] | null | null | null |
02-Arrays/OddOccurrencesInArray.cpp
|
hNrChVz/codility-lessons-solution
|
b76e802c97ed95feb69a1038736db6d494418777
|
[
"FSFAP"
] | null | null | null |
#include <vector>
#include <algorithm>
using namespace std;
/*
My trick here, assuming that all the assumptions are always true, is that sort the array first:
std::sort (A.begin(), A.end());
After sorting, iterate until it finds an unmatched pair.
Time complexity: O(NlogN)
NOTE: (trust that) std:sort will use the best sorting algorithm
*/
int solution(vector<int>& A) {
sort(A.begin(), A.end());
for (unsigned int i = 0; i < A.size(); i += 2) {
if (A[i] != A[i + 1]) {
return A[i];
}
}
return -1;
}
| 17.965517
| 95
| 0.644914
|
hNrChVz
|
8cc10b87b958a738ba1f182a930f278bfa21147d
| 1,487
|
cc
|
C++
|
navicat_patcher/KeystoneAssembler.cc
|
cntangt/navicat_keygen_tools
|
1b0d73fb602b8029bbe0cdfe2b8793832d296147
|
[
"Linux-OpenIB"
] | 1
|
2021-05-06T09:36:08.000Z
|
2021-05-06T09:36:08.000Z
|
navicat_patcher/KeystoneAssembler.cc
|
cntangt/navicat_keygen_tools
|
1b0d73fb602b8029bbe0cdfe2b8793832d296147
|
[
"Linux-OpenIB"
] | null | null | null |
navicat_patcher/KeystoneAssembler.cc
|
cntangt/navicat_keygen_tools
|
1b0d73fb602b8029bbe0cdfe2b8793832d296147
|
[
"Linux-OpenIB"
] | null | null | null |
#include "KeystoneAssembler.h"
namespace nkg {
KeystoneAssembler::KeystoneAssembler(const KeystoneEngine& Engine) noexcept :
m_Engine(Engine) {}
[[nodiscard]]
std::vector<uint8_t> KeystoneAssembler::GenerateMachineCode(std::string_view AssemblyCode, uint64_t Address) const {
ARL::ResourceWrapper pbMachineCode(ARL::ResourceTraits::KeystoneMalloc{});
size_t cbMachineCode = 0;
size_t InstructionsProcessed = 0;
if (ks_asm(m_Engine, AssemblyCode.data(), Address, pbMachineCode.GetAddressOf(), &cbMachineCode, &InstructionsProcessed) != 0) {
throw ARL::KeystoneError(__BASE_FILE__, __LINE__, ks_errno(m_Engine), "ks_asm failed.");
}
return std::vector<uint8_t>(pbMachineCode.Get(), pbMachineCode.Get() + cbMachineCode);
}
KeystoneEngine::KeystoneEngine(ks_arch ArchType, ks_mode Mode) {
auto err = ks_open(ArchType, Mode, GetAddressOf());
if (err != KS_ERR_OK) {
throw ARL::KeystoneError(__BASE_FILE__, __LINE__, err, "ks_open failed.");
}
}
void KeystoneEngine::Option(ks_opt_type Type, ks_opt_value Value) {
auto err = ks_option(Get(), Type, Value);
if (err != KS_ERR_OK) {
throw ARL::KeystoneError(__BASE_FILE__, __LINE__, err, "ks_option failed.");
}
}
KeystoneAssembler KeystoneEngine::CreateAssembler() const {
return KeystoneAssembler(*this);
}
}
| 36.268293
| 136
| 0.652993
|
cntangt
|
8cc244b5c24a95fe7cb08001f05e85bbc5db8240
| 1,119
|
cpp
|
C++
|
UVa/696.cpp
|
aege-projects/competitive-programming
|
3bd83367b6cfbdb7587045895762bf5160801be9
|
[
"MIT"
] | null | null | null |
UVa/696.cpp
|
aege-projects/competitive-programming
|
3bd83367b6cfbdb7587045895762bf5160801be9
|
[
"MIT"
] | null | null | null |
UVa/696.cpp
|
aege-projects/competitive-programming
|
3bd83367b6cfbdb7587045895762bf5160801be9
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
int main() {
int k1[500][500], k2[500][500];
for (int i = 0; i < 500; i++) {
for (int j = 0; j < 500; j++) {
k1[i][j] = 0;
k2[i][j] = 1;
}
}
for (int i = 0; i < 500; i++) {
for (int j = (i%2 == 0 ? 0 : 1); j < 500; j += 2) {
k1[i][j] = 1;
k2[i][j] = 0;
}
}
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
cout << k1[i][j] << " ";
}
cout << "\n";
}
cout << "\n";
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
cout << k2[i][j] << " ";
}
cout << "\n";
}
for (int i = 1; i < 500; i++) {
k1[i][0] = k1[i-1][0];
k1[0][i] = k1[0][i-1];
k2[i][0] = k2[i-1][0];
k2[0][i] = k2[0][i-1];
}
for (int i = 1; i < 500; i++) {
for (int j = 1; j < 500; j++) {
k1[i][j] += k1[i-1][j]+k1[i][j-1]-k1[i-1][j-1];
k2[i][j] += k2[i-1][j]+k2[i][j-1]-k2[i-1][j-1];
}
}
int u, v;
while (true) {
cin >> u >> v;
if (u == 0 && v == 0) {
break;
}
cout << max(k1[u-1][v-1], k2[u-1][v-1]) << " knights may be placed on a " << u << " row " << v << " column board.\n";
}
return 0;
}
| 18.048387
| 119
| 0.37891
|
aege-projects
|
8cc42ecf48be716d641944445851cda959d556c1
| 4,806
|
cpp
|
C++
|
unistatscore/analyser.cpp
|
goldim/unistats
|
e8dd54e46f84422d868c942367f0103949791ede
|
[
"MIT"
] | null | null | null |
unistatscore/analyser.cpp
|
goldim/unistats
|
e8dd54e46f84422d868c942367f0103949791ede
|
[
"MIT"
] | null | null | null |
unistatscore/analyser.cpp
|
goldim/unistats
|
e8dd54e46f84422d868c942367f0103949791ede
|
[
"MIT"
] | null | null | null |
#include "analyser.h"
#include <array>
namespace stats {
using std::string;
Analyser::Analyser()
{
}
void Analyser::addSample(const Sample &sample)
{
string sampleStr = "Выборка: ";
string homogeneity;
if (sample.getVariation() < 17)
{
homogeneity = "абсолютно однородная";
}
else if (sample.getVariation() >= 17 && sample.getVariation() < 35)
{
homogeneity = "достаточно однородная";
}
else if (sample.getVariation() >= 35 && sample.getVariation() < 45)
{
homogeneity = "недостаточно однородная";
}
else
{
homogeneity = "неоднородная";
}
sampleStr += homogeneity;
string skewnessStr = "ассиметрия ";
if (sample.getSkewness() > 0)
{
skewnessStr += "правосторонняя";
}
else
{
skewnessStr += "левосторонняя";
}
string kurtosisStr = "мера крутости: ";
if (sample.getKurtosis() > 0)
{
kurtosisStr += "островершинность";
}
else
{
kurtosisStr += "плосковершинность";
}
string res = sampleStr + ", " + skewnessStr + ", " + kurtosisStr;
_output << res + "<br/>";
}
static double myTrunc(double val)
{
return trunc(1000 * val) / 1000;
}
void Analyser::addAnova(Anova &anova)
{
auto v1 = anova.getV1();
auto v2 = anova.getV2();
if (v1 == 0 || v2 == 0)
{
_output << "Для дисперсионного анализа степени свободы должны быть больше 0. "
"Вероятно выбран 1 элемент";
return;
}
std::vector<std::string> headers{
"Крит. значимости",
"F-набл",
"F-крит",
"H0",
"Влияние"
};
_output << "<b>Заключение дисперсионного анализа:</b>";
_output << "<table><tr>";
for (const auto &header: headers)
_output << "<td><b>" << header<< "</b></td>";
_output << "</tr>";
std::array<double, 3> a = {0.05, 0.01, 0.001};
for (auto &el : a)
{
double Fcrit = anova.FCriticalTest(el);
double Fq = anova.getFTestRes();
_output << "<tr>"
<< "<td>" << el << "</td>"
<< "<td>" << myTrunc(Fq) << "</td>"
<< "<td>" << myTrunc(Fcrit) << "</td>"
<< "<td>" << (Fq > Fcrit?"отверг.":"не отверг.") << "</td>"
<< "<td>" << (Fq > Fcrit?"<font color=green>да</font>":"<font color=red>нет</font>") << "</td>"
<< "</tr>";
}
_output << "</table>";
}
void Analyser::addAnova2(TwoFactorAnova &anova)
{
auto Va = anova.getVA();
auto Vb = anova.getVB();
auto v2 = anova.getV2();
if (Va == 0 || Vb == 0 || v2 == 0)
{
_output << "Для дисперсионного анализа степени свободы должны быть больше 0."
"Выбран 1 элемент.";
return;
}
std::vector<std::string> headers{
"Фактор",
"Крит. значимости",
"F-набл",
"F-крит",
"H0",
"Влияние"
};
_output << "<b>Заключение дисперсионного анализа по двум факторам:</b>";
_output << "<table><tr>";
for (const auto &header: headers)
_output << "<td><b>" << header<< "</b></td>";
_output << "</tr>";
std::array<double, 3> a = {0.05, 0.01, 0.001};
std::array<double, 2> vArr = {Va, Vb};
std::array<double, 2> FArr = {anova.getFTestRes().FA, anova.getFTestRes().FB};
std::array<std::string, 2> factorNameArr = {"A", "B"};
for (auto &el : a)
{
double FcritA = anova.FCriticalTestA(el);
double FcritB = anova.FCriticalTestB(el);
std::array<double, 2> FcritArr = {FcritA, FcritB};
for (int i = 0; i < 2; i++)
{
_output << "<tr>"
<< "<td>" << factorNameArr[i] << "</td>"
<< "<td>" << el << "</td>"
<< "<td>" << myTrunc(FArr[i]) << "</td>"
<< "<td>" << myTrunc(FcritArr[i]) << "</td>"
<< "<td>" << (FArr[i] > FcritArr[i]?"отверг.":"не отверг.") << "</td>"
<< "<td>" << (FArr[i] > FcritArr[i]?"<font color=green>да</font>":"<font color=red>нет</font>") << "</td>"
<< "</tr>";
}
double FcritAB = anova.FCriticalTestAB(el);
bool bFComparing = anova.getFTestRes().FAB > FcritAB;
_output << "<tr>"
<< "<td>" << "AB" << "</td>"
<< "<td>" << el << "</td>"
<< "<td>" << myTrunc(anova.getFTestRes().FAB) << "</td>"
<< "<td>" << myTrunc(FcritAB) << "</td>"
<< "<td>" << (bFComparing?"отверг.":"не отверг.") << "</td>"
<< "<td>" << (bFComparing?"<font color=green>да</font>":"<font color=red>нет</font>") << "</td>"
<< "</tr>";
}
_output << "</table>";
}
}//stats
| 27.152542
| 126
| 0.477528
|
goldim
|
8cc43f5e95370fe6e456795979436ab96c9e99f8
| 21,847
|
cpp
|
C++
|
Engine/ModuleScene.cpp
|
solidajenjo/CyberPimpEngine
|
da4fc5d22bc7c52a45794ea73e2bac903d893178
|
[
"MIT"
] | null | null | null |
Engine/ModuleScene.cpp
|
solidajenjo/CyberPimpEngine
|
da4fc5d22bc7c52a45794ea73e2bac903d893178
|
[
"MIT"
] | null | null | null |
Engine/ModuleScene.cpp
|
solidajenjo/CyberPimpEngine
|
da4fc5d22bc7c52a45794ea73e2bac903d893178
|
[
"MIT"
] | null | null | null |
#include "GameObject.h"
#include "ModuleScene.h"
#include "ModuleFrameBuffer.h"
#include "ModuleRender.h"
#include "ModuleTextures.h"
#include "ModuleEditorCamera.h"
#include "ModuleSpacePartitioning.h"
#include "ModuleFileSystem.h"
#include "ModuleEditor.h"
#include "SubModuleEditorGameViewPort.h"
#include "SubModuleEditorToolBar.h"
#include "QuadTree.h"
#include "Application.h"
#include "imgui/imgui.h"
#include "ComponentMesh.h"
#include "ComponentMap.h"
#include "ComponentCamera.h"
#include "ComponentLight.h"
#include "rapidjson-1.1.0/include/rapidjson/prettywriter.h"
#include "rapidjson-1.1.0/include/rapidjson/document.h"
#include <stack>
#include "SDL/include/SDL_filesystem.h"
#define HIERARCHY_DRAW_TAB 10
bool ModuleScene::Init()
{
LOG("Init Scene module");
root = new GameObject("Scene", true);
directory = new GameObject("Assets", true);
modelFolder = new GameObject("Models", true);
mapFolder = new GameObject("Maps", true);
materialFolder = new GameObject("Materials", true);
AttachToAssets(modelFolder);
AttachToAssets(mapFolder);
AttachToAssets(materialFolder);
return true;
}
update_status ModuleScene::Update()
{
return UPDATE_CONTINUE;
}
bool ModuleScene::CleanUp()
{
LOG("Cleaning scene GameObjects.");
RELEASE(root);
RELEASE(directory);
sceneGameObjects.clear();
LOG("Cleaning scene GameObjects. Done");
selected = nullptr;
sceneCamera = nullptr;
App->textures->CleanUp();
for (GameObject* fgo : lightingFakeGameObjects)
RELEASE(fgo);
lightingFakeGameObjects.resize(0);
return true;
}
bool ModuleScene::SaveScene(const std::string & path) const
{
rapidjson::StringBuffer sb;
rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(sb);
writer.StartArray();
//Keep the roots to rebuild hierarchies
writer.StartObject();
writer.String("scene");
root->Serialize(writer);
writer.EndObject();
writer.StartObject();
writer.String("assets");
directory->Serialize(writer);
writer.EndObject();
//serialize folders
writer.StartObject();
writer.String("maps");
mapFolder->Serialize(writer);
writer.EndObject();
writer.StartObject();
writer.String("materials");
materialFolder->Serialize(writer);
writer.EndObject();
writer.StartObject();
writer.String("models");
modelFolder->Serialize(writer);
writer.EndObject();
//Serialize all the remaining gameobjects
for (std::map<std::string, GameObject*>::const_iterator it = sceneGameObjects.begin(); it != sceneGameObjects.end(); ++it)
{
if (!IsRoot((*it).second))
(*it).second->Serialize(writer);
}
writer.EndArray();
if (App->fileSystem->Write(path, sb.GetString(), strlen(sb.GetString()), true))
{
LOG("Scene saved.");
}
rapidjson::StringBuffer sbConfig;
rapidjson::PrettyWriter<rapidjson::StringBuffer> writerConfig(sbConfig);
writerConfig.StartObject();
writerConfig.String("scale"); writerConfig.Double(App->appScale);
writerConfig.String("kdTreeDepth"); writerConfig.Int(App->spacePartitioning->kDTree.maxDepth);
writerConfig.String("kdTreeBucketSize"); writerConfig.Int(App->spacePartitioning->kDTree.bucketSize);
writerConfig.String("quadTreeDepth"); writerConfig.Int(App->spacePartitioning->quadTree.maxDepth);
writerConfig.String("quadTreeBucketSize"); writerConfig.Int(App->spacePartitioning->quadTree.bucketSize);
writerConfig.String("aa"); writerConfig.Int((int)App->editor->gameViewPort->antialiasing);
writerConfig.String("fogEnabled"); writerConfig.Bool(App->renderer->fog);
writerConfig.String("fogFalloff"); writerConfig.Double(App->renderer->fogFalloff);
writerConfig.String("fogQuadratic"); writerConfig.Double(App->renderer->fogQuadratic);
writerConfig.String("fogColor");
writerConfig.StartArray();
writerConfig.Double(App->renderer->fogColor[0]);
writerConfig.Double(App->renderer->fogColor[1]);
writerConfig.Double(App->renderer->fogColor[2]);
writerConfig.EndArray();
writerConfig.String("editorCamera");
App->camera->editorCamera.Serialize(writerConfig);
writerConfig.EndObject();
if (App->fileSystem->Write(path + ".cfg", sbConfig.GetString(), strlen(sbConfig.GetString()), true))
{
LOG("Scene configuration saved.");
}
return true;
}
bool ModuleScene::LoadScene(const std::string & path)
{
LOG("Loading scene %s", path.c_str());
CleanUp();
App->spacePartitioning->aabbTree.Reset();
bool staticGameObjects = false;
if (!App->fileSystem->Exists(path + ".cfg"))
{
LOG("Error loading scene configuration %s", (path + ".cfg").c_str());
}
else
{
unsigned fileSize = App->fileSystem->Size(path + ".cfg");
char* buffer = new char[fileSize];
if (App->fileSystem->Read(path + ".cfg", buffer, fileSize))
{
rapidjson::Document document;
if (document.Parse<rapidjson::kParseStopWhenDoneFlag>(buffer).HasParseError())
{
LOG("Error loading scene %s. Scene file corrupted.", (path + ".cfg").c_str());
}
else
{
rapidjson::Value config = document.GetObjectJSON();
App->appScale = config["scale"].GetDouble();
switch ((int)App->appScale)
{
case 1:
App->editor->toolBar->scale_item_current = App->editor->toolBar->scale_items[0];
break;
case 10:
App->editor->toolBar->scale_item_current = App->editor->toolBar->scale_items[1];
break;
case 100:
App->editor->toolBar->scale_item_current = App->editor->toolBar->scale_items[2];
break;
case 1000:
App->editor->toolBar->scale_item_current = App->editor->toolBar->scale_items[3];
break;
}
App->spacePartitioning->kDTree.maxDepth = config["kdTreeDepth"].GetInt();
App->spacePartitioning->kDTree.bucketSize = config["kdTreeBucketSize"].GetInt();
App->spacePartitioning->quadTree.maxDepth = config["quadTreeDepth"].GetInt();
App->spacePartitioning->quadTree.bucketSize = config["quadTreeBucketSize"].GetInt();
App->editor->gameViewPort->antialiasing = (SubModuleEditorGameViewPort::AntiaAliasing)config["aa"].GetInt();
App->editor->gameViewPort->framebufferDirty = true;
App->editor->toolBar->aa_item_current = App->editor->toolBar->aa_items[(unsigned)App->editor->gameViewPort->antialiasing];
rapidjson::Value serializedCam = config["editorCamera"].GetObjectJSON();
App->camera->editorCamera.UnSerialize(serializedCam);
App->renderer->fog = config["fogEnabled"].GetBool();
App->renderer->fogFalloff = config["fogFalloff"].GetDouble();
App->renderer->fogQuadratic = config["fogQuadratic"].GetDouble();
App->renderer->fogColor[0] = config["fogColor"][0].GetDouble();
App->renderer->fogColor[1] = config["fogColor"][1].GetDouble();
App->renderer->fogColor[2] = config["fogColor"][2].GetDouble();
}
}
}
if (!App->fileSystem->Exists(path)) //no previous scene found
{
Init();
sceneGameObjects[root->gameObjectUUID] = root;
sceneGameObjects[directory->gameObjectUUID] = directory;
sceneGameObjects[modelFolder->gameObjectUUID] = modelFolder;
sceneGameObjects[mapFolder->gameObjectUUID] = mapFolder;
sceneGameObjects[materialFolder->gameObjectUUID] = materialFolder;
LOG("Error loading scene %s. Not found", path.c_str());
}
else
{
//restore instantiated gameobjects
unsigned fileSize = App->fileSystem->Size(path);
char* buffer = new char[fileSize];
if (App->fileSystem->Read(path, buffer, fileSize))
{
rapidjson::Document document;
if (document.Parse<rapidjson::kParseStopWhenDoneFlag>(buffer).HasParseError())
{
LOG("Error loading scene %s. Scene file corrupted.", path.c_str());
root = new GameObject("Scene", true);
directory = new GameObject("Assets", true);
modelFolder = new GameObject("Models", true);
mapFolder = new GameObject("Maps", true);
materialFolder = new GameObject("Materials", true);
AttachToAssets(modelFolder);
AttachToAssets(mapFolder);
AttachToAssets(materialFolder);
sceneGameObjects[root->gameObjectUUID] = root;
sceneGameObjects[root->gameObjectUUID] = root;
sceneGameObjects[directory->gameObjectUUID] = directory;
sceneGameObjects[modelFolder->gameObjectUUID] = modelFolder;
sceneGameObjects[mapFolder->gameObjectUUID] = mapFolder;
sceneGameObjects[materialFolder->gameObjectUUID] = materialFolder;
}
else
{
rapidjson::Value gameObjects = document.GetArray();
for (rapidjson::Value::ValueIterator it = gameObjects.Begin(); it != gameObjects.End(); ++it)
{
if ((*it).HasMember("scene"))
{
root = new GameObject("");
root->UnSerialize((*it)["scene"]);
sceneGameObjects[root->gameObjectUUID] = root;
}
else if ((*it).HasMember("assets"))
{
directory = new GameObject("");
directory->UnSerialize((*it)["assets"]);
sceneGameObjects[directory->gameObjectUUID] = directory;
}
else if ((*it).HasMember("models"))
{
modelFolder = new GameObject("");
modelFolder->UnSerialize((*it)["models"]);
sceneGameObjects[modelFolder->gameObjectUUID] = modelFolder;
}
else if ((*it).HasMember("maps"))
{
mapFolder = new GameObject("");
mapFolder->UnSerialize((*it)["maps"]);
sceneGameObjects[mapFolder->gameObjectUUID] = mapFolder;
}
else if ((*it).HasMember("materials"))
{
materialFolder = new GameObject("");
materialFolder->UnSerialize((*it)["materials"]);
sceneGameObjects[materialFolder->gameObjectUUID] = materialFolder;
}
else
{
GameObject* newGO = new GameObject("");
if (newGO->UnSerialize(*it))
{
InsertGameObject(newGO);
if (newGO->isStatic)
staticGameObjects = true;
}
}
}
LinkGameObjects();
if (staticGameObjects)
{
App->spacePartitioning->kDTree.Calculate();
}
root->transform->PropagateTransform();
LOG("Lighting tree recalculation");
App->spacePartitioning->aabbTreeLighting.Calculate();
}
delete buffer;
}
else
{
LOG("Error loading scene %s", path.c_str());
}
}
LOG("Scene loaded");
return true;
}
void ModuleScene::InsertFakeGameObject(GameObject* fgo)
{
assert(fgo != nullptr);
switch (fgo->layer)
{
case GameObject::GameObjectLayers::LIGHTING:
lightingFakeGameObjects.push_back(fgo);
ComponentLight* cL = (ComponentLight*)fgo->components.front();
cL->pointSphere.pos = fgo->components.front()->owner->transform->getGlobalPosition();
fgo->aaBBGlobal->SetNegativeInfinity();
fgo->aaBBGlobal->Enclose(cL->pointSphere);
App->spacePartitioning->aabbTreeLighting.InsertGO(fgo);
}
}
void ModuleScene::RemoveFakeGameObject(GameObject* fgo)
{
switch (fgo->layer)
{
case GameObject::GameObjectLayers::LIGHTING:
App->spacePartitioning->aabbTreeLighting.ReleaseNode(fgo->treeNode);
lightingFakeGameObjects.erase(std::find(lightingFakeGameObjects.begin(), lightingFakeGameObjects.end(), fgo));
}
}
void ModuleScene::InsertGameObject(GameObject * newGO)
{
assert(newGO != nullptr);
sceneGameObjects[newGO->gameObjectUUID] = newGO;
if (newGO->transform != nullptr)
newGO->transform->UpdateAABB();
if (newGO->isInstantiated)
App->spacePartitioning->aabbTree.InsertGO(newGO);
}
void ModuleScene::ImportGameObject(GameObject * newGO, ImportedType type)
{
assert(newGO != nullptr);
switch (type)
{
case ImportedType::MAP:
AttachToMaps(newGO);
break;
case ImportedType::MODEL:
AttachToModels(newGO);
break;
case ImportedType::MATERIAL:
AttachToMaterials(newGO);
break;
}
}
void ModuleScene::ShowHierarchy(bool isWorld)
{
if (isWorld)
{
assert(root != nullptr);
DrawNode(root);
}
else
{
assert(directory != nullptr);
DrawNode(directory, isWorld);
}
}
void ModuleScene::DrawNode(GameObject* gObj, bool isWorld)
{
assert(gObj != nullptr);
ImGuiTreeNodeFlags flags;
std::stack<GameObject*> S;
std::stack<int> depthStack;
std::stack<ImVec2> parentPosition;
S.push(gObj);
depthStack.push(0);
parentPosition.push(ImGui::GetCursorPos());
while (!S.empty())
{
gObj = S.top(); S.pop();
ImGui::PushID(gObj->gameObjectUUID);
unsigned depth = depthStack.top(); depthStack.pop();
ImVec2 parentPos = parentPosition.top(); parentPosition.pop();
if (gObj->children.size() == 0)
flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_Leaf;
else
flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick;
if (gObj->selected)
{
flags |= ImGuiTreeNodeFlags_Selected;
}
ImVec2 pos = ImGui::GetCursorPos();
ImGui::SetCursorPos(ImVec2(pos.x + depth, pos.y));
pos = ImGui::GetCursorScreenPos();
if (!IsRoot(gObj))
{
ImGui::GetWindowDrawList()->AddLine(ImVec2(pos.x, pos.y + 5.f), ImVec2(pos.x, parentPos.y), ImColor(1.f, 1.f, 1.f, 1.f));
ImGui::GetWindowDrawList()->AddLine(ImVec2(pos.x, pos.y + 5.f), ImVec2(pos.x + 5.f, pos.y + 5.f), ImColor(1.f, 1.f, 1.f, 1.f));
}
if (ImGui::TreeNodeEx(gObj->name, flags))
{
if (gObj->children.size() > 0)
{
for (std::list<GameObject*>::iterator it = gObj->children.begin(); it != gObj->children.end(); ++it)
{
S.push(*it);
depthStack.push(depth + HIERARCHY_DRAW_TAB);
parentPosition.push(ImGui::GetCursorScreenPos());
}
}
ImGui::TreePop();
}
if (isWorld)
{
if (ImGui::BeginDragDropSource(ImGuiDragDropFlags_SourceAllowNullID))
{
ImGui::SetDragDropPayload("GAMEOBJECT_ID", &gObj->gameObjectUUID, sizeof(gObj->gameObjectUUID));
ImGui::EndDragDropSource();
}
if (ImGui::BeginDragDropTarget())
{
if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload("GAMEOBJECT_ID"))
{
char movedId[sizeof(gObj->gameObjectUUID)];
sprintf_s(movedId, (char*)payload->Data);
GameObject* movedGO = FindInstanceOrigin(movedId);
if (movedGO != nullptr)
{
movedGO->parent->children.remove(movedGO);
movedGO->parent = gObj;
LOG("Moved gameobject %s", movedGO->name);
gObj->InsertChild(movedGO);
movedGO->transform->NewAttachment();
}
}
}
}
else
{
if (ImGui::BeginDragDropSource(ImGuiDragDropFlags_SourceAllowNullID))
{
ImGui::SetDragDropPayload("IMPORTED_GAMEOBJECT_ID", &gObj->gameObjectUUID, sizeof(gObj->gameObjectUUID));
ImGui::EndDragDropSource();
}
}
if (ImGui::IsItemClicked())
{
gObj->selected = !gObj->selected;
if (gObj->selected && selected != gObj)
{
selected != nullptr ? selected->selected = false : 1;
selected = gObj;
}
else if (!gObj->selected && selected == gObj)
{
selected = nullptr;
}
}
if (!IsRoot(gObj) && gObj == selected && ImGui::BeginPopupContextItem("GO_CONTEXT"))
{
ImGui::Text("GameObject operations");
ImGui::Separator();
bool deleteGameObject = false;
ImVec2 curPos = ImGui::GetCursorScreenPos();
ImGui::Text("Delete - Ctrl + X");
ImVec2 size = ImGui::GetItemRectSize();
if (ImGui::IsItemHovered())
{
ImGui::GetWindowDrawList()->AddRectFilled(curPos, ImVec2(curPos.x + size.x * 1.1f, curPos.y + size.y), IM_COL32(200, 200, 200, 55));
}
if (ImGui::IsItemClicked())
deleteGameObject = true;
if (deleteGameObject)
{
ImGui::OpenPopup("Confirm");
}
bool closeContextPopup = false;
if (ImGui::BeginPopup("Confirm", ImGuiWindowFlags_Modal))
{
ImGui::Text("Are you sure?");
if (ImGui::Button("NO", ImVec2(100, 20)))
{
ImGui::CloseCurrentPopup();
closeContextPopup = true;
}
ImGui::SameLine();
if (ImGui::Button("YES", ImVec2(100, 20)))
{
DeleteGameObject(gObj);
selected = nullptr;
App->spacePartitioning->kDTree.Calculate();
ImGui::CloseCurrentPopup();
}
ImGui::EndPopup();
}
curPos = ImGui::GetCursorScreenPos();
ImGui::Text("Duplicate - Ctrl + D");
size = ImGui::GetItemRectSize();
if (ImGui::IsItemHovered())
{
ImGui::GetWindowDrawList()->AddRectFilled(curPos, ImVec2(curPos.x + size.x * 1.1f, curPos.y + size.y), IM_COL32(200, 200, 200, 55));
}
if (ImGui::IsItemClicked())
{
GameObject* clone = gObj->Clone();
gObj->parent->InsertChild(clone);
gObj->parent->transform->PropagateTransform();
closeContextPopup = true;
}
if (closeContextPopup)
ImGui::CloseCurrentPopup();
ImGui::EndPopup();
}
ImGui::PopID();
}
}
void ModuleScene::AttachToRoot(GameObject * go)
{
assert(go != nullptr);
root->InsertChild(go);
FlattenHierarchyOnImport(go);
}
void ModuleScene::AttachToAssets(GameObject * go)
{
assert(go != nullptr);
directory->InsertChild(go);
FlattenHierarchyOnImport(go);
}
void ModuleScene::AttachToMaps(GameObject * go)
{
assert(go != nullptr);
mapFolder->InsertChild(go);
FlattenHierarchyOnImport(go);
}
void ModuleScene::AttachToModels(GameObject * go)
{
assert(go != nullptr);
modelFolder->InsertChild(go);
FlattenHierarchyOnImport(go);
}
void ModuleScene::AttachToMaterials(GameObject * go)
{
assert(go != nullptr);
materialFolder->InsertChild(go);
FlattenHierarchyOnImport(go);
}
void ModuleScene::DestroyGameObject(GameObject * destroyableGO)
{
assert(destroyableGO != nullptr);
if (destroyableGO->layer == GameObject::GameObjectLayers::WORLD_VOLUME && destroyableGO->treeNode != nullptr)
App->spacePartitioning->aabbTree.ReleaseNode(destroyableGO->treeNode);
if (destroyableGO->fakeGameObjectReference != nullptr)
{
lightingFakeGameObjects.erase(std::find(lightingFakeGameObjects.begin(),
lightingFakeGameObjects.end(), destroyableGO->fakeGameObjectReference));
App->spacePartitioning->aabbTreeLighting.ReleaseNode(destroyableGO->fakeGameObjectReference->treeNode);
}
destroyableGO->parent->children.remove(destroyableGO);
sceneGameObjects.erase(destroyableGO->gameObjectUUID);
}
void ModuleScene::DeleteGameObject(GameObject* go, bool isAsset)
{
assert(go != nullptr);
go->parent->children.remove(go);
sceneGameObjects.erase(go->gameObjectUUID);
std::stack<GameObject*> S;
std::stack<GameObject*> DFS; // start the destroy from the leaves of the tree and upwards to avoid crashes
S.push(go);
DFS.push(go);
while (!S.empty())
{
GameObject* node = S.top();
S.pop();
for (std::list<GameObject*>::iterator it = node->children.begin(); it != node->children.end(); ++it)
{
S.push(*it);
DFS.push(*it);
}
}
while (!DFS.empty())
{
DestroyGameObject(DFS.top());
RELEASE(DFS.top());
DFS.pop();
}
}
bool ModuleScene::MakeParent(const std::string &parentUUID, GameObject * son)
{
GameObject* parent = FindInstanceOrigin(parentUUID);
if (parent != nullptr)
{
parent->InsertChild(son);
if (parent->transform != nullptr)
parent->transform->PropagateTransform();
return true;
}
return false;
}
GameObject* ModuleScene::FindInstanceOrigin(const std::string &instance)
{
std::map<std::string, GameObject*>::iterator it = sceneGameObjects.find(instance);
if (it != sceneGameObjects.end())
return (*it).second;
return nullptr; //broken link
}
void ModuleScene::SetSkyBox()
{
/*
if (App->frameBuffer->skyBox == nullptr)
{
assert(sceneGameObjects.size() == 2);
assert(sceneGameObjects.back()->components.size() == 1);
App->frameBuffer->skyBox = (ComponentMesh*)sceneGameObjects.back()->components.front(); //store the skybox mesh on framebuffer module on start. Released there
sceneGameObjects.front()->components.clear();
sceneGameObjects.clear();
root->children.clear();
App->textures->textures.clear();
App->renderer->renderizables.clear(); //Clear renderizables, render skybox on demand only
}
*/
}
void ModuleScene::GetStaticGlobalAABB(AABB* globalAABB, std::vector<GameObject*> &staticGOs, unsigned &GOCount) const
{
bool first = true;
for (std::map<std::string, GameObject*>::const_iterator it = sceneGameObjects.begin(); it != sceneGameObjects.end(); ++it)
{
float3* corners = new float3[16];
if ((*it).second->layer == GameObject::GameObjectLayers::WORLD_VOLUME && (*it).second->isInstantiated && (*it).second->isStatic && (*it).second->aaBBGlobal != nullptr)
{
if (first)
{
globalAABB->SetNegativeInfinity();
globalAABB->Enclose(*(*it).second->aaBBGlobal);
first = false;
}
else
{
(*it).second->aaBBGlobal->GetCornerPoints(&corners[0]);
globalAABB->GetCornerPoints(&corners[8]);
globalAABB->Enclose(&corners[0], 16);
}
staticGOs[++GOCount] = (*it).second;
}
RELEASE(corners);
}
}
void ModuleScene::GetNonStaticGlobalAABB(AABB* globalAABB, std::vector<GameObject*>& nonStaticGOs, unsigned &GOCount) const //TODO:Keep a pool with no static gameobjects
{
bool first = true;
for (std::map<std::string, GameObject*>::const_iterator it = sceneGameObjects.begin(); it != sceneGameObjects.end(); ++it)
{
float3* corners = new float3[16];
if ((*it).second->isInstantiated && (*it).second->layer == GameObject::GameObjectLayers::WORLD_VOLUME && !(*it).second->isStatic && (*it).second->aaBBGlobal != nullptr)
{
if (first)
{
globalAABB->SetNegativeInfinity();
globalAABB->Enclose(*(*it).second->aaBBGlobal);
first = false;
}
else
{
(*it).second->aaBBGlobal->GetCornerPoints(&corners[0]);
globalAABB->GetCornerPoints(&corners[8]);
globalAABB->Enclose(&corners[0], 16);
}
nonStaticGOs[++GOCount] = (*it).second;
assert(GOCount < BUCKET_MAX);
}
RELEASE(corners);
}
}
void ModuleScene::LinkGameObjects()
{
for (std::map<std::string, GameObject*>::iterator it = sceneGameObjects.begin(); it != sceneGameObjects.end(); ++it)
{
MakeParent((*it).second->parentUUID, (*it).second);
}
}
void ModuleScene::FlattenHierarchyOnImport(GameObject * go)
{
assert(go != nullptr);
std::stack<GameObject*> S;
S.push(go);
GameObject* node = nullptr;
while (!S.empty())
{
node = S.top();
S.pop();
sceneGameObjects[node->gameObjectUUID] = node;
for (std::list<GameObject*>::iterator it = node->children.begin(); it != node->children.end(); ++it)
S.push(*it);
}
}
| 30.092287
| 170
| 0.692589
|
solidajenjo
|
bc45567f3986675ca83a8974de72fa177d32cf91
| 2,516
|
cpp
|
C++
|
readDataAndCheckForMagic.cpp
|
ohio813/shutdownonlan
|
80df7789368cfcfd20a65b67585bca3264a7064a
|
[
"BSD-3-Clause"
] | 1
|
2015-06-26T04:18:29.000Z
|
2015-06-26T04:18:29.000Z
|
readDataAndCheckForMagic.cpp
|
ohio813/shutdownonlan
|
80df7789368cfcfd20a65b67585bca3264a7064a
|
[
"BSD-3-Clause"
] | null | null | null |
readDataAndCheckForMagic.cpp
|
ohio813/shutdownonlan
|
80df7789368cfcfd20a65b67585bca3264a7064a
|
[
"BSD-3-Clause"
] | null | null | null |
#include "stdafx.h"
#include "getMACAddresses.h"
#include "globals.h"
#include "log.h"
DWORD readDataAndCheckForMagic(SOCKET oSocket) {
BYTE abBuffer[4096];
int iBytesReceived = recv(oSocket, (char*)abBuffer, sizeof(abBuffer), 0);
if (iBytesReceived == SOCKET_ERROR) {
DWORD dwErrorCode = WSAGetLastError();
// WSAEWOULDBLOCK appears to happen quite frequently
if (dwErrorCode != WSAEWOULDBLOCK) {
logError(_T("Socket receive failed: error code %d (0x%X)."), dwErrorCode, dwErrorCode);
}
return dwErrorCode;
} else {
int iFFCount = 0;
// look for 6 x 0xFF
for (int iFFScanIndex = 0; iFFScanIndex - iFFCount <= iBytesReceived - 6 * 17; iFFScanIndex++) {
if (abBuffer[iFFScanIndex] == 0xFF) {
iFFCount++;
} else {
iFFCount = 0;
}
if (iFFCount >= 6) {
// Found 6 x 0xFF, look up MAC addresses of all network connections
std::list<PBYTE> lpbMACAddresses;
DWORD dwErrorCode = getMACAddresses(lpbMACAddresses);
if (dwErrorCode != ERROR_SUCCESS) {
return dwErrorCode;
}
while (!lpbMACAddresses.empty()) {
PBYTE pbMACAddress = lpbMACAddresses.front();
lpbMACAddresses.pop_front();
// Look for 16 x MAC address following the 6 x 0xFF
size_t iMACScanIndex = iFFScanIndex + 1;
BOOL bMismatchFound = FALSE;
for (size_t iCopy = 0; !bMismatchFound && iCopy < 16; iCopy++) {
for (size_t iByte = 0; !bMismatchFound && iByte < 6; iByte++) {
bMismatchFound = abBuffer[iMACScanIndex++] != pbMACAddress[iByte];
}
}
delete[] pbMACAddress;
if (!bMismatchFound) {
logInformation(_T("Shutdown-on-LAN request received."));
// Found 6 x 0xFF followed by 16 x MAC address: shut down.
if (!InitiateSystemShutdownEx(
NULL, // This machine
gsShutdownReason,
0, // Shut down immediately
TRUE, // Force-close applications (do not save data)
FALSE, // Do not reboot
gdwShutdownReason
)) {
DWORD dwErrorCode = GetLastError();
logError(_T("InitiateSystemShutdownEx failed: error code %d (0x%X)."), dwErrorCode, dwErrorCode);
return dwErrorCode;
}
}
}
}
} // magic data not found
return 0;
}
}
| 38.121212
| 112
| 0.57035
|
ohio813
|
bc473eb1ec1839eb1ce250b533de11c6809b93f5
| 170
|
cpp
|
C++
|
shore/shore-mt/src/fc/fc-noinline.cpp
|
anshsarkar/TailBench
|
25845756aee9a892229c25b681051591c94daafd
|
[
"MIT"
] | 3
|
2018-01-25T00:51:56.000Z
|
2022-01-07T15:09:38.000Z
|
shore/shore-mt/src/fc/fc-noinline.cpp
|
anshsarkar/TailBench
|
25845756aee9a892229c25b681051591c94daafd
|
[
"MIT"
] | 1
|
2021-11-25T18:08:22.000Z
|
2021-11-25T18:08:22.000Z
|
shore/shore-mt/src/fc/fc-noinline.cpp
|
anshsarkar/TailBench
|
25845756aee9a892229c25b681051591c94daafd
|
[
"MIT"
] | 3
|
2018-06-08T08:36:27.000Z
|
2021-12-26T20:36:16.000Z
|
#include <pthread.h>
extern "C" void cpu_info_dtrace_global_hook(long volatile* /*ready*/) { }
extern "C" void cpu_info_dtrace_thread_hook(long volatile* /*cpuid*/) { }
| 34
| 73
| 0.735294
|
anshsarkar
|
bc47e2a4c2137c0604933599c59e235b177940f2
| 503
|
cc
|
C++
|
test/abc218/e.cc
|
nryotaro/at_c
|
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
|
[
"MIT"
] | null | null | null |
test/abc218/e.cc
|
nryotaro/at_c
|
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
|
[
"MIT"
] | null | null | null |
test/abc218/e.cc
|
nryotaro/at_c
|
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
|
[
"MIT"
] | null | null | null |
#include "abc218/e.cc"
#include <gtest/gtest.h>
TEST(abc218e, 1) {
vector<int> a = {1, 1, 1, 3, 4}, b = {2, 3, 4, 2, 2};
vector<ll> c = {1ll, 1ll, 1ll, 2ll, 2ll};
EXPECT_EQ(4, solve(4, 5, a, b, c));
}
TEST(abc218e, 2) {
vector<int> a = {1, 2, 3}, b = {2, 3, 1};
vector<ll> c = {1ll, 0ll, -1ll};
EXPECT_EQ(1, solve(3, 3, a, b, c));
}
TEST(abc218e, 3) {
vector<int> a = {1, 1, 1}, b = {2, 2, 1};
vector<ll> c = {-1ll, 2ll, 3ll};
EXPECT_EQ(5, solve(2, 3, a, b, c));
}
| 25.15
| 57
| 0.487078
|
nryotaro
|
bc525eb9076f9df4abccd9831c629d833264106d
| 3,254
|
cc
|
C++
|
KM/03code/cpp/chenshuo/muduo-udns/Resolver.cc
|
wangcy6/weekly.github.io
|
f249bed5cf5a2b14d798ac33086cea0c1efe432e
|
[
"Apache-2.0"
] | 10
|
2019-03-17T10:13:04.000Z
|
2021-03-03T03:23:34.000Z
|
KM/03code/cpp/chenshuo/muduo-udns/Resolver.cc
|
wangcy6/weekly.github.io
|
f249bed5cf5a2b14d798ac33086cea0c1efe432e
|
[
"Apache-2.0"
] | 44
|
2018-12-14T02:35:47.000Z
|
2021-02-06T09:12:10.000Z
|
KM/03code/cpp/chenshuo/muduo-udns/Resolver.cc
|
wangcy6/weekly
|
f249bed5cf5a2b14d798ac33086cea0c1efe432e
|
[
"Apache-2.0"
] | null | null | null |
#include "Resolver.h"
#include <muduo/base/Logging.h>
#include <muduo/net/Channel.h>
#include <muduo/net/EventLoop.h>
#include <boost/bind.hpp>
#include "udns.h"
#include <assert.h>
#include <stdio.h>
namespace
{
int init_udns()
{
static bool initialized = false;
if (!initialized)
::dns_init(NULL, 0);
initialized = true;
return 1;
}
struct UdnsInitializer
{
UdnsInitializer()
{
init_udns();
}
~UdnsInitializer()
{
::dns_reset(NULL);
}
};
UdnsInitializer udnsInitializer;
const bool kDebug = false;
}
using namespace muduo::net;
Resolver::Resolver(EventLoop* loop)
: loop_(loop),
ctx_(NULL),
fd_(-1),
timerActive_(false)
{
init_udns();
ctx_ = ::dns_new(NULL);
assert(ctx_ != NULL);
::dns_set_opt(ctx_, DNS_OPT_TIMEOUT, 2);
}
Resolver::~Resolver()
{
channel_->disableAll();
channel_->remove();
::dns_free(ctx_);
}
void Resolver::start()
{
fd_ = ::dns_open(ctx_);
channel_.reset(new Channel(loop_, fd_));
channel_->setReadCallback(boost::bind(&Resolver::onRead, this, _1));
channel_->enableReading();
}
bool Resolver::resolve(const StringPiece& hostname, const Callback& cb)
{
loop_->assertInLoopThread();
QueryData* queryData = new QueryData(this, cb);
time_t now = time(NULL);
struct dns_query* query =
::dns_submit_a4(ctx_, hostname.data(), 0, &Resolver::dns_query_a4, queryData);
int timeout = ::dns_timeouts(ctx_, -1, now);
LOG_DEBUG << "timeout " << timeout << " active " << timerActive_ << " " << queryData;
if (!timerActive_)
{
loop_->runAfter(timeout, boost::bind(&Resolver::onTimer, this));
timerActive_ = true;
}
return query != NULL;
}
void Resolver::onRead(Timestamp t)
{
LOG_DEBUG << "onRead " << t.toString();
::dns_ioevent(ctx_, t.secondsSinceEpoch());
}
void Resolver::onTimer()
{
assert(timerActive_ == true);
time_t now = loop_->pollReturnTime().secondsSinceEpoch();
int timeout = ::dns_timeouts(ctx_, -1, now);
LOG_DEBUG << "onTimer " << loop_->pollReturnTime().toString()
<< " timeout " << timeout;
if (timeout < 0)
{
timerActive_ = false;
}
else
{
loop_->runAfter(timeout, boost::bind(&Resolver::onTimer, this));
}
}
void Resolver::onQueryResult(struct dns_rr_a4 *result, const Callback& callback)
{
int status = ::dns_status(ctx_);
LOG_DEBUG << "onQueryResult " << status;
struct sockaddr_in addr;
bzero(&addr, sizeof addr);
addr.sin_family = AF_INET;
addr.sin_port = 0;
if (result)
{
if (kDebug)
{
printf("cname %s\n", result->dnsa4_cname);
printf("qname %s\n", result->dnsa4_qname);
printf("ttl %d\n", result->dnsa4_ttl);
printf("nrr %d\n", result->dnsa4_nrr);
for (int i = 0; i < result->dnsa4_nrr; ++i)
{
char buf[32];
::dns_ntop(AF_INET, &result->dnsa4_addr[i], buf, sizeof buf);
printf(" %s\n", buf);
}
}
addr.sin_addr = result->dnsa4_addr[0];
}
InetAddress inet(addr);
callback(inet);
}
void Resolver::dns_query_a4(struct dns_ctx *ctx, struct dns_rr_a4 *result, void *data)
{
QueryData* query = static_cast<QueryData*>(data);
assert(ctx == query->owner->ctx_);
query->owner->onQueryResult(result, query->callback);
free(result);
delete query;
}
| 21.693333
| 88
| 0.646281
|
wangcy6
|
bc596efd29d8c8952d674e4b4ba9b8dfbe40fa85
| 321
|
cpp
|
C++
|
Nowcoder/NC21308.cpp
|
anine09/ACM
|
e9e8f09157e4ec91c1752a4b4724e28dfeaae4e6
|
[
"MIT"
] | null | null | null |
Nowcoder/NC21308.cpp
|
anine09/ACM
|
e9e8f09157e4ec91c1752a4b4724e28dfeaae4e6
|
[
"MIT"
] | null | null | null |
Nowcoder/NC21308.cpp
|
anine09/ACM
|
e9e8f09157e4ec91c1752a4b4724e28dfeaae4e6
|
[
"MIT"
] | null | null | null |
#include<iostream>
#include<algorithm>
using namespace std;
int num[100000];
int n;
int main(){
cin>>n;
for (int i = 0; i < n; i++)
{
cin >> num[i];
}
stable_sort(num, num + n);
for (int i = 0; i < n - 1;i++){
cout << num[i] << " ";
}
cout << num[n-1];
return 0;
}
| 13.956522
| 35
| 0.457944
|
anine09
|
bc5f8e81ee3b5ff6fc609ba640976ca682a98d52
| 353
|
cpp
|
C++
|
src/gameworld/gameworld/global/activity/impl/activityguildquestion.cpp
|
mage-game/metagame-xm-server
|
193b67389262803fe0eae742800b1e878b5b3087
|
[
"MIT"
] | 3
|
2021-12-16T13:57:28.000Z
|
2022-03-26T07:50:08.000Z
|
src/gameworld/gameworld/global/activity/impl/activityguildquestion.cpp
|
mage-game/metagame-xm-server
|
193b67389262803fe0eae742800b1e878b5b3087
|
[
"MIT"
] | null | null | null |
src/gameworld/gameworld/global/activity/impl/activityguildquestion.cpp
|
mage-game/metagame-xm-server
|
193b67389262803fe0eae742800b1e878b5b3087
|
[
"MIT"
] | 1
|
2022-03-26T07:50:11.000Z
|
2022-03-26T07:50:11.000Z
|
#include "activityguildquestion.hpp"
#include "scene/activityshadow/activityshadow.hpp"
#include "world.h"
#include "config/sharedconfig/sharedconfig.h"
ActivityGuildQuestion::ActivityGuildQuestion(ActivityManager *activity_manager)
: Activity(activity_manager, ACTIVITY_TYPE_GUILD_QUESTION)
{
}
ActivityGuildQuestion::~ActivityGuildQuestion()
{
}
| 22.0625
| 79
| 0.827195
|
mage-game
|
bc60a71070e33b23c341211f6be6acef487b5401
| 11,813
|
cpp
|
C++
|
src/core/device_server.cpp
|
guidebee/irobot
|
261d334d7c16971d791840588abc2904a1d83eaa
|
[
"MIT"
] | null | null | null |
src/core/device_server.cpp
|
guidebee/irobot
|
261d334d7c16971d791840588abc2904a1d83eaa
|
[
"MIT"
] | 5
|
2020-07-10T07:53:38.000Z
|
2020-07-10T07:53:39.000Z
|
src/core/device_server.cpp
|
guidebee/irobot
|
261d334d7c16971d791840588abc2904a1d83eaa
|
[
"MIT"
] | null | null | null |
//
// Created by James Shen on 25/3/20.
// Copyright (c) 2020 GUIDEBEE IT. All rights reserved
//
#include "device_server.hpp"
#include <cassert>
#include <cinttypes>
#include <cstdio>
#include "config.hpp"
#include "platform/net.hpp"
#include "platform/command.hpp"
#include "util/log.hpp"
#define SOCKET_NAME "irobot"
#define SERVER_FILENAME "irobot-server"
#define DEFAULT_SERVER_PATH "./server/" SERVER_FILENAME
#define DEVICE_SERVER_PATH "/data/local/tmp/irobot-server.jar"
namespace irobot {
using namespace irobot::platform;
const char *DeviceServer::GetServerPath() {
const char *server_path_env = getenv("IROBOT_SERVER_PATH");
if (server_path_env) {
LOGD("Using IROBOT_SERVER_PATH: %s", server_path_env);
// if the envvar is set, use it
return server_path_env;
}
#ifndef PORTABLE
LOGD("Using server: " DEFAULT_SERVER_PATH);
// the absolute path is hardcoded
return DEFAULT_SERVER_PATH;
#else
// use irobot-server in the same directory as the executable
char *executable_path = get_executable_path();
if (!executable_path) {
LOGE("Could not get executable path, "
"using " SERVER_FILENAME " from current directory");
// not found, use current directory
return SERVER_FILENAME;
}
char *dir = dirname(executable_path);
size_t dirlen = strlen(dir);
// sizeof(SERVER_FILENAME) gives statically the size including the null byte
size_t len = dirlen + 1 + sizeof(SERVER_FILENAME);
char *server_path = SDL_malloc(len);
if (!server_path) {
LOGE("Could not alloc server path string, "
"using " SERVER_FILENAME " from current directory");
SDL_free(executable_path);
return SERVER_FILENAME;
}
memcpy(server_path, dir, dirlen);
server_path[dirlen] = PATH_SEPARATOR;
memcpy(&server_path[dirlen + 1], SERVER_FILENAME, sizeof(SERVER_FILENAME));
// the final null byte has been copied with SERVER_FILENAME
SDL_free(executable_path);
LOGD("Using server (portable): %s", server_path);
return server_path;
#endif
}
bool DeviceServer::PushServer(const char *serial) {
const char *server_path = GetServerPath();
if (!is_regular_file(server_path)) {
LOGE("'%s' does not exist or is not a regular file\n", server_path);
return false;
}
ProcessType process = adb_push(serial, server_path, DEVICE_SERVER_PATH);
return process_check_success(process, "adb push");
}
bool DeviceServer::EnableTunnelReverse(const char *serial, uint16_t local_port) {
ProcessType process = adb_reverse(serial, SOCKET_NAME, local_port);
return process_check_success(process, "adb reverse");
}
bool DeviceServer::DisableTunnelReverse(const char *serial) {
ProcessType process = adb_reverse_remove(serial, SOCKET_NAME);
return process_check_success(process, "adb reverse --remove");
}
bool DeviceServer::EnableTunnelForward(const char *serial, uint16_t local_port) {
ProcessType process = adb_forward(serial, local_port, SOCKET_NAME);
return process_check_success(process, "adb forward");
}
bool DeviceServer::DisableTunnelForward(const char *serial, uint16_t local_port) {
ProcessType process = adb_forward_remove(serial, local_port);
return process_check_success(process, "adb forward --remove");
}
bool DeviceServer::EnableTunnel() {
if (EnableTunnelReverse(this->serial, this->local_port)) {
return true;
}
LOGW("'adb reverse' failed, fallback to 'adb forward'");
this->tunnel_forward = true;
return EnableTunnelForward(this->serial, this->local_port);
}
bool DeviceServer::DisableTunnel() {
if (this->tunnel_forward) {
return DisableTunnelForward(this->serial, this->local_port);
}
return DisableTunnelReverse(this->serial);
}
ProcessType DeviceServer::ExecuteServer(const struct DeviceServerParameters *params) {
char max_size_string[6];
char bit_rate_string[11];
char max_fps_string[6];
sprintf(max_size_string, "%" PRIu16, params->max_size);
sprintf(bit_rate_string, "%" PRIu32, params->bit_rate);
sprintf(max_fps_string, "%" PRIu16, params->max_fps);
const char *const cmd[] = {
"shell",
"CLASSPATH=" DEVICE_SERVER_PATH, // NOLINT(bugprone-suspicious-missing-comma)
"app_process",
#ifdef SERVER_DEBUGGER
# define SERVER_DEBUGGER_PORT "5005"
"-agentlib:jdwp=transport=dt_socket,suspend=y,server=y,address="
SERVER_DEBUGGER_PORT,
#endif
"/", // unused
"com.guidebee.irobot.Server",
IROBOT_SERVER_VERSION,
max_size_string,
bit_rate_string,
max_fps_string,
this->tunnel_forward ? "true" : "false",
params->crop ? params->crop : "-",
"true", // always send frame meta (packet boundaries + timestamp)
params->control ? "true" : "false",
};
#ifdef SERVER_DEBUGGER
LOGI("Server debugger waiting for a client on device port "
SERVER_DEBUGGER_PORT "...");
// From the computer, run
// adb forward tcp:5005 tcp:5005
// Then, from Android Studio: Run > Debug > Edit configurations...
// On the left, click on '+', "Remote", with:
// Host: localhost
// Port: 5005
// Then click on "Debug"
#endif
return adb_execute(this->serial, cmd, sizeof(cmd) / sizeof(cmd[0]));
}
socket_t DeviceServer::ListenOnPort(uint16_t port) {
return net_listen(IPV4_LOCALHOST, port, 1);
}
socket_t DeviceServer::ConnectAndReadByte(uint16_t port) {
socket_t socket = net_connect(IPV4_LOCALHOST, port);
if (socket == INVALID_SOCKET) {
return INVALID_SOCKET;
}
char byte;
// the connection may succeed even if the server behind the "adb tunnel"
// is not listening, so read one byte to detect a working connection
if (net_recv(socket, &byte, 1) != 1) {
// the server is not listening yet behind the adb tunnel
net_close(socket);
return INVALID_SOCKET;
}
return socket;
}
socket_t DeviceServer::ConnectToServer(uint16_t port, uint32_t attempts, uint32_t delay) {
do {
LOGD("Remaining connection attempts: %d", (int) attempts);
socket_t socket = ConnectAndReadByte(port);
if (socket != INVALID_SOCKET) {
// it worked!
return socket;
}
if (attempts) {
SDL_Delay(delay);
}
} while (--attempts > 0);
return INVALID_SOCKET;
}
void DeviceServer::CloseSocket(socket_t *socket) {
assert(*socket != INVALID_SOCKET);
net_shutdown(*socket, SHUT_RDWR);
if (!net_close(*socket)) {
LOGW("Could not close socket");
return;
}
*socket = INVALID_SOCKET;
}
void DeviceServer::Init() {
this->serial = nullptr;
this->process = PROCESS_NONE;
this->server_socket = INVALID_SOCKET;
this->video_socket = INVALID_SOCKET;
this->control_socket = INVALID_SOCKET;
this->local_port = 0;
this->tunnel_enabled = false;
this->tunnel_forward = false;
}
bool DeviceServer::Start(const char *pSerial,
const DeviceServerParameters *params) {
this->local_port = params->local_port;
if (pSerial) {
this->serial = SDL_strdup(pSerial);
if (!this->serial) {
return false;
}
}
if (!PushServer(pSerial)) {
SDL_free(this->serial);
return false;
}
if (!EnableTunnel()) {
SDL_free(this->serial);
return false;
}
// if "adb reverse" does not work (e.g. over "adb connect"), it fallbacks to
// "adb forward", so the app socket is the client
if (!this->tunnel_forward) {
// At the application level, the device part is "the server" because it
// serves video stream and control. However, at the network level, the
// client listens and the server connects to the client. That way, the
// client can listen before starting the server app, so there is no
// need to try to connect until the server socket is listening on the
// device.
this->server_socket = ListenOnPort(params->local_port);
if (this->server_socket == INVALID_SOCKET) {
LOGE("Could not listen on port %"
PRIu16, params->local_port);
DisableTunnel();
SDL_free(this->serial);
return false;
}
}
// server will connect to our server socket
this->process = ExecuteServer(params);
if (this->process == PROCESS_NONE) {
if (!this->tunnel_forward) {
CloseSocket(&this->server_socket);
}
DisableTunnel();
SDL_free(this->serial);
return false;
}
this->tunnel_enabled = true;
return true;
}
bool DeviceServer::ConnectTo() {
if (!this->tunnel_forward) {
this->video_socket = net_accept(this->server_socket);
if (this->video_socket == INVALID_SOCKET) {
return false;
}
this->control_socket = net_accept(this->server_socket);
if (this->control_socket == INVALID_SOCKET) {
// the video_socket will be cleaned up on destroy
return false;
}
// we don't need the server socket anymore
CloseSocket(&this->server_socket);
} else {
uint32_t attempts = 100;
uint32_t delay = 100; // ms
this->video_socket =
ConnectToServer(this->local_port, attempts, delay);
if (this->video_socket == INVALID_SOCKET) {
return false;
}
// we know that the device is listening, we don't need several attempts
this->control_socket =
net_connect(IPV4_LOCALHOST, this->local_port);
if (this->control_socket == INVALID_SOCKET) {
return false;
}
}
// we don't need the adb tunnel anymore
DisableTunnel(); // ignore failure
this->tunnel_enabled = false;
return true;
}
void DeviceServer::Stop() {
if (this->server_socket != INVALID_SOCKET) {
CloseSocket(&this->server_socket);
}
if (this->video_socket != INVALID_SOCKET) {
CloseSocket(&this->video_socket);
}
if (this->control_socket != INVALID_SOCKET) {
CloseSocket(&this->control_socket);
}
assert(this->process != PROCESS_NONE);
if (!cmd_terminate(this->process)) {
LOGW("Could not terminate server");
}
cmd_simple_wait(this->process, nullptr); // ignore exit code
LOGD("Server terminated");
if (this->tunnel_enabled) {
// ignore failure
DisableTunnel();
}
}
void DeviceServer::Destroy() {
SDL_free(this->serial);
}
}
| 33.751429
| 94
| 0.587065
|
guidebee
|
bc627c86509985097bb2ce5f74a5833d4bb66931
| 619
|
cpp
|
C++
|
Fuji/Source/Drivers/PS2/MFDebug_PS2.cpp
|
TurkeyMan/fuji
|
afd6a26c710ce23965b088ad158fe916d6a1a091
|
[
"BSD-2-Clause"
] | 35
|
2015-01-19T22:07:48.000Z
|
2022-02-21T22:17:53.000Z
|
Fuji/Source/Drivers/PS2/MFDebug_PS2.cpp
|
TurkeyMan/fuji
|
afd6a26c710ce23965b088ad158fe916d6a1a091
|
[
"BSD-2-Clause"
] | 1
|
2022-02-23T09:34:15.000Z
|
2022-02-23T09:34:15.000Z
|
Fuji/Source/Drivers/PS2/MFDebug_PS2.cpp
|
TurkeyMan/fuji
|
afd6a26c710ce23965b088ad158fe916d6a1a091
|
[
"BSD-2-Clause"
] | 4
|
2015-05-11T03:31:35.000Z
|
2018-09-27T04:55:57.000Z
|
#include "Fuji_Internal.h"
#if MF_DEBUG == MF_DRIVER_PS2
#include "MFInput_Internal.h"
#include <stdio.h>
MF_API void MFDebug_Message(const char *pMessage)
{
printf("%s\n", pMessage);
}
MF_API void MFDebug_DebugAssert(const char *pReason, const char *pMessage, const char *pFile, int line)
{
MFDebug_Message(MFStr("%s(%d) : Assertion Failure.",pFile,line));
MFDebug_Message(MFStr("Failed Condition: %s\n%s", pReason, pMessage));
MFCallstack_Log();
// draw some shit on the screen..
while(!MFInput_WasPressed(Button_P2_Start, IDD_Gamepad, 0))
{
MFInput_Update();
}
}
#endif
| 21.344828
| 104
| 0.693053
|
TurkeyMan
|
bc631af571d4d59ee18692a1e9a4491217976c7e
| 674
|
cc
|
C++
|
POJ/2752_Seek the Name, Seek the Fame/2752.cc
|
pdszhh/ACM
|
956b3d03a5d3f070ef24c940b7459f5cccb11d6c
|
[
"MIT"
] | 1
|
2019-05-05T03:51:20.000Z
|
2019-05-05T03:51:20.000Z
|
POJ/2752_Seek the Name, Seek the Fame/2752.cc
|
pdszhh/ACM
|
956b3d03a5d3f070ef24c940b7459f5cccb11d6c
|
[
"MIT"
] | null | null | null |
POJ/2752_Seek the Name, Seek the Fame/2752.cc
|
pdszhh/ACM
|
956b3d03a5d3f070ef24c940b7459f5cccb11d6c
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <stack>
#include <cstdio>
#include <cstring>
using namespace std;
int len;
char S[400010];
int nextval[400010];
void get_nextval() {
for (int k = nextval[0] = -1, j = 0; j != len; ) {
if (k == -1 or S[j] == S[k])
nextval[++j] = ++k;
else
k = nextval[k];
}
}
int main() {
while (scanf("%s", S) != EOF) {
len = strlen(S);
get_nextval();
stack<int> s;
for (int k = len; k != 0; k = nextval[k])
s.push(k);
while (not s.empty()) {
printf("%d ", s.top());
s.pop();
}
printf("\n");
}
return 0;
}
| 18.722222
| 54
| 0.437685
|
pdszhh
|
bc65b5eaf8257f09f0912d4f0e058887d2081775
| 9,592
|
hpp
|
C++
|
include/public/coherence/lang/HeapAnalyzer.hpp
|
chpatel3/coherence-cpp-extend-client
|
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
|
[
"UPL-1.0",
"Apache-2.0"
] | 6
|
2020-07-01T21:38:30.000Z
|
2021-11-03T01:35:11.000Z
|
include/public/coherence/lang/HeapAnalyzer.hpp
|
chpatel3/coherence-cpp-extend-client
|
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
|
[
"UPL-1.0",
"Apache-2.0"
] | 1
|
2020-07-24T17:29:22.000Z
|
2020-07-24T18:29:04.000Z
|
include/public/coherence/lang/HeapAnalyzer.hpp
|
chpatel3/coherence-cpp-extend-client
|
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
|
[
"UPL-1.0",
"Apache-2.0"
] | 6
|
2020-07-10T18:40:58.000Z
|
2022-02-18T01:23:40.000Z
|
/*
* Copyright (c) 2000, 2020, Oracle and/or its affiliates.
*
* Licensed under the Universal Permissive License v 1.0 as shown at
* http://oss.oracle.com/licenses/upl.
*/
#ifndef COH_HEAP_ANALYZER_HPP
#define COH_HEAP_ANALYZER_HPP
#include "coherence/lang/interface_spec.hpp"
#include "coherence/lang/Object.hpp"
#include "coherence/lang/TypedHandle.hpp"
COH_OPEN_NAMESPACE2(coherence,lang)
/**
* HeapAnalyzer provides a base diagnostics interface for tracking heap usage.
*
* There is at most one HeapAnalyzer registered with the system for the
* lifetime of the process. The HeapAnalyzer implementation may be specified
* via the "coherence.heap.analyzer" system property. The property
* can be set to one of the following values:
* <ul>
* <li>none No heap analysis will be performed.</li>
* <li>object The coherence::lang::ObjectCountHeapAnalyzer will be used.</li>
* <li>class The coherence::lang::ClassBasedHeapAnalyzer will be used.</li>
* <li>alloc The coherence::lang::ClassBasedHeapAnalyzer will be used,
* in allocation analysis mode.</li>
* <li>[custom] The name of a class registered with the SystemClassLoader.</li>
* </ul>
*
* In the case where a custom class is specified, it must implement this
* interface. The custom analyzer will be initialized as soon as the class
* is registered with the SystemClassLoader. As static initialization order
* cannot be guaranteed, this custom analyzer will not be notified of managed
* objects created earlier in the static initialization order.
*
* The active analyzer may be obtained from the System::getHeapAnalyzer()
* method.
*
* The HeapAnalyzer and Snapshot interfaces are intentionally narrow.
* Implementations are expected to provide useful information via the toString
* method, as well as by possibly augmenting the interfaces. The minimal
* interface is sufficient for detecting memory leaks.
*
* HeapAnalyzer::Snapshot::View vSnap = hAnalyzer->capture();
* ...
* ...
* std::cout << "Heap changed by: " << hAnalyzer->delta(vSnap) << std::endl;
*
* @see ObjectCountHeapAnalyzer
* @see ClassBasedHeapAnalyzer
*
* @author mf 2008.04.27
*/
class COH_EXPORT HeapAnalyzer
: public interface_spec<HeapAnalyzer>
{
// ----- nested interface: Snapshot -------------------------------------
public:
/**
* Snapshot provides a abstract mechanism for comparing successive
* heap analysis points.
*/
class COH_EXPORT Snapshot
: public interface_spec<Snapshot>
{
// ----- Snapshot interface ---------------------------------
public:
/**
* Return the number of registered objects reflected by this
* snapshot.
*
* @return the number of registered objects
*/
virtual int64_t getObjectCount() const = 0;
/**
* Return the result of "subtracting" the supplied Snapshot
* from this Snapshot.
*
* @param vThat the snapshot to compare against
*
* @return the delta between two snapshots
*/
virtual Snapshot::View delta(Snapshot::View vThat) const = 0;
};
// ----- HeapAnalyzer interface -----------------------------------------
public:
/**
* Capture a Snapshot of the current state of the heap.
*
* Note, when performing captures in a loop, and assigning the captured
* snapshot to a handle referencing a snapshot, it is advisable to
* NULL out the handle first, so as to avoid the new snapshot including
* the "cost" of snapshot it is about to replace.
*
* @return a Snapshot of the current state of the heap.
*/
virtual Snapshot::View capture() const = 0;
/**
* Compute the delta between the supplied Snapshot and the current heap
* state.
*
* @param vThat the snapshot to compare against.
*
* @return a snapshot containing the delta
*/
virtual Snapshot::View delta(Snapshot::View vThat) const = 0;
/**
* Return the number of registered objects.
*
* @return the number of registered objects
*/
virtual int64_t getObjectCount() const = 0;
/**
* Return the number of objects which have been marked as uncollectable.
*
* Return the number of objects which have been marked as uncollectable.
*/
virtual int64_t getImmortalCount() const = 0;
protected:
/**
* Register a newly created Object with the system.
*
* This method is called automatically by coherence::lang::Object once
* the Object has finished construction.
*
* @param o the newly created Object.
*/
virtual void registerObject(const Object& o) = 0;
/**
* Unregister an Object with the system.
*
* This method is called automatically by coherence::lang::Object
* just prior to the deletion of the Object. No new handles or views
* may be created to the object.
*
* @param o the Object to unregister
*/
virtual void unregisterObject(const Object& o) = 0;
/**
* Invoked when an object is deemed to immortal and can never be collected.
*
* Note the specified object will have already been registered via registerObject.
*/
virtual void registerImmortal(const Object& o) = 0;
// ----- static helper methods ------------------------------------------
public:
/**
* Ensure that the delta between the current heap and the supplied
* snapshot is as expected.
*
* This method can be used to perform quick memory leak assertions.
*
* @code
* HeapAnalyzer::Snapshot::View vSnapStart = HeapAnalyzer::ensureHeap();
* ...
* ...
* HeapAnalyzer::ensureHeap(vSnapStart);
* @endcode
*
* @param vSnap the snapshot to ensure; or NULL for return only
* @param cDelta the allowable change in the heap's object count
*
* @return a new Snapshot
*
* @throws IllegalStateException if the delta does not contain the
* expected amount. The text of the exception will include the
* output of the Snapshots toString() method.
*/
static Snapshot::View ensureHeap(Snapshot::View vSnap = NULL,
int64_t cDelta = 0);
// ----- inner class: Block ---------------------------------------------
public:
/**
* The HeapAnalyzer::Block allows for easily verifying that a block
* of code does not leak memory.
*
* @code
* COH_ENSURE_HEAP
* {
* ... // your code here
* }
* @endcode
*/
class Block
{
// ----- constructors ---------------------------------------
public:
/**
* Construct a ZeroBlock object.
*
* This will automatically capture an initial snapshot
*/
Block()
: m_vSnap(ensureHeap())
{
}
/**
* Copy constructor for COH_ENSURE_HEAP macro.
*/
Block(const Block& that)
: m_vSnap(that.m_vSnap)
{
that.m_vSnap = NULL;
}
/**
* Destroy a Block object.
*
* This will test that no memory has been leaked
*/
~Block() COH_NOEXCEPT(false)
{
ensureHeap(m_vSnap);
}
// ----- operators ------------------------------------------
public:
/*
* Boolean conversion for use in COH_ENSURE_HEAP macro.
*
* @return false if snapshot is held, true otherwise
*/
operator bool() const
{
return m_vSnap == NULL;
}
private:
/**
* Blocked assignment operator.
*/
const Block& operator=(const Block&);
/**
* Blocked dynamic allocation.
*/
static void* operator new(size_t);
// ----- data members ---------------------------------------
protected:
mutable Snapshot::View m_vSnap; // on stack
};
// ----- friends --------------------------------------------------------
friend class Object;
};
COH_CLOSE_NAMESPACE2
/**
* Macro for making more readable HeapAnalyzer::Block code blocks See the
* documentation of Block for a usage example.
*
* @see coherence::lang::HeapAnalyzer::Block
*/
#define COH_ENSURE_HEAP \
if (coherence::lang::HeapAnalyzer::Block COH_UNIQUE_IDENTIFIER(_coh_heap_) \
= coherence::lang::HeapAnalyzer::Block()) \
{ \
COH_THROW(coherence::lang::IllegalStateException::create()); \
} \
else
#endif // COH_HEAP_ANALYZER_HPP
| 32.515254
| 90
| 0.541389
|
chpatel3
|
bc69518352aa45fe18a7ff51e828967abd605efe
| 3,554
|
hpp
|
C++
|
qi/async.hpp
|
arntanguy/libqi
|
7f3e1394cb26126b26fa7ff54d2de1371a1c9f96
|
[
"BSD-3-Clause"
] | 61
|
2015-01-08T08:05:28.000Z
|
2022-01-07T16:47:47.000Z
|
qi/async.hpp
|
arntanguy/libqi
|
7f3e1394cb26126b26fa7ff54d2de1371a1c9f96
|
[
"BSD-3-Clause"
] | 30
|
2015-04-06T21:41:18.000Z
|
2021-08-18T13:24:51.000Z
|
qi/async.hpp
|
arntanguy/libqi
|
7f3e1394cb26126b26fa7ff54d2de1371a1c9f96
|
[
"BSD-3-Clause"
] | 64
|
2015-02-23T20:01:11.000Z
|
2022-03-14T13:31:20.000Z
|
#pragma once
/**
** Copyright (C) 2012-2016 Aldebaran Robotics
** See COPYING for the license
*/
#ifndef _QI_ASYNC_HPP_
#define _QI_ASYNC_HPP_
#include <qi/eventloop.hpp>
#include <qi/future.hpp>
#include <qi/strand.hpp>
namespace qi
{
// some required forward declaration
namespace detail
{
template <typename F>
inline auto asyncMaybeActor(F&& cb, qi::Duration delay) ->
typename std::enable_if<detail::IsAsyncBind<F>::value, typename std::decay<decltype(cb())>::type>::type;
template <typename F>
inline auto asyncMaybeActor(F&& cb, qi::Duration delay) ->
typename std::enable_if<!detail::IsAsyncBind<F>::value,
qi::Future<typename std::decay<decltype(cb())>::type>>::type;
template <typename F>
inline auto asyncMaybeActor(F&& cb, qi::SteadyClockTimePoint timepoint) ->
typename std::enable_if<detail::IsAsyncBind<F>::value, typename std::decay<decltype(cb())>::type>::type;
template <typename F>
inline auto asyncMaybeActor(F&& cb, qi::SteadyClockTimePoint timepoint) ->
typename std::enable_if<!detail::IsAsyncBind<F>::value,
qi::Future<typename std::decay<decltype(cb())>::type>>::type;
} // detail
template <typename F>
inline auto asyncAt(F&& callback, qi::SteadyClockTimePoint timepoint)
-> decltype(qi::getEventLoop()->asyncAt(std::forward<F>(callback), timepoint))
{
return qi::getEventLoop()->asyncAt(std::forward<F>(callback), timepoint);
}
template <typename F>
inline auto asyncDelay(F&& callback, qi::Duration delay)
-> decltype(detail::asyncMaybeActor(std::forward<F>(callback), delay))
{
return detail::asyncMaybeActor(std::forward<F>(callback), delay);
}
template <typename F>
inline auto async(F&& callback)
-> decltype(asyncDelay(std::forward<F>(callback), qi::Duration(0)))
{
return asyncDelay(std::forward<F>(callback), qi::Duration(0));
}
/// \copydoc qi::EventLoop::async().
/// \deprecated use qi::async with qi::Duration
template<typename R>
QI_API_DEPRECATED_MSG(Use 'asyncDelay' instead)
inline Future<R> async(boost::function<R()> callback, uint64_t usDelay);
template<typename R>
QI_API_DEPRECATED_MSG(Use 'asyncDelay' instead)
inline Future<R> async(boost::function<R()> callback, qi::Duration delay);
template<typename R>
QI_API_DEPRECATED_MSG(Use 'asyncAt' instead)
inline Future<R> async(boost::function<R()> callback, qi::SteadyClockTimePoint timepoint);
template<typename R>
QI_API_DEPRECATED_MSG(Use 'async' without explicit return type template arguement instead)
inline Future<R> async(detail::Function<R()> callback);
#ifdef DOXYGEN
/// @deprecated since 2.5
template<typename R, typename Func, typename ArgTrack>
QI_API_DEPRECATED qi::Future<R> async(const Func& f, const ArgTrack& toTrack, ...);
#else
#define genCall(n, ATYPEDECL, ATYPES, ADECL, AUSE, comma)\
template <typename R, typename AF, typename ARG0 comma ATYPEDECL>\
inline QI_API_DEPRECATED Future<R> async(const AF& fun, const ARG0& arg0 comma ADECL, qi::Duration delay = qi::Duration(0))\
\
template <typename R, typename AF, typename ARG0 comma ATYPEDECL>\
inline QI_API_DEPRECATED Future<R> async(const AF& fun, const ARG0& arg0 comma ADECL, qi::SteadyClockTimePoint timepoint)\
QI_GEN(genCall)
#undef genCall
#endif
/// Cancels the future when the timeout expires.
///
/// The output future is the same as the input one, to allow functional
/// composition.
template<typename T, typename Duration>
Future<T> cancelOnTimeout(Future<T> fut, Duration timeout);
} // qi
#include <qi/detail/async.hxx>
#endif // _QI_ASYNC_HPP
| 34.504854
| 126
| 0.728756
|
arntanguy
|
bc6c6b0d6b0840dca12c91056363243de192adf1
| 6,251
|
cpp
|
C++
|
src/libs/qlib/qdmparams.cpp
|
3dhater/Racer
|
d7fe4014b1efefe981528547649dc397da7fa780
|
[
"Unlicense"
] | null | null | null |
src/libs/qlib/qdmparams.cpp
|
3dhater/Racer
|
d7fe4014b1efefe981528547649dc397da7fa780
|
[
"Unlicense"
] | null | null | null |
src/libs/qlib/qdmparams.cpp
|
3dhater/Racer
|
d7fe4014b1efefe981528547649dc397da7fa780
|
[
"Unlicense"
] | 1
|
2021-01-03T16:16:47.000Z
|
2021-01-03T16:16:47.000Z
|
/*
* QDMParams - encapsulate DMparams type
* 08-09-98: Created!
* (C) MG/RVG
*/
#include <qlib/dmparams.h>
#include <qlib/debug.h>
DEBUG_ENABLE
#define DME(f,s) if((f)!=DM_SUCCESS)qerr(s)
QDMParams::QDMParams()
{
p=0;
#ifndef WIN32
DME(dmParamsCreate(&p),"QDMParams ctor; can't allocate DMparams");
#endif
}
QDMParams::~QDMParams()
{
#ifndef WIN32
if(p)dmParamsDestroy(p);
#endif
}
/******
* GET *
******/
int QDMParams::GetInt(const char *name)
{
#ifdef WIN32
return 0;
#else
return dmParamsGetInt(p,name);
#endif
}
int QDMParams::GetEnum(const char *name)
{
#ifdef WIN32
return 0;
#else
return dmParamsGetEnum(p,name);
#endif
}
const char *QDMParams::GetString(const char *name)
{
#ifdef WIN32
return 0;
#else
return dmParamsGetString(p,name);
#endif
}
double QDMParams::GetFloat(const char *name)
{
#ifdef WIN32
return 0;
#else
return dmParamsGetFloat(p,name);
#endif
}
DMfraction QDMParams::GetFract(const char *name)
{
#ifdef WIN32
return 0;
#else
return dmParamsGetFract(p,name);
#endif
}
/******
* SET *
******/
void QDMParams::SetImageDefaults(int wid,int hgt,DMimagepacking packing)
{
#ifndef WIN32
DME(dmSetImageDefaults(p,wid,hgt,packing),"QDMParams::SetImageDefaults");
#endif
}
void QDMParams::SetAudioDefaults(int bits,int freq,int channels)
{
#ifndef WIN32
DME(dmSetAudioDefaults(p,bits,freq,channels),"QDMParams::SetAudioDefaults");
#endif
}
void QDMParams::SetInt(const char *name,int n)
{
#ifndef WIN32
dmParamsSetInt(p,name,n);
#endif
}
void QDMParams::SetFloat(const char *name,double v)
{
#ifndef WIN32
dmParamsSetFloat(p,name,v);
#endif
}
void QDMParams::SetEnum(const char *name,int n)
{
#ifndef WIN32
dmParamsSetEnum(p,name,n);
#endif
}
void QDMParams::SetString(const char *name,const char *v)
{
#ifndef WIN32
dmParamsSetString(p,name,v);
#endif
}
/*******
* DEBUG *
********/
static void DbgPrintParams(const DMparams *p,int indent=0)
{
#ifndef WIN32
int len = dmParamsGetNumElems( p );
int i;
int j;
for ( i = 0; i < len; i++ ) {
const char* name = dmParamsGetElem ( p, i );
DMparamtype type = dmParamsGetElemType( p, i );
for ( j = 0; j < indent; j++ ) {
printf( " " );
}
printf( "%8s: ", name );
switch( type )
{
case DM_TYPE_ENUM:
printf( "%d", dmParamsGetEnum( p, name ) );
break;
case DM_TYPE_INT:
printf( "%d", dmParamsGetInt( p, name ) );
break;
case DM_TYPE_STRING:
printf( "%s", dmParamsGetString( p, name ) );
break;
case DM_TYPE_FLOAT:
printf( "%f", dmParamsGetFloat( p, name ) );
break;
case DM_TYPE_FRACTION:
{
DMfraction f;
f = dmParamsGetFract( p, name );
printf( "%d/%d", f.numerator, f.denominator );
}
break;
case DM_TYPE_PARAMS:
DbgPrintParams( dmParamsGetParams( p, name ), indent + 4 );
break;
case DM_TYPE_ENUM_ARRAY:
{
int i;
const DMenumarray* array = dmParamsGetEnumArray( p, name );
for ( i = 0; i < array->elemCount; i++ ) {
printf( "%d ", array->elems[i] );
}
}
break;
case DM_TYPE_INT_ARRAY:
{
int i;
const DMintarray* array = dmParamsGetIntArray( p, name );
for ( i = 0; i < array->elemCount; i++ ) {
printf( "%d ", array->elems[i] );
}
}
break;
case DM_TYPE_STRING_ARRAY:
{
int i;
const DMstringarray* array =
dmParamsGetStringArray( p, name );
for ( i = 0; i < array->elemCount; i++ ) {
printf( "%s ", array->elems[i] );
}
}
break;
case DM_TYPE_FLOAT_ARRAY:
{
int i;
const DMfloatarray* array =
dmParamsGetFloatArray( p, name );
for ( i = 0; i < array->elemCount; i++ ) {
printf( "%f ", array->elems[i] );
}
}
break;
case DM_TYPE_FRACTION_ARRAY:
{
int i;
const DMfractionarray* array =
dmParamsGetFractArray( p, name );
for ( i = 0; i < array->elemCount; i++ ) {
printf( "%d/%d ",
array->elems[i].numerator,
array->elems[i].denominator );
}
}
break;
case DM_TYPE_INT_RANGE:
{
const DMintrange* range = dmParamsGetIntRange( p, name );
printf( "%d ... %d", range->low, range->high );
}
break;
case DM_TYPE_FLOAT_RANGE:
{
const DMfloatrange* range =
dmParamsGetFloatRange( p, name );
printf( "%f ... %f", range->low, range->high );
}
break;
case DM_TYPE_FRACTION_RANGE:
{
const DMfractionrange* range =
dmParamsGetFractRange( p, name );
printf( "%d/%d ... %d/%d",
range->low.numerator,
range->low.denominator,
range->high.numerator,
range->high.denominator );
}
break;
defualt:
printf( "UNKNOWN TYPE" );
}
printf( "\n" );
}
printf("---\n");
#endif
}
void QDMParams::DbgPrint()
{
DbgPrintParams(p);
}
| 25.618852
| 79
| 0.468725
|
3dhater
|