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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
913af1bf9eb994c9987f4ae6755e8be3ee54b9ee | 8,601 | cpp | C++ | 3rdParty/iresearch/core/search/tfidf.cpp | specimen151/arangodb | 1a3a31dace16293426a19364eb4d93c8f17c0d68 | [
"BSL-1.0",
"Zlib",
"Apache-2.0"
] | null | null | null | 3rdParty/iresearch/core/search/tfidf.cpp | specimen151/arangodb | 1a3a31dace16293426a19364eb4d93c8f17c0d68 | [
"BSL-1.0",
"Zlib",
"Apache-2.0"
] | null | null | null | 3rdParty/iresearch/core/search/tfidf.cpp | specimen151/arangodb | 1a3a31dace16293426a19364eb4d93c8f17c0d68 | [
"BSL-1.0",
"Zlib",
"Apache-2.0"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2016 by EMC Corporation, All Rights Reserved
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is EMC Corporation
///
/// @author Andrey Abramov
/// @author Vasiliy Nabatchikov
////////////////////////////////////////////////////////////////////////////////
#include <rapidjson/rapidjson/document.h> // for rapidjson::Document
#include "tfidf.hpp"
#include "scorers.hpp"
#include "analysis/token_attributes.hpp"
#include "index/index_reader.hpp"
#include "index/field_meta.hpp"
NS_LOCAL
irs::sort::ptr make_from_bool(
const rapidjson::Document& json,
const irs::string_ref& args) {
assert(json.IsBool());
PTR_NAMED(irs::tfidf_sort, ptr, json.GetBool());
return ptr;
}
irs::sort::ptr make_from_object(
const rapidjson::Document& json,
const irs::string_ref& args) {
assert(json.IsObject());
PTR_NAMED(irs::tfidf_sort, ptr);
#ifdef IRESEARCH_DEBUG
auto& scorer = dynamic_cast<irs::tfidf_sort&>(*ptr);
#else
auto& scorer = static_cast<irs::tfidf_sort&>(*ptr);
#endif
{
// optional bool
const auto* key= "with-norms";
if (json.HasMember(key)) {
if (!json[key].IsBool()) {
IR_FRMT_ERROR("Non-boolean value in '%s' while constructing tfidf scorer from jSON arguments: %s", key, args.c_str());
return nullptr;
}
scorer.normalize(json[key].GetBool());
}
}
return ptr;
}
irs::sort::ptr make_from_array(
const rapidjson::Document& json,
const irs::string_ref& args) {
assert(json.IsArray());
const auto array = json.GetArray();
const auto size = array.Size();
if (size > 1) {
// wrong number of arguments
IR_FRMT_ERROR(
"Wrong number of arguments while constructing tfidf scorer from jSON arguments (must be <= 1): %s",
args.c_str()
);
return nullptr;
}
// default args
auto norms = irs::tfidf_sort::WITH_NORMS();
// parse `with-norms` optional argument
if (!array.Empty()) {
auto& arg = array[0];
if (!arg.IsBool()) {
IR_FRMT_ERROR(
"Non-float value on position `0` while constructing bm25 scorer from jSON arguments: %s",
args.c_str()
);
return nullptr;
}
norms = arg.GetBool();
}
PTR_NAMED(irs::tfidf_sort, ptr, norms);
return ptr;
}
NS_END // LOCAL
NS_ROOT
NS_BEGIN(tfidf)
// empty frequency
const frequency EMPTY_FREQ;
struct idf final : basic_stored_attribute<float_t> {
DECLARE_ATTRIBUTE_TYPE();
DECLARE_FACTORY_DEFAULT();
idf() : basic_stored_attribute(1.f) { }
void clear() { value = 1.f; }
};
DEFINE_ATTRIBUTE_TYPE(iresearch::tfidf::idf);
DEFINE_FACTORY_DEFAULT(idf);
typedef tfidf_sort::score_t score_t;
class collector final : public iresearch::sort::collector {
public:
collector(bool normalize)
: normalize_(normalize) {
}
virtual void collect(
const sub_reader& segment,
const term_reader& field,
const attribute_view& term_attrs
) override {
UNUSED(segment);
UNUSED(field);
auto& meta = term_attrs.get<iresearch::term_meta>();
if (meta) {
docs_count += meta->docs_count;
}
}
virtual void finish(
attribute_store& filter_attrs,
const iresearch::index_reader& index
) override {
filter_attrs.emplace<tfidf::idf>()->value =
1 + float_t(std::log(index.docs_count() / double_t(docs_count + 1)));
// add norm attribute if requested
if (normalize_) {
filter_attrs.emplace<norm>();
}
}
private:
uint64_t docs_count = 0; // document frequency
bool normalize_;
}; // collector
class scorer : public iresearch::sort::scorer_base<tfidf::score_t> {
public:
DECLARE_FACTORY(scorer);
scorer(
iresearch::boost::boost_t boost,
const tfidf::idf* idf,
const frequency* freq)
: idf_(boost * (idf ? idf->value : 1.f)),
freq_(freq ? freq : &EMPTY_FREQ) {
assert(freq_);
}
virtual void score(byte_type* score_buf) override {
score_cast(score_buf) = tfidf();
}
protected:
FORCE_INLINE float_t tfidf() const {
return idf_ * float_t(std::sqrt(freq_->value));
}
private:
float_t idf_; // precomputed : boost * idf
const frequency* freq_;
}; // scorer
class norm_scorer final : public scorer {
public:
DECLARE_FACTORY(norm_scorer);
norm_scorer(
const iresearch::norm* norm,
iresearch::boost::boost_t boost,
const tfidf::idf* idf,
const frequency* freq)
: scorer(boost, idf, freq),
norm_(norm) {
assert(norm_);
}
virtual void score(byte_type* score_buf) override {
score_cast(score_buf) = tfidf() * norm_->read();
}
private:
const iresearch::norm* norm_;
}; // norm_scorer
class sort final: iresearch::sort::prepared_base<tfidf::score_t> {
public:
DECLARE_FACTORY(prepared);
sort(bool normalize) NOEXCEPT
: normalize_(normalize) {
}
virtual const flags& features() const override {
static const irs::flags FEATURES[] = {
irs::flags({ irs::frequency::type() }), // without normalization
irs::flags({ irs::frequency::type(), irs::norm::type() }), // with normalization
};
return FEATURES[normalize_];
}
virtual collector::ptr prepare_collector() const override {
return iresearch::sort::collector::make<tfidf::collector>(normalize_);
}
virtual scorer::ptr prepare_scorer(
const sub_reader& segment,
const term_reader& field,
const attribute_store& query_attrs,
const attribute_view& doc_attrs
) const override {
if (!doc_attrs.contains<frequency>()) {
return nullptr; // if there is no frequency then all the scores will be the same (e.g. filter irs::all)
}
auto& norm = query_attrs.get<iresearch::norm>();
if (norm && norm->reset(segment, field.meta().norm, *doc_attrs.get<document>())) {
return tfidf::scorer::make<tfidf::norm_scorer>(
&*norm,
boost::extract(query_attrs),
query_attrs.get<tfidf::idf>().get(),
doc_attrs.get<frequency>().get()
);
}
return tfidf::scorer::make<tfidf::scorer>(
boost::extract(query_attrs),
query_attrs.get<tfidf::idf>().get(),
doc_attrs.get<frequency>().get()
);
}
virtual void add(score_t& dst, const score_t& src) const override {
dst += src;
}
virtual bool less(const score_t& lhs, const score_t& rhs) const override {
return lhs < rhs;
}
private:
const std::function<bool(score_t, score_t)>* less_;
bool normalize_;
}; // sort
NS_END // tfidf
DEFINE_SORT_TYPE_NAMED(iresearch::tfidf_sort, "tfidf");
REGISTER_SCORER_JSON(irs::tfidf_sort, irs::tfidf_sort::make);
DEFINE_FACTORY_DEFAULT(irs::tfidf_sort);
/*static*/ sort::ptr tfidf_sort::make(const string_ref& args) {
if (args.null()) {
PTR_NAMED(tfidf_sort, ptr);
return ptr;
}
rapidjson::Document json;
if (json.Parse(args.c_str(), args.size()).HasParseError()) {
IR_FRMT_ERROR(
"Invalid jSON arguments passed while constructing tfidf scorer, arguments: %s",
args.c_str()
);
return nullptr;
}
switch (json.GetType()) {
case rapidjson::kFalseType:
case rapidjson::kTrueType:
return make_from_bool(json, args);
case rapidjson::kObjectType:
return make_from_object(json, args);
case rapidjson::kArrayType:
return make_from_array(json, args);
default: // wrong type
IR_FRMT_ERROR(
"Invalid jSON arguments passed while constructing tfidf scorer, arguments: %s",
args.c_str()
);
return nullptr;
}
}
tfidf_sort::tfidf_sort(bool normalize)
: sort(tfidf_sort::type()),
normalize_(normalize) {
}
sort::prepared::ptr tfidf_sort::prepare() const {
return tfidf::sort::make<tfidf::sort>(normalize_);
}
NS_END // ROOT
// -----------------------------------------------------------------------------
// --SECTION-- END-OF-FILE
// -----------------------------------------------------------------------------
| 25.371681 | 126 | 0.633531 | specimen151 |
913bcf95fe6d859ca7bb360d1e04594ce7e4686f | 3,234 | cpp | C++ | src/widgets/updater.cpp | Kor-Hal/SisterRay | 4e8482525a5d7f77dee186f438ddb16523a61e7e | [
"BSD-3-Clause"
] | null | null | null | src/widgets/updater.cpp | Kor-Hal/SisterRay | 4e8482525a5d7f77dee186f438ddb16523a61e7e | [
"BSD-3-Clause"
] | null | null | null | src/widgets/updater.cpp | Kor-Hal/SisterRay | 4e8482525a5d7f77dee186f438ddb16523a61e7e | [
"BSD-3-Clause"
] | null | null | null | #include "updaters.h"
#include "../impl.h"
#include "../inventories/inventory_utils.h"
#include "../menus/battle_menu/battle_menu_utils.h"
void battleSpellNameViewUpdater(CollectionWidget* self, Widget* widget, u16 flatIndex) {
if (self->collectionType != GridWidgetClass()) {
return;
}
auto typedPtr = (CursorGridWidget*)self;
auto magics = getSrPartyMember(*BATTLE_ACTIVE_ACTOR_ID).srPartyMember->actorMagics;
if (magics[flatIndex].magicIndex == 0xFF) {
disableWidget(getChild(widget, std::string("ARW")));
disableWidget(getChild(widget, std::string("TXT")));
return;
}
enableWidget(getChild(widget, std::string("TXT")));
updateText(getChild(widget, std::string("TXT")), getCommandAction(CMD_MAGIC, magics[flatIndex].magicIndex).attackName.str());
updateTextColor(widget, COLOR_WHITE);
if (magics[flatIndex].allCount) {
enableWidget(getChild(widget, std::string("ARW")));
return;
}
disableWidget(getChild(widget, std::string("ARW")));
}
void battleSummonNameViewUpdater(CollectionWidget* self, Widget* widget, u16 flatIndex) {
if (self->collectionType != GridWidgetClass()) {
return;
}
auto typedPtr = (CursorGridWidget*)self;
auto summons = getSrPartyMember(*BATTLE_ACTIVE_ACTOR_ID).srPartyMember->actorSummons;
if (summons[flatIndex].magicIndex == 0xFF) {
disableWidget(getChild(widget, std::string("TXT")));
return;
}
enableWidget(getChild(widget, std::string("TXT")));
updateText(getChild(widget, std::string("TXT")), getCommandAction(CMD_SUMMON, summons[flatIndex].magicIndex).attackName.str());
updateTextColor(getChild(widget, std::string("TXT")), COLOR_WHITE);
}
void battleEskillNameViewUpdater(CollectionWidget* self, Widget* widget, u16 flatIndex) {
if (self->collectionType != GridWidgetClass()) {
return;
}
auto typedPtr = (CursorGridWidget*)self;
auto eSkills = getSrPartyMember(*BATTLE_ACTIVE_ACTOR_ID).srPartyMember->actorEnemySkills;
if (eSkills[flatIndex].magicIndex == 0xFF) {
disableWidget(widget);
return;
}
enableWidget(widget);
updateText(widget, getCommandAction(CMD_ENEMY_SKILL, eSkills[flatIndex].magicIndex).attackName.str());
updateTextColor(widget, COLOR_WHITE);
}
void battleInventoryRowUpdater(CollectionWidget* self, Widget* widget, u16 flatIndex) {
if (self->collectionType != GridWidgetClass()) {
return;
}
auto typedPtr = (CursorGridWidget*)self;
auto itemID = gContext.battleInventory->getResource(flatIndex).item_id;
if (itemID == 0xFFFF) {
disableWidget(widget);
return;
}
enableWidget(widget);
auto textColor = (isUsableInBattle(itemID)) ? COLOR_WHITE : COLOR_GRAY;
updateText(getChild(widget, std::string("TXT")), getNameFromItemID(itemID));
updateTextColor(getChild(widget, std::string("TXT")), textColor);
updateNumber(getChild(widget, std::string("AMT")), gContext.battleInventory->getResource(itemID).quantity);
updateNumberColor(getChild(widget, std::string("AMT")), textColor);
updateItemIcon(getChild(widget, std::string("ICN")), gContext.itemTypeData.getResource(itemID).itemIconType);
}
| 43.12 | 131 | 0.704391 | Kor-Hal |
913d013dea1393db53086d40db4c61179695401c | 2,314 | hh | C++ | include/G4NRFPtrLevelVector.hh | jvavrek/NIMB2018 | 0aaf4143db2194b9f95002c681e4f860c8c76f7a | [
"MIT"
] | 4 | 2020-06-28T02:18:53.000Z | 2022-01-17T07:54:31.000Z | include/G4NRFPtrLevelVector.hh | jvavrek/NIMB2018 | 0aaf4143db2194b9f95002c681e4f860c8c76f7a | [
"MIT"
] | 3 | 2018-08-16T18:49:53.000Z | 2020-10-19T18:04:25.000Z | include/G4NRFPtrLevelVector.hh | jvavrek/NIMB2018 | 0aaf4143db2194b9f95002c681e4f860c8c76f7a | [
"MIT"
] | null | null | null | //
// ********************************************************************
// * License and Disclaimer *
// * *
// * The Geant4 software is copyright of the Copyright Holders of *
// * the Geant4 Collaboration. It is provided under the terms and *
// * conditions of the Geant4 Software License, included in the file *
// * LICENSE and available at http://cern.ch/geant4/license . These *
// * include a list of copyright holders. *
// * *
// * Neither the authors of this software system, nor their employing *
// * institutes,nor the agencies providing financial support for this *
// * work make any representation or warranty, express or implied, *
// * regarding this software system or assume any liability for its *
// * use. Please see the license in the file LICENSE and URL above *
// * for the full disclaimer and the limitation of liability. *
// * *
// * This code implementation is the result of the scientific and *
// * technical work of the GEANT4 collaboration. *
// * By using, copying, modifying or distributing the software (or *
// * any work based on the software) you agree to acknowledge its *
// * use in resulting scientific publications, and indicate your *
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
//
// -------------------------------------------------------------------
// GEANT 4 class file
//
// CERN, Geneva, Switzerland
//
// File name: G4PtrLevelVector
//
// Author: Maria Grazia Pia (pia@genova.infn.it)
//
// Creation date: 25 October 1998
//
// Modifications:
//
// -------------------------------------------------------------------
#ifndef G4NRFPTRLEVELVECTOR_HH
#define G4NRFPTRLEVELVECTOR_HH
#include <vector>
#include "G4NRFNuclearLevel.hh"
typedef std::vector<G4NRFNuclearLevel *> G4NRFPtrLevelVector;
struct DeleteLevel { void operator () (G4NRFNuclearLevel * aL) {delete aL;} };
#endif
| 43.660377 | 78 | 0.513397 | jvavrek |
913f225bc3f4b445f01494fe4359be3f599d914c | 599 | cpp | C++ | tools/pngbb.cpp | hemantasapkota/lotech | 46598a7c37dfd7cd424e2426564cc32533e1cfd6 | [
"curl"
] | 9 | 2015-06-28T05:47:33.000Z | 2021-06-29T13:35:48.000Z | tools/pngbb.cpp | hemantasapkota/lotech | 46598a7c37dfd7cd424e2426564cc32533e1cfd6 | [
"curl"
] | 5 | 2015-01-10T02:56:53.000Z | 2018-07-27T03:21:14.000Z | tools/pngbb.cpp | hemantasapkota/lotech | 46598a7c37dfd7cd424e2426564cc32533e1cfd6 | [
"curl"
] | 3 | 2015-04-01T14:48:54.000Z | 2015-11-12T11:52:50.000Z | /*
* ./pngbb in.png out.png.
* Reads in.png and generates out.png which contains only the pixels
* in the bounding box of in.png, along with a private chunk containing the
* bounding box information (see ltWriteImage function).
*/
#include "lt.h"
int main(int argc, const char *argv[]) {
if (argc != 3) {
fprintf(stderr, "Usage error: expecting exactly 2 args.\n");
exit(1);
}
LTImageBuffer *buf = ltReadImage(argv[1], "pngbb");
if (buf != NULL) {
ltWriteImage(argv[2], buf);
delete buf;
return 0;
} else {
return 1;
}
}
| 26.043478 | 75 | 0.601002 | hemantasapkota |
913f388667592a7e9f49251a51ecf2b6fb935086 | 1,568 | cpp | C++ | hybridinheritance.cpp | PRASAD-DANGARE/CPP | bf5ba5f87a229d88152fef80cb6a4d73bf578815 | [
"MIT"
] | null | null | null | hybridinheritance.cpp | PRASAD-DANGARE/CPP | bf5ba5f87a229d88152fef80cb6a4d73bf578815 | [
"MIT"
] | null | null | null | hybridinheritance.cpp | PRASAD-DANGARE/CPP | bf5ba5f87a229d88152fef80cb6a4d73bf578815 | [
"MIT"
] | null | null | null | /*
Description : Hybrid Inheritance
Function Date : 1 Dec 2020
Function Author : Prasad Dangare
Input : Integer
*/
#include <iostream>
using namespace std;
class student
{
protected:
int roll_number;
public:
void get_number(int a)
{
roll_number = a;
}
void put_number(void)
{
cout << "Roll Number : " << roll_number << "\n";
}
};
class test : public student
{
protected:
float part1, part2;
public:
void get_marks(float x, float y)
{
part1 = x, part2 = y;
}
void put_marks(void)
{
cout << "Marks Obtained : " << "\n";
cout << "Part1 = " << part1 << "\n";
cout << "Part2 = " << part2 << "\n";
}
};
class sports
{
protected:
float score;
public:
void get_score(float s)
{
score = s;
}
void put_score(void)
{
cout << "Sports wt : " << score << "\n\n";
}
};
class result : public test, public sports
{
float total;
public:
void display(void);
};
void result :: display(void)
{
total = part1 + part2 + score;
put_number();
put_marks();
put_score();
cout << "Total Score : " << total << "\n";
}
int main()
{
result student_1;
student_1.get_number(1234);
student_1.get_marks(27.5, 33.0);
student_1.get_score(6.0);
student_1.display();
return 0;
} | 17.422222 | 59 | 0.478316 | PRASAD-DANGARE |
913fd0228ee7e7f5e6a0caf4929b975cf235d293 | 2,726 | cpp | C++ | lib/lib_info.cpp | GreyMerlin/owl_cpp | ccc6128dbd08dcf7fcbe6679ec6acd714732bbb6 | [
"BSL-1.0"
] | 10 | 2017-12-21T05:20:40.000Z | 2021-09-18T05:14:01.000Z | lib/lib_info.cpp | GreyMerlin/owl_cpp | ccc6128dbd08dcf7fcbe6679ec6acd714732bbb6 | [
"BSL-1.0"
] | 2 | 2017-12-21T07:31:54.000Z | 2021-06-23T08:52:35.000Z | lib/lib_info.cpp | GreyMerlin/owl_cpp | ccc6128dbd08dcf7fcbe6679ec6acd714732bbb6 | [
"BSL-1.0"
] | 7 | 2016-02-17T13:20:31.000Z | 2021-11-08T09:30:43.000Z | /** @file "/owlcpp/lib/lib_info.cpp"
part of owlcpp project.
@n @n Distributed under the Boost Software License, Version 1.0; see doc/license.txt.
@n Copyright Mikhail K Levin 2012
*******************************************************************************/
#ifndef OWLCPP_SOURCE
#define OWLCPP_SOURCE
#endif
#include <sstream>
#include "owlcpp/lib_info.hpp"
#include "boost/preprocessor/stringize.hpp"
#ifndef OWLCPP_NAME
#define OWLCPP_NAME owlcpp
#endif
#ifndef OWLCPP_DESCRIPTION
#define OWLCPP_DESCRIPTION
#endif
#ifndef OWLCPP_VERSION_1
#define OWLCPP_VERSION_1 0
#endif
#ifndef OWLCPP_VERSION_2
#define OWLCPP_VERSION_2 0
#endif
#ifndef OWLCPP_VERSION_3
#define OWLCPP_VERSION_3 0
#endif
#ifndef OWLCPP_VERSION_EXTRA
#define OWLCPP_VERSION_EXTRA ???
#endif
#ifndef OWLCPP_VERSION_DIRTY
#define OWLCPP_VERSION_DIRTY 0
#endif
#ifndef OWLCPP_BUILD
#define OWLCPP_BUILD 0
#endif
namespace owlcpp { namespace{
std::string make_version_str() {
std::ostringstream str;
str
<< 'v' << OWLCPP_VERSION_1 << '.'
<< OWLCPP_VERSION_2 << '.' << OWLCPP_VERSION_3
;
const std::string e = std::string(BOOST_PP_STRINGIZE(OWLCPP_VERSION_EXTRA));
if( ! e.empty() ) str << '-' << e;
if( OWLCPP_VERSION_DIRTY ) str << '~';
return str.str();
}
}//namespace anonymous
/*
*******************************************************************************/
std::string const& Lib_info::name() {
static const std::string s = std::string(BOOST_PP_STRINGIZE(OWLCPP_NAME));
return s;
}
/*
*******************************************************************************/
std::string const& Lib_info::version() {
static const std::string s = make_version_str();
return s;
}
/*
*******************************************************************************/
std::string const& Lib_info::description() {
static const std::string s = std::string(BOOST_PP_STRINGIZE(OWLCPP_DESCRIPTION));
return s;
}
/*
*******************************************************************************/
int Lib_info::version_1() {return OWLCPP_VERSION_1;}
/*
*******************************************************************************/
int Lib_info::version_2() {return OWLCPP_VERSION_2;}
/*
*******************************************************************************/
int Lib_info::version_3() {return OWLCPP_VERSION_3;}
/*
*******************************************************************************/
std::string const& Lib_info::version_e() {
static const std::string s = std::string(BOOST_PP_STRINGIZE(OWLCPP_VERSION_EXTRA));
return s;
}
/*
*******************************************************************************/
int Lib_info::build() {return OWLCPP_BUILD;}
}//namespace owlcpp
| 25.961905 | 86 | 0.535216 | GreyMerlin |
91439ce4efbfbc3dd757cc7d00ea7d088f63defe | 870 | cpp | C++ | src/source/uselibhoard.cpp | dark0z/Hoard | 5afe855606e60ba255915d5cd816474815fc8844 | [
"ECL-2.0",
"Apache-2.0"
] | 827 | 2015-01-13T20:39:45.000Z | 2022-03-29T06:31:59.000Z | src/source/uselibhoard.cpp | dark0z/Hoard | 5afe855606e60ba255915d5cd816474815fc8844 | [
"ECL-2.0",
"Apache-2.0"
] | 41 | 2015-01-25T21:37:58.000Z | 2022-03-15T09:10:24.000Z | src/source/uselibhoard.cpp | dark0z/Hoard | 5afe855606e60ba255915d5cd816474815fc8844 | [
"ECL-2.0",
"Apache-2.0"
] | 107 | 2015-01-19T20:41:53.000Z | 2022-01-25T16:30:38.000Z | /* -*- C++ -*- */
/*
The Hoard Multiprocessor Memory Allocator
www.hoard.org
Author: Emery Berger, http://www.emeryberger.com
Copyright (c) 1998-2020 Emery Berger
See the LICENSE file at the top-level directory of this
distribution and at http://github.com/emeryberger/Hoard.
*/
// Link this code with your executable to use winhoard.
#if defined(_WIN32)
#include <windows.h>
//#include <iostream>
#if defined(_WIN64)
#pragma comment(linker, "/include:ReferenceHoard")
#else
#pragma comment(linker, "/include:_ReferenceHoard")
#endif
extern "C" {
__declspec(dllimport) int ReferenceWinWrapperStub;
void ReferenceHoard()
{
LoadLibraryA ("libhoard.dll");
#if 0
if (lib == NULL) {
std::cerr << "Startup error code = " << GetLastError() << std::endl;
abort();
}
#endif
ReferenceWinWrapperStub = 1;
}
}
#endif
| 18.125 | 74 | 0.673563 | dark0z |
91448f8d861a041abef6512b3b7e73904dcffd9a | 3,860 | cc | C++ | modules/audio_processing/agc2/vad_wrapper.cc | wyshen2020/webrtc | b93e2240f1653b82e24553e092bbab84337774af | [
"BSD-3-Clause"
] | 27 | 2020-04-06T09:52:44.000Z | 2022-03-17T19:07:12.000Z | modules/audio_processing/agc2/vad_wrapper.cc | wyshen2020/webrtc | b93e2240f1653b82e24553e092bbab84337774af | [
"BSD-3-Clause"
] | 1 | 2021-12-02T02:45:34.000Z | 2021-12-02T03:12:02.000Z | modules/audio_processing/agc2/vad_wrapper.cc | wyshen2020/webrtc | b93e2240f1653b82e24553e092bbab84337774af | [
"BSD-3-Clause"
] | 13 | 2020-05-06T01:47:27.000Z | 2022-02-02T21:47:28.000Z | /*
* Copyright (c) 2018 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "modules/audio_processing/agc2/vad_wrapper.h"
#include <array>
#include <utility>
#include "api/array_view.h"
#include "common_audio/resampler/include/push_resampler.h"
#include "modules/audio_processing/agc2/agc2_common.h"
#include "modules/audio_processing/agc2/rnn_vad/common.h"
#include "modules/audio_processing/agc2/rnn_vad/features_extraction.h"
#include "modules/audio_processing/agc2/rnn_vad/rnn.h"
#include "rtc_base/checks.h"
namespace webrtc {
namespace {
constexpr int kNumFramesPerSecond = 100;
class MonoVadImpl : public VoiceActivityDetectorWrapper::MonoVad {
public:
explicit MonoVadImpl(const AvailableCpuFeatures& cpu_features)
: features_extractor_(cpu_features), rnn_vad_(cpu_features) {}
MonoVadImpl(const MonoVadImpl&) = delete;
MonoVadImpl& operator=(const MonoVadImpl&) = delete;
~MonoVadImpl() = default;
int SampleRateHz() const override { return rnn_vad::kSampleRate24kHz; }
void Reset() override { rnn_vad_.Reset(); }
float Analyze(rtc::ArrayView<const float> frame) override {
RTC_DCHECK_EQ(frame.size(), rnn_vad::kFrameSize10ms24kHz);
std::array<float, rnn_vad::kFeatureVectorSize> feature_vector;
const bool is_silence = features_extractor_.CheckSilenceComputeFeatures(
/*samples=*/{frame.data(), rnn_vad::kFrameSize10ms24kHz},
feature_vector);
return rnn_vad_.ComputeVadProbability(feature_vector, is_silence);
}
private:
rnn_vad::FeaturesExtractor features_extractor_;
rnn_vad::RnnVad rnn_vad_;
};
} // namespace
VoiceActivityDetectorWrapper::VoiceActivityDetectorWrapper(
int vad_reset_period_ms,
const AvailableCpuFeatures& cpu_features,
int sample_rate_hz)
: VoiceActivityDetectorWrapper(vad_reset_period_ms,
std::make_unique<MonoVadImpl>(cpu_features),
sample_rate_hz) {}
VoiceActivityDetectorWrapper::VoiceActivityDetectorWrapper(
int vad_reset_period_ms,
std::unique_ptr<MonoVad> vad,
int sample_rate_hz)
: vad_reset_period_frames_(
rtc::CheckedDivExact(vad_reset_period_ms, kFrameDurationMs)),
time_to_vad_reset_(vad_reset_period_frames_),
vad_(std::move(vad)) {
RTC_DCHECK(vad_);
RTC_DCHECK_GT(vad_reset_period_frames_, 1);
resampled_buffer_.resize(
rtc::CheckedDivExact(vad_->SampleRateHz(), kNumFramesPerSecond));
Initialize(sample_rate_hz);
}
VoiceActivityDetectorWrapper::~VoiceActivityDetectorWrapper() = default;
void VoiceActivityDetectorWrapper::Initialize(int sample_rate_hz) {
RTC_DCHECK_GT(sample_rate_hz, 0);
frame_size_ = rtc::CheckedDivExact(sample_rate_hz, kNumFramesPerSecond);
int status =
resampler_.InitializeIfNeeded(sample_rate_hz, vad_->SampleRateHz(),
/*num_channels=*/1);
constexpr int kStatusOk = 0;
RTC_DCHECK_EQ(status, kStatusOk);
vad_->Reset();
}
float VoiceActivityDetectorWrapper::Analyze(AudioFrameView<const float> frame) {
// Periodically reset the VAD.
time_to_vad_reset_--;
if (time_to_vad_reset_ <= 0) {
vad_->Reset();
time_to_vad_reset_ = vad_reset_period_frames_;
}
// Resample the first channel of `frame`.
RTC_DCHECK_EQ(frame.samples_per_channel(), frame_size_);
resampler_.Resample(frame.channel(0).data(), frame_size_,
resampled_buffer_.data(), resampled_buffer_.size());
return vad_->Analyze(resampled_buffer_);
}
} // namespace webrtc
| 36.074766 | 80 | 0.74171 | wyshen2020 |
9144a4b4925780bf0db15600aae9e2f643a63e8b | 9,459 | cpp | C++ | Code/Libraries/Core/src/windowwrapper.cpp | kas1e/Eldritch | 032b4ac52f7508c89efa407d6fe60f40c6281fd9 | [
"Zlib"
] | null | null | null | Code/Libraries/Core/src/windowwrapper.cpp | kas1e/Eldritch | 032b4ac52f7508c89efa407d6fe60f40c6281fd9 | [
"Zlib"
] | null | null | null | Code/Libraries/Core/src/windowwrapper.cpp | kas1e/Eldritch | 032b4ac52f7508c89efa407d6fe60f40c6281fd9 | [
"Zlib"
] | null | null | null | #include "core.h"
#include "windowwrapper.h"
#include "mathcore.h"
#if BUILD_WINDOWS_NO_SDL
#include <Windows.h>
#endif
#include <stdio.h>
#include <proto/dos.h>
#if BUILD_SDL
#ifdef PANDORA
#include <SDL2/SDL.h>
#else
#include "SDL2/SDL.h"
#endif
#endif
#include <memory.h>
Window::Window()
#if BUILD_WINDOWS_NO_SDL
: m_hWnd(NULL),
m_hDC(NULL),
m_hInstance(NULL),
m_WndClassEx(),
m_Style(0)
#endif
#if BUILD_SDL
: m_Window(nullptr)
#endif
,
m_Inited(false) {
#if BUILD_WINDOWS_NO_SDL
memset(&m_WndClassEx, 0, sizeof(WNDCLASSEX));
#endif
}
Window::~Window() {
if (m_Inited) {
Free();
}
}
#if BUILD_WINDOWS_NO_SDL
// TODO: Add some failure handling, and meaningful return values
int Window::Init(const char* Title, const char* ClassName, DWORD Style,
DWORD ExStyle, int Width, int Height, HINSTANCE hInstance,
WNDPROC WndProc /*= NULL*/, uint Icon /*= 0*/,
int ScreenWidth /*= 0*/, int ScreenHeight /*= 0*/) {
XTRACE_FUNCTION;
if (m_Inited) {
return 1;
}
m_hInstance = hInstance;
m_Style = Style;
m_WndClassEx.cbSize = sizeof(WNDCLASSEX);
m_WndClassEx.style = CS_HREDRAW | CS_VREDRAW;
m_WndClassEx.lpfnWndProc = (WndProc != NULL) ? WndProc : DefWindowProc;
m_WndClassEx.hInstance = hInstance;
m_WndClassEx.hIcon =
(Icon == 0 ? NULL : LoadIcon(hInstance, MAKEINTRESOURCE(Icon)));
m_WndClassEx.hCursor = (HCURSOR)LoadImage(NULL, MAKEINTRESOURCE(IDC_ARROW),
IMAGE_CURSOR, 0, 0, LR_SHARED);
m_WndClassEx.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
m_WndClassEx.lpszMenuName = NULL;
m_WndClassEx.lpszClassName = ClassName;
m_WndClassEx.hIconSm = NULL;
RegisterClassEx(&m_WndClassEx);
// Adjust dimensions to accommodate borders
RECT WindowRect;
WindowRect.left = 0;
WindowRect.right = Width;
WindowRect.top = 0;
WindowRect.bottom = Height;
AdjustWindowRect(&WindowRect, Style, false);
int AdjustedWidth = WindowRect.right - WindowRect.left;
int AdjustedHeight = WindowRect.bottom - WindowRect.top;
// Center window, or just position in top-left if it won't fit
const int WindowX = Max(0, (ScreenWidth - AdjustedWidth) >> 1);
const int WindowY = Max(0, (ScreenHeight - AdjustedHeight) >> 1);
// Let calling code know what the window will look like.
// We don't have an hWnd yet, but we can call the WindowProc directly.
if (WndProc) {
POINT NotifySize;
NotifySize.x = AdjustedWidth;
NotifySize.y = AdjustedHeight;
WPARAM wParam = 0;
LPARAM lParam = reinterpret_cast<LPARAM>(&NotifySize);
WndProc(0, WM_NOTIFY_SIZE, wParam, lParam);
}
m_hWnd = CreateWindowEx(ExStyle, ClassName, Title, Style, WindowX, WindowY,
AdjustedWidth, AdjustedHeight, NULL, NULL,
m_hInstance, NULL);
ASSERT(m_hWnd);
#if BUILD_DEV
GetWindowRect(m_hWnd, &WindowRect);
ASSERT(WindowRect.right - WindowRect.left == AdjustedWidth);
ASSERT(WindowRect.bottom - WindowRect.top == AdjustedHeight);
#endif
m_hDC = GetDC(m_hWnd);
m_Inited = true;
return 0;
}
#endif
#if BUILD_SDL
int Window::Init(const char* Title, uint Flags, int Width, int Height) {
XTRACE_FUNCTION;
if (m_Inited) {
return 1;
}
m_Window = SDL_CreateWindow(Title, SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED, Width, Height, Flags);
ASSERT(m_Window);
m_Inited = true;
return 0;
}
#endif
#if BUILD_WINDOWS_NO_SDL
// TODO: Add some failure handling, and meaningful return values
int Window::Show(int nCmdShow) {
ShowWindow(m_hWnd, nCmdShow);
SetWindowPos(m_hWnd, HWND_NOTOPMOST, 0, 0, 0, 0,
SWP_NOSIZE | SWP_NOMOVE); // Make sure we're on top
UpdateWindow(m_hWnd);
return 0;
}
// TODO: Add some failure handling, and meaningful return values
int Window::SetStyle(DWORD Style) {
if (m_Inited) {
m_Style = Style;
SetWindowLongPtr(m_hWnd, GWL_STYLE, Style);
ShowWindow(m_hWnd, SW_SHOWNA);
// UpdateWindow( m_hWnd );
// SetWindowPos( m_hWnd, 0, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE |
// SWP_NOZORDER | SWP_SHOWWINDOW );
}
return 0;
}
#endif
#if BUILD_SDL
int Window::Show() {
SDL_ShowWindow(m_Window);
return 0;
}
#endif
// TODO: Add some failure handling, and meaningful return values
int Window::Free() {
#if BUILD_WINDOWS_NO_SDL
char TempName[256];
GetClassName(m_hWnd, TempName, 256);
if (m_Inited) {
ReleaseDC(m_hWnd, m_hDC);
CHECK(DestroyWindow(m_hWnd));
CHECK(UnregisterClass(TempName, m_hInstance));
m_Inited = false;
return 0;
}
return 1;
#endif
#if BUILD_SDL
if (m_Window) {
SDL_DestroyWindow(m_Window);
m_Inited = false;
return 0;
} else {
return 1;
}
#endif
}
// TODO: Add some failure handling, and meaningful return values
int Window::SetPosition(int x, int y) {
if (m_Inited) {
#if BUILD_WINDOWS_NO_SDL
SetWindowPos(m_hWnd, HWND_NOTOPMOST, x, y, 0, 0, SWP_NOSIZE);
#endif
#if BUILD_SDL
SDL_SetWindowPosition(m_Window, x, y);
#endif
}
return 0;
}
// TODO: Add some failure handling, and meaningful return values
int Window::SetSize(int Width, int Height, bool AdjustForStyle) {
if (!m_Inited) {
return 0;
}
#if BUILD_WINDOWS_NO_SDL
RECT WindowRect;
WindowRect.left = 0;
WindowRect.right = Width;
WindowRect.top = 0;
WindowRect.bottom = Height;
if (AdjustForStyle) {
AdjustWindowRect(&WindowRect, m_Style, false);
Width = WindowRect.right - WindowRect.left;
Height = WindowRect.bottom - WindowRect.top;
}
{
POINT NotifySize;
NotifySize.x = Width;
NotifySize.y = Height;
WPARAM wParam = 0;
LPARAM lParam = reinterpret_cast<LPARAM>(&NotifySize);
SendMessage(m_hWnd, WM_NOTIFY_SIZE, wParam, lParam);
}
// NOTE: This is just to update the size, it does *not* position window at (0,
// 0) (SWP_NOMOVE flag).
const BOOL Success =
SetWindowPos(m_hWnd, HWND_NOTOPMOST, 0, 0, Width, Height, SWP_NOMOVE);
ASSERT(Success);
Unused(Success);
#if BUILD_DEV
GetWindowRect(m_hWnd, &WindowRect);
ASSERT(WindowRect.right - WindowRect.left == Width);
ASSERT(WindowRect.bottom - WindowRect.top == Height);
#endif
#endif // BUILD_WINDOWS_NO_SDL
#if BUILD_SDL
Unused(AdjustForStyle);
SDL_SetWindowSize(m_Window, Width, Height);
#endif
return 0;
}
int Window::SetSize(int Width, int Height, int ScreenWidth, int ScreenHeight,
bool AdjustForStyle) {
if (!m_Inited) {
return 0;
}
#if BUILD_WINDOWS_NO_SDL
RECT WindowRect;
WindowRect.left = 0;
WindowRect.right = Width;
WindowRect.top = 0;
WindowRect.bottom = Height;
if (AdjustForStyle) {
AdjustWindowRect(&WindowRect, m_Style, false);
Width = WindowRect.right - WindowRect.left;
Height = WindowRect.bottom - WindowRect.top;
}
// Center window, or just position in top-left if it won't fit
const int WindowX = Max(0, (ScreenWidth - Width) >> 1);
const int WindowY = Max(0, (ScreenHeight - Height) >> 1);
{
POINT NotifySize;
NotifySize.x = Width;
NotifySize.y = Height;
WPARAM wParam = 0;
LPARAM lParam = reinterpret_cast<LPARAM>(&NotifySize);
SendMessage(m_hWnd, WM_NOTIFY_SIZE, wParam, lParam);
}
const BOOL Success =
SetWindowPos(m_hWnd, HWND_NOTOPMOST, WindowX, WindowY, Width, Height, 0);
ASSERT(Success);
Unused(Success);
#if BUILD_DEV
GetWindowRect(m_hWnd, &WindowRect);
ASSERT(WindowRect.right - WindowRect.left == Width);
ASSERT(WindowRect.bottom - WindowRect.top == Height);
#endif
#endif // BUILD_WINDOWS_NO_SDL
#if BUILD_SDL
Unused(AdjustForStyle);
Unused(ScreenWidth);
Unused(ScreenHeight);
SDL_SetWindowSize(m_Window, Width, Height);
//IDOS->Delay(5);
SDL_SetWindowPosition(m_Window, SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED);
#endif
return 0;
}
// TODO: Add some failure handling, and meaningful return values
int Window::SetTitleText(const char* Text) {
if (m_Inited) {
#if BUILD_WINDOWS_NO_SDL
SetWindowText(m_hWnd, Text);
#endif
#if BUILD_SDL
SDL_SetWindowTitle(m_Window, Text);
#endif
}
return 0;
}
bool Window::HasFocus() const {
#if BUILD_WINDOWS_NO_SDL
return GetForegroundWindow() == m_hWnd;
#endif
#if BUILD_SDL
if (m_Inited) {
#ifdef PANDORA
// On Pandora, SDL2 use FB access, so no real Windows / multitask here...
return true;
#else
const Uint32 WindowFlags = SDL_GetWindowFlags(m_Window);
return (WindowFlags & SDL_WINDOW_INPUT_FOCUS) != 0;
#endif
} else {
return false;
}
#endif
}
void Window::SetBordered(const bool Bordered) {
#if BUILD_WINDOWS_NO_SDL
const DWORD StyleFlags =
Bordered ? (WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX)
: WS_POPUP;
SetStyle(StyleFlags);
#endif
#if BUILD_SDL
SDL_SetWindowBordered(m_Window, Bordered ? SDL_TRUE : SDL_FALSE);
#endif
}
// NOTE: Used with SDL in place of managing display directly.
void Window::SetFullscreen(const bool Fullscreen) {
#if BUILD_WINDOWS_NO_SDL
Unused(Fullscreen);
#endif
#if BUILD_SDL
// NOTE: SDL also has a SDL_WINDOW_FULLSCREEN_DESKTOP for borderless
// "fullscreen windowed" mode,
// but I assume that would be redundant with the stuff I'm already doing to
// update window border.
SDL_SetWindowDisplayMode(m_Window, nullptr);
SDL_SetWindowFullscreen(m_Window, Fullscreen ? SDL_WINDOW_FULLSCREEN : 0);
#endif
} | 25.291444 | 80 | 0.689608 | kas1e |
914518196f302582abd8095eec196d8abf8a98e8 | 14,001 | cpp | C++ | fuse_models/src/unicycle_2d_ignition.cpp | mcx/fuse | 3825e489ceaba394fb07c87e0e52dce9485da19b | [
"BSD-3-Clause"
] | 383 | 2018-07-02T07:20:32.000Z | 2022-03-31T12:51:06.000Z | fuse_models/src/unicycle_2d_ignition.cpp | mcx/fuse | 3825e489ceaba394fb07c87e0e52dce9485da19b | [
"BSD-3-Clause"
] | 117 | 2018-07-16T10:32:52.000Z | 2022-02-02T20:15:16.000Z | fuse_models/src/unicycle_2d_ignition.cpp | BrettRD/fuse | c8481b3b1eb01e855f341187b9f1f88d4d58acc2 | [
"BSD-3-Clause"
] | 74 | 2018-10-01T10:10:45.000Z | 2022-03-02T04:48:22.000Z | /*
* Software License Agreement (BSD License)
*
* Copyright (c) 2019, Locus Robotics
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the 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 <fuse_models/unicycle_2d_ignition.h>
#include <fuse_constraints/absolute_constraint.h>
#include <fuse_core/async_sensor_model.h>
#include <fuse_core/eigen.h>
#include <fuse_core/sensor_model.h>
#include <fuse_core/transaction.h>
#include <fuse_core/util.h>
#include <fuse_core/uuid.h>
#include <fuse_models/SetPose.h>
#include <fuse_models/SetPoseDeprecated.h>
#include <fuse_variables/acceleration_linear_2d_stamped.h>
#include <fuse_variables/orientation_2d_stamped.h>
#include <fuse_variables/position_2d_stamped.h>
#include <fuse_variables/velocity_angular_2d_stamped.h>
#include <fuse_variables/velocity_linear_2d_stamped.h>
#include <fuse_variables/stamped.h>
#include <geometry_msgs/PoseWithCovarianceStamped.h>
#include <pluginlib/class_list_macros.h>
#include <std_srvs/Empty.h>
#include <tf2/convert.h>
#include <tf2/LinearMath/Quaternion.h>
#include <tf2_geometry_msgs/tf2_geometry_msgs.h>
#include <Eigen/Dense>
#include <exception>
#include <stdexcept>
// Register this motion model with ROS as a plugin.
PLUGINLIB_EXPORT_CLASS(fuse_models::Unicycle2DIgnition, fuse_core::SensorModel);
namespace fuse_models
{
Unicycle2DIgnition::Unicycle2DIgnition() :
fuse_core::AsyncSensorModel(1),
started_(false),
initial_transaction_sent_(false),
device_id_(fuse_core::uuid::NIL)
{
}
void Unicycle2DIgnition::onInit()
{
// Read settings from the parameter sever
device_id_ = fuse_variables::loadDeviceId(private_node_handle_);
params_.loadFromROS(private_node_handle_);
// Connect to the reset service
if (!params_.reset_service.empty())
{
reset_client_ = node_handle_.serviceClient<std_srvs::Empty>(ros::names::resolve(params_.reset_service));
}
// Advertise
subscriber_ = node_handle_.subscribe(
ros::names::resolve(params_.topic),
params_.queue_size,
&Unicycle2DIgnition::subscriberCallback,
this);
set_pose_service_ = node_handle_.advertiseService(
ros::names::resolve(params_.set_pose_service),
&Unicycle2DIgnition::setPoseServiceCallback,
this);
set_pose_deprecated_service_ = node_handle_.advertiseService(
ros::names::resolve(params_.set_pose_deprecated_service),
&Unicycle2DIgnition::setPoseDeprecatedServiceCallback,
this);
}
void Unicycle2DIgnition::start()
{
started_ = true;
// TODO(swilliams) Should this be executed every time optimizer.reset() is called, or only once ever?
// I feel like it should be "only once ever".
// Send an initial state transaction immediately, if requested
if (params_.publish_on_startup && !initial_transaction_sent_)
{
auto pose = geometry_msgs::PoseWithCovarianceStamped();
pose.header.stamp = ros::Time::now();
pose.pose.pose.position.x = params_.initial_state[0];
pose.pose.pose.position.y = params_.initial_state[1];
pose.pose.pose.orientation = tf2::toMsg(tf2::Quaternion(tf2::Vector3(0.0, 0.0, 1.0), params_.initial_state[2]));
pose.pose.covariance[0] = params_.initial_sigma[0] * params_.initial_sigma[0];
pose.pose.covariance[7] = params_.initial_sigma[1] * params_.initial_sigma[1];
pose.pose.covariance[35] = params_.initial_sigma[2] * params_.initial_sigma[2];
sendPrior(pose);
initial_transaction_sent_ = true;
}
}
void Unicycle2DIgnition::stop()
{
started_ = false;
}
void Unicycle2DIgnition::subscriberCallback(const geometry_msgs::PoseWithCovarianceStamped::ConstPtr& msg)
{
try
{
process(*msg);
}
catch (const std::exception& e)
{
ROS_ERROR_STREAM(e.what() << " Ignoring message.");
}
}
bool Unicycle2DIgnition::setPoseServiceCallback(fuse_models::SetPose::Request& req, fuse_models::SetPose::Response& res)
{
try
{
process(req.pose);
res.success = true;
}
catch (const std::exception& e)
{
res.success = false;
res.message = e.what();
ROS_ERROR_STREAM(e.what() << " Ignoring request.");
}
return true;
}
bool Unicycle2DIgnition::setPoseDeprecatedServiceCallback(
fuse_models::SetPoseDeprecated::Request& req,
fuse_models::SetPoseDeprecated::Response&)
{
try
{
process(req.pose);
return true;
}
catch (const std::exception& e)
{
ROS_ERROR_STREAM(e.what() << " Ignoring request.");
return false;
}
}
void Unicycle2DIgnition::process(const geometry_msgs::PoseWithCovarianceStamped& pose)
{
// Verify we are in the correct state to process set pose requests
if (!started_)
{
throw std::runtime_error("Attempting to set the pose while the sensor is stopped.");
}
// Validate the requested pose and covariance before we do anything
if (!std::isfinite(pose.pose.pose.position.x) || !std::isfinite(pose.pose.pose.position.y))
{
throw std::invalid_argument("Attempting to set the pose to an invalid position (" +
std::to_string(pose.pose.pose.position.x) + ", " +
std::to_string(pose.pose.pose.position.y) + ").");
}
auto orientation_norm = std::sqrt(pose.pose.pose.orientation.x * pose.pose.pose.orientation.x +
pose.pose.pose.orientation.y * pose.pose.pose.orientation.y +
pose.pose.pose.orientation.z * pose.pose.pose.orientation.z +
pose.pose.pose.orientation.w * pose.pose.pose.orientation.w);
if (std::abs(orientation_norm - 1.0) > 1.0e-3)
{
throw std::invalid_argument("Attempting to set the pose to an invalid orientation (" +
std::to_string(pose.pose.pose.orientation.x) + ", " +
std::to_string(pose.pose.pose.orientation.y) + ", " +
std::to_string(pose.pose.pose.orientation.z) + ", " +
std::to_string(pose.pose.pose.orientation.w) + ").");
}
auto position_cov = fuse_core::Matrix2d();
position_cov << pose.pose.covariance[0], pose.pose.covariance[1],
pose.pose.covariance[6], pose.pose.covariance[7];
if (!fuse_core::isSymmetric(position_cov))
{
throw std::invalid_argument("Attempting to set the pose with a non-symmetric position covariance matri\n " +
fuse_core::to_string(position_cov, Eigen::FullPrecision) + ".");
}
if (!fuse_core::isPositiveDefinite(position_cov))
{
throw std::invalid_argument("Attempting to set the pose with a non-positive-definite position covariance matrix\n" +
fuse_core::to_string(position_cov, Eigen::FullPrecision) + ".");
}
auto orientation_cov = fuse_core::Matrix1d();
orientation_cov << pose.pose.covariance[35];
if (orientation_cov(0) <= 0.0)
{
throw std::invalid_argument("Attempting to set the pose with a non-positive-definite orientation covariance "
"matrix " + fuse_core::to_string(orientation_cov) + ".");
}
// Tell the optimizer to reset before providing the initial state
if (!params_.reset_service.empty())
{
// Wait for the reset service
while (!reset_client_.waitForExistence(ros::Duration(10.0)) && ros::ok())
{
ROS_WARN_STREAM("Waiting for '" << reset_client_.getService() << "' service to become avaiable.");
}
auto srv = std_srvs::Empty();
if (!reset_client_.call(srv))
{
// The reset() service failed. Propagate that failure to the caller of this service.
throw std::runtime_error("Failed to call the '" + reset_client_.getService() + "' service.");
}
}
// Now that the pose has been validated and the optimizer has been reset, actually send the initial state constraints
// to the optimizer
sendPrior(pose);
}
void Unicycle2DIgnition::sendPrior(const geometry_msgs::PoseWithCovarianceStamped& pose)
{
const auto& stamp = pose.header.stamp;
// Create variables for the full state.
// The initial values of the pose are extracted from the provided PoseWithCovarianceStamped message.
// The remaining dimensions are provided as parameters to the parameter server.
auto position = fuse_variables::Position2DStamped::make_shared(stamp, device_id_);
position->x() = pose.pose.pose.position.x;
position->y() = pose.pose.pose.position.y;
auto orientation = fuse_variables::Orientation2DStamped::make_shared(stamp, device_id_);
orientation->yaw() = fuse_core::getYaw(pose.pose.pose.orientation.w,
pose.pose.pose.orientation.x,
pose.pose.pose.orientation.y,
pose.pose.pose.orientation.z);
auto linear_velocity = fuse_variables::VelocityLinear2DStamped::make_shared(stamp, device_id_);
linear_velocity->x() = params_.initial_state[3];
linear_velocity->y() = params_.initial_state[4];
auto angular_velocity = fuse_variables::VelocityAngular2DStamped::make_shared(stamp, device_id_);
angular_velocity->yaw() = params_.initial_state[5];
auto linear_acceleration = fuse_variables::AccelerationLinear2DStamped::make_shared(stamp, device_id_);
linear_acceleration->x() = params_.initial_state[6];
linear_acceleration->y() = params_.initial_state[7];
// Create the covariances for each variable
// The pose covariances are extracted from the provided PoseWithCovarianceStamped message.
// The remaining covariances are provided as parameters to the parameter server.
auto position_cov = fuse_core::Matrix2d();
position_cov << pose.pose.covariance[0], pose.pose.covariance[1],
pose.pose.covariance[6], pose.pose.covariance[7];
auto orientation_cov = fuse_core::Matrix1d();
orientation_cov << pose.pose.covariance[35];
auto linear_velocity_cov = fuse_core::Matrix2d();
linear_velocity_cov << params_.initial_sigma[3] * params_.initial_sigma[3], 0.0,
0.0, params_.initial_sigma[4] * params_.initial_sigma[4];
auto angular_velocity_cov = fuse_core::Matrix1d();
angular_velocity_cov << params_.initial_sigma[5] * params_.initial_sigma[5];
auto linear_acceleration_cov = fuse_core::Matrix2d();
linear_acceleration_cov << params_.initial_sigma[6] * params_.initial_sigma[6], 0.0,
0.0, params_.initial_sigma[7] * params_.initial_sigma[7];
// Create absolute constraints for each variable
auto position_constraint = fuse_constraints::AbsolutePosition2DStampedConstraint::make_shared(
name(),
*position,
fuse_core::Vector2d(position->x(), position->y()),
position_cov);
auto orientation_constraint = fuse_constraints::AbsoluteOrientation2DStampedConstraint::make_shared(
name(),
*orientation,
fuse_core::Vector1d(orientation->yaw()),
orientation_cov);
auto linear_velocity_constraint = fuse_constraints::AbsoluteVelocityLinear2DStampedConstraint::make_shared(
name(),
*linear_velocity,
fuse_core::Vector2d(linear_velocity->x(), linear_velocity->y()),
linear_velocity_cov);
auto angular_velocity_constraint = fuse_constraints::AbsoluteVelocityAngular2DStampedConstraint::make_shared(
name(),
*angular_velocity,
fuse_core::Vector1d(angular_velocity->yaw()),
angular_velocity_cov);
auto linear_acceleration_constraint = fuse_constraints::AbsoluteAccelerationLinear2DStampedConstraint::make_shared(
name(),
*linear_acceleration,
fuse_core::Vector2d(linear_acceleration->x(), linear_acceleration->y()),
linear_acceleration_cov);
// Create the transaction
auto transaction = fuse_core::Transaction::make_shared();
transaction->stamp(stamp);
transaction->addInvolvedStamp(stamp);
transaction->addVariable(position);
transaction->addVariable(orientation);
transaction->addVariable(linear_velocity);
transaction->addVariable(angular_velocity);
transaction->addVariable(linear_acceleration);
transaction->addConstraint(position_constraint);
transaction->addConstraint(orientation_constraint);
transaction->addConstraint(linear_velocity_constraint);
transaction->addConstraint(angular_velocity_constraint);
transaction->addConstraint(linear_acceleration_constraint);
// Send the transaction to the optimizer.
sendTransaction(transaction);
ROS_INFO_STREAM("Received a set_pose request (stamp: " << stamp << ", x: " << position->x() << ", y: " <<
position->y() << ", yaw: " << orientation->yaw() << ")");
}
} // namespace fuse_models
| 41.300885 | 120 | 0.712378 | mcx |
9146a6435da748c123403e1fd07e70e49f009f12 | 10,034 | hpp | C++ | openstudiocore/src/openstudio_lib/OSDocument.hpp | Acidburn0zzz/OpenStudio | 8d7aa85fe5df7987cb6983984d4ce8698f1bd0bd | [
"MIT"
] | null | null | null | openstudiocore/src/openstudio_lib/OSDocument.hpp | Acidburn0zzz/OpenStudio | 8d7aa85fe5df7987cb6983984d4ce8698f1bd0bd | [
"MIT"
] | null | null | null | openstudiocore/src/openstudio_lib/OSDocument.hpp | Acidburn0zzz/OpenStudio | 8d7aa85fe5df7987cb6983984d4ce8698f1bd0bd | [
"MIT"
] | null | null | null | /***********************************************************************************************************************
* OpenStudio(R), Copyright (c) 2008-2018, Alliance for Sustainable Energy, LLC. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
*
* (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
*
* (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products
* derived from this software without specific prior written permission from the respective party.
*
* (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works
* may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior
* written permission from Alliance for Sustainable Energy, LLC.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED
* STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
***********************************************************************************************************************/
#ifndef OPENSTUDIO_OSDOCUMENT_HPP
#define OPENSTUDIO_OSDOCUMENT_HPP
#include "OpenStudioAPI.hpp"
#include "../shared_gui_components/OSQObjectController.hpp"
#include "../model/Model.hpp"
#include "../model/ModelObject.hpp"
#include <QObject>
#include <QString>
#include <boost/smart_ptr.hpp>
class QDir;
namespace openstudio {
namespace runmanager {
class RunManager;
}
class MainTabController;
class MainRightColumnController;
class InspectorController;
class MainWindow;
class LibraryTabWidget;
class OSItemId;
class BuildingComponentDialog;
class ApplyMeasureNowDialog;
class Workspace;
class OPENSTUDIO_API OSDocument : public OSQObjectController {
Q_OBJECT
public:
OSDocument( openstudio::model::Model library,
const openstudio::path &resourcesPath,
openstudio::model::OptionalModel model = boost::none,
QString filePath = QString(),
bool isPlugin = false,
int startTabIndex = 0,
int startSubTabIndex = 0);
virtual ~OSDocument();
// Returns the main window associated with this document.
MainWindow * mainWindow();
// Returns the model associated with this document.
model::Model model();
// Sets the model associated with this document.
// This will close all current windows, make sure to call app->setQuitOnLastWindowClosed(false) before calling this
void setModel(const model::Model& model, bool modified, bool saveCurrentTabs);
// Returns the Workspace associated with this document's model
//boost::optional<Workspace> workspace();
// Set the Workspace associated with this document's model.
// Workspace is created by idf translator when the scripts tab is shown.
// This is used to populate idf measure arguments.
//void setWorkspace(const boost::optional<Workspace>& workspace);
// Returns true if the document has unsaved changes.
bool modified() const;
// Returns the string path to the location where the document is saved.
// If the document is unsaved an empty string will be returned.
QString savePath() const;
// Returns the path to the directory where model resources are stored
QString modelTempDir() const;
// Returns the component library associated with this document.
openstudio::model::Model componentLibrary() const;
// Sets the component library associated with this document.
void setComponentLibrary(const openstudio::model::Model& model);
// Returns true if OSItemId's source is the model
bool fromModel(const OSItemId& itemId) const;
// Returns true if OSItemId's source is the componentLibrary
bool fromComponentLibrary(const OSItemId& itemId) const;
// Returns true if OSItemId's source is the BCL
bool fromBCL(const OSItemId& itemId) const;
// Returns IddObjectType from either model, componentLibrary, or BCL
boost::optional<IddObjectType> getIddObjectType(const OSItemId& itemId) const;
// Returns the model object from either model or componentLibrary if possible
// does not return model object from BCL
boost::optional<model::ModelObject> getModelObject(const OSItemId& itemId) const;
// Retrieves the Component identified by itemId from the local bcl library,
// updates it to the current version and returns it.
boost::optional<model::Component> getComponent(const OSItemId& itemId) const;
// Returns the index of the current tab.
int verticalTabIndex();
// Returns the index of the current sub tab.
// Returns -1 if there are no sub tabs.
int subTabIndex();
enum VerticalTabID
{
SITE,
SCHEDULES,
CONSTRUCTIONS,
LOADS,
SPACE_TYPES,
GEOMETRY,
FACILITY,
SPACES,
THERMAL_ZONES,
HVAC_SYSTEMS,
BUILDING_SUMMARY,
OUTPUT_VARIABLES,
SIMULATION_SETTINGS,
RUBY_SCRIPTS,
RUN_SIMULATION,
RESULTS_SUMMARY
};
enum HorizontalTabID
{
MY_MODEL,
LIBRARY,
EDIT
};
std::shared_ptr<MainRightColumnController> mainRightColumnController() const;
// DLM: would like for this to not be a member variable since it is only used as a modal dialog with a well defined lifetime
boost::shared_ptr<ApplyMeasureNowDialog> m_applyMeasureNowDialog;
signals:
void closeClicked();
void importClicked();
void importgbXMLClicked();
void importSDDClicked();
void importIFCClicked();
void loadFileClicked();
void osmDropped(QString path);
void changeDefaultLibrariesClicked();
void loadLibraryClicked();
void newClicked();
void exitClicked();
void helpClicked();
void aboutClicked();
// called before actual save (copy from temp to user location) occurs
void modelSaving(const openstudio::path &t_path);
void downloadComponentsClicked();
void openLibDlgClicked();
void toolsUpdated();
void toggleUnitsClicked(bool displayIP);
void treeChanged(const openstudio::UUID &t_uuid);
void enableRevertToSaved(bool enable);
public slots:
void markAsModified();
void markAsUnmodified();
void exportIdf();
void exportgbXML();
void exportSDD();
// returns if a file was saved
bool save();
// returns if a file was saved
bool saveAs();
void showRunManagerPreferences();
void scanForTools();
void closeSidebar();
void openSidebar();
void openBclDlg();
void openMeasuresBclDlg();
void openMeasuresDlg();
void openChangeMeasuresDirDlg();
private slots:
void onVerticalTabSelected(int id);
void inspectModelObject(model::OptionalModelObject &, bool readOnly);
void showStartTabAndStartSubTab();
void initializeModel();
void toggleUnits(bool displayIP);
void openLibDlg();
void on_closeBclDlg();
void on_closeMeasuresBclDlg();
void changeBclLogin();
void updateWindowFilePath();
void updateSubTabSelected(int id);
void addStandardMeasures();
public slots:
void enable();
void disable();
void enableTabsAfterRun();
void disableTabsDuringRun();
void weatherFileReset();
private:
enum fileType{
SDD,
GBXML
};
void exportFile(fileType type);
boost::optional<BCLMeasure> standardReportMeasure();
friend class OpenStudioApp;
REGISTER_LOGGER("openstudio.OSDocument");
// Sets the file path and updates the window title to match.
// Used by save and saveAs.
void setSavePath(const QString & savePath);
// When opening an OSM, check the model for a weather file, if a weather file is listed
// copy it into the temp directory. If the listed weather file cannot be found, remove the
// weather file object. Returns false if the user's weather file is reset, returns true otherwise.
bool fixWeatherFileInTemp(bool opening);
void createTab(int verticalId);
void createTabButtons();
openstudio::model::Model m_model;
boost::optional<Workspace> m_workspace;
openstudio::model::Model m_compLibrary;
openstudio::model::Model m_hvacCompLibrary;
openstudio::path m_resourcesPath;
LibraryTabWidget * m_libraryTabWidget;
MainWindow * m_mainWindow;
BuildingComponentDialog * m_onlineMeasuresBclDialog;
BuildingComponentDialog * m_onlineBclDialog;
BuildingComponentDialog * m_localLibraryDialog;
//std::shared_ptr<OSConsoleWidget> m_consoleWidget;
std::shared_ptr<MainTabController> m_mainTabController;
std::shared_ptr<InspectorController> m_inspectorController;
std::shared_ptr<MainRightColumnController> m_mainRightColumnController;
QString m_savePath = QString();
QString m_modelTempDir = QString();
int m_mainTabId = 0;
int m_subTabId = 0;
bool m_isPlugin;
int m_startTabIndex;
int m_startSubTabIndex;
int m_verticalId;
std::vector<int> m_subTabIds;
bool m_enableTabsAfterRun = true;
bool m_tabButtonsCreated = false;
};
} // openstudio
#endif // OPENSTUDIO_OSDOCUMENT_HPP
| 27.045822 | 126 | 0.729619 | Acidburn0zzz |
9146e18996dd7ddcd5ff9bb6298e0de82f32c413 | 683 | hpp | C++ | tests/headers/doggo-or-null.hpp | j-channings/rust-bindgen | 56e8cf97c9368e0bc9f20f5f66ca2a3773ab97b3 | [
"BSD-3-Clause"
] | 1,848 | 2018-11-22T06:08:21.000Z | 2022-03-31T10:54:10.000Z | tests/headers/doggo-or-null.hpp | j-channings/rust-bindgen | 56e8cf97c9368e0bc9f20f5f66ca2a3773ab97b3 | [
"BSD-3-Clause"
] | 845 | 2016-06-22T21:55:20.000Z | 2018-10-31T15:50:10.000Z | tests/headers/doggo-or-null.hpp | j-channings/rust-bindgen | 56e8cf97c9368e0bc9f20f5f66ca2a3773ab97b3 | [
"BSD-3-Clause"
] | 274 | 2018-11-23T17:46:29.000Z | 2022-03-27T04:52:37.000Z | // bindgen-flags: --opaque-type DoggoOrNull --with-derive-partialeq --with-derive-hash -- -std=c++14
class Doggo {
int x;
};
class Null {};
/**
* This type is an opaque union. Unions can't derive anything interesting like
* Debug or Default, even if their layout can, because it would require knowing
* which variant is in use. Opaque unions still end up as a `union` in the Rust
* bindings, but they just have one variant. Even so, can't derive. We should
* probably emit an opaque struct for opaque unions... but until then, we have
* this test to make sure that opaque unions don't derive and still compile.
*/
union DoggoOrNull {
Doggo doggo;
Null none;
};
| 32.52381 | 100 | 0.711567 | j-channings |
914e910a41129cee278cae124b298c7a38252342 | 1,717 | cpp | C++ | C++ Programs/infix_to_postfix.cpp | manvitha1726/RTU-DigitalLibrary | e2dbf042bcebaa52613fa925dfdbe1f72dc13bcd | [
"MIT"
] | 32 | 2020-10-06T09:45:10.000Z | 2021-12-23T02:15:42.000Z | C++ Programs/infix_to_postfix.cpp | manvitha1726/RTU-DigitalLibrary | e2dbf042bcebaa52613fa925dfdbe1f72dc13bcd | [
"MIT"
] | 55 | 2020-10-05T06:21:13.000Z | 2021-09-11T18:06:50.000Z | C++ Programs/infix_to_postfix.cpp | Tausif121/RTU-DigitalLibrary | b0ad54356158ba92c476472241b5b118fb624bf4 | [
"MIT"
] | 248 | 2020-10-05T06:21:19.000Z | 2021-10-03T08:29:23.000Z | #include<iostream>
#include<conio.h>
#include<string.h>
using namespace std;
class Stack
{
public:
char s[100];
int head=-1;
void push(char c)
{
head++;
s[head]=c;
}
char pop()
{
if(head==-1) return '!';
head--;
return s[head+1];
}
char showtop()
{
if(head==-1) return '!';
return s[head];
}
};
int main()
{
char s[100];
Stack x;
cout<<"ENTER THE INFIX EXPRESSION: ";
cin>>s;
cout<<"\n\nPOSTFIX EXPRESSION: ";
for(int i=0;;i++)
{
if(s[i]=='\0') break;
if(s[i]=='(') x.push(s[i]);
else if(s[i]=='*'||s[i]=='/')
{
while(1)
{
char k;
if(x.s[x.head]=='^'||x.s[x.head]=='*'||x.s[x.head]=='/') {k=x.pop(); cout<<k;}
else break;
if (k=='!') break;
}
x.push(s[i]);
}
else if(s[i]=='+'||s[i]=='-')
{
while(1)
{
char k;
if(x.s[x.head]=='^'||x.s[x.head]=='*'||x.s[x.head]=='/'||x.s[x.head]=='+'||x.s[x.head]=='-') {k=x.pop(); cout<<k;}
else break;
if (k=='!') break;
}
x.push(s[i]);
}
else if(s[i]=='^') x.push(s[i]);
else if(s[i]==')')
{
while(1)
{
char k=x.pop();
if(k=='(') break;
cout<<k;
}
}
else cout<<s[i];
}
while(1)
{
char k=x.pop();
if(k=='!') break;
else cout<<k;
}
cout<<"\n..........\nPress any key to exit.";
getch();
}
| 19.735632 | 130 | 0.338381 | manvitha1726 |
914f8ecafaf3d57294ea1b8a64ea6470bc11db69 | 9,888 | cpp | C++ | game/mips2c/functions/texture.cpp | LuminarLight/jak-project | f341be65e9848977158c9a9a2898f0f047a157df | [
"ISC"
] | 602 | 2020-08-23T22:52:42.000Z | 2022-02-07T23:36:14.000Z | game/mips2c/functions/texture.cpp | romatthe/jak-project | 35bdc9b1d3a0a89cff072deb57844aa0e73d15e7 | [
"ISC"
] | 970 | 2020-08-27T03:25:21.000Z | 2022-02-08T01:27:11.000Z | game/mips2c/functions/texture.cpp | romatthe/jak-project | 35bdc9b1d3a0a89cff072deb57844aa0e73d15e7 | [
"ISC"
] | 34 | 2020-08-26T03:23:50.000Z | 2022-02-03T18:49:06.000Z | //--------------------------MIPS2C---------------------
// clang-format off
#include "game/mips2c/mips2c_private.h"
#include "game/kernel/kscheme.h"
namespace Mips2C {
namespace adgif_shader_texture_with_update {
u64 execute(void* ctxt) {
auto* c = (ExecutionContext*)ctxt;
bool bc = false;
c->ld(a2, 16, a0); // ld a2, 16(a0)
c->addiu(v1, r0, 256); // addiu v1, r0, 256
c->andi(a2, a2, 513); // andi a2, a2, 513
c->mtc1(f0, v1); // mtc1 f0, v1
c->cvtsw(f0, f0); // cvt.s.w f0, f0
c->lbu(v1, 4, a1); // lbu v1, 4(a1)
c->lwc1(f1, 44, a1); // lwc1 f1, 44(a1)
c->daddiu(v1, v1, -1); // daddiu v1, v1, -1
c->divs(f0, f0, f1); // div.s f0, f0, f1
c->dsll(v1, v1, 2); // dsll v1, v1, 2
c->or_(a2, a2, v1); // or a2, a2, v1
c->lbu(v1, 7, a1); // lbu v1, 7(a1)
c->dsll(v1, v1, 19); // dsll v1, v1, 19
c->lbu(a3, 5, a1); // lbu a3, 5(a1)
c->or_(a2, a2, v1); // or a2, a2, v1
c->dsll(a3, a3, 5); // dsll a3, a3, 5
c->or_(a2, a2, a3); // or a2, a2, a3
c->ld(t1, 0, a0); // ld t1, 0(a0)
c->dsll(t1, t1, 27); // dsll t1, t1, 27
c->lbu(v1, 6, a1); // lbu v1, 6(a1)
c->dsra32(t1, t1, 30); // dsra32 t1, t1, 30
c->dsll(v1, v1, 20); // dsll v1, v1, 20
c->dsll32(t1, t1, 3); // dsll32 t1, t1, 3
c->lhu(a3, 10, a1); // lhu a3, 10(a1)
c->or_(t1, t1, v1); // or t1, t1, v1
c->lbu(v1, 26, a1); // lbu v1, 26(a1)
c->or_(t1, t1, a3); // or t1, t1, a3
c->dsll(v1, v1, 14); // dsll v1, v1, 14
c->or_(t1, t1, v1); // or t1, t1, v1
c->lhu(v1, 0, a1); // lhu v1, 0(a1)
c->plzcw(v1, v1); // plzcw v1, v1
c->addiu(t0, r0, 30); // addiu t0, r0, 30
c->subu(v1, t0, v1); // subu v1, t0, v1
c->lhu(a3, 2, a1); // lhu a3, 2(a1)
c->dsll(v1, v1, 26); // dsll v1, v1, 26
c->plzcw(a3, a3); // plzcw a3, a3
c->or_(t1, t1, v1); // or t1, t1, v1
c->subu(a3, t0, a3); // subu a3, t0, a3
c->dsll(a3, a3, 30); // dsll a3, a3, 30
c->addiu(v1, r0, 1); // addiu v1, r0, 1
c->or_(t1, t1, a3); // or t1, t1, a3
c->dsll32(v1, v1, 2); // dsll32 v1, v1, 2
c->or_(t1, t1, v1); // or t1, t1, v1
c->lhu(v1, 24, a1); // lhu v1, 24(a1)
c->dsll32(v1, v1, 5); // dsll32 v1, v1, 5
c->lhu(a3, 8, a1); // lhu a3, 8(a1)
c->dsll32(a3, a3, 19); // dsll32 a3, a3, 19
c->or_(t1, t1, v1); // or t1, t1, v1
c->or_(t1, t1, a3); // or t1, t1, a3
c->addiu(v1, r0, 1); // addiu v1, r0, 1
c->dsll32(v1, v1, 29); // dsll32 v1, v1, 29
c->cvtws(f0, f0); // cvt.w.s f0, f0
c->or_(t1, t1, v1); // or t1, t1, v1
c->mfc1(v1, f0); // mfc1 v1, f0
c->sd(t1, 0, a0); // sd t1, 0(a0)
c->plzcw(a3, v1); // plzcw a3, v1
c->subu(a3, t0, a3); // subu a3, t0, a3
c->lbu(t0, 7, a1); // lbu t0, 7(a1)
c->daddiu(t0, t0, -1); // daddiu t0, t0, -1
// nop // sll r0, r0, 0
bc = c->sgpr64(t0) == 0; // beq t0, r0, L22
// nop // sll r0, r0, 0
if (bc) {goto block_2;} // branch non-likely
c->daddiu(t0, a3, -4); // daddiu t0, a3, -4
c->dsll(a3, a3, 4); // dsll a3, a3, 4
c->dsrav(t0, v1, t0); // dsrav t0, v1, t0
c->daddiu(a3, a3, -175); // daddiu a3, a3, -175
c->andi(t0, t0, 15); // andi t0, t0, 15
// nop // sll r0, r0, 0
//beq r0, r0, L23 // beq r0, r0, L23
c->daddu(a3, a3, t0); // daddu a3, a3, t0
goto block_3; // branch always
block_2:
c->daddiu(t0, a3, -5); // daddiu t0, a3, -5
c->dsll(a3, a3, 5); // dsll a3, a3, 5
c->dsrav(t0, v1, t0); // dsrav t0, v1, t0
c->daddiu(a3, a3, -350); // daddiu a3, a3, -350
c->andi(t0, t0, 31); // andi t0, t0, 31
// nop // sll r0, r0, 0
c->daddu(a3, a3, t0); // daddu a3, a3, t0
// nop // sll r0, r0, 0
block_3:
c->andi(a3, a3, 4095); // andi a3, a3, 4095
c->lhu(t1, 12, a1); // lhu t1, 12(a1)
c->dsll32(a3, a3, 0); // dsll32 a3, a3, 0
c->lbu(v1, 27, a1); // lbu v1, 27(a1)
c->or_(a2, a2, a3); // or a2, a2, a3
c->dsll(v1, v1, 14); // dsll v1, v1, 14
c->sd(a2, 16, a0); // sd a2, 16(a0)
c->or_(a2, t1, v1); // or a2, t1, v1
c->lhu(v1, 14, a1); // lhu v1, 14(a1)
// nop // sll r0, r0, 0
c->lbu(a3, 28, a1); // lbu a3, 28(a1)
c->dsll(v1, v1, 20); // dsll v1, v1, 20
c->or_(a2, a2, v1); // or a2, a2, v1
c->dsll32(a3, a3, 2); // dsll32 a3, a3, 2
c->or_(a2, a2, a3); // or a2, a2, a3
c->lhu(v1, 16, a1); // lhu v1, 16(a1)
c->lbu(a3, 29, a1); // lbu a3, 29(a1)
c->dsll32(v1, v1, 8); // dsll32 v1, v1, 8
c->or_(a2, a2, v1); // or a2, a2, v1
c->dsll32(a3, a3, 22); // dsll32 a3, a3, 22
c->or_(a2, a2, a3); // or a2, a2, a3
c->lbu(t0, 4, a1); // lbu t0, 4(a1)
c->daddiu(t0, t0, -5); // daddiu t0, t0, -5
c->sd(a2, 32, a0); // sd a2, 32(a0)
bc = ((s64)c->sgpr64(t0)) < 0; // bltz t0, L24
c->lbu(a3, 30, a1); // lbu a3, 30(a1)
if (bc) {goto block_5;} // branch non-likely
c->lhu(a2, 18, a1); // lhu a2, 18(a1)
c->dsll(a3, a3, 14); // dsll a3, a3, 14
c->or_(a2, a2, a3); // or a2, a2, a3
c->lhu(v1, 20, a1); // lhu v1, 20(a1)
c->dsll(v1, v1, 20); // dsll v1, v1, 20
c->lbu(a3, 31, a1); // lbu a3, 31(a1)
c->or_(a2, a2, v1); // or a2, a2, v1
c->dsll32(a3, a3, 2); // dsll32 a3, a3, 2
c->or_(a2, a2, a3); // or a2, a2, a3
c->lhu(v1, 22, a1); // lhu v1, 22(a1)
c->dsll32(v1, v1, 8); // dsll32 v1, v1, 8
c->lbu(a3, 32, a1); // lbu a3, 32(a1)
c->or_(a2, a2, v1); // or a2, a2, v1
c->dsll32(a3, a3, 22); // dsll32 a3, a3, 22
c->or_(a2, a2, a3); // or a2, a2, a3
c->addiu(v1, r0, 54); // addiu v1, r0, 54
c->sd(a2, 64, a0); // sd a2, 64(a0)
// nop // sll r0, r0, 0
c->sw(v1, 72, a0); // sw v1, 72(a0)
// nop // sll r0, r0, 0
block_5:
c->mov64(v0, a0); // or v0, a0, r0
//jr ra // jr ra
c->daddu(sp, sp, r0); // daddu sp, sp, r0
goto end_of_function; // return
// nop // sll r0, r0, 0
// nop // sll r0, r0, 0
end_of_function:
return c->gprs[v0].du64[0];
}
void link() {
gLinkedFunctionTable.reg("adgif-shader<-texture-with-update!", execute, 128);
}
} // namespace adgif_shader<_texture_with_update
} // namespace Mips2C
| 60.292683 | 79 | 0.299252 | LuminarLight |
91507b9134518b80e1815709a4ff2ece9644e3da | 214 | hpp | C++ | src/App/Configuration.hpp | psiberx/cp2077-tweak-xl | ed974dc664092c8d1f8831c39a5c5b2634ddf72e | [
"MIT"
] | 6 | 2022-03-01T03:46:46.000Z | 2022-03-31T21:12:31.000Z | src/App/Configuration.hpp | psiberx/cp2077-tweak-xl | ed974dc664092c8d1f8831c39a5c5b2634ddf72e | [
"MIT"
] | null | null | null | src/App/Configuration.hpp | psiberx/cp2077-tweak-xl | ed974dc664092c8d1f8831c39a5c5b2634ddf72e | [
"MIT"
] | null | null | null | #pragma once
#include "stdafx.hpp"
#include "Core/Facades/Runtime.hpp"
namespace App::Configuration
{
inline std::filesystem::path GetTweaksDir()
{
return Core::Runtime::GetRootDir() / L"r6" / L"tweaks";
}
}
| 16.461538 | 59 | 0.705607 | psiberx |
915394e8d073163259c72ff8a73e26f778225aa6 | 335 | cpp | C++ | usystem/tests/kernel_api_tests/src/vm.cpp | heatd/Onyx | 404fce9c89a1d4ab561b5be63bd9bc68a6c9d91d | [
"MIT"
] | 44 | 2017-02-16T20:48:09.000Z | 2022-03-14T17:58:57.000Z | usystem/tests/kernel_api_tests/src/vm.cpp | heatd/Onyx | 404fce9c89a1d4ab561b5be63bd9bc68a6c9d91d | [
"MIT"
] | 72 | 2017-02-16T20:22:10.000Z | 2022-03-31T21:17:06.000Z | usystem/tests/kernel_api_tests/src/vm.cpp | heatd/Onyx | 404fce9c89a1d4ab561b5be63bd9bc68a6c9d91d | [
"MIT"
] | 10 | 2017-04-07T19:20:14.000Z | 2021-12-16T03:31:14.000Z | /*
* Copyright (c) 2021 Pedro Falcato
* This file is part of Onyx, and is released under the terms of the MIT License
* check LICENSE at the root directory for more information
*/
#include <unistd.h>
#include <fcntl.h>
#include <cstring>
#include <string>
#include <gtest/gtest.h>
#include <sys/mman.h>
TEST(Vm, MmapWorks)
{
}
| 17.631579 | 79 | 0.707463 | heatd |
9154bf90e1c29faee6cf9a7df244edf60f80908d | 1,781 | hpp | C++ | Mathematics/Function/Computable/Expression/List/Body/a_Body.hpp | p-adic/cpp | 9404a08f26c55a19c53ab0a11edb70f3ed6a8e3c | [
"MIT"
] | 2 | 2020-09-13T07:31:22.000Z | 2022-03-26T08:37:32.000Z | Mathematics/Function/Computable/Expression/List/Body/a_Body.hpp | p-adic/cpp | 9404a08f26c55a19c53ab0a11edb70f3ed6a8e3c | [
"MIT"
] | null | null | null | Mathematics/Function/Computable/Expression/List/Body/a_Body.hpp | p-adic/cpp | 9404a08f26c55a19c53ab0a11edb70f3ed6a8e3c | [
"MIT"
] | null | null | null | // c:/Users/user/Documents/Programming/Mathematics/Function/Computable/Expression/List/Body/a_Body.hpp
#pragma once
#include "a.hpp"
#include "../a.hpp"
#include "../../Variable/a.hpp"
#include "../../a.hpp"
#include "../a_Body.hpp"
#include "../../Variable/a_Body.hpp"
#include "../../a_Body.hpp"
#include "../../../Type/Guide/Valid/a_Body.hpp"
template <typename VArg> inline ExpressionOfComputableFunction<void>::ExpressionOfComputableFunction( const WrappedTypes<VArg>& ) : SyntaxOfComputableFunction( ExpressionString() , VariableString() , LdotsString() , GetTypeSyntax<VArg>().Get() ) {}
template <typename... VA>
ExpressionOfComputableFunction<void>::ExpressionOfComputableFunction( const ExpressionOfComputableFunction<VA>&... va ) : SyntaxOfComputableFunction( ExpressionString() , ListString() , va.Get()... )
{
VLTree<string>& t = Ref();
VLTree<string>::iterator itr_insert = t.LeftMostNode();
VLTree<string>::const_iterator itr = itr_insert;
itr++;
const uint& size = t.size();
uint i = 1;
string argument_name = "";
string argument_type_name = "";
if( size > 2 ){
argument_name = "( ";
}
TRY_CATCH
(
{
while( i < size ){
if( i > 1 ){
argument_name += " , ";
argument_type_name += " \\times ";
}
auto itr_copy = itr;
argument_name += SyntaxToString( itr_copy , 2 );
argument_type_name += SyntaxToString( itr_copy , 2 );
itr++;
i++;
}
} ,
const ErrorType& e ,
CALL_P( e , i , argument_name , argument_type_name )
);
if( size > 2 ){
argument_name += " )";
}
t.insert( itr_insert , argument_type_name );
t.insert( itr_insert , argument_name );
}
| 22.833333 | 249 | 0.613139 | p-adic |
91572fbae81e4c5c4e5530024cfe094c7435fa7c | 1,612 | cpp | C++ | Day12/Graph_topSortKahnAlgo.cpp | tejaswini212/100-Days-Of-Algo | ae90e91e302e2f1c9b1c067416fcb0bc42b12e99 | [
"MIT"
] | 1 | 2022-03-31T13:49:46.000Z | 2022-03-31T13:49:46.000Z | Day12/Graph_topSortKahnAlgo.cpp | tejaswini212/100-Days-Of-Algo | ae90e91e302e2f1c9b1c067416fcb0bc42b12e99 | [
"MIT"
] | null | null | null | Day12/Graph_topSortKahnAlgo.cpp | tejaswini212/100-Days-Of-Algo | ae90e91e302e2f1c9b1c067416fcb0bc42b12e99 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
class Graph{
int V;
list<int> *adj;
public:
Graph(int V){
this->V = V;
adj = new list<int> [V];
}
void addEdge(int u,int v){
adj[u].push_back(v);
}
void topSort();
};
void Graph::topSort(){
//vector to store indegrees of all the nodes
vector<int> in_degree(V,0);
for(int u=0;u<V;u++){
list<int>::iterator itr;
for(itr=adj[u].begin();itr!=adj[u].end();itr++){
in_degree[*itr]++;
}
}
//queue is created and all nodes with indegree equal to zero are enqueued
queue<int> q;
for(int i=0;i<V;i++)
if(in_degree[i]==0)
q.push(i);
//vector to store topological order
vector<int> top_order;
int countVisited=0;
while(!q.empty()){
int u=q.front();
q.pop();
top_order.push_back(u);
list<int>::iterator itr;
for(itr=adj[u].begin();itr!=adj[u].end();itr++)
if(--in_degree[*itr]==0)
q.push(*itr);
countVisited++;
}
if(countVisited!=V){
cout<<"There exists a cycle in a graph\n";
}
else{
cout<<"Below is the topological sort of given graph:\n";
for(int i=0;i<V;i++)
cout<<top_order[i]<<" ";
cout<<"\n";
}
}
int main(){
Graph g(6);
g.addEdge(0,1);
g.addEdge(1,5);
g.addEdge(2,5);
g.addEdge(2,4);
g.addEdge(1,4);
g.addEdge(4,3);
g.addEdge(3,0);
g.topSort();
return 0;
}
| 19.658537 | 77 | 0.485112 | tejaswini212 |
91592c19024271c72e2462f0ced58f79e098f4c3 | 31,284 | cc | C++ | tensorflow/compiler/xla/service/hlo_dataflow_analysis.cc | monokrome/tensorflow | 2533ada7dd45b84d60677b8735e013d21044651a | [
"Apache-2.0"
] | 1 | 2018-12-08T18:04:55.000Z | 2018-12-08T18:04:55.000Z | tensorflow/compiler/xla/service/hlo_dataflow_analysis.cc | monokrome/tensorflow | 2533ada7dd45b84d60677b8735e013d21044651a | [
"Apache-2.0"
] | null | null | null | tensorflow/compiler/xla/service/hlo_dataflow_analysis.cc | monokrome/tensorflow | 2533ada7dd45b84d60677b8735e013d21044651a | [
"Apache-2.0"
] | null | null | null | /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/service/hlo_dataflow_analysis.h"
#include <algorithm>
#include <queue>
#include <vector>
#include "tensorflow/compiler/xla/map_util.h"
#include "tensorflow/compiler/xla/ptr_util.h"
#include "tensorflow/compiler/xla/service/hlo_computation.h"
#include "tensorflow/compiler/xla/service/hlo_instruction.h"
#include "tensorflow/compiler/xla/service/hlo_opcode.h"
#include "tensorflow/compiler/xla/service/liveness_util.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/status.h"
#include "tensorflow/compiler/xla/types.h"
#include "tensorflow/compiler/xla/util.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/logging.h"
namespace xla {
using ::tensorflow::strings::StrAppend;
using ::tensorflow::strings::StrCat;
HloDataflowAnalysis::HloDataflowAnalysis(HloModule* module, bool ssa_form,
bool bitcast_defines_value)
: module_(module),
ssa_form_(ssa_form),
bitcast_defines_value_(bitcast_defines_value),
call_graph_(CallGraph::Build(module)) {}
bool HloDataflowAnalysis::ValueIsDefinedAt(const HloInstruction* instruction,
const ShapeIndex& index) const {
const HloValueSet& value_set = GetValueSet(instruction, index);
if (value_set.value_ids().size() != 1) {
return false;
}
return GetValue(value_set.GetUniqueValueId()).defining_instruction() ==
instruction;
}
const HloValue& HloDataflowAnalysis::GetValueDefinedAt(
const HloInstruction* instruction, const ShapeIndex& index) const {
CHECK(ValueIsDefinedAt(instruction, index));
return GetUniqueValueAt(instruction, index);
}
HloValue& HloDataflowAnalysis::GetValueDefinedAt(
const HloInstruction* instruction, const ShapeIndex& index) {
CHECK(ValueIsDefinedAt(instruction, index));
return GetUniqueValueAt(instruction, index);
}
HloValue::Id HloDataflowAnalysis::NewHloValue(HloInstruction* instruction,
const ShapeIndex& index,
bool is_phi) {
int64 value_id = next_value_id_++;
auto it_added = values_.emplace(
std::piecewise_construct, std::forward_as_tuple(value_id),
std::forward_as_tuple(value_id, instruction, index, is_phi));
CHECK(it_added.second);
// Clear the vector of values as it is now stale. It will be lazily
// reconstructed if needed when HloDataflowAnalysis::values() is called.
values_vector_.clear();
return value_id;
}
void HloDataflowAnalysis::DeleteHloValue(HloValue::Id value_id) {
values_.erase(value_id);
// Clear the vector of values as it is now stale. It will be lazily
// reconstructed if needed when HloDataflowAnalysis::values() is called.
values_vector_.clear();
}
string HloDataflowAnalysis::ToString() const {
string out = StrCat("HloDataflowAnalysis, module ", module_->name(), "\n");
StrAppend(&out, " Instruction value sets:\n");
for (const std::unique_ptr<HloComputation>& computation :
module_->computations()) {
for (const std::unique_ptr<HloInstruction>& instruction :
computation->instructions()) {
StrAppend(&out, " ", instruction->name(), ":\n");
if (ShapeUtil::IsTuple(instruction->shape())) {
GetInstructionValueSet(instruction.get())
.ForEachElement([this, &instruction, &out](
const ShapeIndex& index,
const HloValueSet& value_set) {
StrAppend(&out, " tuple index ", index.ToString(), ":\n");
for (HloValue::Id value_id : value_set.value_ids()) {
StrAppend(
&out, " ", GetValue(value_id).ToShortString(),
ValueIsDefinedAt(instruction.get(), index) ? " (def)" : "",
"\n");
}
});
} else {
const HloValueSet& top_level_value_set =
GetValueSet(instruction.get(), /*index=*/{});
for (HloValue::Id value_id : top_level_value_set.value_ids()) {
StrAppend(&out, " ", GetValue(value_id).ToShortString(),
ValueIsDefinedAt(instruction.get()) ? " (def)" : "", "\n");
}
}
}
}
StrAppend(&out, " HloValues:\n");
for (const auto& pair : values_) {
StrAppend(&out, pair.second.ToString(/*indent=*/4));
}
return out;
}
const HloValue& HloDataflowAnalysis::GetValue(HloValue::Id value_id) const {
return values_.at(value_id);
}
HloValue& HloDataflowAnalysis::GetValue(HloValue::Id value_id) {
return values_.at(value_id);
}
const HloValueSet& HloDataflowAnalysis::GetValueSet(
const HloInstruction* instruction, const ShapeIndex& index) const {
return GetInstructionValueSet(instruction).element(index);
}
HloValueSet& HloDataflowAnalysis::GetValueSet(const HloInstruction* instruction,
const ShapeIndex& index) {
return *GetInstructionValueSet(instruction).mutable_element(index);
}
const std::vector<const HloValue*>& HloDataflowAnalysis::values() const {
if (values_vector_.empty()) {
// Lazily construct vector of values.
values_vector_.reserve(values_.size());
for (auto& pair : values_) {
values_vector_.push_back(&pair.second);
}
std::sort(
values_vector_.begin(), values_vector_.end(),
[](const HloValue* a, const HloValue* b) { return a->id() < b->id(); });
} else {
CHECK_EQ(values_vector_.size(), values_.size());
for (const HloValue* value : values_vector_) {
DCHECK(ContainsKey(values_, value->id()));
DCHECK(&GetValue(value->id()) == value);
}
}
return values_vector_;
}
/* static */
InstructionValueSet HloDataflowAnalysis::Phi(
HloInstruction* instruction,
tensorflow::gtl::ArraySlice<const InstructionValueSet*> inputs,
bool skip_top_level) {
CHECK(ssa_form_);
for (const InstructionValueSet* input : inputs) {
CHECK(ShapeUtil::Compatible(instruction->shape(), input->shape()));
}
InstructionValueSet new_value_set(instruction->shape());
new_value_set.ForEachMutableElement(
[this, instruction, &inputs, skip_top_level](const ShapeIndex& index,
HloValueSet* value_set) {
// If we're skipping the top level, just copy over the existing
// HloValueSet.
if (skip_top_level && index.empty()) {
*value_set = GetInstructionValueSet(instruction).element(index);
return;
}
// Identify the existing phi value at this index if it exists.
const HloValue* existing_phi_value = nullptr;
if (ValueIsDefinedAt(instruction, index) &&
GetUniqueValueAt(instruction, index).is_phi()) {
existing_phi_value = &GetUniqueValueAt(instruction, index);
}
// Construct a vector of unique value IDs of the inputs.
std::vector<HloValue::Id> input_value_ids;
for (const InstructionValueSet* input : inputs) {
for (HloValue::Id value_id : input->element(index).value_ids()) {
input_value_ids.push_back(value_id);
}
}
std::sort(input_value_ids.begin(), input_value_ids.end());
input_value_ids.erase(
std::unique(input_value_ids.begin(), input_value_ids.end()),
input_value_ids.end());
// Remove the existing phi value (if it exists). The phi can be its own
// input, for example, in while body parameters where the body passes
// through the parameter value.
if (existing_phi_value != nullptr) {
auto it = std::find(input_value_ids.begin(), input_value_ids.end(),
existing_phi_value->id());
if (it != input_value_ids.end()) {
input_value_ids.erase(it);
}
}
if (input_value_ids.size() <= 1) {
if (input_value_ids.size() == 1) {
*value_set = HloValueSet({input_value_ids[0]});
}
if (existing_phi_value) {
// The merge point does not have multiple distinct inputs (which are
// not the phi value itself). Therefore there is no need to insert a
// phi value because there is a single reaching definition (or no
// reaching definition).
DeleteHloValue(existing_phi_value->id());
}
} else if (input_value_ids.size() > 1) {
// Multiple distinct values reach this point. A phi value is
// necessary.
if (existing_phi_value) {
// A phi value already exists so reuse it in the new
// InstructionValueSet.
*value_set = HloValueSet({existing_phi_value->id()});
} else {
// Create a new phi value.
*value_set =
HloValueSet({NewHloValue(instruction, index, /*is_phi=*/true)});
}
}
});
return new_value_set;
}
void HloDataflowAnalysis::UpdateLocationsOfValuesAt(
HloInstruction* instruction, const InstructionValueSet& new_value_set,
const InstructionValueSet* prev_value_set) {
if (prev_value_set != nullptr) {
// Remove locations from the old value set.
prev_value_set->ForEachElement(
[this, instruction](const ShapeIndex& index,
const HloValueSet& value_set) {
for (HloValue::Id value_id : value_set.value_ids()) {
// HloValues in the previous value set may have been deleted.
if (!ContainsKey(values_, value_id)) {
continue;
}
// Don't remove the defining location of the value.
HloValue& value = GetValue(value_id);
if (instruction == value.defining_instruction()) {
CHECK_EQ(index, value.defining_index());
} else {
value.RemoveLocation(instruction, index);
}
}
});
}
// Add locations in the new value set.
new_value_set.ForEachElement(
[this, instruction](const ShapeIndex& index,
const HloValueSet& value_set) {
for (HloValue::Id value_id : value_set.value_ids()) {
HloValue& value = GetValue(value_id);
if (instruction == value.defining_instruction()) {
CHECK_EQ(index, value.defining_index());
} else {
value.AddLocation(instruction, index);
}
}
});
}
InstructionValueSet HloDataflowAnalysis::RecomputeBitcastValueSet(
HloInstruction* bitcast) {
CHECK_EQ(bitcast->opcode(), HloOpcode::kBitcast);
if (bitcast_defines_value_) {
return GetInstructionValueSet(bitcast);
} else {
return GetInstructionValueSet(bitcast->operand(0));
}
}
InstructionValueSet HloDataflowAnalysis::RecomputeCopyValueSet(
HloInstruction* copy) {
CHECK_EQ(copy->opcode(), HloOpcode::kCopy);
InstructionValueSet new_value_set = GetInstructionValueSet(copy);
if (ShapeUtil::IsTuple(copy->shape())) {
for (int i = 0; i < ShapeUtil::TupleElementCount(copy->shape()); ++i) {
new_value_set.CopySubtreeFrom(GetInstructionValueSet(copy->operand(0)),
/*source_base_index=*/{i},
/*target_base_index=*/{i});
}
}
return new_value_set;
}
InstructionValueSet HloDataflowAnalysis::RecomputeGetTupleElementValueSet(
HloInstruction* gte) {
CHECK_EQ(gte->opcode(), HloOpcode::kGetTupleElement);
InstructionValueSet new_value_set(gte->shape());
new_value_set.CopySubtreeFrom(GetInstructionValueSet(gte->operand(0)),
/*source_base_index=*/{gte->tuple_index()},
/*target_base_index=*/{});
return new_value_set;
}
InstructionValueSet HloDataflowAnalysis::RecomputeSelectValueSet(
HloInstruction* select) {
CHECK_EQ(select->opcode(), HloOpcode::kSelect);
std::vector<const InstructionValueSet*> inputs = {
&GetInstructionValueSet(select->operand(1)),
&GetInstructionValueSet(select->operand(2))};
// A phi value is not defined at a kSelect instruction because kSelect does
// not create a new value. Rather it forwards a value from its operands. This
// contrasts with kWhile instruction (which does define a phi value) which has
// in-place update semantics.
InstructionValueSet new_value_set = InstructionValueSet::Union(inputs);
*new_value_set.mutable_element(/*index=*/{}) =
GetInstructionValueSet(select).element(/*index=*/{});
return new_value_set;
}
InstructionValueSet HloDataflowAnalysis::RecomputeTupleValueSet(
HloInstruction* tuple) {
CHECK_EQ(tuple->opcode(), HloOpcode::kTuple);
InstructionValueSet new_value_set(tuple->shape());
*new_value_set.mutable_element(/*index=*/{}) =
GetInstructionValueSet(tuple).element(/*index=*/{});
for (int64 i = 0; i < tuple->operands().size(); ++i) {
new_value_set.CopySubtreeFrom(GetInstructionValueSet(tuple->operand(i)),
/*source_base_index=*/{},
/*target_base_index=*/{i});
}
return new_value_set;
}
InstructionValueSet HloDataflowAnalysis::RecomputeWhileValueSet(
HloInstruction* xla_while) {
CHECK_EQ(xla_while->opcode(), HloOpcode::kWhile);
std::vector<const InstructionValueSet*> inputs = {
&GetInstructionValueSet(xla_while->while_body()->root_instruction()),
&GetInstructionValueSet(xla_while->operand(0))};
if (ssa_form_) {
return Phi(xla_while, inputs);
} else {
return InstructionValueSet::Union(inputs);
}
}
void HloDataflowAnalysis::UpdateInstructionValueSet(
HloInstruction* instruction) {
// Recompute from operands.
InstructionValueSet& value_set = GetInstructionValueSet(instruction);
switch (instruction->opcode()) {
case HloOpcode::kBitcast:
value_set = RecomputeBitcastValueSet(instruction);
break;
case HloOpcode::kCopy:
value_set = RecomputeCopyValueSet(instruction);
break;
case HloOpcode::kGetTupleElement:
value_set = RecomputeGetTupleElementValueSet(instruction);
break;
case HloOpcode::kSelect:
value_set = RecomputeSelectValueSet(instruction);
break;
case HloOpcode::kTuple:
value_set = RecomputeTupleValueSet(instruction);
break;
case HloOpcode::kParameter:
value_set = RecomputeParameterValueSet(instruction);
break;
case HloOpcode::kCall:
// The output of a kCall instruction is exactly the output of the root of
// the subcomputation.
value_set =
GetInstructionValueSet(instruction->to_apply()->root_instruction());
break;
case HloOpcode::kWhile:
value_set = RecomputeWhileValueSet(instruction);
break;
default:
// Instruction does not forward HloValues (it defines all values in its
// output). No update is necessary.
return;
}
}
void HloDataflowAnalysis::UpdateInstructionsAndPropagate(
tensorflow::gtl::ArraySlice<HloInstruction*> instructions) {
std::queue<HloInstruction*> worklist;
for (HloInstruction* instruction : instructions) {
worklist.push(instruction);
}
while (!worklist.empty()) {
HloInstruction* instruction = worklist.front();
worklist.pop();
VLOG(3) << "Worklist top: " << instruction->name();
VLOG(3) << ToString();
// Save old value for recomputing uses and live out.
InstructionValueSet old_value = GetInstructionValueSet(instruction);
UpdateInstructionValueSet(instruction);
if (GetInstructionValueSet(instruction) == old_value) {
// No change to the instruction's value set.
VLOG(4) << "No change.";
continue;
}
VLOG(4) << "New value set for " << instruction->name() << ": "
<< GetInstructionValueSet(instruction);
VLOG(4) << "Previously: " << old_value;
// Instruction value was updated. Add users to work list.
for (HloInstruction* user : instruction->users()) {
worklist.push(user);
// If user calls a computation, then the respective parameter(s) of the
// computation need to be updated.
for (HloComputation* called_computation : user->called_computations()) {
for (int64 operand_number : user->OperandIndices(instruction)) {
worklist.push(
called_computation->parameter_instruction(operand_number));
}
}
}
// If instruction is a root instruction, then propagate out to any calling
// instruction and across any while backedge.
if (instruction == instruction->parent()->root_instruction()) {
const CallGraphNode& call_graph_node =
call_graph_->GetNode(instruction->parent());
for (const CallSite& callsite : call_graph_node.caller_callsites()) {
if (callsite.instruction()->opcode() == HloOpcode::kCall) {
worklist.push(callsite.instruction());
} else if (callsite.instruction()->opcode() == HloOpcode::kWhile) {
// Add the while itself, and the body and condition parameters.
worklist.push(callsite.instruction());
worklist.push(
callsite.instruction()->while_body()->parameter_instruction(0));
worklist.push(
callsite.instruction()->while_condition()->parameter_instruction(
0));
}
}
}
// Update uses. First clear all of the old uses at the particular
// operands. Then add the new uses. There may be overlap between the old
// uses and new uses.
UpdateLocationsOfValuesAt(instruction, GetInstructionValueSet(instruction),
&old_value);
}
}
InstructionValueSet HloDataflowAnalysis::RecomputeParameterValueSet(
HloInstruction* parameter) {
CHECK_EQ(parameter->opcode(), HloOpcode::kParameter);
const CallGraphNode& call_graph_node =
call_graph_->GetNode(parameter->parent());
// Subcomputations called in a parallel context (eg, map) do not have dataflow
// from the caller operands.
if (call_graph_node.context() == CallContext::kParallel ||
call_graph_node.caller_callsites().empty()) {
return GetInstructionValueSet(parameter);
}
CHECK_EQ(call_graph_node.context(), CallContext::kSequential);
std::vector<const InstructionValueSet*> inputs;
bool called_from_while = false;
for (const CallSite& callsite : call_graph_node.caller_callsites()) {
if (callsite.instruction()->opcode() == HloOpcode::kCall) {
// The operand values of a call instruction are forwarded to the
// respective parameter instruction of the subcomputation.
inputs.push_back(&GetInstructionValueSet(
callsite.instruction()->operand(parameter->parameter_number())));
} else if (callsite.instruction()->opcode() == HloOpcode::kWhile) {
// In a while instruction, the while operand (ie, the init value) and the
// backedge are dataflow inputs to the parameter instruction. This is the
// case for parameters of both the body and condition computations.
CHECK_EQ(parameter->parameter_number(), 0);
inputs.push_back(
&GetInstructionValueSet(callsite.instruction()->operand(0)));
inputs.push_back(&GetInstructionValueSet(
callsite.instruction()->while_body()->root_instruction()));
called_from_while = true;
} else {
LOG(FATAL) << "CallContext::kSequential computations should only be "
"called from call or while instructions";
}
}
if (ssa_form_ && called_from_while) {
return Phi(parameter, inputs);
} else {
return InstructionValueSet::Union(inputs);
}
}
const InstructionValueSet& HloDataflowAnalysis::GetInstructionValueSet(
const HloInstruction* instruction) const {
return value_sets_.at(instruction);
}
InstructionValueSet& HloDataflowAnalysis::GetInstructionValueSet(
const HloInstruction* instruction) {
return value_sets_.at(instruction);
}
Status HloDataflowAnalysis::InitializeInstructionValueSets() {
for (const std::unique_ptr<HloComputation>& computation :
module_->computations()) {
const CallGraphNode& call_graph_node =
call_graph_->GetNode(computation.get());
for (const std::unique_ptr<HloInstruction>& instruction :
computation->instructions()) {
// Create an empty shape tree.
value_sets_.emplace(std::piecewise_construct,
std::forward_as_tuple(instruction.get()),
std::forward_as_tuple(instruction->shape()));
// Lambda to set the value set to define all values in the output of the
// instruction.
auto define_all_values = [this, &instruction]() {
GetInstructionValueSet(instruction.get())
.ForEachMutableElement([this, &instruction](
const ShapeIndex& index,
HloValueSet* value_set) {
*value_set = HloValueSet({NewHloValue(instruction.get(), index)});
});
};
// Lambda to set the value set to define only the top-level buffer in the
// output of the instruction. Any other values flow from the operands of
// the instruction (or from cross-computation dataflow).
auto define_top_level_only = [this, &instruction]() {
GetValueSet(instruction.get(), /*index=*/{}) =
HloValueSet({NewHloValue(instruction.get(), /*index=*/{})});
};
switch (instruction->opcode()) {
case HloOpcode::kBitcast:
if (bitcast_defines_value_) {
define_all_values();
}
break;
case HloOpcode::kCall:
case HloOpcode::kWhile:
case HloOpcode::kGetTupleElement:
// These instructions define no values. The values in their output
// flow from their operands or from cross computation dataflow.
break;
case HloOpcode::kParameter:
if (call_graph_node.caller_callsites().empty() ||
call_graph_node.context() == CallContext::kParallel) {
// Parameters of computations called in a parallel context (eg, map
// and reduce) as well as parameters of dead computations define all
// values in their output. Otherwise the values of the parameter
// come from the caller (eg, operands to the kCall instruction).
define_all_values();
} else if (call_graph_node.context() == CallContext::kBoth) {
// We do not support a subcomputation that is called from both a
// parallel and sequential context. In this case, the parameter
// would both define a value and propagate a value from its
// caller. This limitation is not really a problem because the call
// graph is typically flattened.
return Unimplemented(
"Computation %s is called in both a parallel (eg, kMap) and "
"sequential (eg, kCall) context",
computation->name().c_str());
}
break;
case HloOpcode::kCopy:
case HloOpcode::kSelect:
case HloOpcode::kTuple:
// These instructions only define their top-level values. Any other
// values flow from their operands.
define_top_level_only();
break;
default:
define_all_values();
break;
}
UpdateLocationsOfValuesAt(instruction.get(),
GetInstructionValueSet(instruction.get()));
}
}
return Status::OK();
}
bool HloDataflowAnalysis::IsDefinedBefore(const HloValue& a, const HloValue& b,
const HloOrdering& ordering) const {
// If 'b' is an entry param then 'a' cannot be defined before 'b' because 'b'
// is live into the module.
if (b.defining_instruction()->parent() == module_->entry_computation() &&
b.defining_instruction()->opcode() == HloOpcode::kParameter) {
return false;
}
// Phi values require special handling. Because XLA does not have a phi
// instruction, the definition instruction of the phis values are
// placeholders: either the subcomputation parameter (body or condition) or
// the while instruction. However, the program point where these values are
// logically defined does not necessarily coincide exactly with program point
// of these place-holder instructions. So we explicitly define the following
// order for phi values:
//
// body/condition parameter phi:
// Defined before all values defined in its computation excepting other
// phis.
//
// while phi:
// defined after all values defined in the condition or body.
//
auto is_body_or_condition_phi = [](const HloValue& v) {
return v.is_phi() &&
v.defining_instruction()->opcode() == HloOpcode::kParameter;
};
if (is_body_or_condition_phi(a) && !is_body_or_condition_phi(b) &&
call_graph_->InstructionIsNestedIn(b.defining_instruction(),
a.defining_instruction()->parent())) {
return true;
}
if (is_body_or_condition_phi(b) &&
call_graph_->InstructionIsNestedIn(a.defining_instruction(),
b.defining_instruction()->parent())) {
return false;
}
// If 'b' is a while phi and 'a' is in the body or condition, then 'a'
// executes before 'b'.
if (b.is_phi() && b.defining_instruction()->opcode() == HloOpcode::kWhile &&
(call_graph_->InstructionIsNestedIn(
a.defining_instruction(), b.defining_instruction()->while_body()) ||
call_graph_->InstructionIsNestedIn(
a.defining_instruction(),
b.defining_instruction()->while_condition()))) {
return true;
}
return ordering.ExecutesBefore(a.defining_instruction(),
b.defining_instruction());
}
bool HloDataflowAnalysis::UseIsBeforeValueDefinition(
const HloUse& use, const HloValue& value,
const HloOrdering& ordering) const {
if (ordering.ExecutesBefore(use.instruction, value.defining_instruction())) {
return true;
}
// If the use is at the instruction where the value is defined, then the use
// is before the def if the instruction allows buffer sharing (in place
// computation).
if (use.instruction == value.defining_instruction() &&
CanShareOperandBufferWithUser(
use.instruction->mutable_operand(use.operand_number),
use.operand_index, value.defining_instruction(),
value.defining_index())) {
return true;
}
// The use at a while is an input to a phi, and logically occurs before values
// are defined in the body or condition computations.
if (use.instruction->opcode() == HloOpcode::kWhile) {
const HloInstruction* xla_while = use.instruction;
if (call_graph_->InstructionIsNestedIn(value.defining_instruction(),
xla_while->while_body()) ||
call_graph_->InstructionIsNestedIn(value.defining_instruction(),
xla_while->while_condition())) {
return true;
}
}
// Similarly if the value is defined at a while, it logically occurs after any
// uses in the body or condition computations.
if (value.defining_instruction()->opcode() == HloOpcode::kWhile) {
CHECK(ssa_form_);
const HloInstruction* xla_while = value.defining_instruction();
if (call_graph_->InstructionIsNestedIn(use.instruction,
xla_while->while_body()) ||
call_graph_->InstructionIsNestedIn(use.instruction,
xla_while->while_condition())) {
return true;
}
}
return false;
}
bool HloDataflowAnalysis::LiveRangeStrictlyBefore(
const HloValue& a, const HloValue& b, const HloOrdering& ordering) const {
VLOG(4) << "LiveRangeStrictlyBefore(a = " << a.ToShortString()
<< ", b = " << b.ToShortString() << ")";
if (!IsDefinedBefore(a, b, ordering)) {
VLOG(4) << "a not defined before b";
return false;
}
// Live-out values from the module can never have ranges strictly before any
// other value.
if (a.live_out_of_module()) {
VLOG(4) << "a is live out of module";
return false;
}
// Live-out values of computations can never have ranges strictly before any
// other value in the computation (including values nested in
// subcomputations).
if (a.live_out_of_computation() &&
call_graph_->InstructionIsNestedIn(b.defining_instruction(),
a.defining_instruction()->parent())) {
VLOG(4) << "a is live out of computation containing b";
return false;
}
// All uses of 'a' must be before 'b' is defined.
for (const HloUse& use : a.uses()) {
if (!UseIsBeforeValueDefinition(use, b, ordering)) {
VLOG(4) << "use of a (" << use << ") not before b is defined";
return false;
}
}
return true;
}
bool HloDataflowAnalysis::MayInterfere(const HloValue& a, const HloValue& b,
const HloOrdering& ordering) const {
// Buffers without disjoint liveness may interfere.
return !LiveRangeStrictlyBefore(a, b, ordering) &&
!LiveRangeStrictlyBefore(b, a, ordering);
}
/* static */
StatusOr<std::unique_ptr<HloDataflowAnalysis>> HloDataflowAnalysis::Run(
HloModule* module, bool ssa_form, bool bitcast_defines_value) {
VLOG(1) << "HloDataflowAnalysis::Run on module " << module->name();
XLA_VLOG_LINES(2, module->ToString());
auto dataflow_analysis = WrapUnique(
new HloDataflowAnalysis(module, ssa_form, bitcast_defines_value));
TF_RETURN_IF_ERROR(dataflow_analysis->InitializeInstructionValueSets());
// Construct list of all instructions to initialize the worklist to propagate
// the data flow. For efficiency sort the instruction in post order so
// producers appear before consumers.
std::vector<HloInstruction*> all_instructions;
for (const HloComputation* computation : module->MakeComputationPostOrder()) {
for (HloInstruction* instruction :
computation->MakeInstructionPostOrder()) {
all_instructions.push_back(instruction);
}
}
dataflow_analysis->UpdateInstructionsAndPropagate(all_instructions);
VLOG(1) << dataflow_analysis->ToString();
return std::move(dataflow_analysis);
}
} // namespace xla
| 40.056338 | 80 | 0.653049 | monokrome |
915be2ee2f6f333f2a943562f1c8e1fd228b778a | 489 | cpp | C++ | sg/renderer/materials/ThinGlass.cpp | ebachard/ospray_studio | 78928c93b482f9f95aa300c8f58c728dadedbe2f | [
"Apache-2.0"
] | 52 | 2018-10-09T23:56:32.000Z | 2022-03-25T09:27:40.000Z | sg/renderer/materials/ThinGlass.cpp | ebachard/ospray_studio | 78928c93b482f9f95aa300c8f58c728dadedbe2f | [
"Apache-2.0"
] | 11 | 2018-11-19T18:51:47.000Z | 2022-03-28T14:03:57.000Z | sg/renderer/materials/ThinGlass.cpp | ebachard/ospray_studio | 78928c93b482f9f95aa300c8f58c728dadedbe2f | [
"Apache-2.0"
] | 8 | 2019-02-10T00:16:24.000Z | 2022-02-17T19:50:15.000Z | // Copyright 2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
#include "../Material.h"
namespace ospray {
namespace sg {
struct OSPSG_INTERFACE ThinGlass : public Material
{
ThinGlass();
~ThinGlass() override = default;
};
OSP_REGISTER_SG_NODE_NAME(ThinGlass, thinGlass);
// ThinGlass definitions //////////////////////////////////////////////////
ThinGlass::ThinGlass() : Material("thinGlass")
{
}
} // namespace sg
} // namespace ospray
| 18.807692 | 77 | 0.615542 | ebachard |
915d4e7addc5dde17aacd2f318267bdc7987a3f4 | 5,438 | cpp | C++ | libs/QRealFourier/sources/qfouriertransformer.cpp | mfkiwl/Serial-Studio | f669d7b7e5f9a6d22f9d4bc26a4500c3feb08c3a | [
"MIT"
] | 2,496 | 2020-11-12T01:17:00.000Z | 2022-03-30T06:03:58.000Z | libs/QRealFourier/sources/qfouriertransformer.cpp | mfkiwl/Serial-Studio | f669d7b7e5f9a6d22f9d4bc26a4500c3feb08c3a | [
"MIT"
] | 75 | 2021-01-14T16:21:21.000Z | 2022-03-14T23:16:09.000Z | libs/QRealFourier/sources/qfouriertransformer.cpp | mfkiwl/Serial-Studio | f669d7b7e5f9a6d22f9d4bc26a4500c3feb08c3a | [
"MIT"
] | 287 | 2021-01-13T20:32:12.000Z | 2022-03-30T09:39:31.000Z | /***********************************************************************
qfouriertransformer.cpp - Source file for QFourierTransformer
Facade class for calculating FFTs from a set of samples.
************************************************************************
This file is part of QRealFourier.
QRealFourier is free software: you can redistribute it and/or modify it
under the terms of the Lesser GNU General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Foobar 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 Lesser GNU General Public
License for more details.
You should have received a copy of the Lesser GNU General Public License
along with Foobar. If not, see <http://www.gnu.org/licenses/>.
************************************************************************
Copyright © 2012 - 2013 Christoph Stallmann, University of Pretoria
Developer: Christoph Stallmann
University of Pretoria
Department of Computer Science
http://www.visore.org
http://sourceforge.net/projects/qrealfourier
http://github.com/visore/QRealFourier
qrealfourier@visore.org
qrealfourier@gmail.com
***********************************************************************/
#include "qfouriertransformer.h"
#include "qfourierfixedcalculator.h"
#include "qfouriervariablecalculator.h"
QFourierTransformer::QFourierTransformer(int size, QString functionName)
{
mWindowFunctions = QWindowFunctionManager<float>::functions();
mWindowFunction = 0;
mCalculator = 0;
initialize();
setSize(size);
setWindowFunction(functionName);
}
QFourierTransformer::~QFourierTransformer()
{
qDeleteAll(mFixedCalculators.begin(), mFixedCalculators.end());
mFixedCalculators.clear();
delete mVariableCalculator;
if(mWindowFunction != 0)
{
delete mWindowFunction;
}
}
QFourierTransformer::Initialization QFourierTransformer::setSize(int size)
{
if(isValidSize(size))
{
mSize = size;
if(mWindowFunction != 0)
{
mWindowFunction->create(mSize);
}
int key = sizeToKey(mSize);
if(mFixedCalculators.contains(key))
{
mCalculator = mFixedCalculators[key];
return QFourierTransformer::FixedSize;
}
else
{
mCalculator = mVariableCalculator;
mCalculator->setSize(mSize);
return QFourierTransformer::VariableSize;
}
}
mSize = 0;
return QFourierTransformer::InvalidSize;
}
bool QFourierTransformer::setWindowFunction(QString functionName)
{
for(int i = 0; i < mWindowFunctions.size(); ++i)
{
if(functionName.trimmed().toLower().replace("function", "") == mWindowFunctions[i].trimmed().toLower().replace("function", ""))
{
if(mWindowFunction != 0)
{
delete mWindowFunction;
}
mWindowFunction = QWindowFunctionManager<float>::createFunction(functionName);
if(mWindowFunction != 0 && isValidSize(mSize))
{
mWindowFunction->create(mSize);
}
return true;
}
}
return false;
}
QStringList QFourierTransformer::windowFunctions()
{
return mWindowFunctions;
}
void QFourierTransformer::transform(float input[], float output[], Direction direction)
{
if(direction == QFourierTransformer::Forward)
{
forwardTransform(input, output);
}
else
{
inverseTransform(input, output);
}
}
void QFourierTransformer::forwardTransform(float *input, float *output)
{
if(mWindowFunction != 0)
{
mWindowFunction->apply(input, mSize);
}
mCalculator->setData(input, output);
mCalculator->forward();
}
void QFourierTransformer::inverseTransform(float input[], float output[])
{
mCalculator->setData(input, output);
mCalculator->inverse();
}
void QFourierTransformer::rescale(float input[])
{
mCalculator->setData(input);
mCalculator->rescale();
}
void QFourierTransformer::initialize()
{
mFixedCalculators.insert(3, new QFourierFixedCalculator<3>());
mFixedCalculators.insert(4, new QFourierFixedCalculator<4>());
mFixedCalculators.insert(5, new QFourierFixedCalculator<5>());
mFixedCalculators.insert(6, new QFourierFixedCalculator<6>());
mFixedCalculators.insert(7, new QFourierFixedCalculator<7>());
mFixedCalculators.insert(8, new QFourierFixedCalculator<8>());
mFixedCalculators.insert(9, new QFourierFixedCalculator<9>());
mFixedCalculators.insert(10, new QFourierFixedCalculator<10>());
mFixedCalculators.insert(11, new QFourierFixedCalculator<11>());
mFixedCalculators.insert(12, new QFourierFixedCalculator<12>());
mFixedCalculators.insert(13, new QFourierFixedCalculator<13>());
mFixedCalculators.insert(14, new QFourierFixedCalculator<14>());
mVariableCalculator = new QFourierVariableCalculator();
}
int QFourierTransformer::sizeToKey(int size)
{
float result = log(float(size)) / log(2.0);
if(result == float(int(result)))
{
return result;
}
return -1;
}
bool QFourierTransformer::isValidSize(int value)
{
return ((value > 0) && ((value & (~value + 1)) == value));
}
void QFourierTransformer::conjugate(float input[])
{
for(int i = mSize / 2 + 1; i < mSize; ++i)
{
input[i] = -input[i];
}
}
QComplexVector QFourierTransformer::toComplex(float input[])
{
int last = mSize / 2;
QVector<QComplexFloat> result(last + 1);
result[0] = QComplexFloat(input[0], 0);
for(int i = 1; i < last; ++i)
{
result[i] = QComplexFloat(input[i], -input[last + i]);
}
result[last] = QComplexFloat(input[last], 0);
return result;
}
| 26.526829 | 129 | 0.70651 | mfkiwl |
915dd98f431a89b44683368c0710b1869d5a1d3e | 31,792 | cpp | C++ | src/ScreenManager.cpp | graemephi/etterna | b984fe493d9f7ac84a35af3e6f80f16607aceb09 | [
"MIT"
] | null | null | null | src/ScreenManager.cpp | graemephi/etterna | b984fe493d9f7ac84a35af3e6f80f16607aceb09 | [
"MIT"
] | null | null | null | src/ScreenManager.cpp | graemephi/etterna | b984fe493d9f7ac84a35af3e6f80f16607aceb09 | [
"MIT"
] | null | null | null | /*
* We maintain a pool of "prepared" screens, which are screens previously loaded
* to be available on demand.
*
* When a screen pops off the stack that's in g_setPersistantScreens, it goes to
* the prepared list. If that screen is used again before it's deleted, it'll
* be reused.
*
* Typically, the first screen in a group will prepare all of the nearby screens
* it may load. When it loads one, the prepared screen will be used.
*
* A group of screens may only want to preload some screens, and not others,
* while still considering those screens part of the same group. For example,
* an attract loop typically has several very lightweight screens and a few
* expensive screens. Preloading the lightweight screens can improve
* responsiveness, but preloading the expensive screens may use too much memory
* and take too long to load all at once. By calling GroupScreen(), entering
* these screens will not trigger cleanup.
*
* Example uses:
* - ScreenOptions1 preloads ScreenOptions2, and persists both. Moving from
* Options1 and Options2 and back is instant and reuses both.
* - ScreenMenu groups and persists itself and ScreenSubmenu. ScreenSubmenu
* is not preloaded, so it will be loaded on demand the first time it's used,
* but will remain loaded if it returns to ScreenMenu.
* - ScreenSelectMusic groups itself and ScreenPlayerOptions, and persists only
* ScreenSelectMusic. This will cause SSMusic will be loaded once, and SPO
* to be loaded on demand.
* - ScreenAttract1 preloads and persists ScreenAttract1, 3, 5 and 7, and
* groups 1 through 7. 1, 3, 5 and 7 will remain in memory; the rest will be
* loaded on demand.
*
* If a screen is added to the screen stack that isn't in the current screen
* group (added to by GroupScreen), the screen group is reset: all prepared
* screens are unloaded and the persistence list is cleared.
*
* Note that not all screens yet support reuse in this way; proper use of
* BeginScreen is required. This will misbehave if a screen pushes another
* screen that's already in use lower on the stack, but that's not useful; it
* would allow infinite screen recursion.
*
* SM_GainFocus/SM_LoseFocus: These are sent to screens when they become the
* topmost screen, or stop being the topmost screen.
*
* A few subtleties:
*
* With delayed screens (eg. ScreenGameplay being pre-loaded by ScreenStage),
* SM_GainFocus isn't sent until the loaded screen actually is activated (put on
* the stack).
*
* With normal screen loads, the new screen is loaded before the old screen is
* destroyed. This means that the old dtor is called *after* the new ctor. If
* some global properties (eg. GAMESTATE) are being unset by the old screen's
* destructor, and set by the new screen's constructor, they'll happen in the
* wrong order. Use SM_GainFocus and SM_LoseFocus, instead.
*
* SM_LoseFocus is always sent after SM_GainFocus, and vice-versa: you can't
* gain focus if you already have it, and you can't lose focus if you don't have
* it.
*/
#include "global.h"
#include "ActorUtil.h"
#include "FontManager.h"
#include "Foreach.h"
#include "GameSoundManager.h"
#include "InputEventPlus.h"
#include "Preference.h"
#include "RageDisplay.h"
#include "RageLog.h"
#include "RageTextureManager.h"
#include "RageUtil.h"
#include "Screen.h"
#include "ScreenDimensions.h"
#include "ScreenManager.h"
#include "SongManager.h"
#include "ThemeManager.h"
ScreenManager* SCREENMAN =
NULL; // global and accessible from anywhere in our program
static Preference<bool> g_bDelayedScreenLoad("DelayedScreenLoad", false);
// static Preference<bool> g_bPruneFonts( "PruneFonts", true );
// Screen registration
static map<RString, CreateScreenFn>* g_pmapRegistrees = NULL;
/** @brief Utility functions for the ScreenManager. */
namespace ScreenManagerUtil {
// in draw order first to last
struct LoadedScreen
{
Screen* m_pScreen;
/* Normally true. If false, the screen is owned by another screen
* and was given to us for use, and it's not ours to free. */
bool m_bDeleteWhenDone;
ScreenMessage m_SendOnPop;
LoadedScreen()
{
m_pScreen = NULL;
m_bDeleteWhenDone = true;
m_SendOnPop = SM_None;
}
};
Actor* g_pSharedBGA; // BGA object that's persistent between screens
RString m_sPreviousTopScreen;
vector<LoadedScreen> g_ScreenStack; // bottommost to topmost
vector<Screen*> g_OverlayScreens;
set<RString> g_setGroupedScreens;
set<RString> g_setPersistantScreens;
vector<LoadedScreen> g_vPreparedScreens;
vector<Actor*> g_vPreparedBackgrounds;
// Add a screen to g_ScreenStack. This is the only function that adds to
// g_ScreenStack.
void
PushLoadedScreen(const LoadedScreen& ls)
{
LOG->Trace("PushScreen: \"%s\"", ls.m_pScreen->GetName().c_str());
LOG->MapLog("ScreenManager::TopScreen",
"Top Screen: %s",
ls.m_pScreen->GetName().c_str());
// Be sure to push the screen first, so GetTopScreen returns the screen
// during BeginScreen.
g_ScreenStack.push_back(ls);
// Set the name of the loading screen.
{
LuaThreadVariable var1("PreviousScreen", m_sPreviousTopScreen);
LuaThreadVariable var2("LoadingScreen", ls.m_pScreen->GetName());
ls.m_pScreen->BeginScreen();
}
// If this is the new top screen, save the name.
if (g_ScreenStack.size() == 1)
m_sPreviousTopScreen = ls.m_pScreen->GetName();
SCREENMAN->RefreshCreditsMessages();
SCREENMAN->PostMessageToTopScreen(SM_GainFocus, 0);
}
bool
ScreenIsPrepped(const RString& sScreenName)
{
FOREACH(LoadedScreen, g_vPreparedScreens, s)
{
if (s->m_pScreen->GetName() == sScreenName)
return true;
}
return false;
}
/* If the named screen is loaded, remove it from the prepared list and
* return it in ls. */
bool
GetPreppedScreen(const RString& sScreenName, LoadedScreen& ls)
{
FOREACH(LoadedScreen, g_vPreparedScreens, s)
{
if (s->m_pScreen->GetName() == sScreenName) {
ls = *s;
g_vPreparedScreens.erase(s);
return true;
}
}
return false;
}
void
BeforeDeleteScreen()
{
// Deleting a screen can take enough time to cause a frame skip.
SCREENMAN->ZeroNextUpdate();
}
/* If we're deleting a screen, it's probably releasing texture and other
* resources, so trigger cleanups. */
void
AfterDeleteScreen()
{
/* Now that we've actually deleted a screen, it makes sense to clear out
* cached textures. */
TEXTUREMAN->DeleteCachedTextures();
/* Cleanup song data. This can free up a fair bit of memory, so do it
* after deleting screens. */
SONGMAN->Cleanup();
}
/* Take ownership of all screens and backgrounds that are owned by
* us (this excludes screens where m_bDeleteWhenDone is false).
* Clear the prepared lists. The contents of apOut must be
* freed by the caller. */
void
GrabPreparedActors(vector<Actor*>& apOut)
{
FOREACH(LoadedScreen, g_vPreparedScreens, s)
if (s->m_bDeleteWhenDone)
apOut.push_back(s->m_pScreen);
g_vPreparedScreens.clear();
FOREACH(Actor*, g_vPreparedBackgrounds, a)
apOut.push_back(*a);
g_vPreparedBackgrounds.clear();
g_setGroupedScreens.clear();
g_setPersistantScreens.clear();
}
/* Called when changing screen groups. Delete all prepared screens,
* reset the screen group and list of persistant screens. */
void
DeletePreparedScreens()
{
vector<Actor*> apActorsToDelete;
GrabPreparedActors(apActorsToDelete);
BeforeDeleteScreen();
FOREACH(Actor*, apActorsToDelete, a)
SAFE_DELETE(*a);
AfterDeleteScreen();
}
} // namespace ScreenManagerUtil;
using namespace ScreenManagerUtil;
RegisterScreenClass::RegisterScreenClass(const RString& sClassName,
CreateScreenFn pfn)
{
if (g_pmapRegistrees == NULL)
g_pmapRegistrees = new map<RString, CreateScreenFn>;
map<RString, CreateScreenFn>::iterator iter =
g_pmapRegistrees->find(sClassName);
ASSERT_M(
iter == g_pmapRegistrees->end(),
ssprintf("Screen class '%s' already registered.", sClassName.c_str()));
(*g_pmapRegistrees)[sClassName] = pfn;
}
ScreenManager::ScreenManager()
{
// Register with Lua.
{
Lua* L = LUA->Get();
lua_pushstring(L, "SCREENMAN");
this->PushSelf(L);
lua_settable(L, LUA_GLOBALSINDEX);
LUA->Release(L);
}
g_pSharedBGA = new Actor;
m_bReloadOverlayScreensAfterInput = false;
m_bZeroNextUpdate = false;
m_PopTopScreen = SM_Invalid;
m_OnDonePreparingScreen = SM_Invalid;
}
ScreenManager::~ScreenManager()
{
LOG->Trace("ScreenManager::~ScreenManager()");
LOG->UnmapLog("ScreenManager::TopScreen");
SAFE_DELETE(g_pSharedBGA);
for (unsigned i = 0; i < g_ScreenStack.size(); i++) {
if (g_ScreenStack[i].m_bDeleteWhenDone)
SAFE_DELETE(g_ScreenStack[i].m_pScreen);
}
g_ScreenStack.clear();
DeletePreparedScreens();
for (unsigned i = 0; i < g_OverlayScreens.size(); i++)
SAFE_DELETE(g_OverlayScreens[i]);
g_OverlayScreens.clear();
// Unregister with Lua.
LUA->UnsetGlobal("SCREENMAN");
}
// This is called when we start up, and when the theme changes or is reloaded.
void
ScreenManager::ThemeChanged()
{
LOG->Trace("ScreenManager::ThemeChanged");
// reload common sounds
m_soundStart.Load(THEME->GetPathS("Common", "start"));
m_soundCoin.Load(THEME->GetPathS("Common", "coin"), true);
m_soundCancel.Load(THEME->GetPathS("Common", "cancel"), true);
m_soundInvalid.Load(THEME->GetPathS("Common", "invalid"));
m_soundScreenshot.Load(THEME->GetPathS("Common", "screenshot"));
// reload song manager colors (to avoid crashes) -aj
SONGMAN->ResetGroupColors();
ReloadOverlayScreens();
// force recreate of new BGA
SAFE_DELETE(g_pSharedBGA);
g_pSharedBGA = new Actor;
}
void
ScreenManager::ReloadOverlayScreens()
{
// unload overlay screens
for (unsigned i = 0; i < g_OverlayScreens.size(); i++)
SAFE_DELETE(g_OverlayScreens[i]);
g_OverlayScreens.clear();
// reload overlay screens
RString sOverlays = THEME->GetMetric("Common", "OverlayScreens");
vector<RString> asOverlays;
split(sOverlays, ",", asOverlays);
for (unsigned i = 0; i < asOverlays.size(); i++) {
Screen* pScreen = MakeNewScreen(asOverlays[i]);
if (pScreen) {
LuaThreadVariable var2("LoadingScreen", pScreen->GetName());
pScreen->BeginScreen();
g_OverlayScreens.push_back(pScreen);
}
}
this->RefreshCreditsMessages();
}
void
ScreenManager::ReloadOverlayScreensAfterInputFinishes()
{
m_bReloadOverlayScreensAfterInput = true;
}
Screen*
ScreenManager::GetTopScreen()
{
if (g_ScreenStack.empty())
return NULL;
return g_ScreenStack[g_ScreenStack.size() - 1].m_pScreen;
}
Screen*
ScreenManager::GetScreen(int iPosition)
{
if (iPosition >= (int)g_ScreenStack.size())
return NULL;
return g_ScreenStack[iPosition].m_pScreen;
}
bool
ScreenManager::AllowOperatorMenuButton() const
{
FOREACH(LoadedScreen, g_ScreenStack, s)
{
if (!s->m_pScreen->AllowOperatorMenuButton())
return false;
}
return true;
}
bool
ScreenManager::IsScreenNameValid(RString const& name) const
{
if (name.empty() || !THEME->HasMetric(name, "Class")) {
return false;
}
RString ClassName = THEME->GetMetric(name, "Class");
return g_pmapRegistrees->find(ClassName) != g_pmapRegistrees->end();
}
bool
ScreenManager::IsStackedScreen(const Screen* pScreen) const
{
// True if the screen is in the screen stack, but not the first.
for (unsigned i = 1; i < g_ScreenStack.size(); ++i)
if (g_ScreenStack[i].m_pScreen == pScreen)
return true;
return false;
}
bool
ScreenManager::get_input_redirected(PlayerNumber pn)
{
if (static_cast<size_t>(pn) >= m_input_redirected.size()) {
return false;
}
return m_input_redirected[pn];
}
void
ScreenManager::set_input_redirected(PlayerNumber pn, bool redir)
{
while (static_cast<size_t>(pn) >= m_input_redirected.size()) {
m_input_redirected.push_back(false);
}
m_input_redirected[pn] = redir;
}
/* Pop the top screen off the stack, sending SM_LoseFocus messages and
* returning the message the popped screen wants sent to the new top
* screen. Does not send SM_GainFocus. */
ScreenMessage
ScreenManager::PopTopScreenInternal(bool bSendLoseFocus)
{
if (g_ScreenStack.empty())
return SM_None;
LoadedScreen ls = g_ScreenStack.back();
g_ScreenStack.erase(g_ScreenStack.end() - 1, g_ScreenStack.end());
if (bSendLoseFocus)
ls.m_pScreen->HandleScreenMessage(SM_LoseFocus);
ls.m_pScreen->EndScreen();
if (g_setPersistantScreens.find(ls.m_pScreen->GetName()) !=
g_setPersistantScreens.end()) {
// Move the screen back to the prepared list.
g_vPreparedScreens.push_back(ls);
} else {
if (ls.m_bDeleteWhenDone) {
BeforeDeleteScreen();
SAFE_DELETE(ls.m_pScreen);
AfterDeleteScreen();
}
}
if (g_ScreenStack.size())
LOG->MapLog("ScreenManager::TopScreen",
"Top Screen: %s",
g_ScreenStack.back().m_pScreen->GetName().c_str());
else
LOG->UnmapLog("ScreenManager::TopScreen");
return ls.m_SendOnPop;
}
void
ScreenManager::Update(float fDeltaTime)
{
// Pop the top screen, if PopTopScreen was called.
if (m_PopTopScreen != SM_Invalid) {
ScreenMessage SM = m_PopTopScreen;
m_PopTopScreen = SM_Invalid;
ScreenMessage SM2 = PopTopScreenInternal();
SendMessageToTopScreen(SM_GainFocus);
SendMessageToTopScreen(SM);
SendMessageToTopScreen(SM2);
}
/* Screens take some time to load. If we don't do this, then screens
* receive an initial update that includes all of the time they spent
* loading, which will chop off their tweens.
*
* We don't want to simply cap update times; for example, the stage
* screen sets a 4 second timer, preps the gameplay screen, and then
* displays the prepped screen after the timer runs out; this lets the
* load time be masked (as long as the load takes less than 4 seconds).
* If we cap that large update delta from the screen load, the update
* to load the new screen will come after 4 seconds plus the load time.
*
* So, let's just zero the first update for every screen. */
ASSERT(!g_ScreenStack.empty() ||
m_sDelayedScreen !=
""); // Why play the game if there is nothing showing?
Screen* pScreen = g_ScreenStack.empty() ? NULL : GetTopScreen();
bool bFirstUpdate = pScreen && pScreen->IsFirstUpdate();
/* Loading a new screen can take seconds and cause a big jump on the new
* Screen's first update. Clamp the first update delta so that the
* animations don't jump. */
if ((pScreen != nullptr) && m_bZeroNextUpdate) {
LOG->Trace("Zeroing this update. Was %f", fDeltaTime);
fDeltaTime = 0;
m_bZeroNextUpdate = false;
}
// Update screens.
{
for (unsigned i = 0; i < g_ScreenStack.size(); i++)
g_ScreenStack[i].m_pScreen->Update(fDeltaTime);
g_pSharedBGA->Update(fDeltaTime);
for (unsigned i = 0; i < g_OverlayScreens.size(); i++)
g_OverlayScreens[i]->Update(fDeltaTime);
}
/* The music may be started on the first update. If we're reading from a CD,
* it might not start immediately. Make sure we start playing the sound
* before continuing, since it's strange to start rendering before the music
* starts. */
if (bFirstUpdate)
SOUND->Flush();
/* If we're currently inside a background screen load, and m_sDelayedScreen
* is set, then the screen called SetNewScreen before we finished preparing.
* Postpone it until we're finished loading. */
if (m_sDelayedScreen.size() != 0) {
LoadDelayedScreen();
}
}
void
ScreenManager::Draw()
{
/* If it hasn't been updated yet, skip the render. We can't call Update(0),
* since that'll confuse the "zero out the next update after loading a
* screen logic. If we don't render, don't call BeginFrame or EndFrame. That
* way, we won't clear the buffer, and we won't wait for vsync. */
if (g_ScreenStack.size() && g_ScreenStack.back().m_pScreen->IsFirstUpdate())
return;
if (!DISPLAY->BeginFrame())
return;
DISPLAY->CameraPushMatrix();
DISPLAY->LoadMenuPerspective(
0, SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_CENTER_X, SCREEN_CENTER_Y);
g_pSharedBGA->Draw();
DISPLAY->CameraPopMatrix();
for (unsigned i = 0; i < g_ScreenStack.size();
i++) // Draw all screens bottom to top
g_ScreenStack[i].m_pScreen->Draw();
for (unsigned i = 0; i < g_OverlayScreens.size(); i++)
g_OverlayScreens[i]->Draw();
DISPLAY->EndFrame();
}
void
ScreenManager::Input(const InputEventPlus& input)
{
// LOG->Trace( "ScreenManager::Input( %d-%d, %d-%d, %d-%d, %d-%d )",
// DeviceI.device, DeviceI.button, GameI.controller, GameI.button,
// MenuI.player, MenuI.button, StyleI.player, StyleI.col );
// First, give overlay screens a shot at the input. If Input returns
// true, it handled the input, so don't pass it further.
for (unsigned i = 0; i < g_OverlayScreens.size(); ++i) {
Screen* pScreen = g_OverlayScreens[i];
bool handled = pScreen->Input(input);
// Pass input to the screen and lua. Contention shouldn't be a problem
// because anybody setting an input callback is probably doing it to
// do something in addition to whatever the screen does.
if (pScreen->PassInputToLua(input) || handled) {
if (m_bReloadOverlayScreensAfterInput) {
ReloadOverlayScreens();
m_bReloadOverlayScreensAfterInput = false;
}
return;
}
}
// Pass input to the topmost screen. If we have a new top screen pending,
// don't send to the old screen, but do send to overlay screens.
if (m_sDelayedScreen != "")
return;
if (g_ScreenStack.empty())
return;
if (!get_input_redirected(input.pn)) {
g_ScreenStack.back().m_pScreen->Input(input);
}
g_ScreenStack.back().m_pScreen->PassInputToLua(input);
}
// Just create a new screen; don't do any associated cleanup.
Screen*
ScreenManager::MakeNewScreen(const RString& sScreenName)
{
RageTimer t;
LOG->Trace("Loading screen: \"%s\"", sScreenName.c_str());
RString sClassName = THEME->GetMetric(sScreenName, "Class");
map<RString, CreateScreenFn>::iterator iter =
g_pmapRegistrees->find(sClassName);
if (iter == g_pmapRegistrees->end()) {
LuaHelpers::ReportScriptErrorFmt(
"Screen \"%s\" has an invalid class \"%s\".",
sScreenName.c_str(),
sClassName.c_str());
return NULL;
}
this->ZeroNextUpdate();
CreateScreenFn pfn = iter->second;
Screen* ret = pfn(sScreenName);
LOG->Trace("Loaded \"%s\" (\"%s\") in %f",
sScreenName.c_str(),
sClassName.c_str(),
t.GetDeltaTime());
return ret;
}
void
ScreenManager::PrepareScreen(const RString& sScreenName)
{
// If the screen is already prepared, stop.
if (ScreenIsPrepped(sScreenName))
return;
Screen* pNewScreen = MakeNewScreen(sScreenName);
if (pNewScreen == NULL) {
return;
}
{
LoadedScreen ls;
ls.m_pScreen = pNewScreen;
g_vPreparedScreens.push_back(ls);
}
/* Don't delete previously prepared versions of the screen's background,
* and only prepare it if it's different than the current background
* and not already loaded. */
RString sNewBGA = THEME->GetPathB(sScreenName, "background");
if (!sNewBGA.empty() && sNewBGA != g_pSharedBGA->GetName()) {
Actor* pNewBGA = NULL;
FOREACH(Actor*, g_vPreparedBackgrounds, a)
{
if ((*a)->GetName() == sNewBGA) {
pNewBGA = *a;
break;
}
}
// Create the new background before deleting the previous so that we
// keep any common textures loaded.
if (pNewBGA == NULL) {
LOG->Trace("Loading screen background \"%s\"", sNewBGA.c_str());
Actor* pActor = ActorUtil::MakeActor(sNewBGA);
if (pActor != NULL) {
pActor->SetName(sNewBGA);
g_vPreparedBackgrounds.push_back(pActor);
}
}
}
// Prune any unused fonts now that we have had a chance to reference the
// fonts
/*
if(g_bPruneFonts) {
FONT->PruneFonts();
}
*/
// TEXTUREMAN->DiagnosticOutput();
}
void
ScreenManager::GroupScreen(const RString& sScreenName)
{
g_setGroupedScreens.insert(sScreenName);
}
void
ScreenManager::PersistantScreen(const RString& sScreenName)
{
g_setPersistantScreens.insert(sScreenName);
}
void
ScreenManager::SetNewScreen(const RString& sScreenName)
{
ASSERT(sScreenName != "");
m_sDelayedScreen = sScreenName;
}
/* Activate the screen and/or its background, if either are loaded.
* Return true if both were activated. */
bool
ScreenManager::ActivatePreparedScreenAndBackground(const RString& sScreenName)
{
bool bLoadedBoth = true;
// Find the prepped screen.
if (GetTopScreen() == NULL || GetTopScreen()->GetName() != sScreenName) {
LoadedScreen ls;
if (!GetPreppedScreen(sScreenName, ls)) {
bLoadedBoth = false;
} else {
PushLoadedScreen(ls);
}
}
// Find the prepared shared background (if any), and activate it.
RString sNewBGA = THEME->GetPathB(sScreenName, "background");
if (sNewBGA != g_pSharedBGA->GetName()) {
Actor* pNewBGA = NULL;
if (sNewBGA.empty()) {
pNewBGA = new Actor;
} else {
FOREACH(Actor*, g_vPreparedBackgrounds, a)
{
if ((*a)->GetName() == sNewBGA) {
pNewBGA = *a;
g_vPreparedBackgrounds.erase(a);
break;
}
}
}
/* If the BGA isn't loaded yet, load a dummy actor. If we're not going
* to use the same BGA for the new screen, always move the old BGA back
* to g_vPreparedBackgrounds now. */
if (pNewBGA == NULL) {
bLoadedBoth = false;
pNewBGA = new Actor;
}
/* Move the old background back to the prepared list, or delete it if
* it's a blank actor. */
if (g_pSharedBGA->GetName() == "")
delete g_pSharedBGA;
else
g_vPreparedBackgrounds.push_back(g_pSharedBGA);
g_pSharedBGA = pNewBGA;
g_pSharedBGA->PlayCommand("On");
}
return bLoadedBoth;
}
void
ScreenManager::LoadDelayedScreen()
{
RString sScreenName = m_sDelayedScreen;
m_sDelayedScreen = "";
if (!IsScreenNameValid(sScreenName)) {
LuaHelpers::ReportScriptError(
"Tried to go to invalid screen: " + sScreenName, "INVALID_SCREEN");
return;
}
// Pop the top screen, if any.
ScreenMessage SM = PopTopScreenInternal();
/* If the screen is already prepared, activate it before performing any
* cleanup, so it doesn't get deleted by cleanup. */
bool bLoaded = ActivatePreparedScreenAndBackground(sScreenName);
vector<Actor*> apActorsToDelete;
if (g_setGroupedScreens.find(sScreenName) == g_setGroupedScreens.end()) {
/* It's time to delete all old prepared screens. Depending on
* DelayedScreenLoad, we can either delete the screens before or after
* we load the new screen. Either way, we must remove them from the
* prepared list before we prepare new screens.
* If DelayedScreenLoad is true, delete them now; this lowers memory
* requirements, but results in redundant loads as we unload common
* data. */
if (g_bDelayedScreenLoad)
DeletePreparedScreens();
else
GrabPreparedActors(apActorsToDelete);
}
// If the screen wasn't already prepared, load it.
if (!bLoaded) {
PrepareScreen(sScreenName);
// Screens may not call SetNewScreen from the ctor or Init(). (We don't
// do this check inside PrepareScreen; that may be called from a thread
// for concurrent loading, and the main thread may call SetNewScreen
// during that time.) Emit an error instead of asserting. -Kyz
if (!m_sDelayedScreen.empty()) {
LuaHelpers::ReportScriptError(
"Setting a new screen during an InitCommand is not allowed.");
m_sDelayedScreen = "";
}
bLoaded = ActivatePreparedScreenAndBackground(sScreenName);
ASSERT(bLoaded);
}
if (!apActorsToDelete.empty()) {
BeforeDeleteScreen();
FOREACH(Actor*, apActorsToDelete, a)
SAFE_DELETE(*a);
AfterDeleteScreen();
}
MESSAGEMAN->Broadcast(Message_ScreenChanged);
SendMessageToTopScreen(SM);
}
void
ScreenManager::AddNewScreenToTop(const RString& sScreenName,
ScreenMessage SendOnPop)
{
// Load the screen, if it's not already prepared.
PrepareScreen(sScreenName);
// Find the prepped screen.
LoadedScreen ls;
bool screen_load_success = GetPreppedScreen(sScreenName, ls);
ASSERT_M(
screen_load_success,
ssprintf("ScreenManager::AddNewScreenToTop: Failed to load screen %s",
sScreenName.c_str()));
ls.m_SendOnPop = SendOnPop;
if (g_ScreenStack.size())
g_ScreenStack.back().m_pScreen->HandleScreenMessage(SM_LoseFocus);
PushLoadedScreen(ls);
}
void
ScreenManager::PopTopScreen(ScreenMessage SM)
{
ASSERT(g_ScreenStack.size() > 0);
m_PopTopScreen = SM;
}
/* Clear the screen stack; only used before major, unusual state changes,
* such as resetting the game or jumping to the service menu. Don't call
* from inside a screen. */
void
ScreenManager::PopAllScreens()
{
// Make sure only the top screen receives LoseFocus.
bool bFirst = true;
while (!g_ScreenStack.empty()) {
PopTopScreenInternal(bFirst);
bFirst = false;
}
DeletePreparedScreens();
}
void
ScreenManager::PostMessageToTopScreen(ScreenMessage SM, float fDelay)
{
Screen* pTopScreen = GetTopScreen();
if (pTopScreen != NULL)
pTopScreen->PostScreenMessage(SM, fDelay);
}
void
ScreenManager::SendMessageToTopScreen(ScreenMessage SM)
{
Screen* pTopScreen = GetTopScreen();
if (pTopScreen != NULL)
pTopScreen->HandleScreenMessage(SM);
}
void
ScreenManager::SystemMessage(const RString& sMessage)
{
LOG->Trace("%s", sMessage.c_str());
Message msg("SystemMessage");
msg.SetParam("Message", sMessage);
msg.SetParam("NoAnimate", false);
MESSAGEMAN->Broadcast(msg);
}
void
ScreenManager::SystemMessageNoAnimate(const RString& sMessage)
{
// LOG->Trace( "%s", sMessage.c_str() ); // don't log because the caller
// is likely calling us every frame
Message msg("SystemMessage");
msg.SetParam("Message", sMessage);
msg.SetParam("NoAnimate", true);
MESSAGEMAN->Broadcast(msg);
}
void
ScreenManager::HideSystemMessage()
{
MESSAGEMAN->Broadcast("HideSystemMessage");
}
void
ScreenManager::RefreshCreditsMessages()
{
MESSAGEMAN->Broadcast("RefreshCreditText");
}
void
ScreenManager::ZeroNextUpdate()
{
m_bZeroNextUpdate = true;
/* Loading probably took a little while. Let's reset stats. This prevents
* us from displaying an unnaturally low FPS value, and the next FPS value
* we display will be accurate, which makes skips in the initial tween-ins
* more apparent. */
DISPLAY->ResetStats();
}
/** @brief Offer a quick way to play any critical sound. */
#define PLAY_CRITICAL(snd) \
\
{ \
RageSoundParams p; \
p.m_bIsCriticalSound = true; \
(snd).Play(false, &p); \
\
}
/* Always play these sounds, even if we're in a silent attract loop. */
void
ScreenManager::PlayInvalidSound()
{
PLAY_CRITICAL(m_soundInvalid);
}
void
ScreenManager::PlayStartSound()
{
PLAY_CRITICAL(m_soundStart);
}
void
ScreenManager::PlayCoinSound()
{
PLAY_CRITICAL(m_soundCoin);
}
void
ScreenManager::PlayCancelSound()
{
PLAY_CRITICAL(m_soundCancel);
}
void
ScreenManager::PlayScreenshotSound()
{
PLAY_CRITICAL(m_soundScreenshot);
}
#undef PLAY_CRITICAL
void
ScreenManager::PlaySharedBackgroundOffCommand()
{
g_pSharedBGA->PlayCommand("Off");
}
// lua start
#include "LuaBinding.h"
/** @brief Allow Lua to have access to the ScreenManager. */
class LunaScreenManager : public Luna<ScreenManager>
{
public:
// Note: PrepareScreen binding is not allowed; loading data inside
// Lua causes the Lua lock to be held for the duration of the load,
// which blocks concurrent rendering
static void ValidateScreenName(lua_State* L, RString& name)
{
if (name == "") {
RString errstr = "Screen name is empty.";
SCREENMAN->SystemMessage(errstr);
luaL_error(L, errstr.c_str());
}
RString ClassName = THEME->GetMetric(name, "Class");
if (g_pmapRegistrees->find(ClassName) == g_pmapRegistrees->end()) {
RString errstr = "Screen \"" + name + "\" has an invalid class \"" +
ClassName + "\".";
SCREENMAN->SystemMessage(errstr);
luaL_error(L, errstr.c_str());
}
}
static int SetNewScreen(T* p, lua_State* L)
{
RString screen = SArg(1);
ValidateScreenName(L, screen);
p->SetNewScreen(screen);
COMMON_RETURN_SELF;
}
static int GetTopScreen(T* p, lua_State* L)
{
Actor* pScreen = p->GetTopScreen();
if (pScreen != NULL)
pScreen->PushSelf(L);
else
lua_pushnil(L);
return 1;
}
static int SystemMessage(T* p, lua_State* L)
{
p->SystemMessage(SArg(1));
COMMON_RETURN_SELF;
}
static int ScreenIsPrepped(T* p, lua_State* L)
{
lua_pushboolean(L, ScreenManagerUtil::ScreenIsPrepped(SArg(1)));
return 1;
}
static int ScreenClassExists(T* p, lua_State* L)
{
lua_pushboolean(
L, g_pmapRegistrees->find(SArg(1)) != g_pmapRegistrees->end());
return 1;
}
static int AddNewScreenToTop(T* p, lua_State* L)
{
RString screen = SArg(1);
ValidateScreenName(L, screen);
ScreenMessage SM = SM_None;
if (lua_gettop(L) >= 2 && !lua_isnil(L, 2)) {
RString sMessage = SArg(2);
SM = ScreenMessageHelpers::ToScreenMessage(sMessage);
}
p->AddNewScreenToTop(screen, SM);
COMMON_RETURN_SELF;
}
// static int GetScreenStackSize( T* p, lua_State *L ) { lua_pushnumber( L,
// ScreenManagerUtil::g_ScreenStack.size() ); return 1; }
static int ReloadOverlayScreens(T* p, lua_State* L)
{
p->ReloadOverlayScreens();
COMMON_RETURN_SELF;
}
static int get_input_redirected(T* p, lua_State* L)
{
PlayerNumber pn = Enum::Check<PlayerNumber>(L, 1);
lua_pushboolean(L, p->get_input_redirected(pn));
return 1;
}
static int set_input_redirected(T* p, lua_State* L)
{
PlayerNumber pn = Enum::Check<PlayerNumber>(L, 1);
p->set_input_redirected(pn, BArg(2));
COMMON_RETURN_SELF;
}
#define SCRMAN_PLAY_SOUND(sound_name) \
static int Play##sound_name(T* p, lua_State* L) \
{ \
p->Play##sound_name(); \
COMMON_RETURN_SELF; \
}
SCRMAN_PLAY_SOUND(InvalidSound);
SCRMAN_PLAY_SOUND(StartSound);
SCRMAN_PLAY_SOUND(CoinSound);
SCRMAN_PLAY_SOUND(CancelSound);
SCRMAN_PLAY_SOUND(ScreenshotSound);
#undef SCRMAN_PLAY_SOUND
LunaScreenManager()
{
ADD_METHOD(SetNewScreen);
ADD_METHOD(GetTopScreen);
ADD_METHOD(SystemMessage);
ADD_METHOD(ScreenIsPrepped);
ADD_METHOD(ScreenClassExists);
ADD_METHOD(AddNewScreenToTop);
// ADD_METHOD( GetScreenStackSize );
ADD_METHOD(ReloadOverlayScreens);
ADD_METHOD(PlayInvalidSound);
ADD_METHOD(PlayStartSound);
ADD_METHOD(PlayCoinSound);
ADD_METHOD(PlayCancelSound);
ADD_METHOD(PlayScreenshotSound);
ADD_GET_SET_METHODS(input_redirected);
}
};
LUA_REGISTER_CLASS(ScreenManager)
// lua end
/*
* (c) 2001-2003 Chris Danford, Glenn Maynard
* 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.
*/
| 28.693141 | 80 | 0.71474 | graemephi |
915e559c092e3f2cfdac859f5eb0fe163b1a6143 | 10,087 | cpp | C++ | DemoApps/GLES3/ParticleSystem/source/PSGpu/ParticleSystemSnow.cpp | alexvonduar/gtec-demo-framework | 6f8a7e429d0e15242ba64eb4cb41bfc2dd7dc749 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | DemoApps/GLES3/ParticleSystem/source/PSGpu/ParticleSystemSnow.cpp | alexvonduar/gtec-demo-framework | 6f8a7e429d0e15242ba64eb4cb41bfc2dd7dc749 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | DemoApps/GLES3/ParticleSystem/source/PSGpu/ParticleSystemSnow.cpp | alexvonduar/gtec-demo-framework | 6f8a7e429d0e15242ba64eb4cb41bfc2dd7dc749 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | /****************************************************************************************************************************************************
* Copyright (c) 2015 Freescale Semiconductor, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the Freescale Semiconductor, 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 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 "ParticleSystemSnow.hpp"
#include <FslBase/Log/Log3Fmt.hpp>
#include <FslBase/UncheckedNumericCast.hpp>
#include <FslBase/System/HighResolutionTimer.hpp>
#include <FslDemoApp/Base/Service/Content/IContentManager.hpp>
#include <FslDemoApp/Base/DemoTime.hpp>
#include <FslUtil/OpenGLES3/GLCheck.hpp>
#include <GLES3/gl31.h>
#include <GLES2/gl2ext.h>
#include "ParticleSnowGPU.hpp"
#include <algorithm>
#include <array>
#include <cassert>
#include <cstddef>
#include <random>
#include <vector>
namespace Fsl
{
using namespace GLES3;
namespace
{
void SeedParticles(std::vector<ParticleSnowGPU>& rParticles, const Vector3& ranges)
{
std::mt19937 random;
std::uniform_real_distribution<float> randomPositionX(-ranges.X, ranges.X);
std::uniform_real_distribution<float> randomPositionY(-ranges.Y, ranges.Y);
std::uniform_real_distribution<float> randomPositionZ(-ranges.Z, ranges.Z);
std::uniform_real_distribution<float> randomVelocityY(-4.0f, -2.00f);
for (auto itr = rParticles.begin(); itr != rParticles.end(); ++itr)
{
itr->Position = Vector3(randomPositionX(random), randomPositionY(random), randomPositionZ(random));
itr->Velocity = Vector3(0, randomVelocityY(random), 0);
}
}
void PostCompilePreLinkCallback(const GLuint hProgram)
{
const std::array<const char*, 3> particleAttribLinkFeedback = {"Out_ParticlePosition", "Out_ParticleVelocity", "Out_ParticleEnergy"};
glTransformFeedbackVaryings(hProgram, UncheckedNumericCast<GLsizei>(particleAttribLinkFeedback.size()), particleAttribLinkFeedback.data(),
GL_INTERLEAVED_ATTRIBS);
GL_CHECK_FOR_ERROR();
}
}
ParticleSystemSnow::ParticleSystemSnow(const uint32_t capacity, const std::shared_ptr<IContentManager>& contentManager, const Vector3& ranges,
const float pointSize)
: m_capacity(capacity)
, m_ranges(ranges)
, m_pointSize(pointSize)
, m_programTransform(contentManager->ReadAllText("PSSnow_TransformFeedbackShader.vert"),
contentManager->ReadAllText("PSSnow_TransformFeedbackShader.frag"), PostCompilePreLinkCallback)
, m_vertexBuffer2(nullptr, capacity, ParticleSnowGPU::GetVertexDeclaration(), GL_STREAM_DRAW)
, m_pCurrentVertexBuffer(&m_vertexBuffer1)
, m_pOtherVertexBuffer(&m_vertexBuffer2)
, m_transformFeedbackObject(0)
, m_transformFeedbackQuery(0)
, m_locFeedbackDeltaTime(GLValues::INVALID_LOCATION)
, m_locFeedbackUpperBoundaryY(GLValues::INVALID_LOCATION)
, m_locFeedbackLowerBoundaryY(GLValues::INVALID_LOCATION)
, m_locViewProjectionMatrix(GLValues::INVALID_LOCATION)
, m_locWorldViewProjectionMatrix(GLValues::INVALID_LOCATION)
, m_locPointSize(GLValues::INVALID_LOCATION)
{
std::vector<ParticleSnowGPU> particles(capacity);
SeedParticles(particles, ranges);
m_vertexBuffer1.Reset(particles, GL_STREAM_DRAW);
{
const auto hProgram = m_programTransform.Get();
const auto vertexDecl = ParticleSnowGPU::GetVertexDeclaration();
m_particleAttribLinkFeedback[0] =
GLVertexAttribLink(glGetAttribLocation(hProgram, "ParticlePosition"), vertexDecl.VertexElementGetIndexOf(VertexElementUsage::Position, 0));
m_particleAttribLinkFeedback[1] =
GLVertexAttribLink(glGetAttribLocation(hProgram, "ParticleVelocity"), vertexDecl.VertexElementGetIndexOf(VertexElementUsage::Custom, 0));
m_particleAttribLinkFeedback[2] =
GLVertexAttribLink(glGetAttribLocation(hProgram, "ParticleEnergy"), vertexDecl.VertexElementGetIndexOf(VertexElementUsage::Custom, 1));
m_locFeedbackDeltaTime = glGetUniformLocation(hProgram, "DeltaTime");
m_locFeedbackUpperBoundaryY = glGetUniformLocation(hProgram, "UpperBoundaryY");
m_locFeedbackLowerBoundaryY = glGetUniformLocation(hProgram, "LowerBoundaryY");
}
GL_CHECK(glGenTransformFeedbacks(1, &m_transformFeedbackObject));
GL_CHECK(glGenQueries(1, &m_transformFeedbackQuery));
ConstructRenderShader(contentManager);
}
ParticleSystemSnow::~ParticleSystemSnow()
{
glDeleteQueries(1, &m_transformFeedbackQuery);
glDeleteTransformFeedbacks(1, &m_transformFeedbackObject);
}
void ParticleSystemSnow::Update(const DemoTime& demoTime)
{
// Advance the simulation using the GPU :)
glEnable(GL_RASTERIZER_DISCARD);
glBindBuffer(m_pCurrentVertexBuffer->GetTarget(), m_pCurrentVertexBuffer->Get());
m_pCurrentVertexBuffer->EnableAttribArrays(m_particleAttribLinkFeedback);
glBindTransformFeedback(GL_TRANSFORM_FEEDBACK, m_transformFeedbackObject);
glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, m_pOtherVertexBuffer->Get());
glUseProgram(m_programTransform.Get());
glUniform1f(m_locFeedbackDeltaTime, demoTime.DeltaTime);
glUniform1f(m_locFeedbackUpperBoundaryY, m_ranges.Y);
glUniform1f(m_locFeedbackLowerBoundaryY, -m_ranges.Y);
glBeginQuery(GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN, m_transformFeedbackQuery);
glBeginTransformFeedback(GL_POINTS);
glDrawArrays(GL_POINTS, 0, m_capacity);
glEndTransformFeedback();
glEndQuery(GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN);
m_pCurrentVertexBuffer->DisableAttribArrays();
glDisable(GL_RASTERIZER_DISCARD);
std::swap(m_pCurrentVertexBuffer, m_pOtherVertexBuffer);
}
void ParticleSystemSnow::Draw(const ParticleDrawContext& context)
{
glEnable(GL_CULL_FACE);
glUseProgram(0);
m_pipeline.Bind();
// configure it
m_pipeline.UseProgramStages(m_shaderVert, GL_VERTEX_SHADER_BIT);
m_pipeline.UseProgramStages(m_shaderGeom, GL_GEOMETRY_SHADER_BIT_EXT, true);
m_pipeline.UseProgramStages(m_shaderFrag, GL_FRAGMENT_SHADER_BIT);
// Load the matrices
if (m_locViewProjectionMatrix >= 0)
{
glProgramUniformMatrix4fv(m_shaderGeom.Get(), m_locViewProjectionMatrix, 1, GL_FALSE, context.MatrixWorldView.DirectAccess());
}
if (m_locWorldViewProjectionMatrix >= 0)
{
glProgramUniformMatrix4fv(m_shaderGeom.Get(), m_locWorldViewProjectionMatrix, 1, GL_FALSE, context.MatrixWorldViewProjection.DirectAccess());
}
if (m_locPointSize >= 0)
{
glProgramUniform1f(m_shaderGeom.Get(), m_locPointSize, m_pointSize);
}
glBindBuffer(m_pCurrentVertexBuffer->GetTarget(), m_pCurrentVertexBuffer->Get());
m_pCurrentVertexBuffer->EnableAttribArrays(m_particleAttribLink);
glDrawArrays(GL_POINTS, 0, m_capacity);
m_pCurrentVertexBuffer->DisableAttribArrays();
m_pipeline.BindClear();
}
void ParticleSystemSnow::ConstructRenderShader(const std::shared_ptr<IContentManager>& contentManager)
{
glUseProgram(0);
std::string strVert = contentManager->ReadAllText("PSSnow_Render.vert");
std::string strFrag = contentManager->ReadAllText("PSSnow_Render.frag");
std::string strGeom = contentManager->ReadAllText("PSSnow_Render.geom");
{
// GLShader shaderVert(GL_VERTEX_SHADER, strVert);
// GLShader shaderFrag(GL_FRAGMENT_SHADER, strFrag);
// GLShader shaderGeom(GL_GEOMETRY_SHADER_EXT, strGeom);
}
m_shaderVert.Reset(GL_VERTEX_SHADER, strVert);
m_shaderGeom.Reset(GL_GEOMETRY_SHADER_EXT, strGeom);
m_shaderFrag.Reset(GL_FRAGMENT_SHADER, strFrag);
GL_CHECK_FOR_ERROR();
auto vertexDecl = ParticleSnowGPU::GetVertexDeclaration();
m_particleAttribLink[0] = GLVertexAttribLink(glGetAttribLocation(m_shaderVert.Get(), "ParticlePosition"),
vertexDecl.VertexElementGetIndexOf(VertexElementUsage::Position, 0));
m_locViewProjectionMatrix = glGetUniformLocation(m_shaderGeom.Get(), "WorldView");
m_locWorldViewProjectionMatrix = glGetUniformLocation(m_shaderGeom.Get(), "WorldViewProjection");
m_locPointSize = glGetUniformLocation(m_shaderGeom.Get(), "PointSize");
// if (m_locViewProjectionMatrix < 0 || m_locWorldViewProjectionMatrix < 0)
// throw NotSupportedException("The shader does not conform to the expected behavior");
glUseProgram(0);
m_pipeline.Reset(true);
GL_CHECK_FOR_ERROR();
}
}
| 43.106838 | 150 | 0.730743 | alexvonduar |
915f5ac519c0366f24fa768b0db8dffd7d45f472 | 21,519 | cpp | C++ | code/appRenderState.cpp | robbitay/ConstPort | d948ceb5f0e22504640578e3ef31e3823b29c1c3 | [
"Unlicense"
] | null | null | null | code/appRenderState.cpp | robbitay/ConstPort | d948ceb5f0e22504640578e3ef31e3823b29c1c3 | [
"Unlicense"
] | null | null | null | code/appRenderState.cpp | robbitay/ConstPort | d948ceb5f0e22504640578e3ef31e3823b29c1c3 | [
"Unlicense"
] | null | null | null | /*
File: appRenderState.cpp
Author: Taylor Robbins
Date: 06\13\2017
Description:
** Lots of functions that facilitate drawing different
** primitives and common things
#included from app.cpp
*/
void InitializeRenderState()
{
Assert(renderState != nullptr);
ClearPointer(renderState);
Vertex_t squareVertices[] =
{
{ {0.0f, 0.0f, 0.0f}, NewVec4(NewColor(Color_White)), {0.0f, 0.0f} },
{ {1.0f, 0.0f, 0.0f}, NewVec4(NewColor(Color_White)), {1.0f, 0.0f} },
{ {0.0f, 1.0f, 0.0f}, NewVec4(NewColor(Color_White)), {0.0f, 1.0f} },
{ {0.0f, 1.0f, 0.0f}, NewVec4(NewColor(Color_White)), {0.0f, 1.0f} },
{ {1.0f, 0.0f, 0.0f}, NewVec4(NewColor(Color_White)), {1.0f, 0.0f} },
{ {1.0f, 1.0f, 0.0f}, NewVec4(NewColor(Color_White)), {1.0f, 1.0f} },
};
renderState->squareBuffer = CreateVertexBuffer(squareVertices, ArrayCount(squareVertices));
renderState->gradientTexture = LoadTexture("Resources/Textures/gradient.png", false, false);
renderState->circleTexture = LoadTexture("Resources/Sprites/circle.png", false, false);
Color_t textureData = {Color_White};
renderState->dotTexture = CreateTexture((u8*)&textureData, 1, 1);
renderState->viewport = NewRec(0, 0, (r32)RenderScreenSize.x, (r32)RenderScreenSize.y);
renderState->worldMatrix = Mat4_Identity;
renderState->viewMatrix = Mat4_Identity;
renderState->projectionMatrix = Mat4_Identity;
renderState->doGrayscaleGradient = false;
renderState->useAlphaTexture = false;
renderState->sourceRectangle = NewRec(0, 0, 1, 1);
renderState->depth = 1.0f;
renderState->circleRadius = 0.0f;
renderState->circleInnerRadius = 0.0f;
renderState->color = NewColor(Color_White);
renderState->secondaryColor = NewColor(Color_White);
}
//+================================================================+
//| State Change Functions |
//+================================================================+
void RsUpdateShader()
{
Assert(renderState->boundShader != nullptr);
if (renderState->boundBuffer != nullptr)
{
glBindVertexArray(renderState->boundShader->vertexArray);
glBindBuffer(GL_ARRAY_BUFFER, renderState->boundBuffer->id);
glVertexAttribPointer(renderState->boundShader->locations.positionAttrib, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex_t), (void*)0);
glVertexAttribPointer(renderState->boundShader->locations.colorAttrib, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex_t), (void*)sizeof(v3));
glVertexAttribPointer(renderState->boundShader->locations.texCoordAttrib, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex_t), (void*)(sizeof(v3)+sizeof(v4)));
}
if (renderState->boundTexture != nullptr)
{
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, renderState->boundTexture->id);
glUniform1i(renderState->boundShader->locations.diffuseTexture, 0);
glUniform2f(renderState->boundShader->locations.textureSize, (r32)renderState->boundTexture->width, (r32)renderState->boundTexture->height);
}
if (renderState->boundAlphaTexture != nullptr)
{
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, renderState->boundAlphaTexture->id);
glUniform1i(renderState->boundShader->locations.alphaTexture, 1);
glUniform1i(renderState->boundShader->locations.useAlphaTexture, 1);
}
else
{
glUniform1i(renderState->boundShader->locations.useAlphaTexture, 0);
}
if (renderState->boundFrameBuffer != nullptr)
{
glBindFramebuffer(GL_FRAMEBUFFER, renderState->boundFrameBuffer->id);
}
else
{
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
glUniformMatrix4fv(renderState->boundShader->locations.worldMatrix, 1, GL_FALSE, &renderState->worldMatrix.values[0][0]);
glUniformMatrix4fv(renderState->boundShader->locations.viewMatrix, 1, GL_FALSE, &renderState->viewMatrix.values[0][0]);
glUniformMatrix4fv(renderState->boundShader->locations.projectionMatrix, 1, GL_FALSE, &renderState->projectionMatrix.values[0][0]);
glUniform1i(renderState->boundShader->locations.doGrayscaleGradient, renderState->doGrayscaleGradient ? 1 : 0);
glUniform4f(renderState->boundShader->locations.sourceRectangle, renderState->sourceRectangle.x, renderState->sourceRectangle.y, renderState->sourceRectangle.width, renderState->sourceRectangle.height);
glUniform1f(renderState->boundShader->locations.circleRadius, renderState->circleRadius);
glUniform1f(renderState->boundShader->locations.circleInnerRadius, renderState->circleInnerRadius);
v4 colorVec = NewVec4(renderState->color);
glUniform4f(renderState->boundShader->locations.diffuseColor, colorVec.r, colorVec.g, colorVec.b, colorVec.a);
colorVec = NewVec4(renderState->secondaryColor);
glUniform4f(renderState->boundShader->locations.secondaryColor, colorVec.r, colorVec.g, colorVec.b, colorVec.a);
}
void RsBindShader(const Shader_t* shaderPntr)
{
renderState->boundShader = shaderPntr;
glUseProgram(shaderPntr->programId);
}
void RsBindFont(const Font_t* fontPntr)
{
renderState->boundFont = fontPntr;
}
void RsBindTexture(const Texture_t* texturePntr)
{
renderState->boundTexture = texturePntr;
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, renderState->boundTexture->id);
glUniform1i(renderState->boundShader->locations.diffuseTexture, 0);
glUniform2f(renderState->boundShader->locations.textureSize, (r32)renderState->boundTexture->width, (r32)renderState->boundTexture->height);
}
void RsBindAlphaTexture(const Texture_t* texturePntr)
{
renderState->boundAlphaTexture = texturePntr;
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, renderState->boundAlphaTexture->id);
glUniform1i(renderState->boundShader->locations.alphaTexture, 1);
glUniform1i(renderState->boundShader->locations.useAlphaTexture, 1);
}
void RsDisableAlphaTexture()
{
renderState->boundAlphaTexture = nullptr;
glUniform1i(renderState->boundShader->locations.useAlphaTexture, 0);
}
void RsBindBuffer(const VertexBuffer_t* vertBufferPntr)
{
renderState->boundBuffer = vertBufferPntr;
glBindVertexArray(renderState->boundShader->vertexArray);
glBindBuffer(GL_ARRAY_BUFFER, vertBufferPntr->id);
glVertexAttribPointer(renderState->boundShader->locations.positionAttrib, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex_t), (void*)0);
glVertexAttribPointer(renderState->boundShader->locations.colorAttrib, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex_t), (void*)sizeof(v3));
glVertexAttribPointer(renderState->boundShader->locations.texCoordAttrib, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex_t), (void*)(sizeof(v3)+sizeof(v4)));
}
void RsBindFrameBuffer(const FrameBuffer_t* frameBuffer)
{
renderState->boundFrameBuffer = frameBuffer;
if (frameBuffer == nullptr)
{
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
else
{
glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer->id);
}
}
void RsSetWorldMatrix(const mat4& worldMatrix)
{
renderState->worldMatrix = worldMatrix;
glUniformMatrix4fv(renderState->boundShader->locations.worldMatrix, 1, GL_FALSE, &worldMatrix.values[0][0]);
}
void RsSetViewMatrix(const mat4& viewMatrix)
{
renderState->viewMatrix = viewMatrix;
glUniformMatrix4fv(renderState->boundShader->locations.viewMatrix, 1, GL_FALSE, &viewMatrix.values[0][0]);
}
void RsSetProjectionMatrix(const mat4& projectionMatrix)
{
renderState->projectionMatrix = projectionMatrix;
glUniformMatrix4fv(renderState->boundShader->locations.projectionMatrix, 1, GL_FALSE, &projectionMatrix.values[0][0]);
}
void RsSetViewport(rec viewport)
{
renderState->viewport = viewport;
#if DOUBLE_RESOLUTION
glViewport(
(i32)renderState->viewport.x*2,
(i32)(RenderScreenSize.y*2 - renderState->viewport.height*2 - renderState->viewport.y*2),
(i32)renderState->viewport.width*2,
(i32)renderState->viewport.height*2
);
#else
glViewport(
(i32)renderState->viewport.x,
(i32)(RenderScreenSize.y - renderState->viewport.height - renderState->viewport.y),
(i32)renderState->viewport.width,
(i32)renderState->viewport.height
);
#endif
mat4 projMatrix;
projMatrix = Mat4Scale(NewVec3(2.0f/viewport.width, -2.0f/viewport.height, 1.0f));
projMatrix = Mat4Multiply(projMatrix, Mat4Translate(NewVec3(-viewport.width/2.0f, -viewport.height/2.0f, 0.0f)));
projMatrix = Mat4Multiply(projMatrix, Mat4Translate(NewVec3(-renderState->viewport.x, -renderState->viewport.y, 0.0f)));
RsSetProjectionMatrix(projMatrix);
}
void RsSetColor(Color_t color)
{
renderState->color = color;
v4 colorVec = NewVec4(color);
glUniform4f(renderState->boundShader->locations.diffuseColor, colorVec.r, colorVec.g, colorVec.b, colorVec.a);
}
void RsSetSecondaryColor(Color_t color)
{
renderState->secondaryColor = color;
v4 colorVec = NewVec4(color);
glUniform4f(renderState->boundShader->locations.secondaryColor, colorVec.r, colorVec.g, colorVec.b, colorVec.a);
}
void RsSetSourceRectangle(rec sourceRectangle)
{
renderState->sourceRectangle = sourceRectangle;
glUniform4f(renderState->boundShader->locations.sourceRectangle, sourceRectangle.x, sourceRectangle.y, sourceRectangle.width, sourceRectangle.height);
}
void RsSetGradientEnabled(bool doGradient)
{
renderState->doGrayscaleGradient = doGradient;
glUniform1i(renderState->boundShader->locations.doGrayscaleGradient, doGradient ? 1 : 0);
}
void RsSetCircleRadius(r32 radius, r32 innerRadius = 0.0f)
{
renderState->circleRadius = radius;
renderState->circleInnerRadius = innerRadius;
glUniform1f(renderState->boundShader->locations.circleRadius, radius);
glUniform1f(renderState->boundShader->locations.circleInnerRadius, innerRadius);
}
void RsSetDepth(r32 depth)
{
renderState->depth = depth;
}
void RsBegin(const Shader_t* startShader, const Font_t* startFont, rec viewport)
{
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glEnable(GL_ALPHA_TEST);
glAlphaFunc(GL_GEQUAL, 0.1f);
RsBindShader(startShader);
RsBindFont(startFont);
RsBindTexture(&renderState->dotTexture);
RsBindBuffer(&renderState->squareBuffer);
RsBindFrameBuffer(nullptr);
RsDisableAlphaTexture();
RsSetWorldMatrix(Matrix4_Identity);
RsSetViewMatrix(Matrix4_Identity);
RsSetProjectionMatrix(Matrix4_Identity);
RsSetViewport(viewport);
RsSetColor(NewColor(Color_White));
RsSetSecondaryColor(NewColor(Color_White));
RsSetSourceRectangle(NewRec(0, 0, 1, 1));
RsSetGradientEnabled(false);
RsSetCircleRadius(0.0f, 0.0f);
RsSetDepth(1.0f);
}
// +--------------------------------------------------------------+
// | Drawing Functions |
// +--------------------------------------------------------------+
void RsClearColorBuffer(Color_t clearColor)
{
v4 clearColorVec = NewVec4(clearColor);
glClearColor(clearColorVec.x, clearColorVec.y, clearColorVec.z, clearColorVec.w);
glClear(GL_COLOR_BUFFER_BIT);
}
void RsClearDepthBuffer(r32 clearDepth)
{
glClearDepth(clearDepth);
glClear(GL_DEPTH_BUFFER_BIT);
}
void RsDrawTexturedRec(rec rectangle, Color_t color)
{
RsBindTexture(renderState->boundTexture);
RsSetSourceRectangle(NewRec(0, 0, 1, 1));
RsSetColor(color);
mat4 worldMatrix = Mat4Multiply(
Mat4Translate(NewVec3(rectangle.x, rectangle.y, renderState->depth)), //Position
Mat4Scale(NewVec3(rectangle.width, rectangle.height, 1.0f))); //Scale
RsSetWorldMatrix(worldMatrix);
RsBindBuffer(&renderState->squareBuffer);
glDrawArrays(GL_TRIANGLES, 0, renderState->squareBuffer.numVertices);
}
void RsDrawTexturedRec(rec rectangle, Color_t color, rec sourceRectangle)
{
rec realSourceRec = NewRec(
sourceRectangle.x / (r32)renderState->boundTexture->width,
sourceRectangle.y / (r32)renderState->boundTexture->height,
sourceRectangle.width / (r32)renderState->boundTexture->width,
sourceRectangle.height / (r32)renderState->boundTexture->height);
RsSetSourceRectangle(realSourceRec);
RsBindTexture(renderState->boundTexture);
RsSetColor(color);
mat4 worldMatrix = Mat4Multiply(
Mat4Translate(NewVec3(rectangle.x, rectangle.y, renderState->depth)), //Position
Mat4Scale(NewVec3(rectangle.width, rectangle.height, 1.0f))); //Scale
RsSetWorldMatrix(worldMatrix);
RsBindBuffer(&renderState->squareBuffer);
glDrawArrays(GL_TRIANGLES, 0, renderState->squareBuffer.numVertices);
}
void RsDrawRectangle(rec rectangle, Color_t color)
{
RsBindTexture(&renderState->dotTexture);
RsSetSourceRectangle(NewRec(0, 0, 1, 1));
RsSetColor(color);
mat4 worldMatrix = Mat4Multiply(
Mat4Translate(NewVec3(rectangle.x, rectangle.y, renderState->depth)), //Position
Mat4Scale(NewVec3(rectangle.width, rectangle.height, 1.0f))); //Scale
RsSetWorldMatrix(worldMatrix);
RsBindBuffer(&renderState->squareBuffer);
glDrawArrays(GL_TRIANGLES, 0, renderState->squareBuffer.numVertices);
}
void RsDrawButton(rec rectangle, Color_t backgroundColor, Color_t borderColor, r32 borderWidth = 1.0f)
{
RsDrawRectangle(rectangle, backgroundColor);
RsDrawRectangle(NewRec(rectangle.x, rectangle.y, rectangle.width, borderWidth), borderColor);
RsDrawRectangle(NewRec(rectangle.x, rectangle.y, borderWidth, rectangle.height), borderColor);
RsDrawRectangle(NewRec(rectangle.x, rectangle.y + rectangle.height - borderWidth, rectangle.width, borderWidth), borderColor);
RsDrawRectangle(NewRec(rectangle.x + rectangle.width - borderWidth, rectangle.y, borderWidth, rectangle.height), borderColor);
}
void RsDrawGradient(rec rectangle, Color_t color1, Color_t color2, Dir2_t direction)
{
RsBindTexture(&renderState->gradientTexture);
RsSetSourceRectangle(NewRec(0, 0, 1, 1));
RsSetColor(color1);
RsSetSecondaryColor(color2);
RsSetGradientEnabled(true);
mat4 worldMatrix = Mat4_Identity;
switch (direction)
{
case Dir2_Right:
default:
{
worldMatrix = Mat4Multiply(
Mat4Translate(NewVec3(rectangle.x, rectangle.y, renderState->depth)),
Mat4Scale(NewVec3(rectangle.width, rectangle.height, 1.0f)));
} break;
case Dir2_Left:
{
worldMatrix = Mat4Multiply(
Mat4Translate(NewVec3(rectangle.x + rectangle.width, rectangle.y, renderState->depth)),
Mat4Scale(NewVec3(-rectangle.width, rectangle.height, 1.0f)));
} break;
case Dir2_Down:
{
worldMatrix = Mat4Multiply(
Mat4Translate(NewVec3(rectangle.x + rectangle.width, rectangle.y, renderState->depth)),
Mat4RotateZ(ToRadians(90)),
Mat4Scale(NewVec3(rectangle.height, rectangle.width, 1.0f)));
} break;
case Dir2_Up:
{
worldMatrix = Mat4Multiply(
Mat4Translate(NewVec3(rectangle.x + rectangle.width, rectangle.y + rectangle.height, renderState->depth)),
Mat4RotateZ(ToRadians(90)),
Mat4Scale(NewVec3(-rectangle.height, rectangle.width, 1.0f)));
} break;
};
RsSetWorldMatrix(worldMatrix);
RsBindBuffer(&renderState->squareBuffer);
glDrawArrays(GL_TRIANGLES, 0, renderState->squareBuffer.numVertices);
RsSetGradientEnabled(false);
}
void RsDrawLine(v2 p1, v2 p2, r32 thickness, Color_t color)
{
RsBindTexture(&renderState->dotTexture);
RsSetSourceRectangle(NewRec(0, 0, 1, 1));
RsSetColor(color);
r32 length = Vec2Length(p2 - p1);
r32 rotation = AtanR32(p2.y - p1.y, p2.x - p1.x);
mat4 worldMatrix = Mat4_Identity;
worldMatrix = Mat4Multiply(Mat4Translate(NewVec3(0.0f, -0.5f, 0.0f)), worldMatrix); //Centering
worldMatrix = Mat4Multiply(Mat4Scale(NewVec3(length, thickness, 1.0f)), worldMatrix); //Scale
worldMatrix = Mat4Multiply(Mat4RotateZ(rotation), worldMatrix); //Rotation
worldMatrix = Mat4Multiply(Mat4Translate(NewVec3(p1.x, p1.y, renderState->depth)), worldMatrix); //Position
RsSetWorldMatrix(worldMatrix);
RsBindBuffer(&renderState->squareBuffer);
glDrawArrays(GL_TRIANGLES, 0, renderState->squareBuffer.numVertices);
}
void RsDrawCircle(v2 center, r32 radius, Color_t color)
{
RsSetCircleRadius(1.0f, 0.0f);
RsDrawRectangle(NewRec(center.x - radius, center.y - radius, radius*2, radius*2), color);
RsSetCircleRadius(0.0f, 0.0f);
}
void RsDrawDonut(v2 center, r32 radius, r32 innerRadius, Color_t color)
{
r32 realInnerRadius = ClampR32(innerRadius / radius, 0.0f, 1.0f);
RsSetCircleRadius(1.0f, realInnerRadius);
RsDrawRectangle(NewRec(center.x - radius, center.y - radius, radius*2, radius*2), color);
RsSetCircleRadius(0.0f, 0.0f);
}
void RsDrawCharacter(u32 charIndex, v2 bottomLeft, Color_t color, r32 scale = 1.0f)
{
const FontCharInfo_t* charInfo = &renderState->boundFont->chars[charIndex];
rec sourceRectangle = NewRec((r32)charInfo->x, (r32)charInfo->y, (r32)charInfo->width, (r32)charInfo->height);
rec drawRectangle = NewRec(
bottomLeft.x + scale*charInfo->offset.x,
bottomLeft.y + scale*charInfo->offset.y,
scale*charInfo->width,
scale*charInfo->height);
if (renderState->boundTexture != &renderState->boundFont->bitmap)
{
RsBindTexture(&renderState->boundFont->bitmap);
}
RsDrawTexturedRec(drawRectangle, color, sourceRectangle);
}
void RsDrawHexCharacter(u8 hexValue, v2 bottomLeft, Color_t color, r32 scale = 1.0f)
{
const Font_t* boundFont = renderState->boundFont;
const FontCharInfo_t* spaceCharInfo = &boundFont->chars[GetFontCharIndex(boundFont, ' ')];
rec charRec = NewRec(bottomLeft.x, bottomLeft.y + boundFont->maxExtendDown*scale - (boundFont->lineHeight-1)*scale, spaceCharInfo->advanceX*scale, (boundFont->lineHeight-1)*scale);
charRec.x = (r32)RoundR32(charRec.x);
charRec.y = (r32)RoundR32(charRec.y);
RsDrawRectangle(charRec, color);
RsDrawRectangle(NewRec(charRec.x, charRec.y, 1, charRec.height), GC->colors.textBackground);
// RsDrawButton(charRec, NewColor(Color_TransparentBlack), color, 1.0f);
r32 innerCharScale = scale*5/8;
char upperHexChar = UpperHexChar(hexValue);
char lowerHexChar = LowerHexChar(hexValue);
u32 upperCharIndex = GetFontCharIndex(boundFont, upperHexChar);
const FontCharInfo_t* upperCharInfo = &boundFont->chars[upperCharIndex];
u32 lowerCharIndex = GetFontCharIndex(boundFont, lowerHexChar);
const FontCharInfo_t* lowerCharInfo = &boundFont->chars[lowerCharIndex];
v2 charPosUpper = charRec.topLeft + NewVec2(1, upperCharInfo->height*innerCharScale + 1);
v2 charPosLower = charRec.topLeft + NewVec2(charRec.width - lowerCharInfo->width*innerCharScale - 1, charRec.height - 1);
// RsDrawCharacter(upperCharIndex, charPosUpper, color, innerCharScale);
// RsDrawCharacter(lowerCharIndex, charPosLower, color, innerCharScale);
RsDrawCharacter(upperCharIndex, charPosUpper, GC->colors.textBackground, innerCharScale);
RsDrawCharacter(lowerCharIndex, charPosLower, GC->colors.textBackground, innerCharScale);
}
void RsDrawString(const char* string, u32 numCharacters, v2 position, Color_t color, r32 scale = 1.0f, Alignment_t alignment = Alignment_Left)
{
RsBindTexture(&renderState->boundFont->bitmap);
v2 stringSize = MeasureString(renderState->boundFont, string, numCharacters);
v2 currentPos = position;
switch (alignment)
{
case Alignment_Center: currentPos.x -= stringSize.x/2; break;
case Alignment_Right: currentPos.x -= stringSize.x; break;
case Alignment_Left: break;
};
for (u32 cIndex = 0; cIndex < numCharacters; cIndex++)
{
if (string[cIndex] == '\t')
{
u32 spaceIndex = GetFontCharIndex(renderState->boundFont, ' ');
currentPos.x += renderState->boundFont->chars[spaceIndex].advanceX * GC->tabWidth * scale;
}
else if (IsCharClassPrintable(string[cIndex]) == false)
{
//Draw
RsDrawHexCharacter(string[cIndex], currentPos, color, scale);
u32 spaceIndex = GetFontCharIndex(renderState->boundFont, ' ');
currentPos.x += renderState->boundFont->chars[spaceIndex].advanceX * scale;
}
else
{
u32 charIndex = GetFontCharIndex(renderState->boundFont, string[cIndex]);
RsDrawCharacter(charIndex, currentPos, color, scale);
currentPos.x += renderState->boundFont->chars[charIndex].advanceX * scale;
}
}
}
void RsDrawString(const char* nullTermString, v2 position, Color_t color, r32 scale = 1.0f, Alignment_t alignment = Alignment_Left)
{
RsDrawString(nullTermString, (u32)strlen(nullTermString), position, color, scale, alignment);
}
void RsPrintString(v2 position, Color_t color, r32 scale, const char* formatString, ...)
{
char printBuffer[256] = {};
va_list args;
va_start(args, formatString);
u32 length = (u32)vsnprintf(printBuffer, 256-1, formatString, args);
va_end(args);
RsDrawString(printBuffer, length, position, color, scale);
}
void RsDrawFormattedString(const char* string, u32 numCharacters, v2 position, r32 maxWidth, Color_t color, Alignment_t alignment = Alignment_Left, bool preserveWords = true)
{
u32 cIndex = 0;
v2 drawPos = position;
while (cIndex < numCharacters)
{
u32 numChars = FindNextFormatChunk(renderState->boundFont, &string[cIndex], numCharacters - cIndex, maxWidth, preserveWords);
if (numChars == 0) { numChars = 1; }
while (numChars > 1 && IsCharClassWhitespace(string[cIndex + numChars-1]))
{
numChars--;
}
RsDrawString(&string[cIndex], numChars, drawPos, color, 1.0f, alignment);
if (cIndex+numChars < numCharacters && string[cIndex+numChars] == '\r')
{
numChars++;
}
if (cIndex+numChars < numCharacters && string[cIndex+numChars] == '\n')
{
numChars++;
}
while (cIndex+numChars < numCharacters && string[cIndex+numChars] == ' ')
{
numChars++;
}
drawPos.y += renderState->boundFont->lineHeight;
cIndex += numChars;
}
}
void RsDrawFormattedString(const char* nullTermString, v2 position, r32 maxWidth, Color_t color, Alignment_t alignment = Alignment_Left, bool preserveWords = true)
{
u32 numCharacters = (u32)strlen(nullTermString);
RsDrawFormattedString(nullTermString, numCharacters, position, maxWidth, color, alignment, preserveWords);
}
| 37.165803 | 203 | 0.749291 | robbitay |
915fd60f472926d391f552a86421bc891f379a9d | 8,110 | cpp | C++ | src/controller_base.cpp | blackberry/Wesnoth | 8b307689158db568ecc6cc3b537e8d382ccea449 | [
"Unlicense"
] | 12 | 2015-03-04T15:07:00.000Z | 2019-09-13T16:31:06.000Z | src/controller_base.cpp | blackberry/Wesnoth | 8b307689158db568ecc6cc3b537e8d382ccea449 | [
"Unlicense"
] | null | null | null | src/controller_base.cpp | blackberry/Wesnoth | 8b307689158db568ecc6cc3b537e8d382ccea449 | [
"Unlicense"
] | 5 | 2017-04-22T08:16:48.000Z | 2020-07-12T03:35:16.000Z | /* $Id: controller_base.cpp 48315 2011-01-16 09:49:08Z mordante $ */
/*
Copyright (C) 2006 - 2011 by Joerg Hinrichs <joerg.hinrichs@alice-dsl.de>
wesnoth playlevel Copyright (C) 2003 by David White <dave@whitevine.net>
Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY.
See the COPYING file for more details.
*/
#include "controller_base.hpp"
#include "dialogs.hpp"
#include "display.hpp"
#include "foreach.hpp"
#include "game_preferences.hpp"
#include "log.hpp"
#include "mouse_handler_base.hpp"
static lg::log_domain log_display("display");
#define ERR_DP LOG_STREAM(err, log_display)
controller_base::controller_base(
int ticks, const config& game_config, CVideo& /*video*/) :
game_config_(game_config),
ticks_(ticks),
key_(),
browse_(false),
scrolling_(false)
{
}
controller_base::~controller_base()
{
}
int controller_base::get_ticks() {
return ticks_;
}
void controller_base::handle_event(const SDL_Event& event)
{
if(gui::in_dialog()) {
return;
}
switch(event.type) {
case SDL_KEYDOWN:
// Detect key press events, unless there something that has keyboard focus
// in which case the key press events should go only to it.
if(have_keyboard_focus()) {
process_keydown_event(event);
hotkey::key_event(get_display(),event.key,this);
} else {
process_focus_keydown_event(event);
break;
}
// intentionally fall-through
case SDL_KEYUP:
process_keyup_event(event);
break;
case SDL_MOUSEMOTION:
// Ignore old mouse motion events in the event queue
SDL_Event new_event;
if(SDL_PeepEvents(&new_event,1,SDL_GETEVENT,
SDL_EVENTMASK(SDL_MOUSEMOTION)) > 0) {
while(SDL_PeepEvents(&new_event,1,SDL_GETEVENT,
SDL_EVENTMASK(SDL_MOUSEMOTION)) > 0) {};
get_mouse_handler_base().mouse_motion_event(new_event.motion, browse_);
} else {
get_mouse_handler_base().mouse_motion_event(event.motion, browse_);
}
break;
case SDL_MOUSEBUTTONDOWN:
case SDL_MOUSEBUTTONUP:
get_mouse_handler_base().mouse_press(event.button, browse_);
post_mouse_press(event);
if (get_mouse_handler_base().get_show_menu()){
show_menu(get_display().get_theme().context_menu()->items(),event.button.x,event.button.y,true);
}
break;
case SDL_ACTIVEEVENT:
if (event.active.type == SDL_APPMOUSEFOCUS && event.active.gain == 0) {
if (get_mouse_handler_base().is_dragging()) {
//simulate mouse button up when the app has lost mouse focus
//this should be a general fix for the issue when the mouse
//is dragged out of the game window and then the button is released
int x, y;
Uint8 mouse_flags = SDL_GetMouseState(&x, &y);
if ((mouse_flags & SDL_BUTTON_LEFT) == 0) {
get_mouse_handler_base().mouse_press(event.button, browse_);
post_mouse_press(event);
}
}
}
break;
default:
break;
}
}
bool controller_base::have_keyboard_focus()
{
return true;
}
void controller_base::process_focus_keydown_event(const SDL_Event& /*event*/) {
//no action by default
}
void controller_base::process_keydown_event(const SDL_Event& /*event*/) {
//no action by default
}
void controller_base::process_keyup_event(const SDL_Event& /*event*/) {
//no action by default
}
void controller_base::post_mouse_press(const SDL_Event& /*event*/) {
//no action by default
}
bool controller_base::handle_scroll(CKey& key, int mousex, int mousey, int mouse_flags)
{
bool mouse_in_window = (SDL_GetAppState() & SDL_APPMOUSEFOCUS) != 0
|| preferences::get("scroll_when_mouse_outside", true);
bool keyboard_focus = have_keyboard_focus();
int scroll_speed = preferences::scroll_speed();
int dx = 0, dy = 0;
int scroll_threshold = (preferences::mouse_scroll_enabled())
? preferences::mouse_scroll_threshold() : 0;
foreach (const theme::menu& m, get_display().get_theme().menus()) {
if (point_in_rect(mousex, mousey, m.get_location())) {
scroll_threshold = 0;
}
}
if ((key[SDLK_UP] && keyboard_focus) ||
(mousey < scroll_threshold && mouse_in_window))
{
dy -= scroll_speed;
}
if ((key[SDLK_DOWN] && keyboard_focus) ||
(mousey > get_display().h() - scroll_threshold && mouse_in_window))
{
dy += scroll_speed;
}
if ((key[SDLK_LEFT] && keyboard_focus) ||
(mousex < scroll_threshold && mouse_in_window))
{
dx -= scroll_speed;
}
if ((key[SDLK_RIGHT] && keyboard_focus) ||
(mousex > get_display().w() - scroll_threshold && mouse_in_window))
{
dx += scroll_speed;
}
if ((mouse_flags & SDL_BUTTON_MMASK) != 0 && preferences::middle_click_scrolls()) {
const SDL_Rect& rect = get_display().map_outside_area();
if (point_in_rect(mousex, mousey,rect)) {
// relative distance from the center to the border
// NOTE: the view is a rectangle, so can be more sensible in one direction
// but seems intuitive to use and it's useful since you must
// more often scroll in the direction where the view is shorter
const double xdisp = ((1.0*mousex / rect.w) - 0.5);
const double ydisp = ((1.0*mousey / rect.h) - 0.5);
// 4.0 give twice the normal speed when mouse is at border (xdisp=0.5)
int speed = 4 * scroll_speed;
dx += round_double(xdisp * speed);
dy += round_double(ydisp * speed);
}
}
return get_display().scroll(dx, dy);
}
void controller_base::play_slice(bool is_delay_enabled)
{
CKey key;
events::pump();
events::raise_process_event();
events::raise_draw_event();
slice_before_scroll();
const theme::menu* const m = get_display().menu_pressed();
if(m != NULL) {
const SDL_Rect& menu_loc = m->location(get_display().screen_area());
show_menu(m->items(),menu_loc.x+1,menu_loc.y + menu_loc.h + 1,false);
return;
}
int mousex, mousey;
Uint8 mouse_flags = SDL_GetMouseState(&mousex, &mousey);
bool was_scrolling = scrolling_;
scrolling_ = handle_scroll(key, mousex, mousey, mouse_flags);
get_display().draw();
// be nice when window is not visible
// NOTE should be handled by display instead, to only disable drawing
if (is_delay_enabled && (SDL_GetAppState() & SDL_APPACTIVE) == 0) {
get_display().delay(200);
}
if (!scrolling_ && was_scrolling) {
// scrolling ended, update the cursor and the brightened hex
get_mouse_handler_base().mouse_update(browse_);
}
slice_end();
}
void controller_base::slice_before_scroll()
{
//no action by default
}
void controller_base::slice_end()
{
//no action by default
}
void controller_base::show_menu(const std::vector<std::string>& items_arg, int xloc, int yloc, bool context_menu)
{
std::vector<std::string> items = items_arg;
hotkey::HOTKEY_COMMAND command;
std::vector<std::string>::iterator i = items.begin();
while(i != items.end()) {
command = hotkey::get_hotkey(*i).get_id();
if(!can_execute_command(command)
|| (context_menu && !in_context_menu(command))) {
i = items.erase(i);
continue;
}
++i;
}
if(items.empty())
return;
command_executor::show_menu(items, xloc, yloc, context_menu, get_display());
}
bool controller_base::in_context_menu(hotkey::HOTKEY_COMMAND /*command*/) const
{
return true;
}
const config& controller_base::get_theme(const config& game_config, std::string theme_name)
{
if (theme_name.empty()) theme_name = preferences::theme();
if (const config &c = game_config.find_child("theme", "name", theme_name))
return c;
ERR_DP << "Theme '" << theme_name << "' not found. Trying the default theme.\n";
if (const config &c = game_config.find_child("theme", "name", "Default"))
return c;
ERR_DP << "Default theme not found.\n";
static config empty;
return empty;
}
| 30.374532 | 114 | 0.690012 | blackberry |
916178b1de3174af3714a7802e13933ca253674e | 3,321 | cpp | C++ | iniparser.cpp | IvanSafonov/iniparser | 6aad81d1a607aaf64c4e26ea9c3f6a877a40ae2f | [
"MIT"
] | 1 | 2020-10-18T23:56:43.000Z | 2020-10-18T23:56:43.000Z | iniparser.cpp | IvanSafonov/iniparser | 6aad81d1a607aaf64c4e26ea9c3f6a877a40ae2f | [
"MIT"
] | null | null | null | iniparser.cpp | IvanSafonov/iniparser | 6aad81d1a607aaf64c4e26ea9c3f6a877a40ae2f | [
"MIT"
] | null | null | null | #include "iniparser.h"
#include <fstream>
#include <regex>
#include <algorithm>
#include <set>
using namespace std;
IniParser::IniParser()
{
}
IniParser::~IniParser()
{
}
bool IniParser::load(const std::string &fileName) {
ifstream file;
file.open(fileName);
if (!file)
return false;
regex rxComment{R"(^\s*[;#].*$)"};
regex rxSection{R"(^\s*\[([^\]]+)\])"};
regex rxOption{R"(^\s*([^=\s]+)\s*=\s*(.*)$)"};
regex rxValueQuoted{R"r(^"([^"]*)"(\s*|\s*[;#].*)$)r"};
regex rxValueStripComment{R"(^([^;#]*).*$)"};
regex rxTrim{R"(^\s+|\s+$)"};
string section = "default";
for (string line; getline(file, line);) {
if (regex_match(line, rxComment))
continue;
smatch matches;
if (regex_search(line, matches, rxSection)) {
section = regex_replace(matches[1].str(), rxTrim, "");
toLower(section);
data[section] = map<string, string>();
continue;
}
if (regex_search(line, matches, rxOption)) {
string option = regex_replace(matches[1].str(), rxTrim, "");
toLower(option);
string rawValue = matches[2].str();
if (regex_search(rawValue, matches, rxValueQuoted))
data[section][option] = matches[1].str();
else if (regex_search(rawValue, matches, rxValueStripComment))
data[section][option] = regex_replace(matches[1].str(), rxTrim, "");
}
}
return true;
}
std::list<std::string> IniParser::sections() const
{
list<string> sections;
for (auto &i : data)
sections.push_back(i.first);
return sections;
}
std::list<std::string> IniParser::options(const std::string §ion) const
{
list<string> options;
auto sectionIt = data.find(section);
if (sectionIt == data.end())
return options;
for (auto &i : sectionIt->second)
options.push_back(i.first);
return options;
}
std::string IniParser::get(const std::string §ion, const std::string &option,
const std::string &def) const
{
auto sectionIt = data.find(section);
if (sectionIt == data.end())
return def;
auto &sec = sectionIt->second;
auto optionIt = sec.find(option);
if (optionIt == sec.end())
return def;
return optionIt->second;
}
bool IniParser::getBool(const std::string §ion, const std::string &option, bool def) const
{
string value = get(section, option);
if (value.empty())
return def;
toLower(value);
static const set<string> trueValues = {"on", "true", "1", "enable"};
return trueValues.find(value) != trueValues.end();
}
int IniParser::getInt(const std::string §ion, const std::string &option, int def) const
{
string value = get(section, option);
if (value.empty())
return def;
try {
return stoi(value);
} catch (...) {}
return def;
}
double IniParser::getDouble(const std::string §ion, const std::string &option, double def) const
{
string value = get(section, option);
if (value.empty())
return def;
try {
return stod(value);
} catch (...) {}
return def;
}
void IniParser::toLower(std::string &str) const
{
transform(str.begin(), str.end(), str.begin(), ::tolower);
}
| 25.945313 | 100 | 0.587173 | IvanSafonov |
91659fa248100b19731dd229ae7fa7cfe3a79a15 | 740 | cpp | C++ | src/projections/Mercator.cpp | Kuhlwein/Demiurge | 0981f1d267efed87d51e2b328a93e1fa0be1158d | [
"MIT"
] | 6 | 2020-09-23T19:49:07.000Z | 2022-01-08T15:53:55.000Z | src/projections/Mercator.cpp | Kuhlwein/Demiurge | 0981f1d267efed87d51e2b328a93e1fa0be1158d | [
"MIT"
] | null | null | null | src/projections/Mercator.cpp | Kuhlwein/Demiurge | 0981f1d267efed87d51e2b328a93e1fa0be1158d | [
"MIT"
] | 1 | 2020-09-23T17:53:26.000Z | 2020-09-23T17:53:26.000Z | //
// Created by kuhlwein on 7/5/20.
//
#include "Project.h"
#include "Mercator.h"
Mercator::Mercator(Project *project) : AbstractCanvas(project) {
}
glm::vec2 Mercator::inverseTransform(glm::vec2 coord) {
float theta = coord.x;
float phi = 2*atan(exp(coord.y))-M_PI/2;
return glm::vec2(theta,phi);
}
Shader *Mercator::inverseShader() {
return Shader::builder()
.include(def_pi).create(R"(
vec2 inverseshader(vec2 coord, inout bool outOfBounds) {
float theta = coord.x;
float phi = 2*atan(exp(coord.y))-M_PI/2;
//if (abs(phi)>89.0/180*M_PI) outOfBounds=true;
return vec2(theta,phi);
}
)");
}
glm::vec2 Mercator::getScale() {
return glm::vec2(M_PI,M_PI);
}
glm::vec2 Mercator::getLimits() {
return glm::vec2(1,3);
}
| 18.974359 | 64 | 0.677027 | Kuhlwein |
916826688e833a6f1652b4c87c2903f91c67b045 | 2,332 | cpp | C++ | plant-simul/plant1/plant1_start_2_3_niVeriStand_rtw/plant1_start_2_3_data.cpp | asamant/masters-thesis-physical-setup | 2adb7928ccb6d0a59849bb30574ee645bd770a63 | [
"MIT"
] | null | null | null | plant-simul/plant1/plant1_start_2_3_niVeriStand_rtw/plant1_start_2_3_data.cpp | asamant/masters-thesis-physical-setup | 2adb7928ccb6d0a59849bb30574ee645bd770a63 | [
"MIT"
] | null | null | null | plant-simul/plant1/plant1_start_2_3_niVeriStand_rtw/plant1_start_2_3_data.cpp | asamant/masters-thesis-physical-setup | 2adb7928ccb6d0a59849bb30574ee645bd770a63 | [
"MIT"
] | null | null | null | #include "ni_modelframework.h"
#if defined VXWORKS || defined kNIOSLinux
#define plant1_start_2_3_P plant1_start_2_3_P DataSection(".NIVS.defaultparams")
#endif
/*
* plant1_start_2_3_data.cpp
*
* Academic License - for use in teaching, academic research, and meeting
* course requirements at degree granting institutions only. Not for
* government, commercial, or other organizational use.
*
* Code generation for model "plant1_start_2_3".
*
* Model version : 1.21
* Simulink Coder version : 8.14 (R2018a) 06-Feb-2018
* C++ source code generated on : Tue Jul 7 13:43:35 2020
*
* Target selection: NIVeriStand.tlc
* Note: GRT includes extra infrastructure and instrumentation for prototyping
* Embedded hardware selection: Intel->x86/Pentium
* Code generation objectives: Unspecified
* Validation result: Not run
*/
#include "plant1_start_2_3.h"
#include "plant1_start_2_3_private.h"
/* Block parameters (default storage) */
P_plant1_start_2_3_T plant1_start_2_3_P = {
/* Computed Parameter: Plant_A
* Referenced by: '<Root>/Plant'
*/
{ 1.0, -2.0, 3.0 },
/* Computed Parameter: Plant_B
* Referenced by: '<Root>/Plant'
*/
1.0,
/* Computed Parameter: Plant_C
* Referenced by: '<Root>/Plant'
*/
{ 1.0, 1.0 },
/* Expression: [2 3]
* Referenced by: '<Root>/Plant'
*/
{ 2.0, 3.0 },
/* Expression: [1 -4]
* Referenced by: '<Root>/Feeback input'
*/
{ 1.0, -4.0 }
};
/*========================================================================*
* NI VeriStand Model Framework code generation
*
* Model : plant1_start_2_3
* Model version : 1.21
* VeriStand Model Framework version : 2019.0.0.0 (2019)
* Source generated on : Tue Jul 7 13:43:34 2020
*========================================================================*/
#if defined VXWORKS || defined kNIOSLinux
typedef struct {
int32_t size;
int32_t width;
int32_t basetype;
} NI_ParamSizeWidth;
NI_ParamSizeWidth P_plant1_start_2_3_T_sizes[] DataSection(
".NIVS.defaultparamsizes") = {
{ sizeof(P_plant1_start_2_3_T), 1 },
{ sizeof(real_T), 3, 0 },
{ sizeof(real_T), 1, 0 },
{ sizeof(real_T), 2, 0 },
{ sizeof(real_T), 2, 0 },
{ sizeof(real_T), 2, 0 },
};
#endif
| 26.5 | 93 | 0.606775 | asamant |
9169024291d2bb89c701e15c253e1ca4e01f16d1 | 27,867 | cc | C++ | content/browser/service_worker/embedded_worker_instance_unittest.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | content/browser/service_worker/embedded_worker_instance_unittest.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | content/browser/service_worker/embedded_worker_instance_unittest.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/service_worker/embedded_worker_instance.h"
#include <stdint.h>
#include <utility>
#include <vector>
#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/command_line.h"
#include "base/macros.h"
#include "base/run_loop.h"
#include "base/stl_util.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "content/browser/service_worker/embedded_worker_status.h"
#include "content/browser/service_worker/embedded_worker_test_helper.h"
#include "content/browser/service_worker/fake_embedded_worker_instance_client.h"
#include "content/browser/service_worker/service_worker_context_core.h"
#include "content/browser/service_worker/service_worker_context_wrapper.h"
#include "content/browser/service_worker/service_worker_registration.h"
#include "content/browser/service_worker/service_worker_test_utils.h"
#include "content/browser/service_worker/service_worker_version.h"
#include "content/public/common/child_process_host.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/browser_task_environment.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/common/features.h"
#include "third_party/blink/public/mojom/service_worker/embedded_worker.mojom.h"
#include "third_party/blink/public/mojom/service_worker/service_worker.mojom.h"
#include "third_party/blink/public/mojom/service_worker/service_worker_event_status.mojom.h"
#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
namespace content {
namespace {
EmbeddedWorkerInstance::StatusCallback ReceiveStatus(
base::Optional<blink::ServiceWorkerStatusCode>* out_status,
base::OnceClosure quit) {
return base::BindOnce(
[](base::Optional<blink::ServiceWorkerStatusCode>* out_status,
base::OnceClosure quit, blink::ServiceWorkerStatusCode status) {
*out_status = status;
std::move(quit).Run();
},
out_status, std::move(quit));
}
const char kHistogramServiceWorkerRuntime[] = "ServiceWorker.Runtime";
} // namespace
class EmbeddedWorkerInstanceTest : public testing::Test,
public EmbeddedWorkerInstance::Listener {
protected:
EmbeddedWorkerInstanceTest()
: task_environment_(BrowserTaskEnvironment::IO_MAINLOOP) {}
enum EventType {
PROCESS_ALLOCATED,
START_WORKER_MESSAGE_SENT,
STARTED,
STOPPED,
DETACHED,
};
struct EventLog {
EventType type;
base::Optional<EmbeddedWorkerStatus> status;
base::Optional<blink::mojom::ServiceWorkerStartStatus> start_status;
};
void RecordEvent(EventType type,
base::Optional<EmbeddedWorkerStatus> status = base::nullopt,
base::Optional<blink::mojom::ServiceWorkerStartStatus>
start_status = base::nullopt) {
EventLog log = {type, status, start_status};
events_.push_back(log);
}
void OnProcessAllocated() override { RecordEvent(PROCESS_ALLOCATED); }
void OnStartWorkerMessageSent() override {
RecordEvent(START_WORKER_MESSAGE_SENT);
}
void OnStarted(blink::mojom::ServiceWorkerStartStatus status,
bool has_fetch_handler) override {
has_fetch_handler_ = has_fetch_handler;
RecordEvent(STARTED, base::nullopt, status);
}
void OnStopped(EmbeddedWorkerStatus old_status) override {
RecordEvent(STOPPED, old_status);
}
void OnDetached(EmbeddedWorkerStatus old_status) override {
RecordEvent(DETACHED, old_status);
}
void SetUp() override {
helper_ = std::make_unique<EmbeddedWorkerTestHelper>(base::FilePath());
}
void TearDown() override { helper_.reset(); }
using RegistrationAndVersionPair =
std::pair<scoped_refptr<ServiceWorkerRegistration>,
scoped_refptr<ServiceWorkerVersion>>;
RegistrationAndVersionPair PrepareRegistrationAndVersion(
const GURL& scope,
const GURL& script_url) {
RegistrationAndVersionPair pair;
blink::mojom::ServiceWorkerRegistrationOptions options;
options.scope = scope;
pair.first =
CreateNewServiceWorkerRegistration(context()->registry(), options);
pair.second = CreateNewServiceWorkerVersion(
context()->registry(), pair.first, script_url,
blink::mojom::ScriptType::kClassic);
return pair;
}
// Calls worker->Start() and runs until the start IPC is sent.
//
// Expects success. For failure cases, call Start() manually.
void StartWorkerUntilStartSent(
EmbeddedWorkerInstance* worker,
blink::mojom::EmbeddedWorkerStartParamsPtr params) {
base::Optional<blink::ServiceWorkerStatusCode> status;
base::RunLoop loop;
worker->Start(std::move(params),
ReceiveStatus(&status, loop.QuitClosure()));
loop.Run();
EXPECT_EQ(blink::ServiceWorkerStatusCode::kOk, status);
EXPECT_EQ(EmbeddedWorkerStatus::STARTING, worker->status());
}
// Calls worker->Start() and runs until startup finishes.
//
// Expects success. For failure cases, call Start() manually.
void StartWorker(EmbeddedWorkerInstance* worker,
blink::mojom::EmbeddedWorkerStartParamsPtr params) {
StartWorkerUntilStartSent(worker, std::move(params));
// TODO(falken): Listen for OnStarted() instead of this.
base::RunLoop().RunUntilIdle();
EXPECT_EQ(EmbeddedWorkerStatus::RUNNING, worker->status());
}
blink::mojom::EmbeddedWorkerStartParamsPtr CreateStartParams(
scoped_refptr<ServiceWorkerVersion> version) {
auto params = blink::mojom::EmbeddedWorkerStartParams::New();
params->service_worker_version_id = version->version_id();
params->scope = version->scope();
params->script_url = version->script_url();
params->is_installed = false;
params->service_worker_receiver = CreateServiceWorker();
params->controller_receiver = CreateController();
params->installed_scripts_info = GetInstalledScriptsInfoPtr();
params->provider_info = CreateProviderInfo(std::move(version));
return params;
}
blink::mojom::ServiceWorkerProviderInfoForStartWorkerPtr CreateProviderInfo(
scoped_refptr<ServiceWorkerVersion> version) {
auto provider_info =
blink::mojom::ServiceWorkerProviderInfoForStartWorker::New();
version->worker_host_ = std::make_unique<ServiceWorkerHost>(
provider_info->host_remote.InitWithNewEndpointAndPassReceiver(),
version.get(), context()->AsWeakPtr());
return provider_info;
}
mojo::PendingReceiver<blink::mojom::ServiceWorker> CreateServiceWorker() {
service_workers_.emplace_back();
return service_workers_.back().BindNewPipeAndPassReceiver();
}
mojo::PendingReceiver<blink::mojom::ControllerServiceWorker>
CreateController() {
controllers_.emplace_back();
return controllers_.back().BindNewPipeAndPassReceiver();
}
void SetWorkerStatus(EmbeddedWorkerInstance* worker,
EmbeddedWorkerStatus status) {
worker->status_ = status;
}
blink::mojom::ServiceWorkerInstalledScriptsInfoPtr
GetInstalledScriptsInfoPtr() {
installed_scripts_managers_.emplace_back();
auto info = blink::mojom::ServiceWorkerInstalledScriptsInfo::New();
info->manager_receiver =
installed_scripts_managers_.back().BindNewPipeAndPassReceiver();
installed_scripts_manager_host_receivers_.push_back(
info->manager_host_remote.InitWithNewPipeAndPassReceiver());
return info;
}
ServiceWorkerContextCore* context() { return helper_->context(); }
// Mojo endpoints.
std::vector<mojo::Remote<blink::mojom::ServiceWorker>> service_workers_;
std::vector<mojo::Remote<blink::mojom::ControllerServiceWorker>> controllers_;
std::vector<mojo::Remote<blink::mojom::ServiceWorkerInstalledScriptsManager>>
installed_scripts_managers_;
std::vector<mojo::PendingReceiver<
blink::mojom::ServiceWorkerInstalledScriptsManagerHost>>
installed_scripts_manager_host_receivers_;
BrowserTaskEnvironment task_environment_;
std::unique_ptr<EmbeddedWorkerTestHelper> helper_;
std::vector<EventLog> events_;
base::test::ScopedFeatureList scoped_feature_list_;
bool has_fetch_handler_;
private:
DISALLOW_COPY_AND_ASSIGN(EmbeddedWorkerInstanceTest);
};
TEST_F(EmbeddedWorkerInstanceTest, StartAndStop) {
const GURL scope("http://example.com/");
const GURL url("http://example.com/worker.js");
RegistrationAndVersionPair pair = PrepareRegistrationAndVersion(scope, url);
auto worker = std::make_unique<EmbeddedWorkerInstance>(pair.second.get());
EXPECT_EQ(EmbeddedWorkerStatus::STOPPED, worker->status());
worker->AddObserver(this);
// Start should succeed.
StartWorker(worker.get(), CreateStartParams(pair.second));
// The 'WorkerStarted' message should have been sent by
// EmbeddedWorkerTestHelper.
EXPECT_EQ(EmbeddedWorkerStatus::RUNNING, worker->status());
EXPECT_EQ(helper_->mock_render_process_id(), worker->process_id());
// Stop the worker.
worker->Stop();
EXPECT_EQ(EmbeddedWorkerStatus::STOPPING, worker->status());
base::RunLoop().RunUntilIdle();
// The 'WorkerStopped' message should have been sent by
// EmbeddedWorkerTestHelper.
EXPECT_EQ(EmbeddedWorkerStatus::STOPPED, worker->status());
// Check if the IPCs are fired in expected order.
ASSERT_EQ(4u, events_.size());
EXPECT_EQ(PROCESS_ALLOCATED, events_[0].type);
EXPECT_EQ(START_WORKER_MESSAGE_SENT, events_[1].type);
EXPECT_EQ(STARTED, events_[2].type);
EXPECT_EQ(blink::mojom::ServiceWorkerStartStatus::kNormalCompletion,
events_[2].start_status.value());
EXPECT_EQ(STOPPED, events_[3].type);
}
// Test that a worker that failed twice will use a new render process
// on the next attempt.
TEST_F(EmbeddedWorkerInstanceTest, ForceNewProcess) {
const GURL scope("http://example.com/");
const GURL url("http://example.com/worker.js");
RegistrationAndVersionPair pair = PrepareRegistrationAndVersion(scope, url);
const int64_t service_worker_version_id = pair.second->version_id();
auto worker = std::make_unique<EmbeddedWorkerInstance>(pair.second.get());
EXPECT_EQ(EmbeddedWorkerStatus::STOPPED, worker->status());
{
// Start once normally.
StartWorker(worker.get(), CreateStartParams(pair.second));
// The worker should be using the default render process.
EXPECT_EQ(helper_->mock_render_process_id(), worker->process_id());
worker->Stop();
base::RunLoop().RunUntilIdle();
}
// Fail twice.
context()->UpdateVersionFailureCount(
service_worker_version_id, blink::ServiceWorkerStatusCode::kErrorFailed);
context()->UpdateVersionFailureCount(
service_worker_version_id, blink::ServiceWorkerStatusCode::kErrorFailed);
{
// Start again.
base::RunLoop run_loop;
StartWorker(worker.get(), CreateStartParams(pair.second));
// The worker should be using the new render process.
EXPECT_EQ(helper_->new_render_process_id(), worker->process_id());
worker->Stop();
base::RunLoop().RunUntilIdle();
}
}
TEST_F(EmbeddedWorkerInstanceTest, StopWhenDevToolsAttached) {
const GURL scope("http://example.com/");
const GURL url("http://example.com/worker.js");
RegistrationAndVersionPair pair = PrepareRegistrationAndVersion(scope, url);
auto worker = std::make_unique<EmbeddedWorkerInstance>(pair.second.get());
EXPECT_EQ(EmbeddedWorkerStatus::STOPPED, worker->status());
// Start the worker and then call StopIfNotAttachedToDevTools().
StartWorker(worker.get(), CreateStartParams(pair.second));
EXPECT_EQ(helper_->mock_render_process_id(), worker->process_id());
worker->StopIfNotAttachedToDevTools();
EXPECT_EQ(EmbeddedWorkerStatus::STOPPING, worker->status());
base::RunLoop().RunUntilIdle();
// The worker must be stopped now.
EXPECT_EQ(EmbeddedWorkerStatus::STOPPED, worker->status());
// Set devtools_attached to true, and do the same.
worker->SetDevToolsAttached(true);
StartWorker(worker.get(), CreateStartParams(pair.second));
EXPECT_EQ(helper_->mock_render_process_id(), worker->process_id());
worker->StopIfNotAttachedToDevTools();
base::RunLoop().RunUntilIdle();
// The worker must not be stopped this time.
EXPECT_EQ(EmbeddedWorkerStatus::RUNNING, worker->status());
// Calling Stop() actually stops the worker regardless of whether devtools
// is attached or not.
worker->Stop();
base::RunLoop().RunUntilIdle();
EXPECT_EQ(EmbeddedWorkerStatus::STOPPED, worker->status());
}
TEST_F(EmbeddedWorkerInstanceTest, DetachAfterSendingStartWorkerMessage) {
const GURL scope("http://example.com/");
const GURL url("http://example.com/worker.js");
RegistrationAndVersionPair pair = PrepareRegistrationAndVersion(scope, url);
auto worker = std::make_unique<EmbeddedWorkerInstance>(pair.second.get());
worker->AddObserver(this);
auto* client = helper_->AddNewPendingInstanceClient<
DelayedFakeEmbeddedWorkerInstanceClient>(helper_.get());
client->UnblockStopWorker();
StartWorkerUntilStartSent(worker.get(), CreateStartParams(pair.second));
ASSERT_EQ(2u, events_.size());
EXPECT_EQ(PROCESS_ALLOCATED, events_[0].type);
EXPECT_EQ(START_WORKER_MESSAGE_SENT, events_[1].type);
events_.clear();
worker->Detach();
base::RunLoop().RunUntilIdle();
EXPECT_EQ(EmbeddedWorkerStatus::STOPPED, worker->status());
EXPECT_EQ(ChildProcessHost::kInvalidUniqueID, worker->process_id());
// "STARTED" event should not be recorded.
ASSERT_EQ(1u, events_.size());
EXPECT_EQ(DETACHED, events_[0].type);
EXPECT_EQ(EmbeddedWorkerStatus::STARTING, events_[0].status.value());
}
TEST_F(EmbeddedWorkerInstanceTest, StopAfterSendingStartWorkerMessage) {
const GURL scope("http://example.com/");
const GURL url("http://example.com/worker.js");
RegistrationAndVersionPair pair = PrepareRegistrationAndVersion(scope, url);
auto worker = std::make_unique<EmbeddedWorkerInstance>(pair.second.get());
worker->AddObserver(this);
auto* client = helper_->AddNewPendingInstanceClient<
DelayedFakeEmbeddedWorkerInstanceClient>(helper_.get());
client->UnblockStopWorker();
StartWorkerUntilStartSent(worker.get(), CreateStartParams(pair.second));
ASSERT_EQ(2u, events_.size());
EXPECT_EQ(PROCESS_ALLOCATED, events_[0].type);
EXPECT_EQ(START_WORKER_MESSAGE_SENT, events_[1].type);
events_.clear();
worker->Stop();
base::RunLoop().RunUntilIdle();
EXPECT_EQ(EmbeddedWorkerStatus::STOPPED, worker->status());
EXPECT_EQ(ChildProcessHost::kInvalidUniqueID, worker->process_id());
// "STARTED" event should not be recorded.
ASSERT_EQ(1u, events_.size());
EXPECT_EQ(STOPPED, events_[0].type);
EXPECT_EQ(EmbeddedWorkerStatus::STOPPING, events_[0].status.value());
events_.clear();
// Restart the worker.
StartWorker(worker.get(), CreateStartParams(pair.second));
// The worker should be started.
ASSERT_EQ(3u, events_.size());
EXPECT_EQ(PROCESS_ALLOCATED, events_[0].type);
EXPECT_EQ(START_WORKER_MESSAGE_SENT, events_[1].type);
EXPECT_EQ(STARTED, events_[2].type);
// Tear down the worker.
worker->Stop();
}
TEST_F(EmbeddedWorkerInstanceTest, Detach) {
const GURL scope("http://example.com/");
const GURL url("http://example.com/worker.js");
RegistrationAndVersionPair pair = PrepareRegistrationAndVersion(scope, url);
auto worker = std::make_unique<EmbeddedWorkerInstance>(pair.second.get());
// Start the worker.
StartWorker(worker.get(), CreateStartParams(pair.second));
// Detach.
worker->Detach();
EXPECT_EQ(EmbeddedWorkerStatus::STOPPED, worker->status());
}
// Test for when sending the start IPC failed.
TEST_F(EmbeddedWorkerInstanceTest, FailToSendStartIPC) {
const GURL scope("http://example.com/");
const GURL url("http://example.com/worker.js");
// Let StartWorker fail; mojo IPC fails to connect to a remote interface.
helper_->AddPendingInstanceClient(nullptr);
RegistrationAndVersionPair pair = PrepareRegistrationAndVersion(scope, url);
auto worker = std::make_unique<EmbeddedWorkerInstance>(pair.second.get());
worker->AddObserver(this);
// Attempt to start the worker. From the browser process's point of view, the
// start IPC was sent.
base::Optional<blink::ServiceWorkerStatusCode> status;
base::RunLoop loop;
worker->Start(CreateStartParams(pair.second),
ReceiveStatus(&status, loop.QuitClosure()));
loop.Run();
EXPECT_EQ(blink::ServiceWorkerStatusCode::kOk, status.value());
// But the renderer should not receive the message and the binding is broken.
// Worker should handle the failure of binding on the remote side as detach.
base::RunLoop().RunUntilIdle();
ASSERT_EQ(3u, events_.size());
EXPECT_EQ(PROCESS_ALLOCATED, events_[0].type);
EXPECT_EQ(START_WORKER_MESSAGE_SENT, events_[1].type);
EXPECT_EQ(DETACHED, events_[2].type);
EXPECT_EQ(EmbeddedWorkerStatus::STARTING, events_[2].status.value());
EXPECT_EQ(EmbeddedWorkerStatus::STOPPED, worker->status());
}
TEST_F(EmbeddedWorkerInstanceTest, RemoveRemoteInterface) {
const GURL scope("http://example.com/");
const GURL url("http://example.com/worker.js");
RegistrationAndVersionPair pair = PrepareRegistrationAndVersion(scope, url);
auto worker = std::make_unique<EmbeddedWorkerInstance>(pair.second.get());
worker->AddObserver(this);
// Attempt to start the worker.
base::Optional<blink::ServiceWorkerStatusCode> status;
base::RunLoop loop;
auto* client = helper_->AddNewPendingInstanceClient<
DelayedFakeEmbeddedWorkerInstanceClient>(helper_.get());
worker->Start(CreateStartParams(pair.second),
ReceiveStatus(&status, loop.QuitClosure()));
loop.Run();
EXPECT_EQ(blink::ServiceWorkerStatusCode::kOk, status.value());
// Disconnect the Mojo connection. Worker should handle the sudden shutdown as
// detach.
client->RunUntilBound();
client->Disconnect();
base::RunLoop().RunUntilIdle();
ASSERT_EQ(3u, events_.size());
EXPECT_EQ(PROCESS_ALLOCATED, events_[0].type);
EXPECT_EQ(START_WORKER_MESSAGE_SENT, events_[1].type);
EXPECT_EQ(DETACHED, events_[2].type);
EXPECT_EQ(EmbeddedWorkerStatus::STARTING, events_[2].status.value());
}
class RecordCacheStorageInstanceClient
: public FakeEmbeddedWorkerInstanceClient {
public:
explicit RecordCacheStorageInstanceClient(EmbeddedWorkerTestHelper* helper)
: FakeEmbeddedWorkerInstanceClient(helper) {}
~RecordCacheStorageInstanceClient() override = default;
void StartWorker(
blink::mojom::EmbeddedWorkerStartParamsPtr start_params) override {
had_cache_storage_ = !!start_params->provider_info->cache_storage;
FakeEmbeddedWorkerInstanceClient::StartWorker(std::move(start_params));
}
bool had_cache_storage() const { return had_cache_storage_; }
private:
bool had_cache_storage_ = false;
};
// Test that the worker is given a CacheStoragePtr during startup.
TEST_F(EmbeddedWorkerInstanceTest, CacheStorageOptimization) {
base::test::ScopedFeatureList scoped_feature_list;
scoped_feature_list.InitAndEnableFeature(
blink::features::kEagerCacheStorageSetupForServiceWorkers);
const GURL scope("http://example.com/");
const GURL url("http://example.com/worker.js");
RegistrationAndVersionPair pair = PrepareRegistrationAndVersion(scope, url);
auto worker = std::make_unique<EmbeddedWorkerInstance>(pair.second.get());
// Start the worker.
auto* client =
helper_->AddNewPendingInstanceClient<RecordCacheStorageInstanceClient>(
helper_.get());
StartWorker(worker.get(), CreateStartParams(pair.second));
// Cache storage should have been sent.
EXPECT_TRUE(client->had_cache_storage());
// Stop the worker.
worker->Stop();
base::RunLoop().RunUntilIdle();
}
// Test that the worker is not given a CacheStoragePtr during startup when
// the feature is disabled.
TEST_F(EmbeddedWorkerInstanceTest, CacheStorageOptimizationIsDisabled) {
base::test::ScopedFeatureList scoped_feature_list;
scoped_feature_list.InitAndDisableFeature(
blink::features::kEagerCacheStorageSetupForServiceWorkers);
const GURL scope("http://example.com/");
const GURL url("http://example.com/worker.js");
RegistrationAndVersionPair pair = PrepareRegistrationAndVersion(scope, url);
auto worker = std::make_unique<EmbeddedWorkerInstance>(pair.second.get());
auto* client =
helper_->AddNewPendingInstanceClient<RecordCacheStorageInstanceClient>(
helper_.get());
// Start the worker.
blink::mojom::EmbeddedWorkerStartParamsPtr params =
CreateStartParams(pair.second);
StartWorker(worker.get(), std::move(params));
// Cache storage should not have been sent.
EXPECT_FALSE(client->had_cache_storage());
// Stop the worker.
worker->Stop();
base::RunLoop().RunUntilIdle();
}
// Starts the worker with kAbruptCompletion status.
class AbruptCompletionInstanceClient : public FakeEmbeddedWorkerInstanceClient {
public:
explicit AbruptCompletionInstanceClient(EmbeddedWorkerTestHelper* helper)
: FakeEmbeddedWorkerInstanceClient(helper) {}
~AbruptCompletionInstanceClient() override = default;
protected:
void EvaluateScript() override {
host()->OnScriptEvaluationStart();
host()->OnStarted(blink::mojom::ServiceWorkerStartStatus::kAbruptCompletion,
/*has_fetch_handler=*/false, helper()->GetNextThreadId(),
blink::mojom::EmbeddedWorkerStartTiming::New());
}
};
// Tests that kAbruptCompletion is the OnStarted() status when the
// renderer reports abrupt completion.
TEST_F(EmbeddedWorkerInstanceTest, AbruptCompletion) {
const GURL scope("http://example.com/");
const GURL url("http://example.com/worker.js");
RegistrationAndVersionPair pair = PrepareRegistrationAndVersion(scope, url);
auto worker = std::make_unique<EmbeddedWorkerInstance>(pair.second.get());
EXPECT_EQ(EmbeddedWorkerStatus::STOPPED, worker->status());
worker->AddObserver(this);
helper_->AddPendingInstanceClient(
std::make_unique<AbruptCompletionInstanceClient>(helper_.get()));
StartWorker(worker.get(), CreateStartParams(pair.second));
ASSERT_EQ(3u, events_.size());
EXPECT_EQ(PROCESS_ALLOCATED, events_[0].type);
EXPECT_EQ(START_WORKER_MESSAGE_SENT, events_[1].type);
EXPECT_EQ(STARTED, events_[2].type);
EXPECT_EQ(blink::mojom::ServiceWorkerStartStatus::kAbruptCompletion,
events_[2].start_status.value());
worker->Stop();
}
// A fake instance client for toggling whether a fetch event handler exists.
class FetchHandlerInstanceClient : public FakeEmbeddedWorkerInstanceClient {
public:
explicit FetchHandlerInstanceClient(EmbeddedWorkerTestHelper* helper)
: FakeEmbeddedWorkerInstanceClient(helper) {}
~FetchHandlerInstanceClient() override = default;
void set_has_fetch_handler(bool has_fetch_handler) {
has_fetch_handler_ = has_fetch_handler;
}
protected:
void EvaluateScript() override {
host()->OnScriptEvaluationStart();
host()->OnStarted(blink::mojom::ServiceWorkerStartStatus::kNormalCompletion,
has_fetch_handler_, helper()->GetNextThreadId(),
blink::mojom::EmbeddedWorkerStartTiming::New());
}
private:
bool has_fetch_handler_ = false;
};
// Tests that whether a fetch event handler exists.
TEST_F(EmbeddedWorkerInstanceTest, HasFetchHandler) {
const GURL scope("http://example.com/");
const GURL url("http://example.com/worker.js");
RegistrationAndVersionPair pair1 = PrepareRegistrationAndVersion(scope, url);
auto worker1 = std::make_unique<EmbeddedWorkerInstance>(pair1.second.get());
EXPECT_EQ(EmbeddedWorkerStatus::STOPPED, worker1->status());
worker1->AddObserver(this);
auto* fetch_handler_worker =
helper_->AddNewPendingInstanceClient<FetchHandlerInstanceClient>(
helper_.get());
fetch_handler_worker->set_has_fetch_handler(true);
StartWorker(worker1.get(), CreateStartParams(pair1.second));
EXPECT_TRUE(has_fetch_handler_);
worker1->Stop();
RegistrationAndVersionPair pair2 = PrepareRegistrationAndVersion(scope, url);
auto worker2 = std::make_unique<EmbeddedWorkerInstance>(pair2.second.get());
EXPECT_EQ(EmbeddedWorkerStatus::STOPPED, worker2->status());
worker2->AddObserver(this);
auto* no_fetch_handler_worker =
helper_->AddNewPendingInstanceClient<FetchHandlerInstanceClient>(
helper_.get());
no_fetch_handler_worker->set_has_fetch_handler(false);
StartWorker(worker2.get(), CreateStartParams(pair2.second));
EXPECT_FALSE(has_fetch_handler_);
worker2->Stop();
}
// Tests recording the lifetime UMA.
TEST_F(EmbeddedWorkerInstanceTest, Lifetime) {
const GURL scope("http://example.com/");
const GURL url("http://example.com/worker.js");
RegistrationAndVersionPair pair = PrepareRegistrationAndVersion(scope, url);
auto worker = std::make_unique<EmbeddedWorkerInstance>(pair.second.get());
base::HistogramTester metrics;
// Start the worker.
StartWorker(worker.get(), CreateStartParams(pair.second));
metrics.ExpectTotalCount(kHistogramServiceWorkerRuntime, 0);
// Stop the worker.
worker->Stop();
base::RunLoop().RunUntilIdle();
EXPECT_EQ(EmbeddedWorkerStatus::STOPPED, worker->status());
// The runtime metric should have been recorded.
metrics.ExpectTotalCount(kHistogramServiceWorkerRuntime, 1);
}
// Tests that the lifetime UMA isn't recorded if DevTools was attached
// while the worker was running.
TEST_F(EmbeddedWorkerInstanceTest, Lifetime_DevToolsAttachedAfterStart) {
const GURL scope("http://example.com/");
const GURL url("http://example.com/worker.js");
RegistrationAndVersionPair pair = PrepareRegistrationAndVersion(scope, url);
auto worker = std::make_unique<EmbeddedWorkerInstance>(pair.second.get());
base::HistogramTester metrics;
// Start the worker.
StartWorker(worker.get(), CreateStartParams(pair.second));
// Attach DevTools.
worker->SetDevToolsAttached(true);
// To make things tricky, detach DevTools.
worker->SetDevToolsAttached(false);
// Stop the worker.
worker->Stop();
base::RunLoop().RunUntilIdle();
EXPECT_EQ(EmbeddedWorkerStatus::STOPPED, worker->status());
// The runtime metric should not have ben recorded since DevTools
// was attached at some point during the worker's life.
metrics.ExpectTotalCount(kHistogramServiceWorkerRuntime, 0);
}
// Tests that the lifetime UMA isn't recorded if DevTools was attached
// before the worker finished starting.
TEST_F(EmbeddedWorkerInstanceTest, Lifetime_DevToolsAttachedDuringStart) {
const GURL scope("http://example.com/");
const GURL url("http://example.com/worker.js");
RegistrationAndVersionPair pair = PrepareRegistrationAndVersion(scope, url);
auto worker = std::make_unique<EmbeddedWorkerInstance>(pair.second.get());
base::HistogramTester metrics;
// Attach DevTools while the worker is starting.
worker->Start(CreateStartParams(pair.second), base::DoNothing());
worker->SetDevToolsAttached(true);
base::RunLoop().RunUntilIdle();
EXPECT_EQ(EmbeddedWorkerStatus::RUNNING, worker->status());
// To make things tricky, detach DevTools.
worker->SetDevToolsAttached(false);
// Stop the worker.
worker->Stop();
base::RunLoop().RunUntilIdle();
EXPECT_EQ(EmbeddedWorkerStatus::STOPPED, worker->status());
// The runtime metric should not have ben recorded since DevTools
// was attached at some point during the worker's life.
metrics.ExpectTotalCount(kHistogramServiceWorkerRuntime, 0);
}
} // namespace content
| 37.556604 | 92 | 0.750063 | Ron423c |
916b1cf28fc32cee193666749f69fd004f72b336 | 18,084 | cxx | C++ | doctype/marcdump.cxx | re-Isearch/re-Isearch | f2a2012c1814b0940a6004b6186a5e6896c1135a | [
"BSD-4-Clause-UC",
"Apache-2.0"
] | 2 | 2022-02-05T17:48:29.000Z | 2022-02-06T15:25:04.000Z | doctype/marcdump.cxx | re-Isearch/re-Isearch | f2a2012c1814b0940a6004b6186a5e6896c1135a | [
"BSD-4-Clause-UC",
"Apache-2.0"
] | null | null | null | doctype/marcdump.cxx | re-Isearch/re-Isearch | f2a2012c1814b0940a6004b6186a5e6896c1135a | [
"BSD-4-Clause-UC",
"Apache-2.0"
] | 1 | 2022-03-30T20:14:00.000Z | 2022-03-30T20:14:00.000Z | // $ID$
/*-@@@
File: marcdump.cxx
Version: $Revision: 1.1 $
Description: Class MARCDUMP - output from Yaz utility marcdump
Author: Archibald Warnock (warnock@clark.net), A/WWW Enterprises
Copyright: A/WWW Enterprises, Columbia, MD
@@@-*/
//#include <iostream.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>
#include "isearch.hxx"
#include "opobj.hxx"
#include "operand.hxx"
#include "termobj.hxx"
#include "sterm.hxx"
#include "rset.hxx"
#include "irset.hxx"
#include "opstack.hxx"
#include "squery.hxx"
#include "operator.hxx"
#include "tokengen.hxx"
#include "marcdump.hxx"
// Local prototypes
static CHR **parse_tags (CHR *b, GPTYPE len);
int usefulMarcDumpField(char *fieldStr);
void marcdumpFieldNumToName(STRING& fieldStr, STRING *fieldName);
int SplitLine(const STRING& TheLine, STRING* Tag, STRING* Buffer);
GDT_BOOLEAN HasSubfield(const STRING& TheContents, STRING* tag);
GDT_BOOLEAN HasSubfieldTag(const STRING& TheContents, STRING& tag);
GDT_BOOLEAN GetSubfield(const STRING& TheContents, const STRING& SubfieldTag,
STRING* Buffer);
INT GetSubfields(const STRING& TheContents, STRLIST* TheSubfields);
MARCDUMP::MARCDUMP (PIDBOBJ DbParent)
: DOCTYPE (DbParent)
{
}
void
MARCDUMP::AddFieldDefs ()
{
DOCTYPE::AddFieldDefs ();
}
void
MARCDUMP::ParseRecords (const RECORD& FileRecord)
{
//Finding the range of a MARC record is easy: The first line always
//starts with 001. We assume that your files will consist of a bunch
//of records concatenated into one big file, so we:
// while not end of file do
// read three bytes
// if it's "001", assume we've reached the start of a new record
// indicate the previous range as a record
// increment the file pointer to the start of the next record.
// done
STRING fn;
FileRecord.GetFullFileName (&fn);
PFILE fp = fopen (fn, "rb");
if (!fp) {
cout << "MARCDUMP::ParseRecords(): Could not access '" << fn << "'\n";
return; // File not accessed
}
RECORD Record;
STRING s;
FileRecord.GetPath(&s);
Record.SetPathN( s );
FileRecord.GetFileName(&s);
Record.SetFileName( s );
FileRecord.GetDocumentType(&s);
Record.SetDocumentType ( s );
int RS, RE;
if (fseek(fp, 0L, SEEK_END) == -1) {
cout << "MARCDUMP::ParseRecords(): Seek failed - ";
cout << fn << "\n";
fclose(fp);
return;
}
GPTYPE FileStart, FileEnd, FileLength;
FileStart = 0;
FileEnd = ftell(fp);
if(FileEnd == 0) {
cout << "MARCDUMP::ParseRecords(): Skipping ";
cout << " zero-length record -" << fn << "...\n";
fclose(fp);
return;
}
if(fseek(fp, (long)FileStart, SEEK_SET) == -1) {
cout << "MARCDUMP::ParseRecords(): Seek failed - " << fn << "\n";
fclose(fp);
return;
}
FileLength = FileEnd - FileStart;
int bytePos = 0; // we're going to start reading with bytePos = 0 so we
// always know how many bytes we've read.
int marcLength = 0; // we keep track of the record length
RS=0; // we also know the first record will begin @ 0.
STRING StartTag;
char LenBuff[16];
char c;
while (FileLength >= bytePos + 3) { // if there are more records to read
// start reading until we get to the newline
while (((c=getc(fp)) != '\n') && (FileLength >= bytePos+3)) {
bytePos++;
marcLength++;
}
// Presumably, we hit a newline. Is the line following a new record
// or not? Check for the 001 tag
LenBuff[0]=getc(fp);
LenBuff[1]=getc(fp);
LenBuff[2]=getc(fp);
LenBuff[3]='\0'; // make a null-term string, and do it every time.
bytePos +=3; // we read 3 bytes, so increment our Pos by 3.
StartTag = LenBuff;
if (StartTag.Equals("001")) {
//we're at the start of a new record
#ifdef DEBUG
cout << "MARCDUMP::ParseRecords(): RecordStart=" << RS
<< ", RecordEnd=" << RS+marcLength << endl;
#endif
Record.SetRecordStart(RS);
Record.SetRecordEnd(RS+marcLength); // former bug : 1 over end of buffer!
Db->DocTypeAddRecord(Record);
RS = RS+marcLength+1;
marcLength = 3; // we already read 3 bytes
} else {
marcLength +=4;
}
}
}
void
MARCDUMP::ParseFields (RECORD *NewRecord)
{
STRING fn;
NewRecord->GetFullFileName (&fn);
PFILE fp = fopen (fn, "rb");
if (!fp) {
cout << "MARCDUMP::ParseFields(): Could not access '" << fn << endl;
return; // File not accessed
}
// Get the offsets to the start and end of the current record,
// and figure out how big the record is
GPTYPE RecStart = NewRecord->GetRecordStart ();
GPTYPE RecEnd = NewRecord->GetRecordEnd ();
if (RecEnd == 0) {
fseek (fp, 0L, SEEK_END);
RecStart = 0;
RecEnd = ftell (fp) - 1;
}
fseek (fp, (long)RecStart, SEEK_SET);
GPTYPE RecLength = RecEnd - RecStart;
CHR *RecBuffer = new CHR[RecLength + 1];
// Read the entire record into the buffer
GPTYPE ActualLength = fread (RecBuffer, 1, RecLength, fp);
fclose (fp);
RecBuffer[ActualLength] = '\0';
CHR tag[4];
strncpy(tag,RecBuffer,3);
tag[3]='\0';
INT StartTag;
sscanf(tag,"%d", &StartTag); // turn the string into an int
if (StartTag != 1) {
cout << "MARCDUMP::ParseField(): Bogus first tag at RecStart = "
<< RecStart << endl;
return;
}
PCHR *tags = parse_tags (RecBuffer, ActualLength);
// Now we've got pairs of tags & values
if (tags == NULL || tags[0] == NULL) {
STRING doctype;
NewRecord->GetDocumentType(&doctype);
if (tags) {
delete tags;
cout << "Warning: No `" << doctype << "' fields/tags in \""
<< fn << "\"\n";
} else {
cout << "Unable to parse `" << doctype << "' record in \""
<< fn << "\"\n";
}
delete [] RecBuffer;
return;
}
FC fc;
DF df;
PDFT pdft;
pdft = new DFT ();
DFD dfd;
STRING FieldName,newFieldName;
// Walk though tags
for (PCHR * tags_ptr = tags; *tags_ptr; tags_ptr++) {
strncpy(tag,*tags_ptr,3);
tag[3]='\0';
PCHR p = tags_ptr[1]; // start of the next field value
if (p == NULL) // If no end of field
p = &RecBuffer[RecLength]; // use end of buffer
// size_t off = strlen (*tags_ptr) + 1; // offset from tag to field start
size_t off = 4;
INT val_start = (*tags_ptr + off) - RecBuffer;
// Also leave off the \n
INT val_len = strlen(*tags_ptr) - off;
// Strip potential trailing white space
while (val_len > 0 && isspace (RecBuffer[val_len + val_start]))
val_len--;
if (val_len <= 0) continue; // Don't bother with empty fields (J. Mandel)
CHR* unified_name = UnifiedName(tag);
// Ignore "unclassified" fields
if (unified_name == NULL)
continue; // ignore these
FieldName = unified_name;
dfd.SetFieldName (FieldName);
Db->DfdtAddEntry (dfd);
fc.SetFieldStart (val_start);
fc.SetFieldEnd (val_start + val_len);
#ifdef DEBUG
cout << "Stored field " << FieldName << " data from offsets "
<< val_start << " to " << val_start + val_len << endl;
#endif
PFCT pfct = new FCT ();
pfct->AddEntry (fc);
df.SetFct (*pfct);
df.SetFieldName (FieldName);
pdft->AddEntry (df);
delete pfct;
marcdumpFieldNumToName(FieldName, &newFieldName);
if (newFieldName.GetLength() > 0) { // if we want the same field to have two names
FieldName = newFieldName;
dfd.SetFieldName(FieldName);
Db->DfdtAddEntry(dfd);
fc.SetFieldStart(val_start);
fc.SetFieldEnd(val_start + val_len);
pfct = new FCT();
pfct->AddEntry(fc);
df.SetFct(*pfct);
df.SetFieldName(FieldName);
pdft->AddEntry(df);
delete pfct;
} // end of if we have a second name
}
NewRecord->SetDft (*pdft);
delete pdft;
delete[]RecBuffer;
delete tags;
}
CHR*
MARCDUMP::UnifiedName (CHR *tag)
{
return tag; // Identity
}
void
MARCDUMP::BeforeSearching(QUERY* SearchQueryPtr)
{
return;
}
void
MARCDUMP::Present (const RESULT& ResultRecord, const STRING& ElementSet,
STRING *StringBufferPtr)
{
STRING RecSyntax;
RecSyntax = SutrsRecordSyntax;
Present(ResultRecord, ElementSet, RecSyntax, StringBufferPtr);
}
void
MARCDUMP::Present(const RESULT& ResultRecord, const STRING& ElementSet,
const STRING& RecordSyntax, STRING* StringBufferPtr)
{
STRING FieldName;
GDT_BOOLEAN Status;
if (RecordSyntax.CaseEquals(HtmlRecordSyntax)) {
PresentHtml(ResultRecord,ElementSet,StringBufferPtr);
} else {
PresentSutrs(ResultRecord,ElementSet,StringBufferPtr);
}
return;
}
void
MARCDUMP::PresentSutrs(const RESULT& ResultRecord, const STRING& ElementSet,
STRING *StringBufferPtr)
{
STRING FieldName;
GDT_BOOLEAN Status;
if (ElementSet.CaseEquals("B")) {
FieldName = "245"; // Brief headline is "title"
Status = Db->GetFieldData(ResultRecord, FieldName, StringBufferPtr);
StringBufferPtr->EraseBefore(7);
} else if (ElementSet.CaseEquals("F")) {
DOCTYPE::Present (ResultRecord, ElementSet, StringBufferPtr);
} else {
FieldName = ElementSet;
DOCTYPE::Present (ResultRecord, FieldName, StringBufferPtr);
}
return;
}
void
MARCDUMP::PresentHtml(const RESULT& ResultRecord, const STRING& ElementSet,
STRING *StringBufferPtr)
{
STRING FieldName;
GDT_BOOLEAN Status;
if (ElementSet.CaseEquals("B")) {
FieldName = "245"; // Brief headline is "title"
Status = Db->GetFieldData(ResultRecord, FieldName, StringBufferPtr);
StringBufferPtr->EraseBefore(7);
} else if (ElementSet.CaseEquals("F")) {
STRING Buffer,Full,TheLine,URL;
STRING Title,Contents,TheTag;
STRLIST FullRecord, SubFields;
INT nLines,i,intTag,nSubFields;
STRING SubTag,SubField,ThisSubfield;
// Get the whole record into a buffer
ResultRecord.GetRecordData(&Full);
// Convert the full record to a bunch of string
FullRecord.Split('\n',Full);
nLines = FullRecord.GetTotalEntries(); // count # of lines
Buffer = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2//EN\">\n";
Buffer.Cat("<HTML>\n<HEAD>\n");
FieldName = "245"; // Brief headline is "title"
Status = Db->GetFieldData(ResultRecord, FieldName, &Title);
Title.EraseBefore(7);
Buffer.Cat("<TITLE>");
Buffer.Cat(Title);
Buffer.Cat("</TITLE>\n</HEAD>\n");
Buffer.Cat("<BODY BGCOLOR=\"#ffffff\" TEXT=\"#000000\">\n");
for (i=1;i<nLines;i++) {
FullRecord.GetEntry(i,&TheLine);
intTag = SplitLine(TheLine,&TheTag,&Contents);
if (intTag == 5)
continue;
else if (intTag == 7)
continue;
else if (intTag == 8)
continue;
else if (intTag == 256)
continue;
else if (intTag == 516)
continue;
else if (intTag == 538)
continue;
else if (intTag == 856) {
// Are there subfields?
SubTag = "$u";
if (HasSubfieldTag(Contents,SubTag)) {
GetSubfield(Contents, SubTag, &SubField);
Contents = SubField;
}
nSubFields = GetSubfields(TheLine,&SubFields);
SubFields.GetValue("$u",&ThisSubfield);
URL = "<a href=\"";
URL.Cat(Contents);
URL.Cat("\">");
URL.Cat(Contents);
URL.Cat("</a>");
Contents = URL;
}
marcdumpFieldNumToName(TheTag, &FieldName);
if (FieldName.GetLength() > 0) {
Buffer.Cat("<B>");
Buffer.Cat(FieldName);
Buffer.Cat(": </B>");
Buffer.Cat(Contents);
Buffer.Cat("<br>\n");
} else {
Buffer.Cat("<B>");
Buffer.Cat(TheTag);
Buffer.Cat(": </B>");
Buffer.Cat(Contents);
Buffer.Cat("<br>\n");
}
}
Buffer.Cat("</BODY>\n</HTML>\n");
*StringBufferPtr = Buffer;
} else {
FieldName = ElementSet;
DOCTYPE::Present (ResultRecord, ElementSet, StringBufferPtr);
}
return;
}
MARCDUMP::~MARCDUMP()
{
}
/*-
What: Given a buffer containing the output of the marcdump program,
returns a list of char* to all characters pointing to the TAG
marcdump Records:
001 ...
005 ...
007 ...
....
1) Each field starts on a new line
2) The first 3 digits define the field name
3) Someday we'll parse for subfields
-*/
static CHR **parse_tags (CHR *b, GPTYPE len)
{
PCHR *t; // array of pointers to first char of tags
size_t tc = 0; // tag count
GPTYPE i=0;
#define TAG_GROW_SIZE 48
size_t max_num_tags = TAG_GROW_SIZE; // max num tags for which space is allocated
// You should allocate these as you need them, but for now...
max_num_tags = TAG_GROW_SIZE;
t = new CHR* [max_num_tags];
CHR* p;
p = strtok(b,"\n");
t[tc++] = p;
while (p=strtok(NULL,"\n")) {
t[tc] = p;
// Expand memory if needed
if (++tc == max_num_tags - 1) {
// allocate more space
max_num_tags += TAG_GROW_SIZE;
CHR **New = new CHR* [max_num_tags];
if (New == NULL) {
delete [] t;
return NULL; // NO MORE CORE!
}
memcpy(New, t, tc*sizeof(CHR*));
delete [] t;
t = New;
}
}
t[tc] = (CHR*)NULL;
return t;
}
int
usefulMarcDumpField(char *fieldStr)
{
return 1;
}
// This function converts a numeric field name into an equivalent string,
// except that it provides a nice way to search multiple fields at once.
// If you map more than one field number (say, 245 and 246) to the same
// text name (say, title), then you can search both fields by asking for
// a search in the text name, ie.
//
// Isearch -d foo 245/bar
//
// will search field 245 for "bar", while
//
// Isearch -d foo title/bar
//
// will search both fields 245 and 246 for "bar", assuming you've
// configured this routine to map both into the string "title". This
// works for the Z39.50 field mapping, too, as long as the map file
// associates the attribute number with the text field name.
void
marcdumpFieldNumToName(STRING& fieldStr, STRING *fieldName)
{
int fieldNum;
fieldNum = fieldStr.GetInt();
*fieldName="";
switch (fieldNum) {
case 1:
*fieldName = "Identifier"; break;
/*
case 10:
*fieldName = "LCCN"; break;
case 20:
*fieldName = "ISBN"; break;
case 22:
*fieldName = "ISSN"; break;
*/
case 40:
*fieldName = "Source"; break;
/*
case 82:
*fieldName = "Dewey"; break;
case 100:
*fieldName = "Author"; break;
*/
case 245:
*fieldName = "Title"; break;
case 246:
*fieldName = "Title"; break;
/*
case 250:
*fieldName = "Edition/Version"; break;
case 260:
*fieldName = "Publisher"; break;
case 310:
*fieldName = "Frequency"; break;
case 362:
*fieldName = "Beginning_Date"; break;
*/
case 440:
*fieldName = "Series"; break;
case 490:
*fieldName = "Series"; break;
/*
case 500:
*fieldName = "Note"; break;
*/
case 520:
*fieldName = "Description"; break;
/*
case 524:
*fieldName = "Citation"; break;
case 540:
*fieldName = "Terms"; break;
*/
case 600:
*fieldName = "Subject"; break;
case 610:
*fieldName = "Subject"; break;
case 611:
*fieldName = "Subject"; break;
case 630:
*fieldName = "Subject"; break;
case 650:
*fieldName = "Subject"; break;
case 651:
*fieldName = "Subject"; break;
case 655:
*fieldName = "Genre"; break;
case 700:
*fieldName = "Author"; break;
case 710:
*fieldName = "Author"; break;
case 711:
*fieldName = "Author"; break;
/*
case 740:
*fieldName = "Title"; break;
case 830:
*fieldName = "Uniform_Title"; break;
*/
case 856:
*fieldName = "Location"; break;
case 997:
*fieldName = "Course"; break;
default:
*fieldName =""; break;
}
}
// Splits the line into the tag, and the contents
int
SplitLine(const STRING& TheLine, STRING* Tag, STRING* Buffer)
{
STRING tmp = TheLine;
INT TagNum;
*Tag = tmp;
Tag->EraseAfter(3);
TagNum = Tag->GetInt();
tmp.EraseBefore(5);
*Buffer = tmp;
return TagNum;
}
// Tests to see if the buffer contains any subtag ($) chars
GDT_BOOLEAN
HasSubfield(const STRING& TheContents, STRING* tag)
{
STRINGINDEX here;
STRING tmp;
*tag="";
if (here=TheContents.Search('$')) {
// Found a subtag marker, check to see if it's genuine
tmp = TheContents;
tmp.EraseBefore(here);
tmp.EraseAfter(3);
// It should have the form "$X "
here=tmp.Search(" ");
if (here == 3) {
tmp.EraseAfter(2);
*tag = tmp;
return GDT_TRUE;
}
}
return GDT_FALSE;
}
// Tests to see if a particular subtag is present
GDT_BOOLEAN
HasSubfieldTag(const STRING& TheContents, STRING& tag)
{
STRINGINDEX here;
STRING tmp;
CHR *pTag, *pField, *ptr;
GDT_BOOLEAN status=GDT_FALSE;
pTag = tag.NewCString();
pField = TheContents.NewCString();
if (ptr=strstr(pField,pTag)) {
status = GDT_TRUE;
}
delete [] pTag;
delete [] pField;
return status;
}
GDT_BOOLEAN
GetSubfield(const STRING& TheContents, const STRING& SubfieldTag,
STRING* Buffer)
{
STRINGINDEX here;
STRING tmp;
CHR *pTag, *pField, *ptr;
GDT_BOOLEAN status=GDT_FALSE;
pTag = SubfieldTag.NewCString();
pField = TheContents.NewCString();
*Buffer="";
if (ptr=strstr(pField,pTag)) {
*Buffer = ptr+3;
status = GDT_TRUE;
}
delete [] pTag;
delete [] pField;
return status;
}
INT
GetSubfields(const STRING& TheContents, STRLIST* TheSubfields)
{
STRLIST List;
STRING Contents=TheContents;
STRING tmp,Tag,Field;
STRING NewContents;
STRINGINDEX here;
INT nSubs;
List.Split('$',Contents);
nSubs = List.GetTotalEntries();
// If nSubs=1, there are no subfields
if (nSubs > 1) {
for (INT i=2;i<=nSubs;i++) {
List.GetEntry(i,&tmp);
// The first character is the subfield tag, the rest is the contents
Tag = "$";
Tag.Cat(tmp);
here=Tag.Search(" ");
Tag.EraseAfter(here);
Field = tmp;
here=Field.Search(" ");
Field.EraseBefore(here+1);
NewContents = Tag;
NewContents.Cat("=");
NewContents.Cat(Field);
TheSubfields->AddEntry(NewContents);
}
}
return (nSubs-1);
}
| 24.339166 | 87 | 0.626299 | re-Isearch |
916beb4c7c82d6dfcd78be0842fa09b3639164ef | 9,470 | cxx | C++ | java/jni/direct_bt/DBTGattChar.cxx | sgothel/direct_bt | e19a11a60d509a42a1a1167a2b7215345784e462 | [
"MIT"
] | 10 | 2020-09-03T16:23:12.000Z | 2022-03-10T13:51:40.000Z | java/jni/direct_bt/DBTGattChar.cxx | sgothel/direct_bt | e19a11a60d509a42a1a1167a2b7215345784e462 | [
"MIT"
] | null | null | null | java/jni/direct_bt/DBTGattChar.cxx | sgothel/direct_bt | e19a11a60d509a42a1a1167a2b7215345784e462 | [
"MIT"
] | 3 | 2020-09-03T05:21:46.000Z | 2020-09-04T18:44:00.000Z | /*
* Author: Sven Gothel <sgothel@jausoft.com>
* Copyright (c) 2020 Gothel Software e.K.
* Copyright (c) 2020 ZAFENA AB
*
* 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 "jau_direct_bt_DBTGattChar.h"
#include <jau/debug.hpp>
#include "helper_base.hpp"
#include "helper_dbt.hpp"
#include "direct_bt/BTDevice.hpp"
#include "direct_bt/BTAdapter.hpp"
using namespace direct_bt;
using namespace jau;
jstring Java_jau_direct_1bt_DBTGattChar_toStringImpl(JNIEnv *env, jobject obj) {
try {
BTGattChar *nativePtr = getJavaUplinkObject<BTGattChar>(env, obj);
JavaGlobalObj::check(nativePtr->getJavaObject(), E_FILE_LINE);
return from_string_to_jstring(env, nativePtr->toString());
} catch(...) {
rethrow_and_raise_java_exception(env);
}
return nullptr;
}
void Java_jau_direct_1bt_DBTGattChar_deleteImpl(JNIEnv *env, jobject obj, jlong nativeInstance) {
(void)obj;
try {
BTGattChar *characteristic = castInstance<BTGattChar>(nativeInstance);
(void)characteristic;
// No delete: Service instance owned by BTGattService -> BTDevice
} catch(...) {
rethrow_and_raise_java_exception(env);
}
}
static const std::string _descriptorClazzCtorArgs("(JLjau/direct_bt/DBTGattChar;Ljava/lang/String;S[B)V");
jobject Java_jau_direct_1bt_DBTGattChar_getDescriptorsImpl(JNIEnv *env, jobject obj) {
try {
BTGattChar *characteristic = getJavaUplinkObject<BTGattChar>(env, obj);
JavaGlobalObj::check(characteristic->getJavaObject(), E_FILE_LINE);
jau::darray<BTGattDescRef> & descriptorList = characteristic->descriptorList;
// BTGattDesc(final long nativeInstance, final BTGattChar characteristic,
// final String type_uuid, final short handle, final byte[] value)
// BTGattDesc(final long nativeInstance, final BTGattChar characteristic,
// final String type_uuid, final short handle, final byte[] value)
std::function<jobject(JNIEnv*, jclass, jmethodID, BTGattDesc *)> ctor_desc =
[](JNIEnv *env_, jclass clazz, jmethodID clazz_ctor, BTGattDesc *descriptor)->jobject {
// prepare adapter ctor
std::shared_ptr<BTGattChar> _characteristic = descriptor->getGattCharChecked();
JavaGlobalObj::check(_characteristic->getJavaObject(), E_FILE_LINE);
jobject jcharacteristic = JavaGlobalObj::GetObject(_characteristic->getJavaObject());
const jstring juuid = from_string_to_jstring(env_, descriptor->type->toUUID128String());
java_exception_check_and_throw(env_, E_FILE_LINE);
const size_t value_size = descriptor->value.size();
jbyteArray jval = env_->NewByteArray((jsize)value_size);
env_->SetByteArrayRegion(jval, 0, (jsize)value_size, (const jbyte *)descriptor->value.get_ptr());
java_exception_check_and_throw(env_, E_FILE_LINE);
jobject jdesc = env_->NewObject(clazz, clazz_ctor, (jlong)descriptor, jcharacteristic,
juuid, (jshort)descriptor->handle, jval);
java_exception_check_and_throw(env_, E_FILE_LINE);
JNIGlobalRef::check(jdesc, E_FILE_LINE);
std::shared_ptr<JavaAnon> jDescRef = descriptor->getJavaObject(); // GlobalRef
JavaGlobalObj::check(jDescRef, E_FILE_LINE);
env_->DeleteLocalRef(juuid);
env_->DeleteLocalRef(jval);
env_->DeleteLocalRef(jdesc);
return JavaGlobalObj::GetObject(jDescRef);
};
return convert_vector_sharedptr_to_jarraylist<jau::darray<BTGattDescRef>, BTGattDesc>(
env, descriptorList, _descriptorClazzCtorArgs.c_str(), ctor_desc);
} catch(...) {
rethrow_and_raise_java_exception(env);
}
return nullptr;
}
jbyteArray Java_jau_direct_1bt_DBTGattChar_readValueImpl(JNIEnv *env, jobject obj) {
try {
BTGattChar *characteristic = getJavaUplinkObject<BTGattChar>(env, obj);
JavaGlobalObj::check(characteristic->getJavaObject(), E_FILE_LINE);
POctets res(BTGattHandler::number(BTGattHandler::Defaults::MAX_ATT_MTU), 0, jau::endian::little);
if( !characteristic->readValue(res) ) {
ERR_PRINT("Characteristic readValue failed: %s", characteristic->toString().c_str());
return env->NewByteArray((jsize)0);
}
const size_t value_size = res.size();
jbyteArray jres = env->NewByteArray((jsize)value_size);
env->SetByteArrayRegion(jres, 0, (jsize)value_size, (const jbyte *)res.get_ptr());
java_exception_check_and_throw(env, E_FILE_LINE);
return jres;
} catch(...) {
rethrow_and_raise_java_exception(env);
}
return nullptr;
}
jboolean Java_jau_direct_1bt_DBTGattChar_writeValueImpl(JNIEnv *env, jobject obj, jbyteArray jval, jboolean withResponse) {
try {
if( nullptr == jval ) {
throw IllegalArgumentException("byte array null", E_FILE_LINE);
}
const int value_size = env->GetArrayLength(jval);
if( 0 == value_size ) {
return JNI_TRUE;
}
BTGattChar *characteristic = getJavaUplinkObject<BTGattChar>(env, obj);
JavaGlobalObj::check(characteristic->getJavaObject(), E_FILE_LINE);
JNICriticalArray<uint8_t, jbyteArray> criticalArray(env); // RAII - release
uint8_t * value_ptr = criticalArray.get(jval, criticalArray.Mode::NO_UPDATE_AND_RELEASE);
if( NULL == value_ptr ) {
throw InternalError("GetPrimitiveArrayCritical(byte array) is null", E_FILE_LINE);
}
TROOctets value(value_ptr, value_size, jau::endian::little);
bool res;
if( withResponse ) {
res = characteristic->writeValue(value);
} else {
res = characteristic->writeValueNoResp(value);
}
if( !res ) {
ERR_PRINT("Characteristic writeValue(withResponse %d) failed: %s",
withResponse, characteristic->toString().c_str());
return JNI_FALSE;
}
return JNI_TRUE;
} catch(...) {
rethrow_and_raise_java_exception(env);
}
return JNI_FALSE;
}
jboolean Java_jau_direct_1bt_DBTGattChar_configNotificationIndicationImpl(JNIEnv *env, jobject obj,
jboolean enableNotification, jboolean enableIndication, jbooleanArray jEnabledState) {
try {
BTGattChar *characteristic = getJavaUplinkObjectUnchecked<BTGattChar>(env, obj);
if( nullptr == characteristic ) {
if( !enableNotification && !enableIndication ) {
// OK to have native characteristic being shutdown @ disable
DBG_PRINT("Characteristic's native instance has been deleted");
return false;
}
throw IllegalStateException("Characteristic's native instance deleted", E_FILE_LINE);
}
JavaGlobalObj::check(characteristic->getJavaObject(), E_FILE_LINE);
if( nullptr == jEnabledState ) {
throw IllegalArgumentException("boolean array null", E_FILE_LINE);
}
const int state_size = env->GetArrayLength(jEnabledState);
if( 2 > state_size ) {
throw IllegalArgumentException("boolean array smaller than 2, length "+std::to_string(state_size), E_FILE_LINE);
}
JNICriticalArray<jboolean, jbooleanArray> criticalArray(env); // RAII - release
jboolean * state_ptr = criticalArray.get(jEnabledState, criticalArray.Mode::UPDATE_AND_RELEASE);
if( NULL == state_ptr ) {
throw InternalError("GetPrimitiveArrayCritical(boolean array) is null", E_FILE_LINE);
}
bool cccdEnableResult[2];
bool res = characteristic->configNotificationIndication(enableNotification, enableIndication, cccdEnableResult);
DBG_PRINT("BTGattChar::configNotificationIndication Config Notification(%d), Indication(%d): Result %d",
cccdEnableResult[0], cccdEnableResult[1], res);
state_ptr[0] = cccdEnableResult[0];
state_ptr[1] = cccdEnableResult[1];
return res;
} catch(...) {
rethrow_and_raise_java_exception(env);
}
return JNI_FALSE;
}
| 45.311005 | 124 | 0.667476 | sgothel |
916db555cc93696805c644485df400e7d22d0928 | 2,065 | cpp | C++ | src/third_party/mozjs/platform/x86_64/windows/build/debugger/Unified_cpp_js_src_debugger0.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/third_party/mozjs/platform/x86_64/windows/build/debugger/Unified_cpp_js_src_debugger0.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/third_party/mozjs/platform/x86_64/windows/build/debugger/Unified_cpp_js_src_debugger0.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | #define MOZ_UNIFIED_BUILD
#include "debugger/DebugScript.cpp"
#ifdef PL_ARENA_CONST_ALIGN_MASK
#error "debugger/DebugScript.cpp uses PL_ARENA_CONST_ALIGN_MASK, so it cannot be built in unified mode."
#undef PL_ARENA_CONST_ALIGN_MASK
#endif
#ifdef INITGUID
#error "debugger/DebugScript.cpp defines INITGUID, so it cannot be built in unified mode."
#undef INITGUID
#endif
#include "debugger/Debugger.cpp"
#ifdef PL_ARENA_CONST_ALIGN_MASK
#error "debugger/Debugger.cpp uses PL_ARENA_CONST_ALIGN_MASK, so it cannot be built in unified mode."
#undef PL_ARENA_CONST_ALIGN_MASK
#endif
#ifdef INITGUID
#error "debugger/Debugger.cpp defines INITGUID, so it cannot be built in unified mode."
#undef INITGUID
#endif
#include "debugger/DebuggerMemory.cpp"
#ifdef PL_ARENA_CONST_ALIGN_MASK
#error "debugger/DebuggerMemory.cpp uses PL_ARENA_CONST_ALIGN_MASK, so it cannot be built in unified mode."
#undef PL_ARENA_CONST_ALIGN_MASK
#endif
#ifdef INITGUID
#error "debugger/DebuggerMemory.cpp defines INITGUID, so it cannot be built in unified mode."
#undef INITGUID
#endif
#include "debugger/Environment.cpp"
#ifdef PL_ARENA_CONST_ALIGN_MASK
#error "debugger/Environment.cpp uses PL_ARENA_CONST_ALIGN_MASK, so it cannot be built in unified mode."
#undef PL_ARENA_CONST_ALIGN_MASK
#endif
#ifdef INITGUID
#error "debugger/Environment.cpp defines INITGUID, so it cannot be built in unified mode."
#undef INITGUID
#endif
#include "debugger/Frame.cpp"
#ifdef PL_ARENA_CONST_ALIGN_MASK
#error "debugger/Frame.cpp uses PL_ARENA_CONST_ALIGN_MASK, so it cannot be built in unified mode."
#undef PL_ARENA_CONST_ALIGN_MASK
#endif
#ifdef INITGUID
#error "debugger/Frame.cpp defines INITGUID, so it cannot be built in unified mode."
#undef INITGUID
#endif
#include "debugger/NoExecute.cpp"
#ifdef PL_ARENA_CONST_ALIGN_MASK
#error "debugger/NoExecute.cpp uses PL_ARENA_CONST_ALIGN_MASK, so it cannot be built in unified mode."
#undef PL_ARENA_CONST_ALIGN_MASK
#endif
#ifdef INITGUID
#error "debugger/NoExecute.cpp defines INITGUID, so it cannot be built in unified mode."
#undef INITGUID
#endif | 37.545455 | 107 | 0.821792 | benety |
916f77bb5ca21ef3f1ea64a0025bfdcb97ca475b | 252 | cpp | C++ | src/BarProject/TCPClient.cpp | gallowstree/ArduinoMazeNavV2 | fdd35ce066cb4c3d78496beeda2ef831f7fb6713 | [
"MIT"
] | null | null | null | src/BarProject/TCPClient.cpp | gallowstree/ArduinoMazeNavV2 | fdd35ce066cb4c3d78496beeda2ef831f7fb6713 | [
"MIT"
] | null | null | null | src/BarProject/TCPClient.cpp | gallowstree/ArduinoMazeNavV2 | fdd35ce066cb4c3d78496beeda2ef831f7fb6713 | [
"MIT"
] | null | null | null | #include "TCPClient.h"
TCPClient::TCPClient(){}
int TCPClient::connect(char * host, int port)
{
return client.connect(host,port);
}
void TCPClient::sendData(String data)
{
client.print(data);
}
void TCPClient::close()
{
client.stop();
} | 14 | 45 | 0.674603 | gallowstree |
91715be46775913e27346f5d5280da1f36ace818 | 2,962 | cpp | C++ | source/tools/show_devices_sycl/main.cpp | intel/compute-benchmarks | d0b3ea3c7e9c9b275b259287f5fe0c22f16b58b8 | [
"MIT"
] | null | null | null | source/tools/show_devices_sycl/main.cpp | intel/compute-benchmarks | d0b3ea3c7e9c9b275b259287f5fe0c22f16b58b8 | [
"MIT"
] | null | null | null | source/tools/show_devices_sycl/main.cpp | intel/compute-benchmarks | d0b3ea3c7e9c9b275b259287f5fe0c22f16b58b8 | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2022 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "framework/sycl/sycl.h"
#include <cstring>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
// ------------------------------------------------------------------------- Helpers for creating/freeing platforms and devices
std::vector<sycl::device> createSubDevices(const sycl::device &rootDevice) {
auto domain = rootDevice.get_info<sycl::info::device::partition_type_affinity_domain>();
if (domain != sycl::info::partition_affinity_domain::numa) {
return {};
}
std::vector<sycl::device> result = rootDevice.create_sub_devices<sycl::info::partition_property::partition_by_affinity_domain>(domain);
return result;
}
// ------------------------------------------------------------------------- Printing functions
void showPlatform(size_t indentLevel, const sycl::platform &platform, size_t platformIndex) {
const std::string indent0(indentLevel + 0, '\t');
std::cout << indent0 << "Platform " << platformIndex << ": " << platform.get_info<sycl::info::platform::name>() << '\n';
}
void showDevice(size_t indentLevel, const sycl::device &device, const std::string &deviceLabel, size_t deviceIndex) {
const std::string indent0(indentLevel + 0, '\t');
const std::string indent1(indentLevel + 1, '\t');
const std::string indent2(indentLevel + 2, '\t');
// Print device header
std::cout << indent0 << deviceLabel << " " << deviceIndex << ": " << device.get_info<sycl::info::device::name>() << '\n';
}
void showDeviceAndItsSubDevices(size_t indentLevel, size_t deviceLevel, const sycl::device &device, size_t deviceIndex) {
const std::string deviceNames[] = {
"RootDevice",
"SubDevice",
"SubSubDevice",
};
const std::string deviceLabel = deviceNames[deviceLevel];
showDevice(indentLevel, device, deviceLabel, deviceIndex);
std::vector<sycl::device> subDevices = createSubDevices(device);
for (auto subDeviceIndex = 0u; subDeviceIndex < subDevices.size(); subDeviceIndex++) {
showDeviceAndItsSubDevices(indentLevel + 1, deviceLevel + 1, subDevices[subDeviceIndex], subDeviceIndex);
}
}
// ------------------------------------------------------------------------- Main procedure
int main() {
Configuration::loadDefaultConfiguration();
std::vector<sycl::platform> platforms = sycl::platform::get_platforms();
for (auto platformIndex = 0u; platformIndex < platforms.size(); platformIndex++) {
sycl::platform platform = platforms[platformIndex];
showPlatform(0u, platform, platformIndex);
std::vector<sycl::device> devices = platform.get_devices();
for (auto deviceIndex = 0u; deviceIndex < devices.size(); deviceIndex++) {
sycl::device device = devices[deviceIndex];
showDeviceAndItsSubDevices(1u, 0u, device, deviceIndex);
}
}
return 0;
}
| 37.025 | 139 | 0.633018 | intel |
917261d0dc69ebc96ab34b4c739bffcdb1ae675b | 7,485 | cpp | C++ | utils/cluster.cpp | adam-lafontaine/AugmentedAI | a4736ce59963ee86313a5936aaf09f0f659e4184 | [
"MIT"
] | null | null | null | utils/cluster.cpp | adam-lafontaine/AugmentedAI | a4736ce59963ee86313a5936aaf09f0f659e4184 | [
"MIT"
] | null | null | null | utils/cluster.cpp | adam-lafontaine/AugmentedAI | a4736ce59963ee86313a5936aaf09f0f659e4184 | [
"MIT"
] | null | null | null | /*
Copyright (c) 2021 Adam Lafontaine
*/
#include "cluster_config.hpp"
#include <cstdlib>
#include <algorithm>
#include <random>
#include <iterator>
#include <iostream>
#include <functional>
namespace cluster
{
//======= TYPES ===================
typedef struct ClusterCount // used for tracking the number of times a given result is found
{
cluster_result_t result;
unsigned count;
} cluster_count_t;
using closest_t = std::function<distance_result_t(data_row_t const& data, value_row_list_t const& value_list)>;
using cluster_once_t = std::function<cluster_result_t(data_row_list_t const& x_list, size_t num_clusters)>;
//======= HELPERS ====================
static size_t max_value(index_list_t const& list)
{
return *std::max_element(list.begin(), list.end());
}
// convert a list of data_row_t to value_row_t
static value_row_list_t to_value_row_list(data_row_list_t const& data_row_list)
{
auto list = make_value_row_list(data_row_list.size(), data_row_list[0].size());
for (size_t i = 0; i < data_row_list.size(); ++i)
{
auto data_row = data_row_list[i];
for (size_t j = 0; j < data_row.size(); ++j)
list[i][j] = data_to_value(data_row[j]);
}
return list;
}
// selects random data to be used as centroids
static value_row_list_t random_values(data_row_list_t const& x_list, size_t num_clusters)
{
// C++ 17 std::sample
data_row_list_t samples;
samples.reserve(num_clusters);
std::sample(x_list.begin(), x_list.end(), std::back_inserter(samples),
num_clusters, std::mt19937{ std::random_device{}() });
return to_value_row_list(samples);
}
// assigns a cluster index to each data point
static cluster_result_t assign_clusters(data_row_list_t const& x_list, value_row_list_t& centroids, closest_t const& closest)
{
index_list_t x_clusters;
x_clusters.reserve(x_list.size());
double total_distance = 0;
for (auto const& x_data : x_list)
{
auto c = closest(x_data, centroids);
x_clusters.push_back(c.index);
total_distance += c.distance;
}
cluster_result_t res = { std::move(x_clusters), std::move(centroids), total_distance / x_list.size() };
return res;
}
// finds new centroids based on the averages of data clustered together
static value_row_list_t calc_centroids(data_row_list_t const& x_list, index_list_t const& x_clusters, size_t num_clusters)
{
const auto data_size = x_list[0].size();
auto values = make_value_row_list(num_clusters, data_size);
std::vector<unsigned> counts(num_clusters, 0);
for (size_t i = 0; i < x_list.size(); ++i)
{
const auto cluster_index = x_clusters[i];
++counts[cluster_index];
for (size_t d = 0; d < data_size; ++d)
values[cluster_index][d] += data_to_value(x_list[i][d]); // totals for each cluster
}
for (size_t k = 0; k < num_clusters; ++k)
{
for (size_t d = 0; d < data_size; ++d)
values[k][d] = values[k][d] / counts[k]; // convert to average
}
return values;
}
// re-label cluster assignments so that they are consistent accross iterations
static void relabel_clusters(cluster_result_t& result, size_t num_clusters)
{
std::vector<uint8_t> flags(num_clusters, 0); // tracks if cluster index has been mapped
std::vector<size_t> map(num_clusters, 0); // maps old cluster index to new cluster index
const auto all_flagged = [&]()
{
for (auto const flag : flags)
{
if (!flag)
return false;
}
return true;
};
size_t i = 0;
size_t label = 0;
for (; label < num_clusters && i < result.x_clusters.size() && !all_flagged(); ++i)
{
size_t c = result.x_clusters[i];
if (flags[c])
continue;
map[c] = label;
flags[c] = 1;
++label;
}
// re-label cluster assignments
for (i = 0; i < result.x_clusters.size(); ++i)
{
size_t c = result.x_clusters[i];
result.x_clusters[i] = map[c];
}
}
//======= CLUSTERING ALGORITHMS ==========================
// returns the result with the smallest distance
static cluster_result_t cluster_min_distance(data_row_list_t const& x_list, size_t num_clusters, cluster_once_t const& cluster_once)
{
auto result = cluster_once(x_list, num_clusters);
auto min = result;
for (size_t i = 0; i < CLUSTER_ATTEMPTS; ++i)
{
result = cluster_once(x_list, num_clusters);
if (result.average_distance < min.average_distance)
min = std::move(result);
}
return min;
}
/*
// returns the most popular result
// stops when the same result has been found for more than half of the attempts
static cluster_result_t cluster_max_count(data_row_list_t const& x_list, size_t num_clusters, cluster_once_t const& cluster_once)
{
std::vector<cluster_count_t> counts;
counts.reserve(CLUSTER_ATTEMPTS);
auto result = cluster_once(x_list, num_clusters);
counts.push_back({ std::move(result), 1 });
for (size_t i = 0; i < CLUSTER_ATTEMPTS; ++i)
{
result = cluster_once(x_list, num_clusters);
bool add_clusters = true;
for (auto& c : counts)
{
if (list_distance(result.x_clusters, c.result.x_clusters) != 0)
continue;
++c.count;
if (c.count > CLUSTER_ATTEMPTS / 2)
return c.result;
add_clusters = false;
break;
}
if (add_clusters)
{
counts.push_back({ std::move(result), 1 });
}
}
auto constexpr comp = [](cluster_count_t const& lhs, cluster_count_t const& rhs) { return lhs.count < rhs.count; };
auto const best = *std::max_element(counts.begin(), counts.end(), comp);
return best.result;
}
*/
//======= CLASS METHODS ==============================
distance_result_t Cluster::closest(data_row_t const& data, value_row_list_t const& value_list) const
{
distance_result_t res = { 0, m_dist_func(data, value_list[0]) };
for (size_t i = 1; i < value_list.size(); ++i)
{
auto dist = m_dist_func(data, value_list[i]);
if (dist < res.distance)
{
res.distance = dist;
res.index = i;
}
}
return res;
}
size_t Cluster::find_centroid(data_row_t const& data, value_row_list_t const& centroids) const
{
auto result = closest(data, centroids);
return result.index;
}
cluster_result_t Cluster::cluster_once(data_row_list_t const& x_list, size_t num_clusters) const
{
const auto closest_f = [&](data_row_t const& data, value_row_list_t const& value_list) // TODO: why?
{
return closest(data, value_list);
};
auto centroids = random_values(x_list, num_clusters); // start with random centroids
auto result = assign_clusters(x_list, centroids, closest_f);
relabel_clusters(result, num_clusters);
for (size_t i = 0; i < CLUSTER_ITERATIONS; ++i)
{
centroids = calc_centroids(x_list, result.x_clusters, num_clusters);
auto res_try = assign_clusters(x_list, centroids, closest_f);
if (max_value(res_try.x_clusters) < num_clusters - 1)
continue;
auto res_old = std::move(result);
result = std::move(res_try);
relabel_clusters(result, num_clusters);
if (list_distance(res_old.x_clusters, result.x_clusters) == 0)
return result;
}
return result;
}
value_row_list_t Cluster::cluster_data(data_row_list_t const& x_list, size_t num_clusters) const
{
// wrap member function in a lambda to pass it to algorithm
const auto cluster_once_f = [&](data_row_list_t const& x_list, size_t num_clusters) // TODO: why?
{
return cluster_once(x_list, num_clusters);
};
auto result = cluster_min_distance(x_list, num_clusters, cluster_once_f);
return result.centroids;
}
}
| 25.287162 | 133 | 0.685237 | adam-lafontaine |
917370d931183c64581308f00895629d846bcef8 | 7,760 | cc | C++ | iree/base/tracing.cc | kintel/iree | 7dbe1aea471e880327694ffbfc0b536f1e587f2c | [
"Apache-2.0"
] | null | null | null | iree/base/tracing.cc | kintel/iree | 7dbe1aea471e880327694ffbfc0b536f1e587f2c | [
"Apache-2.0"
] | 1 | 2021-06-16T12:18:44.000Z | 2021-06-16T12:18:44.000Z | iree/base/tracing.cc | kintel/iree | 7dbe1aea471e880327694ffbfc0b536f1e587f2c | [
"Apache-2.0"
] | null | null | null | // Copyright 2019 The IREE Authors
//
// Licensed under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include "iree/base/tracing.h"
#include "iree/base/target_platform.h"
// Textually include the Tracy implementation.
// We do this here instead of relying on an external build target so that we can
// ensure our configuration specified in tracing.h is picked up.
#if IREE_TRACING_FEATURES != 0
#include "third_party/tracy/TracyClient.cpp"
#endif // IREE_TRACING_FEATURES
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
#if defined(TRACY_ENABLE) && defined(IREE_PLATFORM_WINDOWS)
static HANDLE iree_dbghelp_mutex;
void IREEDbgHelpInit(void) {
iree_dbghelp_mutex = CreateMutex(NULL, FALSE, NULL);
}
void IREEDbgHelpLock(void) {
WaitForSingleObject(iree_dbghelp_mutex, INFINITE);
}
void IREEDbgHelpUnlock(void) { ReleaseMutex(iree_dbghelp_mutex); }
#endif // TRACY_ENABLE && IREE_PLATFORM_WINDOWS
#if IREE_TRACING_FEATURES != 0
void iree_tracing_set_thread_name_impl(const char* name) {
tracy::SetThreadName(name);
}
iree_zone_id_t iree_tracing_zone_begin_impl(
const iree_tracing_location_t* src_loc, const char* name,
size_t name_length) {
const iree_zone_id_t zone_id = tracy::GetProfiler().GetNextZoneId();
#ifndef TRACY_NO_VERIFY
{
TracyLfqPrepareC(tracy::QueueType::ZoneValidation);
tracy::MemWrite(&item->zoneValidation.id, zone_id);
TracyLfqCommitC;
}
#endif // TRACY_NO_VERIFY
{
#if IREE_TRACING_FEATURES & IREE_TRACING_FEATURE_INSTRUMENTATION_CALLSTACKS
TracyLfqPrepareC(tracy::QueueType::ZoneBeginCallstack);
#else
TracyLfqPrepareC(tracy::QueueType::ZoneBegin);
#endif // IREE_TRACING_FEATURE_INSTRUMENTATION_CALLSTACKS
tracy::MemWrite(&item->zoneBegin.time, tracy::Profiler::GetTime());
tracy::MemWrite(&item->zoneBegin.srcloc,
reinterpret_cast<uint64_t>(src_loc));
TracyLfqCommitC;
}
#if IREE_TRACING_FEATURES & IREE_TRACING_FEATURE_INSTRUMENTATION_CALLSTACKS
tracy::GetProfiler().SendCallstack(IREE_TRACING_MAX_CALLSTACK_DEPTH);
#endif // IREE_TRACING_FEATURE_INSTRUMENTATION_CALLSTACKS
if (name_length) {
#ifndef TRACY_NO_VERIFY
{
TracyLfqPrepareC(tracy::QueueType::ZoneValidation);
tracy::MemWrite(&item->zoneValidation.id, zone_id);
TracyLfqCommitC;
}
#endif // TRACY_NO_VERIFY
auto name_ptr = reinterpret_cast<char*>(tracy::tracy_malloc(name_length));
memcpy(name_ptr, name, name_length);
TracyLfqPrepareC(tracy::QueueType::ZoneName);
tracy::MemWrite(&item->zoneTextFat.text,
reinterpret_cast<uint64_t>(name_ptr));
tracy::MemWrite(&item->zoneTextFat.size,
static_cast<uint64_t>(name_length));
TracyLfqCommitC;
}
return zone_id;
}
iree_zone_id_t iree_tracing_zone_begin_external_impl(
const char* file_name, size_t file_name_length, uint32_t line,
const char* function_name, size_t function_name_length, const char* name,
size_t name_length) {
uint64_t src_loc = tracy::Profiler::AllocSourceLocation(
line, file_name, file_name_length, function_name, function_name_length,
name, name_length);
const iree_zone_id_t zone_id = tracy::GetProfiler().GetNextZoneId();
#ifndef TRACY_NO_VERIFY
{
TracyLfqPrepareC(tracy::QueueType::ZoneValidation);
tracy::MemWrite(&item->zoneValidation.id, zone_id);
TracyLfqCommitC;
}
#endif // TRACY_NO_VERIFY
{
#if IREE_TRACING_FEATURES & IREE_TRACING_FEATURE_INSTRUMENTATION_CALLSTACKS
TracyLfqPrepareC(tracy::QueueType::ZoneBeginAllocSrcLocCallstack);
#else
TracyLfqPrepareC(tracy::QueueType::ZoneBeginAllocSrcLoc);
#endif // IREE_TRACING_FEATURE_INSTRUMENTATION_CALLSTACKS
tracy::MemWrite(&item->zoneBegin.time, tracy::Profiler::GetTime());
tracy::MemWrite(&item->zoneBegin.srcloc, src_loc);
TracyLfqCommitC;
}
#if IREE_TRACING_FEATURES & IREE_TRACING_FEATURE_INSTRUMENTATION_CALLSTACKS
tracy::GetProfiler().SendCallstack(IREE_TRACING_MAX_CALLSTACK_DEPTH);
#endif // IREE_TRACING_FEATURE_INSTRUMENTATION_CALLSTACKS
return zone_id;
}
void iree_tracing_set_plot_type_impl(const char* name_literal,
uint8_t plot_type) {
tracy::Profiler::ConfigurePlot(name_literal,
static_cast<tracy::PlotFormatType>(plot_type));
}
void iree_tracing_plot_value_i64_impl(const char* name_literal, int64_t value) {
tracy::Profiler::PlotData(name_literal, value);
}
void iree_tracing_plot_value_f32_impl(const char* name_literal, float value) {
tracy::Profiler::PlotData(name_literal, value);
}
void iree_tracing_plot_value_f64_impl(const char* name_literal, double value) {
tracy::Profiler::PlotData(name_literal, value);
}
void iree_tracing_mutex_announce(const iree_tracing_location_t* src_loc,
uint32_t* out_lock_id) {
uint32_t lock_id =
tracy::GetLockCounter().fetch_add(1, std::memory_order_relaxed);
assert(lock_id != std::numeric_limits<uint32_t>::max());
*out_lock_id = lock_id;
auto item = tracy::Profiler::QueueSerial();
tracy::MemWrite(&item->hdr.type, tracy::QueueType::LockAnnounce);
tracy::MemWrite(&item->lockAnnounce.id, lock_id);
tracy::MemWrite(&item->lockAnnounce.time, tracy::Profiler::GetTime());
tracy::MemWrite(&item->lockAnnounce.lckloc,
reinterpret_cast<uint64_t>(src_loc));
tracy::MemWrite(&item->lockAnnounce.type, tracy::LockType::Lockable);
tracy::Profiler::QueueSerialFinish();
}
void iree_tracing_mutex_terminate(uint32_t lock_id) {
auto item = tracy::Profiler::QueueSerial();
tracy::MemWrite(&item->hdr.type, tracy::QueueType::LockTerminate);
tracy::MemWrite(&item->lockTerminate.id, lock_id);
tracy::MemWrite(&item->lockTerminate.time, tracy::Profiler::GetTime());
tracy::Profiler::QueueSerialFinish();
}
void iree_tracing_mutex_before_lock(uint32_t lock_id) {
auto item = tracy::Profiler::QueueSerial();
tracy::MemWrite(&item->hdr.type, tracy::QueueType::LockWait);
tracy::MemWrite(&item->lockWait.thread, tracy::GetThreadHandle());
tracy::MemWrite(&item->lockWait.id, lock_id);
tracy::MemWrite(&item->lockWait.time, tracy::Profiler::GetTime());
tracy::Profiler::QueueSerialFinish();
}
void iree_tracing_mutex_after_lock(uint32_t lock_id) {
auto item = tracy::Profiler::QueueSerial();
tracy::MemWrite(&item->hdr.type, tracy::QueueType::LockObtain);
tracy::MemWrite(&item->lockObtain.thread, tracy::GetThreadHandle());
tracy::MemWrite(&item->lockObtain.id, lock_id);
tracy::MemWrite(&item->lockObtain.time, tracy::Profiler::GetTime());
tracy::Profiler::QueueSerialFinish();
}
void iree_tracing_mutex_after_try_lock(uint32_t lock_id, bool was_acquired) {
if (was_acquired) {
iree_tracing_mutex_after_lock(lock_id);
}
}
void iree_tracing_mutex_after_unlock(uint32_t lock_id) {
auto item = tracy::Profiler::QueueSerial();
tracy::MemWrite(&item->hdr.type, tracy::QueueType::LockRelease);
tracy::MemWrite(&item->lockRelease.thread, tracy::GetThreadHandle());
tracy::MemWrite(&item->lockRelease.id, lock_id);
tracy::MemWrite(&item->lockRelease.time, tracy::Profiler::GetTime());
tracy::Profiler::QueueSerialFinish();
}
#endif // IREE_TRACING_FEATURES
#ifdef __cplusplus
} // extern "C"
#endif // __cplusplus
#if defined(__cplusplus) && \
(IREE_TRACING_FEATURES & IREE_TRACING_FEATURE_ALLOCATION_TRACKING)
void* operator new(size_t count) noexcept {
auto ptr = malloc(count);
IREE_TRACE_ALLOC(ptr, count);
return ptr;
}
void operator delete(void* ptr) noexcept {
IREE_TRACE_FREE(ptr);
free(ptr);
}
#endif // __cplusplus && IREE_TRACING_FEATURE_ALLOCATION_TRACKING
| 34.954955 | 80 | 0.748196 | kintel |
9176d8b08742830c750aa5bc0215da7a1aa8502b | 920 | cpp | C++ | TOI16/Uncomplete-TEST/1109.cpp | mrmuffinnxz/TOI-preparation | 85a7d5b70d7fc661950bbb5de66a6885a835e755 | [
"MIT"
] | null | null | null | TOI16/Uncomplete-TEST/1109.cpp | mrmuffinnxz/TOI-preparation | 85a7d5b70d7fc661950bbb5de66a6885a835e755 | [
"MIT"
] | null | null | null | TOI16/Uncomplete-TEST/1109.cpp | mrmuffinnxz/TOI-preparation | 85a7d5b70d7fc661950bbb5de66a6885a835e755 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
#define endll "\n"
int n;
pair<int,int> arr[100001], temp[100001];
int merge(int l,int mid, int r)
{
int i=l, j=mid, k=l;
int sum=0;
while(i<=mid-1 && j<=r)
{
if(arr[i].first <= arr[j].first) temp[k++] = arr[i++];
else
{
sum += (mid-i);
temp[k++] = arr[j++];
}
}
while(i<=mid-1) temp[k++] = arr[i++];
while(j<=r) temp[k++] = arr[j++];
for(int p=l;p<=r;p++)
arr[p] = temp[p];
return sum;
}
int mergesort(int l,int r)
{
int sum = 0;
if(r > l)
{
int mid = (l+r)/2;
sum += mergesort(l,mid);
sum += mergesort(mid+1,r);
sum += merge(l,mid+1,r);
}
cout<<l<<" "<<r<<" "<<sum<<endll;
return sum;
}
main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cin>>n;
for(int i=0;i<n;i++)
cin>>arr[i].first>>arr[i].second;
for(int i=0;i<n;i++)
cout<<arr[i].first<<" "<<arr[i].second<<endll;
cout<<mergesort(0,n-1);
}
| 14.603175 | 56 | 0.521739 | mrmuffinnxz |
91782ac2f1e95b4ebad4dd7b7014dabf54da8541 | 1,199 | hpp | C++ | modules/scene_manager/include/map_msgs/srv/save_map__request__traits.hpp | Omnirobotic/godot | d50b5d047bbf6c68fc458c1ad097321ca627185d | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null | modules/scene_manager/include/map_msgs/srv/save_map__request__traits.hpp | Omnirobotic/godot | d50b5d047bbf6c68fc458c1ad097321ca627185d | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | 3 | 2019-11-14T12:20:06.000Z | 2020-08-07T13:51:10.000Z | modules/scene_manager/include/map_msgs/srv/save_map__request__traits.hpp | Omnirobotic/godot | d50b5d047bbf6c68fc458c1ad097321ca627185d | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null | // generated from rosidl_generator_cpp/resource/msg__traits.hpp.em
// generated code does not contain a copyright notice
#ifndef MAP_MSGS__SRV__SAVE_MAP__REQUEST__TRAITS_HPP_
#define MAP_MSGS__SRV__SAVE_MAP__REQUEST__TRAITS_HPP_
#include <stdint.h>
#include <type_traits>
namespace rosidl_generator_traits
{
#ifndef __ROSIDL_GENERATOR_CPP_TRAITS
#define __ROSIDL_GENERATOR_CPP_TRAITS
template<typename T>
inline const char * data_type();
template<typename T>
struct has_fixed_size : std::false_type {};
template<typename T>
struct has_bounded_size : std::false_type {};
#endif // __ROSIDL_GENERATOR_CPP_TRAITS
#include "map_msgs/srv/save_map__request__struct.hpp"
template<>
struct has_fixed_size<map_msgs::srv::SaveMap_Request>
: std::integral_constant<bool, has_fixed_size<std_msgs::msg::String>::value> {};
template<>
struct has_bounded_size<map_msgs::srv::SaveMap_Request>
: std::integral_constant<bool, has_bounded_size<std_msgs::msg::String>::value> {};
template<>
inline const char * data_type<map_msgs::srv::SaveMap_Request>()
{
return "map_msgs::srv::SaveMap_Request";
}
} // namespace rosidl_generator_traits
#endif // MAP_MSGS__SRV__SAVE_MAP__REQUEST__TRAITS_HPP_
| 25.510638 | 84 | 0.803169 | Omnirobotic |
9179a4fe75d7fdbe342b6748d90b659676d8ef49 | 2,328 | cpp | C++ | src/RotationControl.cpp | rustyducks/navigation | 2c549072173b05ebc750c7a0b05dd41833f44ceb | [
"MIT"
] | null | null | null | src/RotationControl.cpp | rustyducks/navigation | 2c549072173b05ebc750c7a0b05dd41833f44ceb | [
"MIT"
] | null | null | null | src/RotationControl.cpp | rustyducks/navigation | 2c549072173b05ebc750c7a0b05dd41833f44ceb | [
"MIT"
] | null | null | null | #include "Navigation/RotationControl.h"
#include "Navigation/Parameters.h"
namespace rd {
RotationControl::RotationControl(const PositionControlParameters ¶ms) : PositionControlBase(params), state_(eRotationControlState::ACCELERATE) {}
Speed RotationControl::computeSpeed(const PointOriented &robotPose, const Speed &robotSpeed, double dt, double) {
double rotationSpeed = 0.;
Angle diff = targetAngle_ - robotPose.theta();
double angleToStop;
if (state_ == eRotationControlState::ACCELERATE) {
if (diff < 0) {
rotationSpeed = robotSpeed.vtheta() - params_.maxRotationalAcceleration * dt;
} else {
rotationSpeed = robotSpeed.vtheta() + params_.maxRotationalAcceleration * dt;
}
if (std::abs(rotationSpeed) >= params_.maxRotationalSpeed) {
state_ = eRotationControlState::CRUISING;
rotationSpeed = std::min(params_.maxRotationalSpeed, std::max(-params_.maxRotationalSpeed, rotationSpeed));
}
angleToStop = 0.5 * robotSpeed.vtheta() * robotSpeed.vtheta() / params_.maxRotationalAcceleration;
if (angleToStop + dt * std::abs(rotationSpeed) >= std::abs(diff.value())) {
state_ = eRotationControlState::DECELERATE;
}
}
if (state_ == eRotationControlState::CRUISING) {
if (diff < 0) {
rotationSpeed = -params_.maxRotationalSpeed;
} else {
rotationSpeed = params_.maxRotationalSpeed;
}
angleToStop = 0.5 * robotSpeed.vtheta() * robotSpeed.vtheta() / params_.maxRotationalAcceleration;
if (angleToStop + dt * std::abs(robotSpeed.vtheta()) >= std::abs(diff.value())) {
state_ = eRotationControlState::DECELERATE;
}
}
if (state_ == eRotationControlState::DECELERATE) {
if (diff < 0) {
rotationSpeed = std::min(-params_.minRotationalSpeed, robotSpeed.vtheta() + params_.maxRotationalAcceleration * dt);
} else {
rotationSpeed = std::max(params_.minRotationalSpeed, robotSpeed.vtheta() - params_.maxRotationalAcceleration * dt);
}
if (std::abs(diff.value()) <= params_.admittedAnglePositionError) {
rotationSpeed = 0.;
isGoalReached_ = true;
}
}
return Speed(0.0, 0.0, rotationSpeed);
}
void RotationControl::setTargetAngle(const Angle &angle) {
targetAngle_ = angle;
state_ = eRotationControlState::ACCELERATE;
isGoalReached_ = false;
}
} // namespace rd
| 39.457627 | 149 | 0.705756 | rustyducks |
917b5cf644038138fc496999557aa6c0a78590d0 | 1,123 | cpp | C++ | paint/src/Tool.cpp | nickveys/opengl-play | a297b4ea804255fd54e4b1e78fb7d79d3e185b23 | [
"MIT"
] | null | null | null | paint/src/Tool.cpp | nickveys/opengl-play | a297b4ea804255fd54e4b1e78fb7d79d3e185b23 | [
"MIT"
] | null | null | null | paint/src/Tool.cpp | nickveys/opengl-play | a297b4ea804255fd54e4b1e78fb7d79d3e185b23 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <glut.h>
#include "Paintable.h"
#include "Tool.h"
/* default tool setup */
struct color4f Tool::color = { 1.0f, 1.0f, 1.0f, 1.0f };
GLfloat Tool::size = 2.0f;
GLfloat Tool::width = 2.0f;
bool Tool::fill = false;
Tool::Tool() {
mouseCurrentlyDown = false;
}
void Tool::mouseDown(struct point2f p) {
mouseCurrentlyDown = true;
}
void Tool::mouseMove(struct point2f p) {
/* do nothing */
}
void Tool::mouseUp(struct point2f p) {
/* ignore up clicks from clicking the menus */
if(mouseCurrentlyDown) {
mouseCurrentlyDown = false;
}
}
void Tool::setColor(GLfloat r, GLfloat g, GLfloat b) {
color.r = r;
color.g = g;
color.b = b;
}
void Tool::notifyIntermediatePaintableCreated(Paintable* p) {
std::vector< ToolListener* >::const_iterator itr = toolListeners.begin();
while(itr != toolListeners.end()) {
(*itr)->intermediatePaintableCreated(p);
itr++;
}
}
void Tool::notifyFinalPaintableCreated(Paintable* p) {
std::vector< ToolListener* >::const_iterator itr = toolListeners.begin();
while(itr != toolListeners.end()) {
(*itr)->finalPaintableCreated(p);
itr++;
}
}
| 20.796296 | 74 | 0.684773 | nickveys |
917c7363a2f44ec5c8592566a480355d518e4fa0 | 7,472 | cpp | C++ | RadeonGPUAnalyzerCLI/Src/kcCLICommander.cpp | EwoutH/RGA | 3eb9694b04882ea6f0984755faa171c6785b533d | [
"MIT"
] | 2 | 2019-05-18T11:39:59.000Z | 2019-05-18T11:40:05.000Z | RadeonGPUAnalyzerCLI/Src/kcCLICommander.cpp | Acidburn0zzz/RGA | 35cd028602e21f6b8853fdc86b16153b693acb72 | [
"MIT"
] | null | null | null | RadeonGPUAnalyzerCLI/Src/kcCLICommander.cpp | Acidburn0zzz/RGA | 35cd028602e21f6b8853fdc86b16153b693acb72 | [
"MIT"
] | null | null | null | //=================================================================
// Copyright 2017 Advanced Micro Devices, Inc. All rights reserved.
//=================================================================
// C++
#include <cassert>
// Backend.
#include <RadeonGPUAnalyzerBackend/Include/beUtils.h>
// Local.
#include <RadeonGPUAnalyzerCLI/Src/kcUtils.h>
#include <RadeonGPUAnalyzerCLI/Src/kcXmlWriter.h>
#include <RadeonGPUAnalyzerCLI/Src/kcCLICommander.h>
#include <RadeonGPUAnalyzerCLI/Src/kcCLICommanderLightning.h>
#include <RadeonGPUAnalyzerCLI/Src/kcCLICommanderVulkan.h>
// Shared.
#include <Utils/Include/rgLog.h>
void kcCLICommander::Version(Config& config, LoggingCallBackFunc_t callback)
{
kcUtils::PrintRgaVersion();
}
std::string GetInputlLanguageString(beKA::RgaMode mode)
{
switch (mode)
{
case beKA::RgaMode::Mode_OpenCL:
return "OpenCL";
case beKA::RgaMode::Mode_OpenGL:
return "OpenGL";
case beKA::RgaMode::Mode_Vulkan:
return "Vulkan";
case beKA::RgaMode::Mode_Vk_Offline:
case beKA::RgaMode::Mode_Vk_Offline_Spv:
case beKA::RgaMode::Mode_Vk_Offline_SpvTxt:
return "Vulkan Offline";
case beKA::Mode_HLSL:
return "DX";
default:
assert(false && STR_ERR_UNKNOWN_MODE);
return "";
}
}
void kcCLICommander::ListAdapters(Config & config, LoggingCallBackFunc_t callback)
{
GT_UNREFERENCED_PARAMETER(config);
std::stringstream msg;
msg << STR_ERR_COMMAND_NOT_SUPPORTED << std::endl;
callback(msg.str());
}
bool kcCLICommander::RunPostCompileSteps(const Config & config)
{
return true;
}
bool kcCLICommander::GenerateVersionInfoFile(const Config& config)
{
bool status = true;
std::string fileName = config.m_versionInfoFile;
// If the file requires wrapping with double-quotes, do it.
if (fileName.find(' ') != std::string::npos &&
fileName.find("\"") != std::string::npos)
{
std::stringstream wrappedFileName;
wrappedFileName << "\"" << fileName << "\"";
fileName = wrappedFileName.str();
}
// Delete the version info file if it already exists.
if (!fileName.empty() && kcUtils::FileNotEmpty(fileName))
{
status = kcUtils::DeleteFile(fileName);
}
// Generate the Version Info header.
rgLog::stdErr << STR_INFO_GENERATING_VERSION_INFO_FILE << fileName << std::endl;
status = status && kcXmlWriter::AddVersionInfoHeader(fileName);
assert(status);
if (status)
{
// Try generating the version info file for ROCm OpenCL mode.
bool isRocmVersionInfoGenerated =
kcCLICommanderLightning::GenerateRocmVersionInfo(fileName);
assert(isRocmVersionInfoGenerated);
if (!isRocmVersionInfoGenerated)
{
rgLog::stdErr << STR_ERR_FAILED_GENERATE_VERSION_INFO_FILE_ROCM_CL << std::endl;
}
// Try generating the version info file for Vulkan live-driver mode.
bool isVulkanVersionInfoGenerated =
kcCLICommanderVulkan::GenerateVulkanVersionInfo(config,
fileName, config.m_printProcessCmdLines);
if (isVulkanVersionInfoGenerated)
{
// Try generating system version info for Vulkan live-driver mode.
isVulkanVersionInfoGenerated = kcCLICommanderVulkan::GenerateSystemVersionInfo(config,
fileName, config.m_printProcessCmdLines);
assert(isVulkanVersionInfoGenerated);
if (!isVulkanVersionInfoGenerated)
{
rgLog::stdErr << STR_ERR_FAILED_GENERATE_VERSION_INFO_FILE_VULKAN_SYSTEM << std::endl;
}
}
else
{
rgLog::stdErr << STR_ERR_FAILED_GENERATE_VERSION_INFO_FILE_VULKAN << std::endl;
}
// We are good if at least one of the modes managed to generate the version info.
status = isRocmVersionInfoGenerated || isVulkanVersionInfoGenerated;
assert(status);
}
else
{
rgLog::stdErr << STR_ERR_FAILED_GENERATE_VERSION_INFO_HEADER << std::endl;
}
if (!status)
{
rgLog::stdErr << STR_ERR_FAILED_GENERATE_VERSION_INFO_FILE << std::endl;
}
return status;
}
bool kcCLICommander::ListEntries(const Config & config, LoggingCallBackFunc_t callback)
{
rgLog::stdErr << STR_ERR_COMMAND_NOT_SUPPORTED << std::endl;
return false;
}
bool kcCLICommander::GetParsedIsaCSVText(const std::string& isaText, const std::string& device, bool addLineNumbers, std::string& csvText)
{
bool ret = false;
std::string parsedIsa;
if (beProgramBuilder::ParseISAToCSV(isaText, device, parsedIsa, addLineNumbers, true) == beKA::beStatus_SUCCESS)
{
csvText = (addLineNumbers ? STR_CSV_PARSED_ISA_HEADER_LINE_NUMS : STR_CSV_PARSED_ISA_HEADER) + parsedIsa;
ret = true;
}
return ret;
}
bool kcCLICommander::InitRequestedAsicList(const std::vector<std::string>& devices, RgaMode mode,
const std::set<std::string>& supportedDevices,
std::set<std::string>& matchedDevices, bool allowUnknownDevices)
{
if (!devices.empty())
{
// Take the devices which the user selected.
for (const std::string& device : devices)
{
std::string matchedArchName;
bool foundSingleTarget = kcUtils::FindGPUArchName(device, matchedArchName, true, allowUnknownDevices);
if (foundSingleTarget)
{
// Check if the matched architecture is in the list of known ASICs.
// The architecture returned by FindGPUArchName() is an extended name, for example: "gfx804 (Graphics IP v8)",
// while the items in the list of known ASICs are "short" names: "gfx804".
bool isSupported = false;
matchedArchName = kcUtils::ToLower(matchedArchName);
for (const std::string& asic : supportedDevices)
{
if (matchedArchName.find(kcUtils::ToLower(asic)) != std::string::npos)
{
matchedDevices.insert(asic);
isSupported = true;
break;
}
}
if (!isSupported && !allowUnknownDevices)
{
rgLog::stdErr << STR_ERR_ERROR << GetInputlLanguageString(mode)
<< STR_ERR_TARGET_IS_NOT_SUPPORTED << matchedArchName << std::endl;
}
}
}
}
else
{
// Take all known devices and do not print anything.
for (const std::string& device : supportedDevices)
{
std::string archName = "";
std::string tmpMsg;
bool found = kcUtils::FindGPUArchName(device, archName, false, allowUnknownDevices);
if (found)
{
matchedDevices.insert(device);
}
}
}
bool ret = (matchedDevices.size() != 0);
return ret;
}
beKA::beStatus kcCLICommander::WriteISAToFile(const std::string& fileName, const std::string& isaText)
{
beStatus res = beStatus::beStatus_Invalid;
res = kcUtils::WriteTextFile(fileName, isaText, m_LogCallback) ?
beKA::beStatus_SUCCESS : beKA::beStatus_WriteToFile_FAILED;
if (res != beKA::beStatus_SUCCESS)
{
rgLog::stdErr << STR_ERR_FAILED_ISA_FILE_WRITE << fileName << std::endl;
}
return res;
} | 32.9163 | 138 | 0.626606 | EwoutH |
917cbad064112c3d05cf0d79bb3c4531a1cb44d4 | 172 | cpp | C++ | test/unit-tests/volume/volume_renamer_test.cpp | YongJin-Cho/poseidonos | c07a0240316d4536aa09f22d7977604f3650d752 | [
"BSD-3-Clause"
] | null | null | null | test/unit-tests/volume/volume_renamer_test.cpp | YongJin-Cho/poseidonos | c07a0240316d4536aa09f22d7977604f3650d752 | [
"BSD-3-Clause"
] | null | null | null | test/unit-tests/volume/volume_renamer_test.cpp | YongJin-Cho/poseidonos | c07a0240316d4536aa09f22d7977604f3650d752 | [
"BSD-3-Clause"
] | null | null | null | #include "src/volume/volume_renamer.h"
#include <gtest/gtest.h>
namespace pos
{
TEST(VolumeRenamer, VolumeRenamer_)
{
}
TEST(VolumeRenamer, Do_)
{
}
} // namespace pos
| 10.75 | 38 | 0.72093 | YongJin-Cho |
917e8441bda7bed99371bcf5d84084afaaa40072 | 2,085 | cc | C++ | solutions/kattis/administrativeproblems.cc | zwliew/ctci | 871f4fc957be96c6d0749d205549b7b35dc53d9e | [
"MIT"
] | 4 | 2020-11-07T14:38:02.000Z | 2022-01-03T19:02:36.000Z | solutions/kattis/administrativeproblems.cc | zwliew/ctci | 871f4fc957be96c6d0749d205549b7b35dc53d9e | [
"MIT"
] | 1 | 2019-04-17T06:55:14.000Z | 2019-04-17T06:55:14.000Z | solutions/kattis/administrativeproblems.cc | zwliew/ctci | 871f4fc957be96c6d0749d205549b7b35dc53d9e | [
"MIT"
] | null | null | null | #include <algorithm>
#include <array>
#include <bitset>
#include <chrono>
#include <climits>
#include <cmath>
#include <cstring>
#include <deque>
#include <ext/pb_ds/assoc_container.hpp>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace std;
#ifdef LOCAL
#include "../../_library/cc/debug.h"
#define FILE "test"
#else
#define debug(...) 0
#define FILE ""
#endif
int main() {
cin.tie(nullptr)->sync_with_stdio(false);
if (fopen(FILE ".in", "r")) {
freopen(FILE ".in", "r", stdin);
freopen(FILE ".out", "w", stdout);
}
int t;
cin >> t;
while (t--) {
int n, m;
cin >> n >> m;
unordered_map<string, array<int64_t, 3>> cars;
unordered_map<string, string> spyUsing;
map<string, int64_t> total;
for (int i = 0; i < n; ++i) {
string name;
int p, q, k;
cin >> name >> p >> q >> k;
cars[name] = {p, q, k};
}
while (m--) {
int tmp;
string s;
char e;
cin >> tmp >> s >> e;
if (e == 'p') {
string c;
cin >> c;
if (spyUsing[s].size()) {
total[s] = -1;
} else if (total[s] != -1) {
total[s] += cars[c][1];
spyUsing[s] = c;
}
} else if (e == 'r') {
int d;
cin >> d;
if (spyUsing[s].empty()) {
total[s] = -1;
} else if (total[s] != -1) {
total[s] += d * cars[spyUsing[s]][2];
spyUsing[s] = "";
}
} else {
int p;
cin >> p;
if (spyUsing[s].empty()) {
total[s] = -1;
} else if (total[s] != -1) {
total[s] += (p * cars[spyUsing[s]][0] + 99) / 100;
}
}
}
for (auto& [k, v] : total) {
cout << k << " ";
if (v == -1 || spyUsing[k].size()) {
cout << "INCONSISTENT";
} else {
cout << v;
}
cout << "\n";
}
}
}
| 20.85 | 60 | 0.478657 | zwliew |
91836f20c8c289f7c687aeecff49e16081a780e1 | 887 | cpp | C++ | 1_Games/[C++] Tetris/code/hgeFunc.cpp | Team-on/works | 16978b61c0d6bcb37e910efb4b5b80e9a2460230 | [
"MIT"
] | 10 | 2018-11-12T19:43:28.000Z | 2020-09-09T18:48:30.000Z | 1_Games/[C++] Tetris/code/hgeFunc.cpp | Team-on/works | 16978b61c0d6bcb37e910efb4b5b80e9a2460230 | [
"MIT"
] | null | null | null | 1_Games/[C++] Tetris/code/hgeFunc.cpp | Team-on/works | 16978b61c0d6bcb37e910efb4b5b80e9a2460230 | [
"MIT"
] | null | null | null | #include "preCompiled.h"
#include "hgeFunc.h"
#include "renderFunc.h"
#include "inputFunc.h"
bool GameFrameFunc() {
if (hge->Input_GetKeyState(HGEK_ESCAPE)) {
soundMusic->Stop();
return true;
}
if (GameInput()) {
return true;
}
return false;
}
bool GameRenderFunc() {
hge->Gfx_BeginScene();
RenderGame();
RenderGameInfo();
hge->Gfx_EndScene();
return false;
}
bool MenuFrameFunc() {
return MenuInput();
}
bool MenuRenderFunc() {
hge->Gfx_BeginScene();
RenderMenu();
hge->Gfx_EndScene();
return false;
}
bool SettingsFrameFunc() {
return SettingsInput();
}
bool SettingsRenderFunc() {
hge->Gfx_BeginScene();
RenderSettings();
hge->Gfx_EndScene();
return false;
}
bool CreditsFrameFunc() {
return CreditsInput();
}
bool CreditsRenderFunc() {
hge->Gfx_BeginScene();
hge->Gfx_Clear(0);
RenderCredits();
hge->Gfx_EndScene();
return false;
} | 12.855072 | 43 | 0.687711 | Team-on |
91838d5b1f3250f8f284c174997e5a6547043fe3 | 794 | cpp | C++ | UVa 10162 last digit/sample/10162 - Last Digit.cpp | tadvi/uva | 0ac0cbdf593879b4fb02a3efc09adbb031cb47d5 | [
"MIT"
] | 1 | 2020-11-24T03:17:21.000Z | 2020-11-24T03:17:21.000Z | UVa 10162 last digit/sample/10162 - Last Digit.cpp | tadvi/uva | 0ac0cbdf593879b4fb02a3efc09adbb031cb47d5 | [
"MIT"
] | null | null | null | UVa 10162 last digit/sample/10162 - Last Digit.cpp | tadvi/uva | 0ac0cbdf593879b4fb02a3efc09adbb031cb47d5 | [
"MIT"
] | 1 | 2021-04-11T16:22:31.000Z | 2021-04-11T16:22:31.000Z | #include <stdio.h>
#include <string.h>
long long mpow(long long x, long long y, long long mod) {
if(y == 0) return 1;
if(y&1)
return x*mpow(x*x%mod, y/2, mod)%mod;
return mpow(x*x%mod, y/2, mod);
}
int cycle[101];
void findcycle() {
int i, j;
for(i = 0; i < 10; i++) {
for(j = i*10+1; j <= i*10+10; j++) {
cycle[j] = cycle[j-1]+mpow(j, j, 10);
//printf("%lld ", mpow(j, j, 10));
}
}
}
int main() {
findcycle();
char s[200];
while(scanf("%s", s) == 1) {
if(s[0] == '0' && s[1] == '\0')
break;
int n;
if(strlen(s) > 5)
sscanf(s+strlen(s)-5, "%d", &n);
else
sscanf(s, "%d", &n);
printf("%d\n", (cycle[n%100])%10);
}
return 0;
}
| 23.352941 | 57 | 0.425693 | tadvi |
918616b474bf901786707c3f46298f505a9f13c4 | 1,270 | cpp | C++ | src/HardDriveInfo/Win32OperatingSystem.cpp | yottaawesome/bits-test | 3ce1d08b0f86161b11d50e50f04170c624c27bcd | [
"MIT"
] | 1 | 2020-11-29T19:06:20.000Z | 2020-11-29T19:06:20.000Z | src/HardDriveInfo/Win32OperatingSystem.cpp | yottaawesome/bits-test | 3ce1d08b0f86161b11d50e50f04170c624c27bcd | [
"MIT"
] | 1 | 2020-12-12T21:35:45.000Z | 2020-12-12T21:35:45.000Z | src/HardDriveInfo/Win32OperatingSystem.cpp | yottaawesome/bits-test | 3ce1d08b0f86161b11d50e50f04170c624c27bcd | [
"MIT"
] | null | null | null | #include "Header.hpp"
int Win32OperatingSystem()
{
WmiProxy wmiProxy;
WmiServer server = wmiProxy.ConnectServer(L"ROOT\\CIMV2");
WmiObjectEnumerator objectEnum = server.Query(L"select * from Win32_OperatingSystem");
while (IWbemClassObject* wbemClassObj = objectEnum.Next())
{
WmiClassObject classObj(wbemClassObj);
Log(L"BuildNumber", classObj.String(L"BuildNumber"));
Log(L"BuildType", classObj.String(L"BuildType"));
Log(L"Locale", classObj.String(L"Locale"));
Log(L"Manufacturer", classObj.String(L"Manufacturer"));
Log(L"Name", classObj.String(L"Name"));
Log(L"OSType", classObj.Int32(L"OSType"));
Log(L"Primary", classObj.Bool(L"Primary"));
Log(L"BootDevice", classObj.String(L"BootDevice"));
Log(L"CountryCode", classObj.String(L"CountryCode"));
Log(L"Version", classObj.String(L"Version"));
Log(L"NumberOfUsers", classObj.Int32(L"NumberOfUsers"));
Log(L"CurrentTimeZone", classObj.Short(L"CurrentTimeZone"));
Log(L"LastBootUpTime", classObj.String(L"LastBootUpTime"));
Log(L"InstallDate", classObj.String(L"InstallDate"));
Log(L"OSArchitecture", classObj.String(L"OSArchitecture"));
Log(L"OperatingSystemSKU", classObj.Int32(L"OperatingSystemSKU"));
Log(L"OSLanguage", classObj.Int32(L"OSLanguage"));
}
return 0;
} | 37.352941 | 87 | 0.734646 | yottaawesome |
9186428070d989d125f328ed02f09eb3d5f7dcb3 | 436 | cpp | C++ | Code/766_Toeplitz_Matrix.cpp | DCOLIVERSUN/LeetCode | e0ef5ed8a267d81cc794914c3c1f22b013a32871 | [
"MIT"
] | 1 | 2019-11-12T08:15:33.000Z | 2019-11-12T08:15:33.000Z | Code/766_Toeplitz_Matrix.cpp | DCOLIVERSUN/LeetCode | e0ef5ed8a267d81cc794914c3c1f22b013a32871 | [
"MIT"
] | null | null | null | Code/766_Toeplitz_Matrix.cpp | DCOLIVERSUN/LeetCode | e0ef5ed8a267d81cc794914c3c1f22b013a32871 | [
"MIT"
] | null | null | null | class Solution {
public:
bool isToeplitzMatrix(vector<vector<int>>& matrix) {
if (matrix.empty() || matrix[0].empty()) return false;
for (int i = 0; i < matrix.size(); ++i) {
for (int j = 0; j < matrix[0].size(); ++j) {
if (i > 0 && j > 0 && matrix[i - 1][j - 1] != matrix[i][j]) {
return false;
}
}
}
return true;
}
};
| 29.066667 | 77 | 0.417431 | DCOLIVERSUN |
918677d6506b62a3060a161b6839242052060132 | 572 | cc | C++ | chrome/browser/storage/appcache_feature_prefs.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | chrome/browser/storage/appcache_feature_prefs.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | chrome/browser/storage/appcache_feature_prefs.cc | Yannic/chromium | ab32e8aacb08c9fce0dc4bf09eec456ba46e3710 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | // Copyright 2020 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/storage/appcache_feature_prefs.h"
#include "chrome/common/pref_names.h"
#include "components/prefs/pref_registry_simple.h"
namespace appcache_feature_prefs {
void RegisterProfilePrefs(PrefRegistrySimple* registry) {
registry->RegisterBooleanPref(prefs::kAppCacheForceEnabled,
/*default_value=*/false);
}
} // namespace appcache_feature_prefs
| 31.777778 | 73 | 0.753497 | mghgroup |
918881110005b3a420df0881b6c52546869c3bbd | 537 | cpp | C++ | RightL.cpp | imor/Quadris | 85b119c887b5473a15a1aaaecf4a772e2aff2359 | [
"MIT"
] | null | null | null | RightL.cpp | imor/Quadris | 85b119c887b5473a15a1aaaecf4a772e2aff2359 | [
"MIT"
] | null | null | null | RightL.cpp | imor/Quadris | 85b119c887b5473a15a1aaaecf4a772e2aff2359 | [
"MIT"
] | null | null | null | #include "RightL.h"
using namespace std;
RightL::RightL(int originX, int originY, Texture* texture) :
Tetramino(originX, originY, 2, texture)
{
setOrigin(originX, originY);
}
void RightL::setOrigin(int x, int y)
{
blockPositions[0].setX(x + texture->getWidth());
blockPositions[0].setY(y - texture->getHeight());
blockPositions[1].setX(x - texture->getWidth());
blockPositions[1].setY(y);
blockPositions[2].setX(x);
blockPositions[2].setY(y);
blockPositions[3].setX(x + texture->getWidth());
blockPositions[3].setY(y);
}
| 21.48 | 60 | 0.705773 | imor |
9189dea489df2bca4d92dda3fc1578a81f88a6f5 | 5,716 | cpp | C++ | tests/client/client.cpp | cthulhu-irl/touca-cpp | 97392a1f84c7a92211ee86bcb527637a6c9a5cba | [
"Apache-2.0"
] | 12 | 2021-06-27T01:44:49.000Z | 2022-03-11T10:08:34.000Z | sdk/cpp/tests/client/client.cpp | trytouca/trytouca | eae38a96407d1ecac543c5a5fb05cbbe632ddfca | [
"Apache-2.0"
] | 8 | 2021-06-25T13:05:29.000Z | 2022-03-26T20:28:14.000Z | sdk/cpp/tests/client/client.cpp | trytouca/trytouca | eae38a96407d1ecac543c5a5fb05cbbe632ddfca | [
"Apache-2.0"
] | 4 | 2021-06-25T11:31:12.000Z | 2022-03-16T05:50:52.000Z | // Copyright 2021 Touca, Inc. Subject to Apache-2.0 License.
#include "touca/client/detail/client.hpp"
#include "catch2/catch.hpp"
#include "tests/devkit/tmpfile.hpp"
#include "touca/devkit/resultfile.hpp"
#include "touca/devkit/utils.hpp"
using namespace touca;
std::string save_and_read_back(const touca::ClientImpl& client) {
TmpFile file;
CHECK_NOTHROW(client.save(file.path, {}, DataFormat::JSON, true));
return detail::load_string_file(file.path.string());
}
ElementsMap save_and_load_back(const touca::ClientImpl& client) {
TmpFile file;
CHECK_NOTHROW(client.save(file.path, {}, DataFormat::FBS, true));
ResultFile resultFile(file.path);
return resultFile.parse();
}
TEST_CASE("empty client") {
touca::ClientImpl client;
REQUIRE(client.is_configured() == false);
CHECK(client.configuration_error().empty() == true);
REQUIRE_NOTHROW(client.configure({{"api-key", "some-secret-key"},
{"api-url", "http://localhost:8081"},
{"team", "myteam"},
{"suite", "mysuite"},
{"version", "myversion"},
{"offline", "true"}}));
CHECK(client.is_configured() == true);
CHECK(client.configuration_error().empty() == true);
// Calling post for a client with no testcase should fail.
SECTION("post") {
REQUIRE_NOTHROW(client.post());
CHECK(client.post() == false);
}
SECTION("save") {
const auto& output = save_and_read_back(client);
CHECK(output == "[]");
}
}
#if _POSIX_C_SOURCE >= 200112L
TEST_CASE("configure with environment variables") {
touca::ClientImpl client;
client.configure();
CHECK(client.is_configured() == true);
setenv("TOUCA_API_KEY", "some-key", 1);
setenv("TOUCA_API_URL", "https://api.touca.io/@/some-team/some-suite", 1);
client.configure({{"version", "myversion"}, {"offline", "true"}});
CHECK(client.is_configured() == true);
CHECK(client.configuration_error() == "");
CHECK(client.options().api_key == "some-key");
CHECK(client.options().team == "some-team");
CHECK(client.options().suite == "some-suite");
unsetenv("TOUCA_API_KEY");
unsetenv("TOUCA_API_URL");
}
#endif
TEST_CASE("using a configured client") {
touca::ClientImpl client;
const touca::ClientImpl::OptionsMap options_map = {{"team", "myteam"},
{"suite", "mysuite"},
{"version", "myversion"},
{"offline", "true"}};
REQUIRE_NOTHROW(client.configure(options_map));
REQUIRE(client.is_configured() == true);
CHECK(client.configuration_error().empty() == true);
SECTION("testcase switch") {
CHECK_NOTHROW(client.add_hit_count("ignored-key"));
CHECK(client.declare_testcase("some-case"));
CHECK_NOTHROW(client.add_hit_count("some-key"));
CHECK(client.declare_testcase("some-other-case"));
CHECK_NOTHROW(client.add_hit_count("some-other-key"));
CHECK(client.declare_testcase("some-case"));
CHECK_NOTHROW(client.add_hit_count("some-other-key"));
const auto& content = save_and_load_back(client);
REQUIRE(content.count("some-case"));
REQUIRE(content.count("some-other-case"));
CHECK(content.at("some-case")->overview().keysCount == 2);
CHECK(content.at("some-other-case")->overview().keysCount == 1);
}
SECTION("results") {
client.declare_testcase("some-case");
const auto& v1 = data_point::boolean(true);
CHECK_NOTHROW(client.check("some-value", v1));
CHECK_NOTHROW(client.add_hit_count("some-other-value"));
CHECK_NOTHROW(client.add_array_element("some-array-value", v1));
const auto& content = save_and_read_back(client);
const auto& expected =
R"("results":[{"key":"some-array-value","value":"[true]"},{"key":"some-other-value","value":"1"},{"key":"some-value","value":"true"}])";
CHECK_THAT(content, Catch::Contains(expected));
}
/**
* bug
*/
SECTION("assumptions") {
client.declare_testcase("some-case");
const auto& v1 = data_point::boolean(true);
CHECK_NOTHROW(client.assume("some-value", v1));
const auto& content = save_and_read_back(client);
const auto& expected = R"([])";
CHECK_THAT(content, Catch::Contains(expected));
}
SECTION("metrics") {
const auto& tc = client.declare_testcase("some-case");
CHECK(tc->metrics().empty());
CHECK_NOTHROW(client.start_timer("a"));
CHECK(tc->metrics().empty());
CHECK_THROWS_AS(client.stop_timer("b"), std::invalid_argument);
CHECK_NOTHROW(client.start_timer("b"));
CHECK(tc->metrics().empty());
CHECK_NOTHROW(client.stop_timer("b"));
CHECK(tc->metrics().size() == 1);
CHECK(tc->metrics().count("b"));
const auto& content = save_and_read_back(client);
const auto& expected =
R"("results":[],"assertion":[],"metrics":[{"key":"b","value":"0"}])";
CHECK_THAT(content, Catch::Contains(expected));
}
SECTION("forget_testcase") {
client.declare_testcase("some-case");
const auto& v1 = data_point::boolean(true);
client.check("some-value", v1);
client.assume("some-assertion", v1);
client.start_timer("some-metric");
client.stop_timer("some-metric");
client.forget_testcase("some-case");
const auto& content = save_and_read_back(client);
CHECK_THAT(content, Catch::Contains(R"([])"));
}
/**
* Calling post when client is locally configured should throw exception.
*/
SECTION("post") {
REQUIRE_NOTHROW(client.declare_testcase("mycase"));
REQUIRE_NOTHROW(client.post());
REQUIRE(client.post() == false);
}
}
| 36.877419 | 144 | 0.635934 | cthulhu-irl |
918afeef8fa01a15e812d1e95c8ec82f6aafec8f | 3,050 | cpp | C++ | src/Utility/Box.cpp | heltena/KYEngine | 4ccb89d0b20683feb245ffe85dd34b6ffdc42c8e | [
"MIT"
] | null | null | null | src/Utility/Box.cpp | heltena/KYEngine | 4ccb89d0b20683feb245ffe85dd34b6ffdc42c8e | [
"MIT"
] | null | null | null | src/Utility/Box.cpp | heltena/KYEngine | 4ccb89d0b20683feb245ffe85dd34b6ffdc42c8e | [
"MIT"
] | null | null | null | #include <KYEngine/Utility/Box.h>
#include <algorithm>
Box::Box()
{
m_values[0] = 0.0f;
m_values[1] = 0.0f;
m_values[2] = 1.0f;
m_values[3] = 1.0f;
}
Box::Box(const Box& other)
{
for(int i = 0; i < 4; i++)
m_values[i] = other.m_values[i];
}
Box::Box(float width, float height)
{
m_values[0] = 0.0f;
m_values[1] = 0.0f;
m_values[2] = width;
m_values[3] = height;
}
Box::Box(float left, float top, float width, float height)
{
m_values[0] = left;
m_values[1] = top;
m_values[2] = width;
m_values[3] = height;
}
float& Box::operator[](int index)
{
return m_values[index];
}
float Box::operator[](int index) const
{
return m_values[index];
}
Box& Box::operator=(const Box& other)
{
for(int i = 0; i < 4; i++)
m_values[i] = other.m_values[i];
return *this;
}
Box& Box::addSize(double width, double height, bool center)
{
if (center) {
m_values[0] -= width / 2.;
m_values[1] -= height / 2.;
}
m_values[2] += width;
m_values[3] += height;
return *this;
}
Box& Box::unionWith(const Box& other)
{
float right = std::max(m_values[0] + m_values[2], other.m_values[0] + other.m_values[2]);
float bottom = std::max(m_values[1] + m_values[3], other.m_values[1] + other.m_values[3]);
m_values[0] = std::min(m_values[0], other.m_values[0]);
m_values[1] = std::min(m_values[1], other.m_values[1]);
m_values[2] = right - m_values[0];
m_values[3] = bottom - m_values[1];
return *this;
}
Box& Box::scale(const Vector4& scale)
{
m_values[2] *= scale[0];
m_values[3] *= scale[1];
return *this;
}
Box& Box::translate(const Vector4& offset)
{
m_values[0] += offset[0];
m_values[1] += offset[1];
return *this;
}
Box Box::intersection(const Box& other) const
{
float f[2], t[2];
for(int i = 0; i < 2; i++) {
float a = m_values[i];
float b = m_values[i] + m_values[2 + i];
float c = other.m_values[i];
float d = other.m_values[i] + other.m_values[2 + i];
if (a > b)
std::swap(a, b);
if (c > d)
std::swap(c, d);
if (a > c) {
std::swap(a, c);
std::swap(b, d);
}
if (b < c) // a----b c----d
return Box(0, 0, 0, 0);
if (b == c) { // a----b/c----d
f[i] = b;
t[i] = b;
} else if (b < d) { // a----c===b---d
f[i] = c;
t[i] = b;
} else { // a----c===d----b
f[i] = c;
t[i] = d;
}
}
return Box(f[0], f[1], t[0] - f[0], t[1] - f[1]);
}
bool Box::contains(const Vector4& pos) const
{
return (pos[0] >= m_values[0])
&& (pos[0] <= m_values[0] + m_values[2])
&& (pos[1] >= m_values[1])
&& (pos[1] <= m_values[1] + m_values[3]);
}
std::ostream& Box::write(std::ostream& out) const
{
return out
<< "(" << m_values[0]
<< ", " << m_values[1]
<< ", " << m_values[2]
<< ", " << m_values[3]
<< ")";
}
std::ostream& operator<<(std::ostream& out, const Box& item) {
return item.write(out);
}
| 20.469799 | 91 | 0.518689 | heltena |
925f584ce478fbd81e5cc39f492f724ba713b542 | 1,393 | cpp | C++ | tools/builder/tests/units/test_contours.cpp | ostis-ai/sc-machine | f8a30b4555e4ef21f302cbdf35614e77a24c116f | [
"MIT"
] | null | null | null | tools/builder/tests/units/test_contours.cpp | ostis-ai/sc-machine | f8a30b4555e4ef21f302cbdf35614e77a24c116f | [
"MIT"
] | 9 | 2022-03-01T07:33:48.000Z | 2022-03-24T17:06:07.000Z | tools/builder/tests/units/test_contours.cpp | ostis-ai/sc-machine | f8a30b4555e4ef21f302cbdf35614e77a24c116f | [
"MIT"
] | 7 | 2022-02-18T13:34:24.000Z | 2022-03-25T09:59:42.000Z | #include <gtest/gtest.h>
#include "builder_test.hpp"
#include "sc-memory/sc_scs_helper.hpp"
#include "tests/sc-memory/_test/dummy_file_interface.hpp"
TEST_F(ScBuilderTest, contours)
{
SCsHelper helper(*m_ctx, std::make_shared<DummyFileInterface>());
std::string const scsTempl =
"struct1 ="
"[*"
"=> nrel_idtf:"
"[Identifier1] (* <- lang_en;; *);;"
"=> nrel_relation_1:"
"other;;"
"*];;";
EXPECT_TRUE(helper.GenerateBySCsText(scsTempl));
auto links = m_ctx->FindLinksByContent("Identifier1");
EXPECT_FALSE(links.empty());
ScAddr const structAddr = m_ctx->HelperFindBySystemIdtf("struct1");
ScTemplate templ;
templ.TripleWithRelation(
structAddr,
ScType::EdgeDCommonVar,
ScType::LinkVar >> "_link",
ScType::EdgeAccessVarPosPerm,
m_ctx->HelperFindBySystemIdtf("nrel_idtf"));
ScTemplateSearchResult result;
m_ctx->HelperSearchTemplate(templ, result);
EXPECT_FALSE(result.IsEmpty());
ScAddr found;
for (auto const & item : links)
{
if (item == result[0]["_link"])
{
found = item;
break;
}
}
EXPECT_TRUE(found.IsValid());
EXPECT_TRUE(m_ctx->HelperCheckEdge(m_ctx->HelperFindBySystemIdtf("lang_en"), found, ScType::EdgeAccessConstPosPerm));
EXPECT_TRUE(m_ctx->HelperCheckEdge(structAddr, m_ctx->HelperFindBySystemIdtf("other"), ScType::EdgeDCommonConst));
}
| 26.788462 | 119 | 0.684135 | ostis-ai |
9260ab5bc8b6ee92be0a168c054a8a2687c38ba9 | 5,583 | hpp | C++ | third_party/boost/simd/arch/common/generic/function/all_reduce.hpp | SylvainCorlay/pythran | 908ec070d837baf77d828d01c3e35e2f4bfa2bfa | [
"BSD-3-Clause"
] | 6 | 2018-02-25T22:23:33.000Z | 2021-01-15T15:13:12.000Z | third_party/boost/simd/arch/common/generic/function/all_reduce.hpp | SylvainCorlay/pythran | 908ec070d837baf77d828d01c3e35e2f4bfa2bfa | [
"BSD-3-Clause"
] | null | null | null | third_party/boost/simd/arch/common/generic/function/all_reduce.hpp | SylvainCorlay/pythran | 908ec070d837baf77d828d01c3e35e2f4bfa2bfa | [
"BSD-3-Clause"
] | 7 | 2017-12-12T12:36:31.000Z | 2020-02-10T14:27:07.000Z | //==================================================================================================
/**
Copyright 2016 NumScale SAS
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
**/
//==================================================================================================
#ifndef BOOST_SIMD_ARCH_COMMON_GENERIC_FUNCTION_ALL_REDUCE_HPP_INCLUDED
#define BOOST_SIMD_ARCH_COMMON_GENERIC_FUNCTION_ALL_REDUCE_HPP_INCLUDED
#include <boost/simd/detail/overload.hpp>
#include <boost/simd/function/shuffle.hpp>
#include <boost/simd/function/combine.hpp>
#include <boost/simd/detail/dispatch/detail/declval.hpp>
#include <boost/simd/detail/nsm.hpp>
namespace boost { namespace simd { namespace detail
{
namespace tt = nsm::type_traits;
//------------------------------------------------------------------------------------------------
// This meta-permutation implements the butterfly pattern required for log-tree based reductions.
//
// V is a vector of cardinal 4 : [ v0 | v1 | v2 | v3 ]
// The log-tree reduction will require : [ v2 | v3 | v0 | v1 ]
// and : [ v3 | v2 | v1 | v0 ]
//
// Basically this requires permuting cardinal/2^n value at each iteration
// stopping when only 1 element is left to be permuted.
//------------------------------------------------------------------------------------------------
template<int Step> struct butterfly_perm
{
template<typename I, typename>
struct apply : tt::integral_constant<int,(I::value >= Step) ? I::value-Step : I::value+Step>
{};
};
template<int Step> struct butterfly
{
using next_t = butterfly<Step/2>;
template<typename Op, typename V>
BOOST_FORCEINLINE
auto operator()(Op const& op, V const& a0) const BOOST_NOEXCEPT
-> decltype( next_t{}( op, op(a0, boost::simd::shuffle< butterfly_perm<Step> >(a0)) ) )
{
next_t next;
return next( op, op(a0, boost::simd::shuffle< butterfly_perm<Step> >(a0)) );
}
};
template<> struct butterfly<1>
{
template<typename Op, typename V>
BOOST_FORCEINLINE
auto operator()(Op const& op, V const& a0) const BOOST_NOEXCEPT
-> decltype( op(boost::simd::shuffle< butterfly_perm<1> >(a0),a0) )
{
return op(boost::simd::shuffle< butterfly_perm<1> >(a0),a0);
}
};
} } }
namespace boost { namespace simd { namespace ext
{
namespace bs = boost::simd;
namespace bd = boost::dispatch;
BOOST_DISPATCH_OVERLOAD_FALLBACK ( ( typename BinOp, typename Neutral
, typename Arg, typename Ext
)
, tag::all_reduce_
, bd::cpu_
, bd::elementwise_<BinOp>
, bs::pack_<bd::unspecified_<Neutral>, Ext>
, bs::pack_<bd::unspecified_<Arg>, Ext>
)
{
using function_t = bd::functor<BinOp>;
using result_t = decltype( bd::functor<BinOp>()( bd::detail::declval<Arg>()
, bd::detail::declval<Neutral>()
)
);
// ---------------------------------------------------------------------------------------------
// singleton case
template<typename K, typename N> static BOOST_FORCEINLINE
result_t fold_( function_t const& op, Neutral const& z, Arg const& a0
, K const&, nsm::list<N> const&
)
{
return op( z, a0 );
}
// ---------------------------------------------------------------------------------------------
// Native case
template<typename N0, typename N1, typename... N> static BOOST_FORCEINLINE
result_t fold_( function_t const& op, Neutral const& z, Arg const& a0
, native_storage const&, nsm::list<N0,N1,N...> const&
)
{
return op(detail::butterfly<Arg::static_size/2>{}(op,a0),z);
}
// ---------------------------------------------------------------------------------------------
// Aggregate case
template<typename N0, typename N1, typename... N> static BOOST_FORCEINLINE
result_t fold_( function_t const& op, Neutral const& z, Arg const& a0
, aggregate_storage const&, nsm::list<N0,N1,N...> const&
)
{
auto r = detail::all_reduce(op,z.storage()[0],a0.storage()[0]);
r = detail::all_reduce(op,r,a0.storage()[1]);
return combine(r,r);
}
// ---------------------------------------------------------------------------------------------
// Scalar case
template<typename N0, typename N1, typename... N> static BOOST_FORCEINLINE
result_t fold_( function_t const& op, Neutral const& z, Arg const& a0
, scalar_storage const&, nsm::list<N0,N1,N...> const&
)
{
auto r = op( bs::extract<0>(a0), z );
r = op( bs::extract<1>(a0), r );
(void)std::initializer_list<bool> { ((r = op(bs::extract<N::value>(a0),r)),true)... };
return result_t(r);
}
BOOST_FORCEINLINE result_t
operator()(function_t const& op, Neutral const& z, Arg const& a0) const
{
return fold_(op, z, a0, typename Arg::storage_kind{}, typename Arg::traits::static_range{});
}
};
} } }
#endif
| 39.595745 | 100 | 0.491671 | SylvainCorlay |
9262bfebc838c82d6139563fb0628222f4d5e53f | 952 | hpp | C++ | engine/include/core/event/providers/glfw.hpp | dorosch/engine | 0cd277675264f848ac141f7e5663242bd7b43438 | [
"MIT"
] | null | null | null | engine/include/core/event/providers/glfw.hpp | dorosch/engine | 0cd277675264f848ac141f7e5663242bd7b43438 | [
"MIT"
] | null | null | null | engine/include/core/event/providers/glfw.hpp | dorosch/engine | 0cd277675264f848ac141f7e5663242bd7b43438 | [
"MIT"
] | null | null | null | #ifndef __GLFW_EVENT_PROVIDER_HPP__
#define __GLFW_EVENT_PROVIDER_HPP__
#ifndef GLEW_STATIC
#define GLEW_STATIC
#endif
#include <memory>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include "core/event/provider.hpp"
#include "core/event/observer.hpp"
#include "tools/logger.hpp"
using namespace Tool::Logger;
namespace Engine {
namespace Event {
class GLFWEventProvider : public EventProvider {
protected:
std::unique_ptr<Logger> logger = std::make_unique<Logger>("glfwe");
public:
void MouseEventCallback() {};
void KeyboardEventCallback() {};
void MouseEventCallback(GLFWwindow *, int, int, int);
void KeyboardEventCallback(GLFWwindow *, int, int, int, int);
static void MouseEventCallbackStatic(GLFWwindow *, int, int, int);
static void KeyboardEventCallbackStatic(GLFWwindow *, int, int, int, int);
};
}
}
#endif
| 24.410256 | 86 | 0.667017 | dorosch |
92639205dd8eac2e5abe556a50a3eff5296c232f | 6,743 | cpp | C++ | KDBMS/Table.cpp | karbovskiydmitriy/KDBMS | 573ba629dc88f79b8c85127f42eb2b5806178d07 | [
"MIT"
] | null | null | null | KDBMS/Table.cpp | karbovskiydmitriy/KDBMS | 573ba629dc88f79b8c85127f42eb2b5806178d07 | [
"MIT"
] | null | null | null | KDBMS/Table.cpp | karbovskiydmitriy/KDBMS | 573ba629dc88f79b8c85127f42eb2b5806178d07 | [
"MIT"
] | null | null | null | #include "Table.hpp"
Table::Table(String name, vector<TableColumn> *columns)
{
this->name = name;
this->columns = columns;
}
Response Table::Insert(TableRow *row)
{
if (row != nullptr)
{
if (row->fields.size() == this->columns->size())
{
this->rows.push_back(row);
return Response(ErrorCode::OK);
}
else
{
return Response(ErrorCode::TYPE_CONFLICT);
}
}
return Response(ErrorCode::NULL_ARGUMENT);
}
Response Table::Select(Condition *condition)
{
if (condition != nullptr)
{
vector<TableRow *> *entries = new vector<TableRow *>();
for (const auto &iterator : this->rows)
{
if (condition->Check(iterator->fields))
{
entries->push_back(iterator);
}
}
return Response(ErrorCode::OK, entries);
}
else
{
vector<TableRow *> *entries = new vector<TableRow *>();
for (const auto &iterator : this->rows)
{
entries->push_back(iterator);
}
return Response(ErrorCode::OK, entries);
}
}
Response Table::Update(Condition *condition, String columnName, Data value)
{
if (condition != nullptr)
{
int index = this->GetColumnIndex(columnName);
if (index != -1)
{
for (const auto &iterator : this->rows)
{
if (condition->Check(iterator->fields))
{
iterator->fields.data()[index] = value;
}
}
}
else
{
return Response(ErrorCode::NOT_FOUND);
}
return Response(ErrorCode::OK);
}
return Response(ErrorCode::NULL_ARGUMENT);
}
Response Table::Update(Condition *condition, int index, Data value)
{
if (condition != nullptr)
{
if (index >= 0 && index < (int)this->columns->size())
{
for (const auto &iterator : this->rows)
{
if (condition->Check(iterator->fields))
{
iterator->fields.data()[index] = value;
}
}
}
else
{
return Response(ErrorCode::NOT_FOUND);
}
return Response(ErrorCode::OK);
}
return Response(ErrorCode::NULL_ARGUMENT);
}
Response Table::Delete(Condition *condition)
{
if (condition != nullptr)
{
vector<TableRow *> toDelete;
for (const auto &iterator : this->rows)
{
if (condition->Check(iterator->fields))
{
toDelete.push_back(iterator);
}
}
for (int i = 0; i < (int)toDelete.size(); i++)
{
DeleteRow(toDelete.data()[i]);
}
return Response(ErrorCode::OK);
}
else
{
this->rows.clear();
return Response(ErrorCode::OK);
}
}
int Table::GetColumnIndex(String columnName)
{
if (this->columns != nullptr)
{
for (int i = 0; i < (int)this->columns->size(); i++)
{
if (this->columns->data()[i].name == columnName)
{
return i;
}
}
return -1;
}
else
{
return -1;
}
}
Type Table::GetColumnType(String columnName)
{
if (this->columns != nullptr)
{
for (int i = 0; i < (int)this->columns->size(); i++)
{
if (this->columns->data()[i].name == columnName)
{
return this->columns->data()->type;
}
}
return Type::NONE;
}
else
{
return Type::NONE;
}
}
SerializedObject Table::Serialize()
{
uint32_t nameLength = Strlen(this->name.c_str());
uint64_t length = 12ull + nameLength;
vector<SerializedObject> serializedColumns;
for (auto column = this->columns->begin(); column != this->columns->end(); column++)
{
SerializedObject object = column->Serialize();
serializedColumns.push_back(object);
length += offsetof(SerializedObject, data) + object.length;
}
vector<SerializedObject> serializedRows;
for (const auto &row : this->rows)
{
SerializedObject object = row->Serialize();
serializedRows.push_back(object);
length += offsetof(SerializedObject, data) + object.length;
}
char *buffer = new char[(uint32_t)length];
char *bufferPointer = buffer;
((uint32_t *)bufferPointer)[0] = nameLength;
bufferPointer += 4;
memcpy(bufferPointer, this->name.c_str(), nameLength);
bufferPointer += nameLength;
((uint32_t *)bufferPointer)[0] = serializedColumns.size();
bufferPointer += 4;
for (const auto &object : serializedColumns)
{
memcpy(bufferPointer, &object, offsetof(SerializedObject, data));
bufferPointer += offsetof(SerializedObject, data);
memcpy(bufferPointer, object.data, (size_t)object.length);
bufferPointer += object.length;
}
((uint32_t *)bufferPointer)[0] = serializedRows.size();
bufferPointer += 4;
for (const auto &object : serializedRows)
{
memcpy(bufferPointer, &object, offsetof(SerializedObject, data));
bufferPointer += offsetof(SerializedObject, data);
memcpy(bufferPointer, object.data, (size_t)object.length);
bufferPointer += object.length;
}
return SerializedObject(ObjectType::TABLE, length, buffer);
}
bool Table::Deserialize(SerializedObject object)
{
if (object.length <= 0)
{
return false;
}
if (object.data == null)
{
return false;
}
char *bufferPointer = (char *)object.data;
uint32_t nameLength = ((uint32_t *)bufferPointer)[0];
bufferPointer += 4;
char *nameBuffer = new char[nameLength + 4];
((uint32_t *)(nameBuffer + nameLength))[0] = 0;
memcpy(nameBuffer, bufferPointer, nameLength);
this->name.clear();
this->name = String(nameBuffer);
delete[] nameBuffer;
bufferPointer += nameLength;
if (this->columns != nullptr)
{
this->columns->clear();
}
this->columns = new vector<TableColumn>();
uint32_t columnsCount = ((uint32_t *)bufferPointer)[0];
bufferPointer += 4;
for (int i = 0; i < (int)columnsCount; i++)
{
SerializedObject object;
memcpy(&object, bufferPointer, offsetof(SerializedObject, data));
bufferPointer += offsetof(SerializedObject, data);
object.data = bufferPointer;
bufferPointer += object.length;
TableColumn column = TableColumn(String(), Type::NONE);
bool result = column.Deserialize(object);
if (!result)
{
return false;
}
this->columns->push_back(column);
}
if (this->rows.size() != 0)
{
this->rows.clear();
}
this->rows = list<TableRow *>();
uint32_t rowsCount = ((uint32_t *)bufferPointer)[0];
bufferPointer += 4;
for (int i = 0; i < (int)rowsCount; i++)
{
SerializedObject object;
memcpy(&object, bufferPointer, offsetof(SerializedObject, data));
bufferPointer += offsetof(SerializedObject, data);
object.data = bufferPointer;
bufferPointer += object.length;
TableRow *row = new TableRow(this->columns, vector<Data>());
bool result = row->Deserialize(object);
if (!result)
{
return false;
}
this->rows.push_back(row);
}
return true;
}
String Table::ToString()
{
String result = String(TEXT("Table\n")) + String(TEXT("Columns: "));
for (const auto &iterator : *this->columns)
{
result += TEXT("\t") + iterator.name;
}
return result;
}
bool Table::DeleteRow(TableRow *row)
{
if (row != nullptr)
{
for (const auto &iterator : this->rows)
{
if (iterator == row)
{
this->rows.remove(row);
return true;
}
}
}
return false;
}
| 20.128358 | 85 | 0.659202 | karbovskiydmitriy |
9264407db64f1b3f18f0e34006af1ae05dc7fc61 | 13,533 | cpp | C++ | lib/stages/visRawReader.cpp | james-s-willis/kotekan | 155e874bb039702cec72c1785362a017548aa00a | [
"MIT"
] | null | null | null | lib/stages/visRawReader.cpp | james-s-willis/kotekan | 155e874bb039702cec72c1785362a017548aa00a | [
"MIT"
] | null | null | null | lib/stages/visRawReader.cpp | james-s-willis/kotekan | 155e874bb039702cec72c1785362a017548aa00a | [
"MIT"
] | null | null | null | #include "visRawReader.hpp"
#include "StageFactory.hpp"
#include "datasetState.hpp"
#include "errors.h"
#include "metadata.h"
#include "version.h"
#include "visBuffer.hpp"
#include "visUtil.hpp"
#include "fmt.hpp"
#include "gsl-lite.hpp"
#include "json.hpp"
#include <algorithm>
#include <atomic>
#include <cstdint>
#include <cstring>
#include <errno.h>
#include <exception>
#include <fcntl.h>
#include <fstream>
#include <functional>
#include <iostream>
#include <memory>
#include <regex>
#include <signal.h>
#include <stdexcept>
#include <sys/mman.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
using kotekan::bufferContainer;
using kotekan::Config;
using kotekan::Stage;
REGISTER_KOTEKAN_STAGE(visRawReader);
visRawReader::visRawReader(Config& config, const string& unique_name,
bufferContainer& buffer_container) :
Stage(config, unique_name, buffer_container, std::bind(&visRawReader::main_thread, this)) {
filename = config.get<std::string>(unique_name, "infile");
readahead_blocks = config.get<size_t>(unique_name, "readahead_blocks");
max_read_rate = config.get_default<double>(unique_name, "max_read_rate", 0.0);
sleep_time = config.get_default<float>(unique_name, "sleep_time", -1);
chunked = config.exists(unique_name, "chunk_size");
if (chunked) {
chunk_size = config.get<std::vector<int>>(unique_name, "chunk_size");
if (chunk_size.size() != 3)
throw std::invalid_argument("Chunk size needs exactly three "
"elements (has "
+ std::to_string(chunk_size.size()) + ").");
chunk_t = chunk_size[2];
chunk_f = chunk_size[0];
if (chunk_size[0] < 1 || chunk_size[1] < 1 || chunk_size[2] < 1)
throw std::invalid_argument("visRawReader: config: Chunk size "
"needs to be greater or equal to (1,1,1) (is ("
+ std::to_string(chunk_size[0]) + ","
+ std::to_string(chunk_size[1]) + ","
+ std::to_string(chunk_size[2]) + ")).");
}
// Get the list of buffers that this stage should connect to
out_buf = get_buffer("out_buf");
register_producer(out_buf, unique_name.c_str());
// Read the metadata
std::string md_filename = (filename + ".meta");
INFO("Reading metadata file: {:s}", md_filename);
struct stat st;
if (stat(md_filename.c_str(), &st) == -1)
throw std::ios_base::failure(
fmt::format(fmt("visRawReader: Error reading from metadata file: {:s}"), md_filename));
size_t filesize = st.st_size;
std::vector<uint8_t> packed_json(filesize);
std::ifstream metadata_file(md_filename, std::ios::binary);
if (metadata_file) // only read if no error
metadata_file.read((char*)&packed_json[0], filesize);
if (!metadata_file) // check if open and read successful
throw std::ios_base::failure("visRawReader: Error reading from "
"metadata file: "
+ md_filename);
json _t = json::from_msgpack(packed_json);
metadata_file.close();
// Extract the attributes and index maps
_metadata = _t["attributes"];
_times = _t["index_map"]["time"].get<std::vector<time_ctype>>();
auto freqs = _t["index_map"]["freq"].get<std::vector<freq_ctype>>();
_inputs = _t["index_map"]["input"].get<std::vector<input_ctype>>();
_prods = _t["index_map"]["prod"].get<std::vector<prod_ctype>>();
_ev = _t["index_map"]["ev"].get<std::vector<uint32_t>>();
if (_t.at("index_map").find("stack") != _t.at("index_map").end()) {
_stack = _t.at("index_map").at("stack").get<std::vector<stack_ctype>>();
_rstack = _t.at("reverse_map").at("stack").get<std::vector<rstack_ctype>>();
_num_stack = _t.at("structure").at("num_stack").get<uint32_t>();
}
for (auto f : freqs) {
// TODO: add freq IDs to raw file format instead of restoring them here
// TODO: CHIME specific.
uint32_t freq_id = 1024.0 / 400.0 * (800.0 - f.centre);
DEBUG("restored freq_id for f_centre={:.2f} : {:d}", f.centre, freq_id);
_freqs.push_back({freq_id, f});
}
// check git version tag
// TODO: enforce that they match if build type == "release"?
if (_metadata.at("git_version_tag").get<std::string>() != std::string(get_git_commit_hash()))
INFO("Git version tags don't match: dataset in file {:s} has tag {:s}, while the local git "
"version tag is {:s}",
filename, _metadata.at("git_version_tag").get<std::string>(), get_git_commit_hash());
// Extract the structure
file_frame_size = _t["structure"]["frame_size"].get<size_t>();
metadata_size = _t["structure"]["metadata_size"].get<size_t>();
data_size = _t["structure"]["data_size"].get<size_t>();
nfreq = _t["structure"]["nfreq"].get<size_t>();
ntime = _t["structure"]["ntime"].get<size_t>();
if (chunked) {
// Special case if dimensions less than chunk size
chunk_f = std::min(chunk_f, nfreq);
chunk_t = std::min(chunk_t, ntime);
// Number of elements in a chunked row
row_size = (chunk_f * chunk_t) * (nfreq / chunk_f) + (nfreq % chunk_f) * chunk_t;
}
// Check metadata is the correct size
if (sizeof(visMetadata) != metadata_size) {
std::string msg = fmt::format(fmt("Metadata in file {:s} is larger ({:d} bytes) than "
"visMetadata ({:d} bytes)."),
filename, metadata_size, sizeof(visMetadata));
throw std::runtime_error(msg);
}
// Check that buffer is large enough
if ((unsigned int)(out_buf->frame_size) < data_size || out_buf->frame_size < 0) {
std::string msg =
fmt::format(fmt("Data in file {:s} is larger ({:d} bytes) than buffer size "
"({:d} bytes)."),
filename, data_size, out_buf->frame_size);
throw std::runtime_error(msg);
}
// Open up the data file and mmap it
INFO("Opening data file: {:s}.data", filename);
if ((fd = open((filename + ".data").c_str(), O_RDONLY)) == -1) {
throw std::runtime_error(
fmt::format(fmt("Failed to open file {:s}.data: {:s}."), filename, strerror(errno)));
}
mapped_file =
(uint8_t*)mmap(NULL, ntime * nfreq * file_frame_size, PROT_READ, MAP_SHARED, fd, 0);
if (mapped_file == MAP_FAILED)
throw std::runtime_error(fmt::format(fmt("Failed to map file {:s}.data to memory: {:s}."),
filename, strerror(errno)));
}
visRawReader::~visRawReader() {
if (munmap(mapped_file, ntime * nfreq * file_frame_size) == -1) {
// Make sure kotekan is exiting...
FATAL_ERROR("Failed to unmap file {:s}.data: {:s}.", filename, strerror(errno));
}
close(fd);
}
void visRawReader::change_dataset_state(dset_id_t ds_id) {
datasetManager& dm = datasetManager::instance();
// Add the states: acq_dataset_id, metadata, time, prod, freq, input,
// eigenvalue and stack.
std::vector<state_id_t> states;
if (!_stack.empty())
states.push_back(dm.create_state<stackState>(_num_stack, std::move(_rstack)).first);
states.push_back(dm.create_state<inputState>(_inputs).first);
states.push_back(dm.create_state<eigenvalueState>(_ev).first);
states.push_back(dm.create_state<freqState>(_freqs).first);
states.push_back(dm.create_state<prodState>(_prods).first);
states.push_back(dm.create_state<timeState>(_times).first);
states.push_back(dm.create_state<metadataState>(_metadata.at("weight_type"),
_metadata.at("instrument_name"),
_metadata.at("git_version_tag"))
.first);
states.push_back(dm.create_state<acqDatasetIdState>(ds_id).first);
// register it as root dataset
_dataset_id = dm.add_dataset(states);
}
void visRawReader::read_ahead(int ind) {
off_t offset = position_map(ind) * file_frame_size;
if (madvise(mapped_file + offset, file_frame_size, MADV_WILLNEED) == -1)
DEBUG("madvise failed: {:s}", strerror(errno));
}
int visRawReader::position_map(int ind) {
if (chunked) {
// chunked row index
int ri = ind / row_size;
// Special case at edges of time*freq array
int t_width = std::min(ntime - ri * chunk_t, chunk_t);
// chunked column index
int ci = (ind % row_size) / (t_width * chunk_f);
// edges case
int f_width = std::min(nfreq - ci * chunk_f, chunk_f);
// time and frequency indices
// time is fastest varying
int fi = ci * chunk_f + ((ind % row_size) % (t_width * f_width)) / t_width;
int ti = ri * chunk_t + ((ind % row_size) % (t_width * f_width)) % t_width;
return ti * nfreq + fi;
} else {
return ind;
}
}
void visRawReader::main_thread() {
double start_time, end_time;
size_t frame_id = 0;
uint8_t* frame;
size_t ind = 0, read_ind = 0, file_ind;
size_t nframe = nfreq * ntime;
// Calculate the minimum time we should take to read the data to satisfy the
// rate limiting
double min_read_time =
(max_read_rate > 0 ? file_frame_size / (max_read_rate * 1024 * 1024) : 0.0);
DEBUG("Minimum read time per frame {}s", min_read_time);
// Initial readahead for frames
for (read_ind = 0; read_ind < readahead_blocks; read_ind++) {
read_ahead(read_ind);
}
while (!stop_thread && ind < nframe) {
// Get the start time of the loop for rate limiting
start_time = current_time();
// Wait for an empty frame in the output buffer
if ((frame = wait_for_empty_frame(out_buf, unique_name.c_str(), frame_id)) == nullptr) {
break;
}
// Issue the read ahead request
if (read_ind < (ntime * nfreq)) {
read_ahead(read_ind);
}
// Get the index into the file
file_ind = position_map(ind);
// Allocate the metadata space
allocate_new_metadata_object(out_buf, frame_id);
// Check first byte indicating empty frame
if (*(mapped_file + file_ind * file_frame_size) != 0) {
// Copy the metadata from the file
std::memcpy(out_buf->metadata[frame_id]->metadata,
mapped_file + file_ind * file_frame_size + 1, metadata_size);
// Copy the data from the file
std::memcpy(frame, mapped_file + file_ind * file_frame_size + metadata_size + 1,
data_size);
} else {
// Set metadata if file contained an empty frame
((visMetadata*)(out_buf->metadata[frame_id]->metadata))->num_prod = _prods.size();
((visMetadata*)(out_buf->metadata[frame_id]->metadata))->num_ev = _ev.size();
((visMetadata*)(out_buf->metadata[frame_id]->metadata))->num_elements = _inputs.size();
// Fill data with zeros
size_t num_vis = _stack.size() > 0 ? _stack.size() : _prods.size();
auto frame = visFrameView(out_buf, frame_id, _inputs.size(), num_vis, _ev.size());
std::fill(frame.vis.begin(), frame.vis.end(), 0.0);
std::fill(frame.weight.begin(), frame.weight.end(), 0.0);
std::fill(frame.eval.begin(), frame.eval.end(), 0.0);
std::fill(frame.evec.begin(), frame.evec.end(), 0.0);
std::fill(frame.gain.begin(), frame.gain.end(), 0.0);
std::fill(frame.flags.begin(), frame.flags.end(), 0.0);
frame.freq_id = 0;
frame.erms = 0;
DEBUG("visRawReader: Reading empty frame: {:d}", frame_id);
}
// Read first frame to get true dataset ID
if (ind == 0) {
change_dataset_state(
((visMetadata*)(out_buf->metadata[frame_id]->metadata))->dataset_id);
}
// Set the dataset ID to one associated with this file
((visMetadata*)(out_buf->metadata[frame_id]->metadata))->dataset_id = _dataset_id;
// Try and clear out the cached data as we don't need it again
if (madvise(mapped_file + file_ind * file_frame_size, file_frame_size, MADV_DONTNEED) == -1)
DEBUG("madvise failed: {:s}", strerror(errno));
// Release the frame and advance all the counters
mark_frame_full(out_buf, unique_name.c_str(), frame_id);
frame_id = (frame_id + 1) % out_buf->num_frames;
read_ind++;
ind++;
// Get the end time for the loop and sleep for long enough to satisfy
// the max rate
end_time = current_time();
double sleep_time = min_read_time - (end_time - start_time);
DEBUG("Sleep time {}", sleep_time);
if (sleep_time > 0) {
auto ts = double_to_ts(sleep_time);
nanosleep(&ts, NULL);
}
}
if (sleep_time > 0) {
INFO("Read all data. Sleeping and then exiting kotekan...");
timespec ts = double_to_ts(sleep_time);
nanosleep(&ts, nullptr);
exit_kotekan(ReturnCode::CLEAN_EXIT);
} else {
INFO("Read all data. Exiting stage, but keeping kotekan alive.");
}
}
| 40.517964 | 100 | 0.598167 | james-s-willis |
9265d78d773141c87ee53a31fa84206aa2c43596 | 691 | cpp | C++ | atcoder/abc/abc160/d.cpp | yu3mars/proconVSCodeGcc | fcf36165bb14fb6f555664355e05dd08d12e426b | [
"MIT"
] | null | null | null | atcoder/abc/abc160/d.cpp | yu3mars/proconVSCodeGcc | fcf36165bb14fb6f555664355e05dd08d12e426b | [
"MIT"
] | null | null | null | atcoder/abc/abc160/d.cpp | yu3mars/proconVSCodeGcc | fcf36165bb14fb6f555664355e05dd08d12e426b | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
#define REP(i,n) for(int i=0, i##_len=(n); i<i##_len; ++i)
#define all(x) (x).begin(),(x).end()
#define m0(x) memset(x,0,sizeof(x))
int dx4[4] = {1,0,-1,0}, dy4[4] = {0,1,0,-1};
int main()
{
int n,x,y;
cin>>n>>x>>y;
x--;
y--;
vector<int> ans(n);
for (int j = 0; j < n; j++)
{
for (int i = 0; i < j; i++)//i<j
{
int d = min(j-i,abs(i-x)+abs(j-y)+1);
ans[d]++;
}
}
for (int i = 1; i < n; i++)
{
cout<<ans[i]<<endl;
}
return 0;
} | 18.184211 | 58 | 0.442836 | yu3mars |
92665ce36db6b634ce075c8c1fbefa63428da6cd | 5,619 | cpp | C++ | src/tools/download.cpp | alexandria-org/alexandria | ca0c890fea3ba931ad849ded95d6187838718a4c | [
"MIT"
] | 113 | 2022-02-12T00:07:52.000Z | 2022-03-28T08:02:39.000Z | src/tools/download.cpp | alexandria-org/alexandria | ca0c890fea3ba931ad849ded95d6187838718a4c | [
"MIT"
] | 8 | 2021-09-26T07:52:47.000Z | 2022-03-28T06:56:02.000Z | src/tools/download.cpp | alexandria-org/alexandria | ca0c890fea3ba931ad849ded95d6187838718a4c | [
"MIT"
] | 5 | 2022-03-18T22:20:50.000Z | 2022-03-25T15:41:06.000Z | /*
* MIT License
*
* Alexandria.org
*
* Copyright (c) 2021 Josef Cullhed, <info@alexandria.org>, et al.
*
* 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 "download.h"
#include "transfer/transfer.h"
#include "file/tsv_file_remote.h"
#include "profiler/profiler.h"
#include "algorithm/algorithm.h"
#include "url_link/link.h"
#include "common/system.h"
#include "config.h"
#include "logger/logger.h"
#include <math.h>
#include <unordered_set>
#include <future>
using namespace std;
namespace tools {
const size_t max_num_batches = 24;
vector<string> download_batch(const string &batch) {
file::tsv_file_remote warc_paths_file(string("crawl-data/") + batch + "/warc.paths.gz");
vector<string> warc_paths;
warc_paths_file.read_column_into(0, warc_paths);
vector<string> files_to_download;
for (const string &str : warc_paths) {
string warc_path = str;
const size_t pos = warc_path.find(".warc.gz");
if (pos != string::npos) {
warc_path.replace(pos, 8, ".gz");
}
files_to_download.push_back(warc_path);
//if (files_to_download.size() == 100) break;
}
return transfer::download_gz_files_to_disk(files_to_download);
}
unordered_set<size_t> make_url_set_one_thread(const vector<string> &files) {
unordered_set<size_t> result;
for (const string &file_path : files) {
ifstream infile(file_path);
string line;
while (getline(infile, line)) {
const url_link::link link(line);
result.insert(link.target_url().hash());
}
}
return result;
}
unordered_set<size_t> make_url_set(const vector<string> &files) {
unordered_set<size_t> total_result;
size_t idx = 0;
for (const string &file_path : files) {
ifstream infile(file_path);
string line;
while (getline(infile, line)) {
const url_link::link link(line);
total_result.insert(link.target_url().hash());
}
cout << "size: " << total_result.size() << " done " << (++idx) << "/" << files.size() << endl;
}
return total_result;
}
void upload_cache(size_t file_index, size_t thread_id, const string &data, size_t node_id) {
const string filename = "crawl-data/NODE-" + to_string(node_id) + "-small/files/" + to_string(thread_id) + "-" + to_string(file_index) + "-" +
to_string(profiler::now_micro()) + ".gz";
int error = transfer::upload_gz_file(filename, data);
if (error == transfer::ERROR) {
LOG_INFO("Upload failed!");
}
}
void parse_urls_with_links_thread(const vector<string> &warc_paths, const unordered_set<size_t> &url_set) {
const size_t max_cache_size = 150000;
size_t thread_id = common::thread_id();
size_t file_index = 1;
LOG_INFO("url_set.size() == " + to_string(url_set.size()));
vector<vector<string>> cache(max_num_batches);
for (const string &warc_path : warc_paths) {
ifstream infile(warc_path);
string line;
while (getline(infile, line)) {
const URL url(line.substr(0, line.find("\t")));
if (url_set.count(url.hash())) {
const size_t node_id = url.host_hash() % max_num_batches;
cache[node_id].push_back(line);
}
}
for (size_t node_id = 0; node_id < max_num_batches; node_id++) {
if (cache[node_id].size() > max_cache_size) {
const string cache_data = boost::algorithm::join(cache[node_id], "\n");
cache[node_id].clear();
upload_cache(file_index++, thread_id, cache_data, node_id);
}
}
}
for (size_t node_id = 0; node_id < max_num_batches; node_id++) {
if (cache[node_id].size() > 0) {
const string cache_data = boost::algorithm::join(cache[node_id], "\n");
cache[node_id].clear();
upload_cache(file_index++, thread_id, cache_data, node_id);
}
}
}
void upload_urls_with_links(const vector<string> &local_files, const unordered_set<size_t> &url_set) {
size_t num_threads = 24;
vector<vector<string>> thread_input;
algorithm::vector_chunk(local_files, ceil((double)local_files.size() / num_threads), thread_input);
vector<thread> threads;
for (size_t i = 0; i < thread_input.size(); i++) {
threads.emplace_back(thread(parse_urls_with_links_thread, thread_input[i], cref(url_set)));
}
for (thread &one_thread : threads) {
one_thread.join();
}
}
void prepare_batch(size_t batch_num) {
const vector<string> files = download_batch("NODE-" + to_string(batch_num));
const vector<string> link_files = download_batch("LINK-" + to_string(batch_num));
unordered_set<size_t> url_set = make_url_set(link_files);
upload_urls_with_links(files, url_set);
transfer::delete_downloaded_files(link_files);
transfer::delete_downloaded_files(files);
}
}
| 31.216667 | 144 | 0.706531 | alexandria-org |
926861ad88d7db25eab56ca1d0a06a75875b4bde | 1,208 | cpp | C++ | source/Vertex.cpp | nicovanbentum/Scatter | 72fc7386767d8c058c55fbe15055ea9397d018e1 | [
"MIT"
] | null | null | null | source/Vertex.cpp | nicovanbentum/Scatter | 72fc7386767d8c058c55fbe15055ea9397d018e1 | [
"MIT"
] | null | null | null | source/Vertex.cpp | nicovanbentum/Scatter | 72fc7386767d8c058c55fbe15055ea9397d018e1 | [
"MIT"
] | null | null | null | #include "pch.h"
#include "Vertex.h"
namespace scatter {
VkVertexInputBindingDescription Vertex::getBindingDescription() {
VkVertexInputBindingDescription bindingDescription{};
bindingDescription.binding = 0;
bindingDescription.stride = sizeof(Vertex);
bindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
return bindingDescription;
}
std::array<VkVertexInputAttributeDescription, 3> Vertex::getAttributeDescriptions() {
std::array<VkVertexInputAttributeDescription, 3> attributeDescription{};
attributeDescription[0].binding = 0;
attributeDescription[0].location = 0;
attributeDescription[0].format = VK_FORMAT_R32G32B32_SFLOAT;
attributeDescription[0].offset = offsetof(Vertex, pos);
attributeDescription[1].binding = 0;
attributeDescription[1].location = 1;
attributeDescription[1].format = VK_FORMAT_R32G32_SFLOAT;
attributeDescription[1].offset = offsetof(Vertex, texcoord);
attributeDescription[2].binding = 0;
attributeDescription[2].location = 2;
attributeDescription[2].format = VK_FORMAT_R32G32B32_SFLOAT;
attributeDescription[2].offset = offsetof(Vertex, normal);
return attributeDescription;
}
} // scatter | 35.529412 | 85 | 0.768212 | nicovanbentum |
92689b10d3ff9b104ba3bd3674e40b0e241afca0 | 677 | cpp | C++ | src/expressions/data/tuple.cpp | rationalis-petra/hydra | a1c14e560f5f1c64983468e5fd0be7b32824971d | [
"MIT"
] | 2 | 2021-01-14T11:19:02.000Z | 2021-03-07T03:08:08.000Z | src/expressions/data/tuple.cpp | rationalis-petra/hydra | a1c14e560f5f1c64983468e5fd0be7b32824971d | [
"MIT"
] | null | null | null | src/expressions/data/tuple.cpp | rationalis-petra/hydra | a1c14e560f5f1c64983468e5fd0be7b32824971d | [
"MIT"
] | null | null | null |
#include <string>
#include <typeinfo>
#include "utils.hpp"
#include "expressions.hpp"
using namespace std;
using namespace expr;
using namespace interp;
Parent* Tuple::parent;
int Tuple::size() {
return values.size();
}
Object* Tuple::operator[](int i) {
return values[i];
}
void Tuple::mark_node() {
if (marked) return;
Object::mark_node();
for (Object* o : values) {
o->mark_node();
}
}
string Tuple::to_string(LocalRuntime &r, LexicalScope &s) {
string out = "(|";
for (unsigned i = 0; i < values.size() ; i++) {
out += modulus_to_string(values[i], r, s);
if (i != values.size() - 1)
out += " ";
}
out += "|)";
return out;
}
| 16.512195 | 59 | 0.60709 | rationalis-petra |
92692c9d8c5f392980f8924a8e025eb6f1fea978 | 2,903 | cc | C++ | src/quantsystem/engine/real_time/backtesting_real_time_handler.cc | ydxt25/QuantSystem | b4298121ce8fbe13d8fe7fcaf502565736df9bfe | [
"Apache-2.0"
] | 49 | 2016-11-03T20:51:45.000Z | 2022-03-30T22:34:25.000Z | src/quantsystem/engine/real_time/backtesting_real_time_handler.cc | seepls/QuantSystem | b4298121ce8fbe13d8fe7fcaf502565736df9bfe | [
"Apache-2.0"
] | null | null | null | src/quantsystem/engine/real_time/backtesting_real_time_handler.cc | seepls/QuantSystem | b4298121ce8fbe13d8fe7fcaf502565736df9bfe | [
"Apache-2.0"
] | 33 | 2016-07-17T05:19:59.000Z | 2022-03-07T17:45:57.000Z | /*
* \copyright Copyright 2015 All Rights Reserved.
* \license @{
*
* 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 <thread>
#include <chrono>
#include <functional>
#include "quantsystem/common/util/stl_util.h"
#include "quantsystem/common/securities/security.h"
#include "quantsystem/engine/real_time/backtesting_real_time_handler.h"
namespace quantsystem {
using securities::Security;
namespace engine {
namespace realtime {
BacktestingRealTimeHandler::BacktestingRealTimeHandler(
IAlgorithm* algorithm,
AlgorithmNodePacket* job)
: exit_triggered_(false),
algorithm_(algorithm),
job_(job) {
is_active_ = true;
}
BacktestingRealTimeHandler::~BacktestingRealTimeHandler() {
STLDeleteElements(&events_);
}
void RealTimeEventHelper(IAlgorithm* algorithm, const Security* security) {
algorithm->OnEndOfDay();
algorithm->OnEndOfDay(security->symbol());
}
void BacktestingRealTimeHandler::SetupEvents(const DateTime& date) {
ClearEvents();
vector<const Security*> securities;
algorithm_->securities()->Values(&securities);
for (int i = 0; i < securities.size(); ++i) {
const Security* security = securities[i];
RealTimeEvent::CallBackType* func = new RealTimeEvent::CallBackType(
std::bind(RealTimeEventHelper, algorithm_, security));
AddEvent(new RealTimeEvent(security->exchange()->market_close() -
TimeSpan::FromMinutes(10), func));
}
}
void BacktestingRealTimeHandler::Run() {
is_active_ = true;
while (!exit_triggered_) {
std::this_thread::sleep_for(std::chrono::seconds(50));
}
is_active_ = false;
}
void BacktestingRealTimeHandler::AddEvent(RealTimeEvent* new_event) {
events_.push_back(new_event);
}
void BacktestingRealTimeHandler::ScanEvents() {
for (int i = 0; i < events_.size(); ++i) {
events_[i]->Scan(time_);
}
}
void BacktestingRealTimeHandler::ResetEvents() {
for (int i = 0; i < events_.size(); ++i) {
events_[i]->Reset();
}
}
void BacktestingRealTimeHandler::ClearEvents() {
STLDeleteElements(&events_);
}
void BacktestingRealTimeHandler::SetTime(const DateTime& time) {
if (time_ != time) {
SetupEvents(time);
ResetEvents();
}
time_ = time;
ScanEvents();
}
void BacktestingRealTimeHandler::Exit() {
exit_triggered_ = true;
}
} // namespace realtime
} // namespace engine
} // namespace quantsystem
| 27.647619 | 75 | 0.715122 | ydxt25 |
926e2857a2c0ccf45687d2691699f2bec4ea0bd4 | 552 | cpp | C++ | src/srbpy/alignment/Straight.cpp | billhu0228/SmartRoadBridgePy | 4a5d34028a2612aef846b580733bf6f488110798 | [
"MIT"
] | 2 | 2020-08-05T10:46:45.000Z | 2020-08-11T11:05:18.000Z | src/srbpy/alignment/Straight.cpp | billhu0228/SmartRoadBridgePy | 4a5d34028a2612aef846b580733bf6f488110798 | [
"MIT"
] | null | null | null | src/srbpy/alignment/Straight.cpp | billhu0228/SmartRoadBridgePy | 4a5d34028a2612aef846b580733bf6f488110798 | [
"MIT"
] | 1 | 2020-08-26T07:50:22.000Z | 2020-08-26T07:50:22.000Z | #include "Straight.h"
Straight::Straight(void)
{
__length = 0;
}
Straight::Straight(double length, Vector& st, Angle& sdir, EITypeID idd, LeftRightEnum lr)
:PQXElement(idd, st, sdir, lr)
{
__length = length;
}
Vector Straight::get_point_on_curve(double l_from_st) const
{
double x = l_from_st;
double y = 0;
Vector res = Vector(y, x).rotate2d(start_angle * -1);
return start_point + res;
}
//
//double Straight::length() const
//{
// return __length;
//}
Angle Straight::end_angle() const
{
return Angle(start_angle.GetRadian());
}
| 14.526316 | 90 | 0.690217 | billhu0228 |
926fe89208ba245ac81ac70a74c0fbc531ce3f36 | 788 | cpp | C++ | Src/F_Interfaces/Base/AMReX_distromap_fi.cpp | ylunalin/amrex | 5715b2fc8a77e0db17bfe7907982e29ec44811ca | [
"BSD-3-Clause-LBNL"
] | 8 | 2020-01-21T11:12:38.000Z | 2022-02-12T12:35:45.000Z | Src/F_Interfaces/Base/AMReX_distromap_fi.cpp | ylunalin/amrex | 5715b2fc8a77e0db17bfe7907982e29ec44811ca | [
"BSD-3-Clause-LBNL"
] | null | null | null | Src/F_Interfaces/Base/AMReX_distromap_fi.cpp | ylunalin/amrex | 5715b2fc8a77e0db17bfe7907982e29ec44811ca | [
"BSD-3-Clause-LBNL"
] | 2 | 2020-11-27T03:07:52.000Z | 2021-03-01T16:40:31.000Z |
#include <AMReX_DistributionMapping.H>
#include <AMReX_Print.H>
using namespace amrex;
extern "C" {
void amrex_fi_new_distromap (DistributionMapping*& dm, const BoxArray* ba)
{
dm = new DistributionMapping(*ba);
}
void amrex_fi_new_distromap_from_pmap (DistributionMapping*& dm, const int* pmap, const int plen)
{
Vector<int> PMap(pmap,pmap+plen);
dm = new DistributionMapping(std::move(PMap));
}
void amrex_fi_delete_distromap (DistributionMapping* dm)
{
delete dm;
}
void amrex_fi_clone_distromap (DistributionMapping*& dmo, const DistributionMapping* dmi)
{
delete dmo;
dmo = new DistributionMapping(*dmi);
}
void amrex_fi_print_distromap (const DistributionMapping* dm)
{
AllPrint() << *dm;
}
}
| 21.888889 | 101 | 0.689086 | ylunalin |
927440be6f04684c7b946e541a7b8bbfcde17b68 | 1,324 | cpp | C++ | aws-cpp-sdk-appsync/source/model/ListResolversByFunctionResult.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-02-12T08:09:30.000Z | 2022-02-12T08:09:30.000Z | aws-cpp-sdk-appsync/source/model/ListResolversByFunctionResult.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-appsync/source/model/ListResolversByFunctionResult.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/appsync/model/ListResolversByFunctionResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <utility>
using namespace Aws::AppSync::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;
ListResolversByFunctionResult::ListResolversByFunctionResult()
{
}
ListResolversByFunctionResult::ListResolversByFunctionResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
*this = result;
}
ListResolversByFunctionResult& ListResolversByFunctionResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
JsonView jsonValue = result.GetPayload().View();
if(jsonValue.ValueExists("resolvers"))
{
Array<JsonView> resolversJsonList = jsonValue.GetArray("resolvers");
for(unsigned resolversIndex = 0; resolversIndex < resolversJsonList.GetLength(); ++resolversIndex)
{
m_resolvers.push_back(resolversJsonList[resolversIndex].AsObject());
}
}
if(jsonValue.ValueExists("nextToken"))
{
m_nextToken = jsonValue.GetString("nextToken");
}
return *this;
}
| 26.48 | 126 | 0.762085 | Neusoft-Technology-Solutions |
9278926880230c5261d56d0cff9cab775bf91239 | 6,138 | cc | C++ | zircon/tools/kernel-buildsig/kernel-buildsig.cc | opensource-assist/fuschia | 66646c55b3d0b36aae90a4b6706b87f1a6261935 | [
"BSD-3-Clause"
] | 3 | 2020-08-02T04:46:18.000Z | 2020-08-07T10:10:53.000Z | zircon/tools/kernel-buildsig/kernel-buildsig.cc | opensource-assist/fuschia | 66646c55b3d0b36aae90a4b6706b87f1a6261935 | [
"BSD-3-Clause"
] | null | null | null | zircon/tools/kernel-buildsig/kernel-buildsig.cc | opensource-assist/fuschia | 66646c55b3d0b36aae90a4b6706b87f1a6261935 | [
"BSD-3-Clause"
] | 1 | 2020-08-07T10:11:49.000Z | 2020-08-07T10:11:49.000Z | // Copyright 2017 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <errno.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <string>
namespace {
#define BUILDSIG_START_MAGIC UINT64_C(0x5452545347495342) // BSIGSTRT
#define BUILDSIG_END_MAGIC UINT64_C(0x53444e4547495342) // BSIGENDS
struct buildsig {
uint64_t start_magic;
uint64_t buildsig_address;
uint64_t lk_version_address;
uint64_t note_address;
uint64_t end_magic;
};
#define LK_VERSION_STRUCT_VERSION 0x2
struct lk_version {
uint32_t struct_version;
uint32_t pad;
uint64_t arch;
uint64_t platform;
uint64_t target;
uint64_t project;
uint64_t buildid;
};
#define ELF_BUILDID_NOTE_NAME "GNU"
#define ELF_BUILDID_NOTE_NAMESZ (sizeof("GNU"))
#define ELF_BUILDID_NOTE_TYPE 3
struct elf_buildid_note {
uint32_t namesz;
uint32_t descsz;
uint32_t type;
char name[(ELF_BUILDID_NOTE_NAMESZ + 3) & ~3];
};
class reader {
public:
reader(FILE* input) : input_(input) {}
bool scan() {
pos_ = 0;
do {
if (consider()) {
print();
return true;
}
pos_ += 8;
} while (fseek(input_, pos_, SEEK_SET) == 0);
return false;
}
private:
FILE* input_;
long int pos_;
buildsig sig_;
bool needs_byteswap_;
static const int indent = 4;
class extracted_item {
public:
extracted_item(const char* name) : name_(name) {}
const char* name() const { return name_; }
std::string* contents() { return &contents_; }
const std::string* contents() const { return &contents_; }
void print(bool last = false) const {
printf("%*s{\"%s\": \"%s\"}%s\n", indent, "", name(), contents()->c_str(), last ? "" : ",");
}
private:
const char* name_;
std::string contents_;
};
extracted_item arch_{"arch"};
extracted_item platform_{"platform"};
extracted_item target_{"target"};
extracted_item project_{"project"};
extracted_item buildid_{"buildid"};
extracted_item elf_buildid_{"elf_build_id"};
void print() const {
puts("{");
arch_.print();
platform_.print();
target_.print();
project_.print();
buildid_.print();
elf_buildid_.print(true);
puts("}");
}
static uint64_t byteswap_constant(uint64_t constant) { return __builtin_bswap64(constant); }
void byteswap(uint64_t* x) {
if (needs_byteswap_)
*x = __builtin_bswap64(*x);
}
void byteswap(uint32_t* x) {
if (needs_byteswap_)
*x = __builtin_bswap32(*x);
}
bool consider() {
if (fread(&sig_, sizeof(sig_), 1, input_) == 1) {
if (sig_.start_magic == BUILDSIG_START_MAGIC && sig_.end_magic == BUILDSIG_END_MAGIC) {
needs_byteswap_ = false;
return decode();
}
if (sig_.start_magic == byteswap_constant(BUILDSIG_START_MAGIC) &&
sig_.end_magic == byteswap_constant(BUILDSIG_END_MAGIC)) {
needs_byteswap_ = true;
return decode();
}
}
return false;
}
bool decode() {
byteswap(&sig_.buildsig_address);
lk_version version;
if (!read_from_address(sig_.lk_version_address, &version, sizeof(version)))
return false;
byteswap(&version.struct_version);
if (version.struct_version != LK_VERSION_STRUCT_VERSION)
return false;
return (read_string_from_address(version.arch, &arch_) &&
read_string_from_address(version.platform, &platform_) &&
read_string_from_address(version.target, &target_) &&
read_string_from_address(version.project, &project_) &&
read_string_from_address(version.buildid, &buildid_) &&
handle_buildid_note(sig_.note_address));
}
bool read_from_address(uint64_t address, void* buf, size_t size) {
return seek_to_address(address) && fread(buf, size, 1, input_) == 1;
}
bool read_string_from_address(uint64_t address, extracted_item* item) {
if (seek_to_address(address)) {
char* buf = NULL;
size_t size = 0;
if (getdelim(&buf, &size, '\0', input_) > 0) {
*item->contents() = buf;
free(buf);
return true;
}
}
return false;
}
bool seek_to_address(uint64_t address) {
byteswap(&address);
if (address > sig_.buildsig_address) {
address -= sig_.buildsig_address;
address += pos_;
return (fseek(input_, address, SEEK_SET) == 0 &&
static_cast<uint64_t>(ftell(input_)) == address);
}
return false;
}
bool handle_buildid_note(uint64_t address) {
elf_buildid_note note;
if (read_from_address(address, ¬e, sizeof(note))) {
byteswap(¬e.namesz);
byteswap(¬e.descsz);
byteswap(¬e.type);
if (note.namesz == ELF_BUILDID_NOTE_NAMESZ && note.type == ELF_BUILDID_NOTE_TYPE &&
!memcmp(note.name, ELF_BUILDID_NOTE_NAME, ELF_BUILDID_NOTE_NAMESZ)) {
auto desc = std::make_unique<uint8_t[]>(note.descsz);
if (fread(desc.get(), note.descsz, 1, input_) == 1) {
std::string* text = elf_buildid_.contents();
text->clear();
for (uint32_t i = 0; i < note.descsz; ++i) {
char buf[3] = "XX";
snprintf(buf, sizeof(buf), "%02x", desc[i]);
*text += buf;
}
return true;
}
}
}
return false;
}
};
} // anonymous namespace
int main(int argc, char* argv[]) {
const char* filename;
FILE* input;
switch (argc) {
case 1:
filename = "<standard input>";
input = stdin;
break;
case 2:
filename = argv[1];
input = fopen(filename, "rb");
if (!input) {
fprintf(stderr, "%s: %s: %s\n", argv[0], filename, strerror(errno));
return 2;
}
break;
default:
fprintf(stderr, "Usage: %s [FILENAME]\n", argv[0]);
return 1;
}
if (reader{input}.scan())
return 0;
if (ferror(input)) {
fprintf(stderr, "%s: %s: %s\n", argv[0], filename, strerror(errno));
} else {
fprintf(stderr, "%s: %s: Cannot find a signature\n", argv[0], filename);
}
return 2;
}
| 26.230769 | 98 | 0.627566 | opensource-assist |
9278a1a2fd2b860fbc3199bacee4b986be681274 | 3,774 | cpp | C++ | Testing/Interaction/mafRefSysTest.cpp | FusionBox2/MAF2 | b576955f4f6b954467021f12baedfebcaf79a382 | [
"Apache-2.0"
] | 1 | 2018-01-23T09:13:40.000Z | 2018-01-23T09:13:40.000Z | Testing/Interaction/mafRefSysTest.cpp | gradicosmo/MAF2 | 86ddf1f52a2de4479c09fd3f43dc321ff412af42 | [
"Apache-2.0"
] | null | null | null | Testing/Interaction/mafRefSysTest.cpp | gradicosmo/MAF2 | 86ddf1f52a2de4479c09fd3f43dc321ff412af42 | [
"Apache-2.0"
] | 3 | 2020-09-24T16:04:53.000Z | 2020-09-24T16:50:30.000Z | /*=========================================================================
Program: MAF2
Module: mafRefSysTest
Authors: Stefano Perticoni
Copyright (c) B3C
All rights reserved. See Copyright.txt or
http://www.scsitaly.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "mafDefines.h"
//----------------------------------------------------------------------------
// NOTE: Every CPP file in the MAF must include "mafDefines.h" as first.
// This force to include Window,wxWidgets and VTK exactly in this order.
// Failing in doing this will result in a run-time error saying:
// "Failure#0: The value of ESP was not properly saved across a function call"
//----------------------------------------------------------------------------
#include "mafRefSysTest.h"
#include <cppunit/config/SourcePrefix.h>
#include "mafRefSys.h"
#include "mafVMESurface.h"
#include "mafTransform.h"
#include "vtkRenderer.h"
void mafRefSysTest::setUp()
{
}
void mafRefSysTest::tearDown()
{
}
void mafRefSysTest::TestFixture()
{
}
void mafRefSysTest::TestConstructorDestructor()
{
mafRefSys refSys;
}
void mafRefSysTest::TestCopyConstructor()
{
mafRefSys refSysSource;
refSysSource.SetTypeToView();
mafRefSys refSysTarget;
refSysTarget = refSysSource;
int targetType = refSysTarget.GetType();
CPPUNIT_ASSERT(targetType == mafRefSys::VIEW);
}
void mafRefSysTest::TestSetTypeToCustom()
{
mafRefSys refSys;
mafMatrix *matrix = mafMatrix::New();
refSys.SetTypeToCustom(matrix);
CPPUNIT_ASSERT(refSys.GetType() == mafRefSys::CUSTOM);
CPPUNIT_ASSERT(refSys.GetMatrix() == matrix);
}
void mafRefSysTest::TestSetTypeToLocal()
{
mafRefSys refSys;
refSys.SetTypeToLocal();
CPPUNIT_ASSERT(refSys.GetType() == mafRefSys::LOCAL);
}
void mafRefSysTest::TestSetTypeToView()
{
mafRefSys refSys;
refSys.SetTypeToView();
CPPUNIT_ASSERT(refSys.GetType() == mafRefSys::VIEW);
}
void mafRefSysTest::TestSetTypeToParent()
{
mafRefSys refSys;
mafVMESurface *vme = mafVMESurface::New();
refSys.SetVME(vme);
refSys.SetTypeToParent(vme);
CPPUNIT_ASSERT(refSys.GetType() == mafRefSys::PARENT);
}
void mafRefSysTest::TestSetTypeToGlobal()
{
mafRefSys refSys;
refSys.SetTypeToGlobal();
CPPUNIT_ASSERT(refSys.GetType() == mafRefSys::GLOBAL);
}
void mafRefSysTest::TestSetGetType()
{
mafRefSys refSys;
int type = mafRefSys::LOCAL;
refSys.SetType(type);
int retType = refSys.GetType();
CPPUNIT_ASSERT(retType == type);
}
void mafRefSysTest::TestSetGetTransform()
{
mafRefSys refSys;
mafTransform *transform = mafTransform::New();
refSys.SetTransform(transform);
CPPUNIT_ASSERT(true);
}
void mafRefSysTest::TestSetGetMatrix()
{
mafRefSys refSys;
mafMatrix *matrix = mafMatrix::New();
refSys.SetMatrix(matrix);
refSys.GetMatrix();
CPPUNIT_ASSERT(true);
}
void mafRefSysTest::TestSetGetRenderer()
{
mafRefSys refSys;
vtkRenderer *renderer = vtkRenderer::New();
refSys.SetRenderer(renderer);
CPPUNIT_ASSERT(renderer == refSys.GetRenderer());
vtkDEL(renderer);
}
void mafRefSysTest::TestSetGetVME()
{
mafRefSys refSys;
mafVMESurface *vme = mafVMESurface::New();
refSys.SetVME(vme);
CPPUNIT_ASSERT(vme == refSys.GetVME());
}
void mafRefSysTest::TestDeepCopy()
{
mafRefSys refSysSource;
mafRefSys refSysTarget;
refSysTarget.DeepCopy(&refSysSource);
CPPUNIT_ASSERT(true);
}
void mafRefSysTest::TestReset()
{
mafRefSys refSys;
refSys.SetTypeToView();
refSys.Reset();
CPPUNIT_ASSERT(refSys.GetType() == mafRefSys::GLOBAL);
}
| 23.440994 | 78 | 0.685215 | FusionBox2 |
9278f72097cce6b4a6663e1e031f062163dfde3b | 1,017 | cpp | C++ | question_solution/first_time/1057.cpp | xiaoland/CaiojSolution | a12c505235d70b414071ea894fa72cddbcfabc6d | [
"Apache-2.0"
] | 1 | 2020-09-24T13:35:45.000Z | 2020-09-24T13:35:45.000Z | question_solution/first_time/1057.cpp | xiaoland/CaiojSolution | a12c505235d70b414071ea894fa72cddbcfabc6d | [
"Apache-2.0"
] | null | null | null | question_solution/first_time/1057.cpp | xiaoland/CaiojSolution | a12c505235d70b414071ea894fa72cddbcfabc6d | [
"Apache-2.0"
] | null | null | null | // author: Lan_zhijiang
// description: 含价值的填满型背包1
// 二维数组版
// 背包问题就是要你作出在限制条件下的最佳组合选择
// 解决背包问题最朴素的方法就是列出所有可能性
// 但根据题目条件的不同,都有不同的优化
// 我们还要特别注意节省内存,将自己的算法进行简化,找出多余的部分(比如将二维数组转为一维数组来使用)
// 要检查草稿有没有错误,按着你写的代码再来自己执行一遍,不要弄错了
#include <cstdio>
#include <cstring>
#include <algorithm> // 背包问题要用的max
using namespace std; // algotithm不可少
int n, m[101], t[101], tl;
int out[101][1001];
void read_in() {
scanf("%d%d", &tl, &n);
for(int i = 1; i<=n; i++) {
scanf("%d%d", &t[i], &m[i]);
}
}
int main() {
read_in();
for(int i = 1; i<=n; i++) { // 将时间=0或宝石=0的地方都填上0(任何一个为0都没意义)
out[i][0] = 0;
}
for(int i = 1; i<=tl; i++) {
out[0][i] = 0;
}
for(int i = 1; i<=n; i++) {
for(int j = 1; j<=tl; j++) {
if(j<t[i]) {
out[i][j] = out[i-1][j];
}
else {
out[i][j] = max(out[i-1][j], out[i-1][j - t[i]]+m[i]);
}
}
}
printf("%d\n", out[n][tl]);
return 0;
}
| 20.34 | 70 | 0.485742 | xiaoland |
927dbb2399b605df98f94cee47e40d5d50c710a6 | 4,397 | cpp | C++ | src/engine/subsystems/physics/bullet/bullet_physics_body.cpp | ukrainskiysergey/BallMaze | 84d211ec0733fff7d2b13d5ffce707fb1813fe4e | [
"MIT"
] | null | null | null | src/engine/subsystems/physics/bullet/bullet_physics_body.cpp | ukrainskiysergey/BallMaze | 84d211ec0733fff7d2b13d5ffce707fb1813fe4e | [
"MIT"
] | null | null | null | src/engine/subsystems/physics/bullet/bullet_physics_body.cpp | ukrainskiysergey/BallMaze | 84d211ec0733fff7d2b13d5ffce707fb1813fe4e | [
"MIT"
] | null | null | null | #include "engine/subsystems/physics/bullet/bullet_physics_body.h"
#include "engine/subsystems/physics/bullet/bullet_physics_world.h"
#include "engine/subsystems/physics/bullet/bullet_collision_shape.h"
BulletPhysicsBody::BulletPhysicsBody(BulletPhysicsWorld* world, const std::shared_ptr<BulletCollisionShape>& shape, const vec3& position, const Quaternion& rotation, float mass)
: world(world),
shape(shape),
motionState(std::make_unique<btDefaultMotionState>(
btTransform(
btQuaternion(rotation.getX(), rotation.getY(), rotation.getZ(), rotation.getW()),
btVector3(position.getX(), position.getY(), position.getZ()))))
{
btVector3 inertia(0, 0, 0);
if (mass != 0.0f)
shape->getCollisionShape()->calculateLocalInertia(mass, inertia);
btRigidBody::btRigidBodyConstructionInfo rigidBodyCI(mass, motionState.get(), shape->getCollisionShape(), inertia);
rigidBody = std::make_unique<btRigidBody>(rigidBodyCI);
rigidBody->setUserPointer(this);
rigidBody->setActivationState(DISABLE_DEACTIVATION);
world->getDynamicsWorld()->addRigidBody(rigidBody.get());
}
BulletPhysicsBody::~BulletPhysicsBody()
{
world->getDynamicsWorld()->removeRigidBody(rigidBody.get());
}
Transform BulletPhysicsBody::getWorldTransform() const
{
btTransform transform;
motionState->getWorldTransform(transform);
auto origin = transform.getOrigin();
auto rotation = transform.getRotation();
return Transform({ origin.getX(), origin.getY(), origin.getZ() }, Quaternion(rotation.getX(), rotation.getY(), rotation.getZ(), rotation.getW()));
}
void BulletPhysicsBody::setWorldTransform(const Transform& transform)
{
btTransform bulletTransform(
btQuaternion(transform.rotation.getX(), transform.rotation.getY(), transform.rotation.getZ(), transform.rotation.getW()),
btVector3(transform.position.getX(), transform.position.getY(), transform.position.getZ()));
rigidBody->setWorldTransform(bulletTransform);
motionState->setWorldTransform(bulletTransform);
}
void BulletPhysicsBody::setPosition(const vec3& position)
{
auto& transform = rigidBody->getWorldTransform();
transform.setOrigin(btVector3(position.getX(), position.getY(), position.getZ()));
rigidBody->setWorldTransform(transform);
motionState->setWorldTransform(transform);
}
void BulletPhysicsBody::setRotation(const Quaternion& rotation)
{
auto& transform = rigidBody->getWorldTransform();
transform.setRotation(btQuaternion(rotation.getX(), rotation.getY(), rotation.getZ(), rotation.getW()));
rigidBody->setWorldTransform(transform);
motionState->setWorldTransform(transform);
}
void BulletPhysicsBody::setFriction(float friction)
{
rigidBody->setFriction(friction);
}
void BulletPhysicsBody::setRollingFriction(float rollingFriction)
{
rigidBody->setRollingFriction(rollingFriction);
}
void BulletPhysicsBody::setSpinningFriction(float spinningFriction)
{
rigidBody->setSpinningFriction(spinningFriction);
}
void BulletPhysicsBody::setRestitution(float restitution)
{
rigidBody->setRestitution(restitution);
}
void BulletPhysicsBody::clearForces()
{
rigidBody->clearForces();
}
void BulletPhysicsBody::applyTorque(const vec3& torque)
{
rigidBody->applyTorque(btVector3(torque.getX(), torque.getY(), torque.getZ()));
}
void BulletPhysicsBody::applyTorqueImpulse(const vec3& torque)
{
rigidBody->applyTorqueImpulse(btVector3(torque.getX(), torque.getY(), torque.getZ()));
}
void BulletPhysicsBody::applyCentralForce(const vec3& force)
{
rigidBody->applyCentralForce(btVector3(force.getX(), force.getY(), force.getZ()));
}
void BulletPhysicsBody::applyCentralImpulse(const vec3& impulse)
{
rigidBody->applyCentralImpulse(btVector3(impulse.getX(), impulse.getY(), impulse.getZ()));
}
void BulletPhysicsBody::disableContactResponse()
{
rigidBody->setCollisionFlags(rigidBody->getCollisionFlags() | btCollisionObject::CF_NO_CONTACT_RESPONSE);
}
void BulletPhysicsBody::stop()
{
clearForces();
rigidBody->setLinearVelocity(btVector3(0.0f, 0.0f, 0.0f));
rigidBody->setAngularVelocity(btVector3(0.0f, 0.0f, 0.0f));
}
void BulletPhysicsBody::setKinematic(bool kinematic)
{
if (kinematic)
rigidBody->setCollisionFlags(rigidBody->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
else
rigidBody->setCollisionFlags(rigidBody->getCollisionFlags() & ~btCollisionObject::CF_KINEMATIC_OBJECT);
}
btRigidBody* BulletPhysicsBody::getBulletRigidBody() const
{
return rigidBody.get();
}
| 33.06015 | 177 | 0.784398 | ukrainskiysergey |
927e4912bd148eb2a29739e99023714dfb67cf1c | 4,004 | cpp | C++ | ARK2D/src/ARK2D/Tests/TransitionTest.cpp | ashleygwinnell/ark2d | bbfbee742ace9c52841dad4fab74d0d120ffe662 | [
"Unlicense"
] | 6 | 2015-08-25T19:16:20.000Z | 2021-04-19T16:47:58.000Z | ARK2D/src/ARK2D/Tests/TransitionTest.cpp | ashleygwinnell/ark2d | bbfbee742ace9c52841dad4fab74d0d120ffe662 | [
"Unlicense"
] | 1 | 2015-09-17T14:03:12.000Z | 2015-09-17T14:03:12.000Z | ARK2D/src/ARK2D/Tests/TransitionTest.cpp | ashleygwinnell/ark2d | bbfbee742ace9c52841dad4fab74d0d120ffe662 | [
"Unlicense"
] | 1 | 2018-10-02T19:59:47.000Z | 2018-10-02T19:59:47.000Z | /*
* TransitionTest.cpp
*
* Created on: Mar 23, 2012
* Author: ashleygwinnell
*/
#include "TransitionTest.h"
//#include "../../ARK.h"
#include "../State/Transition/SlideRectanglesAcrossTransition.h"
#include "../State/Transition/TranslateOutInTransition.h"
#include "../State/Transition/FadeToColourTransition.h"
#include "../State/Transition/FadeFromColourTransition.h"
namespace ARK {
namespace Tests {
TransitionTestGameState::TransitionTestGameState(int index, string name): GameState() {
this->index = index;
this->name = name;
}
void TransitionTestGameState::enter(GameContainer* container, StateBasedGame* game, GameState* from) {
}
void TransitionTestGameState::leave(GameContainer* container, StateBasedGame* game, GameState* to) {
}
unsigned int TransitionTestGameState::id() { return this->index; }
void TransitionTestGameState::init(GameContainer* container, StateBasedGame* game) {
}
void TransitionTestGameState::update(GameContainer* container, StateBasedGame* game, GameTimer* timer) {
}
void TransitionTestGameState::render(GameContainer* container, StateBasedGame* game, Renderer* g) {
g->setDrawColor(Color::darker_grey);
g->fillRect(10,10,container->getWidth()-20, container->getHeight()-20);
g->setDrawColor(Color::dark_grey);
g->fillRect(30,30,container->getWidth()-60, container->getHeight()-60);
g->setDrawColor(Color::grey);
g->fillRect(50,50,container->getWidth()-100, container->getHeight()-100);
g->setDrawColor(Color::black_50a);
g->fillCircleSpikey(container->getWidth()/2, container->getHeight()/2, container->getHeight()/4, 120);
}
TransitionTestGameState::~TransitionTestGameState() {
}
TransitionTest::TransitionTest():
StateBasedGame("Transition Test"),
transitionIndex(0),
leaveTransitions(),
entryTransitions()
{
}
void TransitionTest::initStates(GameContainer* container) {
Color* myWhite = new Color("#ffffff");
//Color* myWhite2 = myWhite->copy();
Color* myWhite3 = new Color(255,255,255);
leaveTransitions.add(new SlideRectanglesAcrossTransition(myWhite, 30, SlideRectanglesAcrossTransition::DIRECTION_LEFT, 1.0f));
entryTransitions.add(NULL);
leaveTransitions.add(new TranslateOutInTransition(SlideRectanglesAcrossTransition::DIRECTION_LEFT, 1.0f));
entryTransitions.add(NULL);
leaveTransitions.add(new FadeToColourTransition(1.0f, myWhite3));
entryTransitions.add(new FadeFromColourTransition(1.0f, myWhite3));
//leaveTransitions.add(NULL);
//entryTransitions.add(NULL);
addState(new TransitionTestGameState(0, "State One"));
addState(new TransitionTestGameState(1, "State Two"));
addState(new TransitionTestGameState(2, "State Three"));
addState(new TransitionTestGameState(3, "State Four"));
enterState((unsigned int) 0);
}
void TransitionTest::update(GameContainer* container, GameTimer* timer) {
StateBasedGame::update(container, timer);
Input* i = ARK2D::getInput();
if (i->isKeyPressed(Input::KEY_SPACE) || i->isKeyPressed(Input::KEY_ENTER)) {
enterState(transitionIndex, leaveTransitions.get(transitionIndex), entryTransitions.get(transitionIndex));
transitionIndex++;
if (transitionIndex >= leaveTransitions.size()) {
transitionIndex = 0;
}
}
}
void TransitionTest::render(GameContainer* container, Renderer* g) {
StateBasedGame::render(container, g);
g->drawStringCenteredAt(StringUtil::append("",transitionIndex), container->getWidth()/2, container->getHeight()/2);
if (isTransitioning()) {
g->drawString("Transitioning...", 10, 10);
}
}
void TransitionTest::resize(GameContainer* container, int width, int height) {
StateBasedGame::resize(container, width, height);
}
TransitionTest::~TransitionTest() {
}
int TransitionTest::start() {
ARK::Tests::TransitionTest* test = new ARK::Tests::TransitionTest();
GameContainer container(*test, 800, 600, 32, false);
container.start();
return 0;
}
}
}
| 32.032 | 129 | 0.724775 | ashleygwinnell |
927ee1dd68f0d5636217928373823f6fb4c03469 | 2,762 | cpp | C++ | Core/JPetTreeHeader/JPetTreeHeaderTest.cpp | Alvarness/j-pet-framework | 899ab32bf9a7f4daecaf8ed2dd7c8bc8922e73bd | [
"Apache-2.0"
] | null | null | null | Core/JPetTreeHeader/JPetTreeHeaderTest.cpp | Alvarness/j-pet-framework | 899ab32bf9a7f4daecaf8ed2dd7c8bc8922e73bd | [
"Apache-2.0"
] | null | null | null | Core/JPetTreeHeader/JPetTreeHeaderTest.cpp | Alvarness/j-pet-framework | 899ab32bf9a7f4daecaf8ed2dd7c8bc8922e73bd | [
"Apache-2.0"
] | null | null | null | #define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetTreeHeaderTest
#include <boost/test/unit_test.hpp>
#include <boost/filesystem.hpp>
#include "./JPetTreeHeader/JPetTreeHeader.h"
BOOST_AUTO_TEST_SUITE(JPetTreeHeaderSuite)
BOOST_AUTO_TEST_CASE(emptyHeader){
JPetTreeHeader treeHeader;
BOOST_REQUIRE_EQUAL(treeHeader.getRunNumber(), -1 );
BOOST_REQUIRE_EQUAL(treeHeader.getBaseFileName(), "filename not set" );
BOOST_REQUIRE_EQUAL(treeHeader.getSourcePosition(), -1 );
BOOST_REQUIRE_EQUAL(treeHeader.getStagesNb(), 0 );
BOOST_REQUIRE_EQUAL(treeHeader.getProcessingStageInfo(0).fModuleName, "module not set");
BOOST_REQUIRE_EQUAL(treeHeader.getProcessingStageInfo(10).fModuleDescription, "description not set");
BOOST_REQUIRE_EQUAL(treeHeader.getProcessingStageInfo(12).fModuleVersion, -1);
BOOST_REQUIRE_EQUAL(treeHeader.getProcessingStageInfo(12).fCreationTime, "-1");
BOOST_REQUIRE_EQUAL(treeHeader.getVariable( "" ), "");
}
BOOST_AUTO_TEST_CASE(checkingEmptyStage){
JPetTreeHeader treeHeader;
BOOST_REQUIRE_EQUAL(treeHeader.emptyProcessingStageInfo().fModuleName, treeHeader.getProcessingStageInfo(0).fModuleName);
BOOST_REQUIRE_EQUAL(treeHeader.emptyProcessingStageInfo().fModuleDescription, treeHeader.getProcessingStageInfo(0).fModuleDescription);
BOOST_REQUIRE_EQUAL(treeHeader.emptyProcessingStageInfo().fModuleVersion, treeHeader.getProcessingStageInfo(0).fModuleVersion);
BOOST_REQUIRE_EQUAL(treeHeader.emptyProcessingStageInfo().fCreationTime, treeHeader.getProcessingStageInfo(0).fCreationTime);
}
BOOST_AUTO_TEST_CASE(headerWithNumber){
JPetTreeHeader treeHeader(345);
BOOST_REQUIRE_EQUAL(treeHeader.getRunNumber(), 345 );
}
BOOST_AUTO_TEST_CASE(headerWithStageInfo){
JPetTreeHeader treeHeader;
treeHeader.addStageInfo("name", "myDescription", 3, "time_stamp");
BOOST_REQUIRE_EQUAL(treeHeader.getStagesNb(), 1);
BOOST_REQUIRE_EQUAL(treeHeader.getRunNumber(), -1 );
BOOST_REQUIRE_EQUAL(treeHeader.getBaseFileName(), "filename not set" );
BOOST_REQUIRE_EQUAL(treeHeader.getSourcePosition(), -1 );
BOOST_REQUIRE_EQUAL(treeHeader.getProcessingStageInfo(0).fModuleName, "name");
BOOST_REQUIRE_EQUAL(treeHeader.getProcessingStageInfo(0).fModuleDescription, "myDescription");
}
BOOST_AUTO_TEST_CASE(simpleTest){
JPetTreeHeader treeHeader;
treeHeader.setBaseFileName("baseFileName");
BOOST_REQUIRE_EQUAL(treeHeader.getBaseFileName(), "baseFileName");
treeHeader.setSourcePosition(2);
BOOST_REQUIRE_EQUAL(treeHeader.getSourcePosition(), 2);
}
BOOST_AUTO_TEST_CASE(headerWithVariable){
JPetTreeHeader treeHeader;
treeHeader.setVariable("name", "value");
BOOST_REQUIRE_EQUAL(treeHeader.getVariable("name"), "value");
BOOST_REQUIRE_EQUAL(treeHeader.getVariable("blank name"), "");
}
BOOST_AUTO_TEST_SUITE_END()
| 43.15625 | 136 | 0.828747 | Alvarness |
92819c144d2f05f814acab0151720fdb297a3f01 | 18,098 | cpp | C++ | source/common/engine/stringtable.cpp | Quake-Backup/Raze | 16c81f0b1f409436ebf576d2c23f2459a29b34b4 | [
"RSA-MD"
] | 1 | 2022-03-30T15:53:09.000Z | 2022-03-30T15:53:09.000Z | source/common/engine/stringtable.cpp | Quake-Backup/Raze | 16c81f0b1f409436ebf576d2c23f2459a29b34b4 | [
"RSA-MD"
] | null | null | null | source/common/engine/stringtable.cpp | Quake-Backup/Raze | 16c81f0b1f409436ebf576d2c23f2459a29b34b4 | [
"RSA-MD"
] | null | null | null | /*
** stringtable.cpp
** Implements the FStringTable class
**
**---------------------------------------------------------------------------
** Copyright 1998-2006 Randy Heit
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions
** are met:
**
** 1. Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** 2. Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
** 3. The name of the author may not be used to endorse or promote products
** derived from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
** OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
** IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
** INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
** NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
** THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**---------------------------------------------------------------------------
**
*/
#include <string.h>
#include "stringtable.h"
#include "cmdlib.h"
#include "filesystem.h"
#include "sc_man.h"
#include "printf.h"
#include "i_interface.h"
//==========================================================================
//
//
//
//==========================================================================
void FStringTable::LoadStrings (const char *language)
{
int lastlump, lump;
lastlump = 0;
while ((lump = fileSystem.FindLump("LMACROS", &lastlump)) != -1)
{
readMacros(lump);
}
lastlump = 0;
while ((lump = fileSystem.FindLump ("LANGUAGE", &lastlump)) != -1)
{
auto lumpdata = fileSystem.GetFileData(lump);
if (!ParseLanguageCSV(lump, lumpdata))
LoadLanguage (lump, lumpdata);
}
UpdateLanguage(language);
allMacros.Clear();
}
//==========================================================================
//
// This was tailored to parse CSV as exported by Google Docs.
//
//==========================================================================
TArray<TArray<FString>> FStringTable::parseCSV(const TArray<uint8_t> &buffer)
{
const size_t bufLength = buffer.Size();
TArray<TArray<FString>> data;
TArray<FString> row;
TArray<char> cell;
bool quoted = false;
/*
auto myisspace = [](int ch) { return ch == '\t' || ch == '\r' || ch == '\n' || ch == ' '; };
while (*vcopy && myisspace((unsigned char)*vcopy)) vcopy++; // skip over leaading whitespace;
auto vend = vcopy + strlen(vcopy);
while (vend > vcopy && myisspace((unsigned char)vend[-1])) *--vend = 0; // skip over trailing whitespace
*/
for (size_t i = 0; i < bufLength; ++i)
{
if (buffer[i] == '"')
{
// Double quotes inside a quoted string count as an escaped quotation mark.
if (quoted && i < bufLength - 1 && buffer[i + 1] == '"')
{
cell.Push('"');
i++;
}
else if (cell.Size() == 0 || quoted)
{
quoted = !quoted;
}
}
else if (buffer[i] == ',')
{
if (!quoted)
{
cell.Push(0);
ProcessEscapes(cell.Data());
row.Push(cell.Data());
cell.Clear();
}
else
{
cell.Push(buffer[i]);
}
}
else if (buffer[i] == '\r')
{
// Ignore all CR's.
}
else if (buffer[i] == '\n' && !quoted)
{
cell.Push(0);
ProcessEscapes(cell.Data());
row.Push(cell.Data());
data.Push(std::move(row));
cell.Clear();
}
else
{
cell.Push(buffer[i]);
}
}
// Handle last line without linebreak
if (cell.Size() > 0 || row.Size() > 0)
{
cell.Push(0);
ProcessEscapes(cell.Data());
row.Push(cell.Data());
data.Push(std::move(row));
}
return data;
}
//==========================================================================
//
//
//
//==========================================================================
bool FStringTable::readMacros(int lumpnum)
{
auto lumpdata = fileSystem.GetFileData(lumpnum);
auto data = parseCSV(lumpdata);
for (unsigned i = 1; i < data.Size(); i++)
{
auto macroname = data[i][0];
auto language = data[i][1];
if (macroname.IsEmpty() || language.IsEmpty()) continue;
FStringf combined_name("%s/%s", language.GetChars(), macroname.GetChars());
FName name = combined_name.GetChars();
StringMacro macro;
for (int k = 0; k < 4; k++)
{
macro.Replacements[k] = data[i][k+2];
}
allMacros.Insert(name, macro);
}
return true;
}
//==========================================================================
//
//
//
//==========================================================================
bool FStringTable::ParseLanguageCSV(int lumpnum, const TArray<uint8_t> &buffer)
{
if (buffer.Size() < 11) return false;
if (strnicmp((const char*)buffer.Data(), "default,", 8) && strnicmp((const char*)buffer.Data(), "identifier,", 11 )) return false;
auto data = parseCSV(buffer);
int labelcol = -1;
int filtercol = -1;
TArray<std::pair<int, unsigned>> langrows;
bool hasDefaultEntry = false;
if (data.Size() > 0)
{
for (unsigned column = 0; column < data[0].Size(); column++)
{
auto &entry = data[0][column];
if (entry.CompareNoCase("filter") == 0)
{
filtercol = column;
}
else if (entry.CompareNoCase("identifier") == 0)
{
labelcol = column;
}
else
{
auto languages = entry.Split(" ", FString::TOK_SKIPEMPTY);
for (auto &lang : languages)
{
if (lang.CompareNoCase("default") == 0)
{
langrows.Push(std::make_pair(column, default_table));
hasDefaultEntry = true;
}
else if (lang.Len() < 4)
{
lang.ToLower();
langrows.Push(std::make_pair(column, MAKE_ID(lang[0], lang[1], lang[2], 0)));
}
}
}
}
for (unsigned i = 1; i < data.Size(); i++)
{
auto &row = data[i];
if (filtercol > -1)
{
auto filterstr = row[filtercol];
if (filterstr.IsNotEmpty())
{
bool ok = false;
if (sysCallbacks.CheckGame)
{
auto filter = filterstr.Split(" ", FString::TOK_SKIPEMPTY);
for (auto& entry : filter)
{
if (sysCallbacks.CheckGame(entry))
{
ok = true;
break;
}
}
}
if (!ok) continue;
}
}
FName strName = row[labelcol].GetChars();
if (hasDefaultEntry)
{
DeleteForLabel(lumpnum, strName);
}
for (auto &langentry : langrows)
{
auto str = row[langentry.first];
if (str.Len() > 0)
{
InsertString(lumpnum, langentry.second, strName, str);
}
else
{
DeleteString(langentry.second, strName);
}
}
}
}
return true;
}
//==========================================================================
//
//
//
//==========================================================================
void FStringTable::LoadLanguage (int lumpnum, const TArray<uint8_t> &buffer)
{
bool errordone = false;
TArray<uint32_t> activeMaps;
FScanner sc;
bool hasDefaultEntry = false;
sc.OpenMem("LANGUAGE", buffer);
sc.SetCMode (true);
while (sc.GetString ())
{
if (sc.Compare ("["))
{ // Process language identifiers
activeMaps.Clear();
hasDefaultEntry = false;
sc.MustGetString ();
do
{
size_t len = sc.StringLen;
if (len != 2 && len != 3)
{
if (len == 1 && sc.String[0] == '~')
{
// deprecated and ignored
sc.ScriptMessage("Deprecated option '~' found in language list");
sc.MustGetString ();
continue;
}
if (len == 1 && sc.String[0] == '*')
{
activeMaps.Clear();
activeMaps.Push(global_table);
}
else if (len == 7 && stricmp (sc.String, "default") == 0)
{
activeMaps.Clear();
activeMaps.Push(default_table);
hasDefaultEntry = true;
}
else
{
sc.ScriptError ("The language code must be 2 or 3 characters long.\n'%s' is %lu characters long.",
sc.String, len);
}
}
else
{
if (activeMaps.Size() != 1 || (activeMaps[0] != default_table && activeMaps[0] != global_table))
activeMaps.Push(MAKE_ID(tolower(sc.String[0]), tolower(sc.String[1]), tolower(sc.String[2]), 0));
}
sc.MustGetString ();
} while (!sc.Compare ("]"));
}
else
{ // Process string definitions.
if (activeMaps.Size() == 0)
{
// LANGUAGE lump is bad. We need to check if this is an old binary
// lump and if so just skip it to allow old WADs to run which contain
// such a lump.
if (!sc.isText())
{
if (!errordone) Printf("Skipping binary 'LANGUAGE' lump.\n");
errordone = true;
return;
}
sc.ScriptError ("Found a string without a language specified.");
}
bool skip = false;
if (sc.Compare("$"))
{
sc.MustGetStringName("ifgame");
sc.MustGetStringName("(");
sc.MustGetString();
skip |= (!sysCallbacks.CheckGame || !sysCallbacks.CheckGame(sc.String));
sc.MustGetStringName(")");
sc.MustGetString();
}
FName strName (sc.String);
sc.MustGetStringName ("=");
sc.MustGetString ();
FString strText (sc.String, ProcessEscapes (sc.String));
sc.MustGetString ();
while (!sc.Compare (";"))
{
ProcessEscapes (sc.String);
strText += sc.String;
sc.MustGetString ();
}
if (!skip)
{
if (hasDefaultEntry)
{
DeleteForLabel(lumpnum, strName);
}
// Insert the string into all relevant tables.
for (auto map : activeMaps)
{
InsertString(lumpnum, map, strName, strText);
}
}
}
}
}
//==========================================================================
//
//
//
//==========================================================================
void FStringTable::DeleteString(int langid, FName label)
{
allStrings[langid].Remove(label);
}
//==========================================================================
//
// This deletes all older entries for a given label. This gets called
// when a string in the default table gets updated.
//
//==========================================================================
void FStringTable::DeleteForLabel(int lumpnum, FName label)
{
decltype(allStrings)::Iterator it(allStrings);
decltype(allStrings)::Pair *pair;
auto filenum = fileSystem.GetFileContainer(lumpnum);
while (it.NextPair(pair))
{
auto entry = pair->Value.CheckKey(label);
if (entry && entry->filenum < filenum)
{
pair->Value.Remove(label);
}
}
}
//==========================================================================
//
//
//
//==========================================================================
void FStringTable::InsertString(int lumpnum, int langid, FName label, const FString &string)
{
const char *strlangid = (const char *)&langid;
TableElement te = { fileSystem.GetFileContainer(lumpnum), { string, string, string, string } };
ptrdiff_t index;
while ((index = te.strings[0].IndexOf("@[")) >= 0)
{
auto endindex = te.strings[0].IndexOf(']', index);
if (endindex == -1)
{
Printf("Bad macro in %s : %s\n", strlangid, label.GetChars());
break;
}
FString macroname(te.strings[0].GetChars() + index + 2, endindex - index - 2);
FStringf lookupstr("%s/%s", strlangid, macroname.GetChars());
FStringf replacee("@[%s]", macroname.GetChars());
FName lookupname(lookupstr.GetChars(), true);
auto replace = allMacros.CheckKey(lookupname);
for (int i = 0; i < 4; i++)
{
const char *replacement = replace? replace->Replacements[i].GetChars() : "";
te.strings[i].Substitute(replacee, replacement);
}
}
allStrings[langid].Insert(label, te);
}
//==========================================================================
//
//
//
//==========================================================================
void FStringTable::UpdateLanguage(const char *language)
{
if (language) activeLanguage = language;
else language = activeLanguage.GetChars();
size_t langlen = strlen(language);
int LanguageID = (langlen < 2 || langlen > 3) ?
MAKE_ID('e', 'n', 'u', '\0') :
MAKE_ID(language[0], language[1], language[2], '\0');
currentLanguageSet.Clear();
auto checkone = [&](uint32_t lang_id)
{
auto list = allStrings.CheckKey(lang_id);
if (list && currentLanguageSet.FindEx([&](const auto &element) { return element.first == lang_id; }) == currentLanguageSet.Size())
currentLanguageSet.Push(std::make_pair(lang_id, list));
};
checkone(override_table);
checkone(global_table);
checkone(LanguageID);
checkone(LanguageID & MAKE_ID(0xff, 0xff, 0, 0));
checkone(default_table);
}
//==========================================================================
//
// Replace \ escape sequences in a string with the escaped characters.
//
//==========================================================================
size_t FStringTable::ProcessEscapes (char *iptr)
{
char *sptr = iptr, *optr = iptr, c;
while ((c = *iptr++) != '\0')
{
if (c == '\\')
{
c = *iptr++;
if (c == 'n')
c = '\n';
else if (c == 'c')
c = TEXTCOLOR_ESCAPE;
else if (c == 'r')
c = '\r';
else if (c == 't')
c = '\t';
else if (c == 'x')
{
c = 0;
for (int i = 0; i < 2; i++)
{
char cc = *iptr++;
if (cc >= '0' && cc <= '9')
c = (c << 4) + cc - '0';
else if (cc >= 'a' && cc <= 'f')
c = (c << 4) + 10 + cc - 'a';
else if (cc >= 'A' && cc <= 'F')
c = (c << 4) + 10 + cc - 'A';
else
{
iptr--;
break;
}
}
if (c == 0) continue;
}
else if (c == '\n')
continue;
}
*optr++ = c;
}
*optr = '\0';
return optr - sptr;
}
//==========================================================================
//
// Checks if the given key exists in any one of the default string tables that are valid for all languages.
// To replace IWAD content this condition must be true.
//
//==========================================================================
bool FStringTable::exists(const char *name)
{
if (name == nullptr || *name == 0)
{
return false;
}
FName nm(name, true);
if (nm != NAME_None)
{
uint32_t defaultStrings[] = { default_table, global_table, override_table };
for (auto mapid : defaultStrings)
{
auto map = allStrings.CheckKey(mapid);
if (map)
{
auto item = map->CheckKey(nm);
if (item) return true;
}
}
}
return false;
}
//==========================================================================
//
// Finds a string by name and returns its value
//
//==========================================================================
const char *FStringTable::GetString(const char *name, uint32_t *langtable, int gender) const
{
if (name == nullptr || *name == 0)
{
return nullptr;
}
if (gender == -1 && sysCallbacks.GetGender) gender = sysCallbacks.GetGender();
if (gender < 0 || gender > 3) gender = 0;
FName nm(name, true);
if (nm != NAME_None)
{
for (auto map : currentLanguageSet)
{
auto item = map.second->CheckKey(nm);
if (item)
{
if (langtable) *langtable = map.first;
auto c = item->strings[gender].GetChars();
if (c && *c == '$' && c[1] == '$')
return GetString(c + 2, langtable, gender);
return c;
}
}
}
return nullptr;
}
//==========================================================================
//
// Finds a string by name in a given language
//
//==========================================================================
const char *FStringTable::GetLanguageString(const char *name, uint32_t langtable, int gender) const
{
if (name == nullptr || *name == 0)
{
return nullptr;
}
if (gender == -1 && sysCallbacks.GetGender) gender = sysCallbacks.GetGender();
if (gender < 0 || gender > 3) gender = 0;
FName nm(name, true);
if (nm != NAME_None)
{
auto map = allStrings.CheckKey(langtable);
if (map == nullptr) return nullptr;
auto item = map->CheckKey(nm);
if (item)
{
return item->strings[gender].GetChars();
}
}
return nullptr;
}
bool FStringTable::MatchDefaultString(const char *name, const char *content) const
{
// This only compares the first line to avoid problems with bad linefeeds. For the few cases where this feature is needed it is sufficient.
auto c = GetLanguageString(name, FStringTable::default_table);
if (!c) return false;
// Check a secondary key, in case the text comparison cannot be done due to needed orthographic fixes (see Harmony's exit text)
FStringf checkkey("%s_CHECK", name);
auto cc = GetLanguageString(checkkey, FStringTable::default_table);
if (cc) c = cc;
return (c && !strnicmp(c, content, strcspn(content, "\n\r\t")));
}
//==========================================================================
//
// Finds a string by name and returns its value. If the string does
// not exist, returns the passed name instead.
//
//==========================================================================
const char *FStringTable::operator() (const char *name) const
{
const char *str = operator[] (name);
return str ? str : name;
}
//==========================================================================
//
// Find a string with the same exact text. Returns its name.
// This does not need to check genders, it is only used by
// Dehacked on the English table for finding stock strings.
//
//==========================================================================
const char *StringMap::MatchString (const char *string) const
{
StringMap::ConstIterator it(*this);
StringMap::ConstPair *pair;
while (it.NextPair(pair))
{
if (pair->Value.strings[0].CompareNoCase(string) == 0)
{
return pair->Key.GetChars();
}
}
return nullptr;
}
FStringTable GStrings;
| 26.191027 | 140 | 0.539728 | Quake-Backup |
9281b390d33a9df2bf6e8d2293f428d2cca5bf8d | 20,444 | cpp | C++ | trackbar.cpp | reupen/ui_helpers | 7db30d91f58116ece51e2cdaf83c4e2be819609e | [
"BSD-3-Clause"
] | 2 | 2016-04-12T13:45:36.000Z | 2021-11-30T17:17:02.000Z | trackbar.cpp | reupen/ui_helpers | 7db30d91f58116ece51e2cdaf83c4e2be819609e | [
"BSD-3-Clause"
] | 1 | 2019-07-12T23:39:30.000Z | 2019-07-13T08:56:52.000Z | trackbar.cpp | reupen/ui_helpers | 7db30d91f58116ece51e2cdaf83c4e2be819609e | [
"BSD-3-Clause"
] | 5 | 2016-04-12T13:45:38.000Z | 2019-07-12T23:37:01.000Z | #include "stdafx.h"
/**
* \file trackbar.cpp
* trackbar custom control
* Copyright (C) 2005
* \author musicmusic
*/
namespace uih {
BOOL TrackbarBase::create_tooltip(const TCHAR* text, POINT pt)
{
destroy_tooltip();
DLLVERSIONINFO2 dvi;
bool b_comctl_6 = SUCCEEDED(uih::get_comctl32_version(dvi)) && dvi.info1.dwMajorVersion >= 6;
m_wnd_tooltip = CreateWindowEx(WS_EX_TOPMOST | (b_comctl_6 ? WS_EX_TRANSPARENT : 0), TOOLTIPS_CLASS, nullptr,
WS_POPUP | TTS_NOPREFIX | TTS_ALWAYSTIP, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, get_wnd(),
nullptr, mmh::get_current_instance(), nullptr);
SetWindowPos(m_wnd_tooltip, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
TOOLINFO ti;
memset(&ti, 0, sizeof(ti));
ti.cbSize = TTTOOLINFO_V1_SIZE;
ti.uFlags = TTF_SUBCLASS | TTF_TRANSPARENT | TTF_TRACK | TTF_ABSOLUTE;
ti.hwnd = get_wnd();
ti.hinst = mmh::get_current_instance();
ti.lpszText = const_cast<TCHAR*>(text);
uih::tooltip_add_tool(m_wnd_tooltip, &ti);
SendMessage(m_wnd_tooltip, TTM_TRACKPOSITION, 0, MAKELONG(pt.x, pt.y + 21));
SendMessage(m_wnd_tooltip, TTM_TRACKACTIVATE, TRUE, (LPARAM)&ti);
return TRUE;
}
void TrackbarBase::destroy_tooltip()
{
if (m_wnd_tooltip) {
DestroyWindow(m_wnd_tooltip);
m_wnd_tooltip = nullptr;
}
}
BOOL TrackbarBase::update_tooltip(POINT pt, const TCHAR* text)
{
if (!m_wnd_tooltip)
return FALSE;
SendMessage(m_wnd_tooltip, TTM_TRACKPOSITION, 0, MAKELONG(pt.x, pt.y + 21));
TOOLINFO ti;
memset(&ti, 0, sizeof(ti));
ti.cbSize = TTTOOLINFO_V1_SIZE;
ti.uFlags = TTF_SUBCLASS | TTF_TRANSPARENT | TTF_TRACK | TTF_ABSOLUTE;
ti.hwnd = get_wnd();
ti.hinst = mmh::get_current_instance();
ti.lpszText = const_cast<TCHAR*>(text);
uih::tooltip_update_tip_text(m_wnd_tooltip, &ti);
return TRUE;
}
void TrackbarBase::set_callback(TrackbarCallback* p_host)
{
m_host = p_host;
}
void TrackbarBase::set_show_tooltips(bool val)
{
m_show_tooltips = val;
if (!val)
destroy_tooltip();
}
void TrackbarBase::set_position_internal(unsigned pos)
{
if (!m_dragging) {
POINT pt;
GetCursorPos(&pt);
ScreenToClient(get_wnd(), &pt);
update_hot_status(pt);
}
RECT rc;
get_thumb_rect(&rc);
HRGN rgn_old = CreateRectRgnIndirect(&rc);
get_thumb_rect(pos, m_range, &rc);
HRGN rgn_new = CreateRectRgnIndirect(&rc);
CombineRgn(rgn_new, rgn_old, rgn_new, RGN_OR);
DeleteObject(rgn_old);
m_display_position = pos;
// InvalidateRgn(m_wnd, rgn_new, TRUE);
RedrawWindow(get_wnd(), nullptr, rgn_new, RDW_INVALIDATE | RDW_ERASE | RDW_UPDATENOW | RDW_ERASENOW);
DeleteObject(rgn_new);
}
void TrackbarBase::set_position(unsigned pos)
{
m_position = pos;
if (!m_dragging) {
set_position_internal(pos);
}
}
unsigned TrackbarBase::get_position() const
{
return m_position;
}
void TrackbarBase::set_range(unsigned range)
{
RECT rc;
get_thumb_rect(&rc);
HRGN rgn_old = CreateRectRgnIndirect(&rc);
get_thumb_rect(m_display_position, range, &rc);
HRGN rgn_new = CreateRectRgnIndirect(&rc);
CombineRgn(rgn_new, rgn_old, rgn_new, RGN_OR);
DeleteObject(rgn_old);
m_range = range;
RedrawWindow(get_wnd(), nullptr, rgn_new, RDW_INVALIDATE | RDW_ERASE | RDW_UPDATENOW | RDW_ERASENOW);
DeleteObject(rgn_new);
}
unsigned TrackbarBase::get_range() const
{
return m_range;
}
void TrackbarBase::set_scroll_step(unsigned u_val)
{
m_step = u_val;
}
unsigned TrackbarBase::get_scroll_step() const
{
return m_step;
}
void TrackbarBase::set_orientation(bool b_vertical)
{
m_vertical = b_vertical;
// TODO: write handler
}
bool TrackbarBase::get_orientation() const
{
return m_vertical;
}
void TrackbarBase::set_auto_focus(bool b_state)
{
m_auto_focus = b_state;
}
bool TrackbarBase::get_auto_focus() const
{
return m_auto_focus;
}
void TrackbarBase::set_direction(bool b_reversed)
{
m_reversed = b_reversed;
}
void TrackbarBase::set_mouse_wheel_direction(bool b_reversed)
{
m_mouse_wheel_reversed = b_reversed;
}
bool TrackbarBase::get_direction() const
{
return m_reversed;
}
void TrackbarBase::set_enabled(bool enabled)
{
EnableWindow(get_wnd(), enabled);
}
bool TrackbarBase::get_enabled() const
{
return IsWindowEnabled(get_wnd()) != 0;
}
void Trackbar::get_thumb_rect(unsigned pos, unsigned range, RECT* rc) const
{
RECT rc_client;
GetClientRect(get_wnd(), &rc_client);
unsigned cx = calculate_thumb_size();
if (get_orientation()) {
rc->left = 2;
rc->right = rc_client.right - 2;
rc->top = range ? MulDiv(get_direction() ? range - pos : pos, rc_client.bottom - cx, range)
: get_direction() ? rc_client.bottom - cx : 0;
rc->bottom = rc->top + cx;
} else {
rc->top = 2;
rc->bottom = rc_client.bottom - 2;
rc->left = range ? MulDiv(get_direction() ? range - pos : pos, rc_client.right - cx, range)
: get_direction() ? rc_client.right - cx : 0;
rc->right = rc->left + cx;
}
}
void Trackbar::get_channel_rect(RECT* rc) const
{
RECT rc_client;
GetClientRect(get_wnd(), &rc_client);
unsigned cx = calculate_thumb_size();
rc->left = get_orientation() ? rc_client.right / 2 - 2 : rc_client.left + cx / 2;
rc->right = get_orientation() ? rc_client.right / 2 + 2 : rc_client.right - cx + cx / 2;
rc->top = get_orientation() ? rc_client.top + cx / 2 : rc_client.bottom / 2 - 2;
rc->bottom = get_orientation() ? rc_client.bottom - cx + cx / 2 : rc_client.bottom / 2 + 2;
}
void TrackbarBase::get_thumb_rect(RECT* rc) const
{
get_thumb_rect(m_display_position, m_range, rc);
}
bool TrackbarBase::get_hot() const
{
return m_thumb_hot;
}
bool TrackbarBase::get_tracking() const
{
return m_dragging;
}
void TrackbarBase::update_hot_status(POINT pt)
{
RECT rc;
get_thumb_rect(&rc);
bool in_rect = PtInRect(&rc, pt) != 0;
POINT pts = pt;
MapWindowPoints(get_wnd(), HWND_DESKTOP, &pts, 1);
bool b_in_wnd = WindowFromPoint(pts) == get_wnd();
bool b_new_hot = in_rect && b_in_wnd;
if (m_thumb_hot != b_new_hot) {
m_thumb_hot = b_new_hot;
if (m_thumb_hot)
SetCapture(get_wnd());
else if (GetCapture() == get_wnd() && !m_dragging)
ReleaseCapture();
RedrawWindow(get_wnd(), &rc, nullptr, RDW_INVALIDATE | /*RDW_ERASE|*/ RDW_UPDATENOW /*|RDW_ERASENOW*/);
}
}
void Trackbar::draw_background(HDC dc, const RECT* rc) const
{
HWND wnd_parent = GetParent(get_wnd());
POINT pt = {0, 0};
POINT pt_old = {0, 0};
MapWindowPoints(get_wnd(), wnd_parent, &pt, 1);
OffsetWindowOrgEx(dc, pt.x, pt.y, &pt_old);
if (SendMessage(wnd_parent, WM_ERASEBKGND, reinterpret_cast<WPARAM>(dc), 0) == FALSE)
SendMessage(wnd_parent, WM_PRINTCLIENT, reinterpret_cast<WPARAM>(dc), PRF_ERASEBKGND);
SetWindowOrgEx(dc, pt_old.x, pt_old.y, nullptr);
}
void Trackbar::draw_thumb(HDC dc, const RECT* rc) const
{
if (get_theme_handle()) {
const auto part_id = get_orientation() ? TKP_THUMBVERT : TKP_THUMB;
const auto state_id
= get_enabled() ? (get_tracking() ? TUS_PRESSED : (get_hot() ? TUS_HOT : TUS_NORMAL)) : TUS_DISABLED;
DrawThemeBackground(get_theme_handle(), dc, part_id, state_id, rc, nullptr);
} else {
HPEN pn_highlight = CreatePen(PS_SOLID, 1, GetSysColor(COLOR_3DHIGHLIGHT));
HPEN pn_light = CreatePen(PS_SOLID, 1, GetSysColor(COLOR_3DLIGHT));
HPEN pn_dkshadow = CreatePen(PS_SOLID, 1, GetSysColor(COLOR_3DDKSHADOW));
HPEN pn_shadow = CreatePen(PS_SOLID, 1, GetSysColor(COLOR_3DSHADOW));
HPEN pn_old = SelectPen(dc, pn_highlight);
MoveToEx(dc, rc->left, rc->top, nullptr);
LineTo(dc, rc->right - 1, rc->top);
SelectPen(dc, pn_dkshadow);
LineTo(dc, rc->right - 1, rc->bottom - 1);
SelectPen(dc, pn_highlight);
MoveToEx(dc, rc->left, rc->top, nullptr);
LineTo(dc, rc->left, rc->bottom - 1);
SelectPen(dc, pn_dkshadow);
LineTo(dc, rc->right, rc->bottom - 1);
SelectPen(dc, pn_light);
MoveToEx(dc, rc->left + 1, rc->top + 1, nullptr);
LineTo(dc, rc->right - 2, rc->top + 1);
MoveToEx(dc, rc->left + 1, rc->top + 1, nullptr);
LineTo(dc, rc->left + 1, rc->bottom - 2);
SelectPen(dc, pn_shadow);
LineTo(dc, rc->right - 1, rc->bottom - 2);
MoveToEx(dc, rc->right - 2, rc->top + 1, nullptr);
LineTo(dc, rc->right - 2, rc->bottom - 2);
SelectPen(dc, pn_old);
DeleteObject(pn_light);
DeleteObject(pn_highlight);
DeleteObject(pn_shadow);
DeleteObject(pn_dkshadow);
RECT rc_fill = *rc;
rc_fill.top += 2;
rc_fill.left += 2;
rc_fill.right -= 2;
rc_fill.bottom -= 2;
HBRUSH br = GetSysColorBrush(COLOR_BTNFACE);
FillRect(dc, &rc_fill, br);
if (!get_enabled()) {
COLORREF cr_btnhighlight = GetSysColor(COLOR_BTNHIGHLIGHT);
for (int x = rc_fill.left; x < rc_fill.right; x++)
for (int y = rc_fill.top; y < rc_fill.bottom; y++)
if ((x + y) % 2)
SetPixel(dc, x, y, cr_btnhighlight); // i dont have anything better than SetPixel
}
}
}
void Trackbar::draw_channel(HDC dc, const RECT* rc) const
{
if (get_theme_handle()) {
DrawThemeBackground(
get_theme_handle(), dc, get_orientation() ? TKP_TRACKVERT : TKP_TRACK, TUTS_NORMAL, rc, nullptr);
} else {
RECT rc_temp = *rc;
DrawEdge(dc, &rc_temp, EDGE_SUNKEN, BF_RECT);
}
}
HTHEME TrackbarBase::get_theme_handle() const
{
return m_theme;
}
bool TrackbarBase::on_hooked_message(uih::MessageHookType p_type, int code, WPARAM wp, LPARAM lp)
{
auto lpkeyb = uih::GetKeyboardLParam(lp);
if (wp == VK_ESCAPE && !lpkeyb.transition_code && !lpkeyb.previous_key_state) {
destroy_tooltip();
if (GetCapture() == get_wnd())
ReleaseCapture();
m_dragging = false;
set_position_internal(m_position);
uih::deregister_message_hook(uih::MessageHookType::type_keyboard, this);
m_hook_registered = false;
return true;
}
return false;
}
unsigned Trackbar::calculate_thumb_size() const
{
RECT rc_client;
GetClientRect(get_wnd(), &rc_client);
return MulDiv(get_orientation() ? rc_client.right : rc_client.bottom, 9, 20);
}
unsigned TrackbarBase::calculate_position_from_point(const POINT& pt_client) const
{
RECT rc_channel;
RECT rc_client;
GetClientRect(get_wnd(), &rc_client);
get_channel_rect(&rc_channel);
POINT pt = pt_client;
if (get_orientation()) {
pfc::swap_t(pt.x, pt.y);
pfc::swap_t(rc_channel.left, rc_channel.top);
pfc::swap_t(rc_channel.bottom, rc_channel.right);
pfc::swap_t(rc_client.left, rc_client.top);
pfc::swap_t(rc_client.bottom, rc_client.right);
}
int cx = pt.x;
if (cx < rc_channel.left)
cx = rc_channel.left;
else if (cx > rc_channel.right)
cx = rc_channel.right;
return rc_channel.right - rc_channel.left
? MulDiv(m_reversed ? rc_channel.right - cx : cx - rc_channel.left, m_range, rc_channel.right - rc_channel.left)
: 0;
}
LRESULT TrackbarBase::on_message(HWND wnd, UINT msg, WPARAM wp, LPARAM lp)
{
switch (msg) {
case WM_NCCREATE:
break;
case WM_CREATE: {
if (IsThemeActive() && IsAppThemed()) {
m_theme = OpenThemeData(wnd, L"Trackbar");
}
} break;
case WM_THEMECHANGED: {
{
if (m_theme) {
CloseThemeData(m_theme);
m_theme = nullptr;
}
if (IsThemeActive() && IsAppThemed())
m_theme = OpenThemeData(wnd, L"Trackbar");
}
} break;
case WM_DESTROY: {
if (m_hook_registered) {
uih::deregister_message_hook(uih::MessageHookType::type_keyboard, this);
m_hook_registered = false;
}
{
if (m_theme)
CloseThemeData(m_theme);
m_theme = nullptr;
}
} break;
case WM_NCDESTROY:
break;
case WM_SIZE:
RedrawWindow(wnd, nullptr, nullptr, RDW_INVALIDATE | RDW_ERASE);
break;
case WM_MOUSEMOVE: {
POINT pt = {GET_X_LPARAM(lp), GET_Y_LPARAM(lp)};
if (m_dragging) {
if (!m_last_mousemove.m_valid || wp != m_last_mousemove.m_wp || lp != m_last_mousemove.m_lp) {
if (get_enabled()) {
unsigned pos = calculate_position_from_point(pt);
set_position_internal(pos);
if (m_wnd_tooltip && m_host) {
POINT pts = pt;
ClientToScreen(wnd, &pts);
TrackbarString temp;
m_host->get_tooltip_text(pos, temp);
update_tooltip(pts, temp.data());
}
if (m_host)
m_host->on_position_change(pos, true);
}
}
m_last_mousemove.m_valid = true;
m_last_mousemove.m_wp = wp;
m_last_mousemove.m_lp = lp;
} else {
update_hot_status(pt);
}
} break;
case WM_ENABLE: {
RECT rc;
get_thumb_rect(&rc);
InvalidateRect(wnd, &rc, TRUE);
} break;
case WM_MBUTTONDOWN:
case WM_RBUTTONDOWN:
case WM_XBUTTONDOWN: {
if (get_enabled() && get_auto_focus() && GetFocus() != wnd)
SetFocus(wnd);
if (m_dragging) {
destroy_tooltip();
if (GetCapture() == wnd)
ReleaseCapture();
uih::deregister_message_hook(uih::MessageHookType::type_keyboard, this);
m_hook_registered = false;
// SetFocus(IsWindow(m_wnd_prev) ? m_wnd_prev : uFindParentPopup(wnd));
m_dragging = false;
set_position_internal(m_position);
}
} break;
case WM_LBUTTONDOWN: {
if (get_enabled()) {
if (get_auto_focus() && GetFocus() != wnd)
SetFocus(wnd);
POINT pt;
pt.x = GET_X_LPARAM(lp);
pt.y = GET_Y_LPARAM(lp);
RECT rc_client;
GetClientRect(wnd, &rc_client);
if (PtInRect(&rc_client, pt)) {
m_dragging = true;
SetCapture(wnd);
// SetFocus(wnd);
uih::register_message_hook(uih::MessageHookType::type_keyboard, this);
m_hook_registered = true;
unsigned pos = calculate_position_from_point(pt);
set_position_internal(pos);
POINT pts = pt;
ClientToScreen(wnd, &pts);
if (m_show_tooltips && m_host) {
TrackbarString temp;
m_host->get_tooltip_text(pos, temp);
create_tooltip(temp.data(), pts);
}
}
m_last_mousemove.m_valid = false;
}
}
return 0;
case WM_LBUTTONUP: {
if (m_dragging) {
destroy_tooltip();
if (GetCapture() == wnd)
ReleaseCapture();
m_dragging = false;
if (get_enabled()) {
POINT pt;
pt.x = GET_X_LPARAM(lp);
pt.y = GET_Y_LPARAM(lp);
unsigned pos = calculate_position_from_point(pt);
set_position(pos);
}
// SetFocus(IsWindow(m_wnd_prev) ? m_wnd_prev : uFindParentPopup(wnd));
uih::deregister_message_hook(uih::MessageHookType::type_keyboard, this);
m_hook_registered = false;
if (m_host)
m_host->on_position_change(m_display_position, false);
m_last_mousemove.m_valid = false;
}
}
return 0;
case WM_KEYDOWN:
case WM_KEYUP: {
if ((wp == VK_ESCAPE || wp == VK_RETURN) && m_host && m_host->on_key(wp, lp))
return 0;
if (!(lp & (1 << 31)) && (wp == VK_LEFT || wp == VK_DOWN || wp == VK_RIGHT || wp == VK_UP)) {
bool down = !(wp == VK_LEFT || wp == VK_UP); //! get_direction();
unsigned newpos = m_position;
if (down && m_step > m_position)
newpos = 0;
else if (!down && m_step + m_position > m_range)
newpos = m_range;
else
newpos += down ? -(int)m_step : m_step;
if (newpos != m_position) {
set_position(newpos);
if (m_host)
m_host->on_position_change(m_position, false);
}
}
if (!(lp & (1 << 31)) && (wp == VK_HOME || wp == VK_END)) {
bool down = wp != VK_END; //! get_direction();
unsigned newpos;
if (down)
newpos = m_range;
else
newpos = 0;
if (newpos != m_position) {
set_position(newpos);
if (m_host)
m_host->on_position_change(m_position, false);
}
}
} break;
case WM_MOUSEWHEEL: {
UINT ucNumLines = 3; // 3 is the default
SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, &ucNumLines, 0);
short zDelta = GET_WHEEL_DELTA_WPARAM(wp);
if (ucNumLines == WHEEL_PAGESCROLL)
ucNumLines = 3;
int delta = MulDiv(m_step * zDelta, ucNumLines, WHEEL_DELTA);
bool down = delta < 0;
// if (get_direction()) down = down == false;
if (!get_orientation())
down = !down;
if (m_mouse_wheel_reversed)
down = !down;
unsigned offset = abs(delta);
unsigned newpos = m_position;
if (down && offset > m_position)
newpos = 0;
else if (!down && offset + m_position > m_range)
newpos = m_range;
else
newpos += down ? -static_cast<int>(offset) : offset;
if (newpos != m_position) {
set_position(newpos);
if (m_host)
m_host->on_position_change(m_position, false);
}
}
return 0;
#if 0
case WM_KEYDOWN:
if (wp == VK_ESCAPE)
{
destroy_tooltip();
if (GetCapture() == wnd)
ReleaseCapture();
SetFocus(IsWindow(m_wnd_prev) ? m_wnd_prev : uFindParentPopup(wnd));
m_dragging = false;
set_position_internal(m_position);
return 0;
}
break;
case WM_SETFOCUS:
m_wnd_prev = (HWND)wp;
break;
#endif
case WM_MOVE:
RedrawWindow(wnd, nullptr, nullptr, RDW_ERASE | RDW_INVALIDATE);
break;
case WM_ERASEBKGND:
return FALSE;
case WM_PAINT: {
RECT rc_client;
GetClientRect(wnd, &rc_client);
PAINTSTRUCT ps;
HDC dc = BeginPaint(wnd, &ps);
RECT rc_thumb;
get_thumb_rect(&rc_thumb);
RECT rc_track; // channel
get_channel_rect(&rc_track);
// Offscreen rendering to eliminate flicker
HDC dc_mem = CreateCompatibleDC(dc);
// Create a rect same size of update rect
HBITMAP bm_mem = CreateCompatibleBitmap(dc, rc_client.right, rc_client.bottom);
auto bm_old = (HBITMAP)SelectObject(dc_mem, bm_mem);
// we should always be erasing first, so shouldn't be needed
BitBlt(dc_mem, 0, 0, rc_client.right, rc_client.bottom, dc, 0, 0, SRCCOPY);
if (ps.fErase) {
draw_background(dc_mem, &rc_client);
}
draw_channel(dc_mem, &rc_track);
draw_thumb(dc_mem, &rc_thumb);
BitBlt(dc, 0, 0, rc_client.right, rc_client.bottom, dc_mem, 0, 0, SRCCOPY);
SelectObject(dc_mem, bm_old);
DeleteObject(bm_mem);
DeleteDC(dc_mem);
EndPaint(wnd, &ps);
}
return 0;
}
return DefWindowProc(wnd, msg, wp, lp);
}
} // namespace uih
| 30.377415 | 120 | 0.589513 | reupen |
928294383946e7e2df7d4757bcc7c02cc26b1caf | 3,323 | cpp | C++ | src/dropbox/sharing/SharingMountFolderError.cpp | slashdotted/dropboxQt | 63d43fa882cec8fb980a2aab2464a2d7260b8089 | [
"MIT"
] | 17 | 2016-12-03T09:12:29.000Z | 2020-06-20T22:08:44.000Z | src/dropbox/sharing/SharingMountFolderError.cpp | slashdotted/dropboxQt | 63d43fa882cec8fb980a2aab2464a2d7260b8089 | [
"MIT"
] | 8 | 2017-01-05T17:50:16.000Z | 2021-08-06T18:56:29.000Z | src/dropbox/sharing/SharingMountFolderError.cpp | slashdotted/dropboxQt | 63d43fa882cec8fb980a2aab2464a2d7260b8089 | [
"MIT"
] | 8 | 2017-09-13T17:28:40.000Z | 2020-07-27T00:41:44.000Z | /**********************************************************
DO NOT EDIT
This file was generated from stone specification "sharing"
Part of "Ardi - the organizer" project.
osoft4ardi@gmail.com
www.prokarpaty.net
***********************************************************/
#include "dropbox/sharing/SharingMountFolderError.h"
namespace dropboxQt{
namespace sharing{
///MountFolderError
MountFolderError::operator QJsonObject()const{
QJsonObject js;
this->toJson(js, "");
return js;
}
void MountFolderError::toJson(QJsonObject& js, QString name)const{
switch(m_tag){
case MountFolderError_ACCESS_ERROR:{
if(!name.isEmpty())
js[name] = QString("access_error");
m_access_error.toJson(js, "access_error");
}break;
case MountFolderError_INSIDE_SHARED_FOLDER:{
if(!name.isEmpty())
js[name] = QString("inside_shared_folder");
}break;
case MountFolderError_INSUFFICIENT_QUOTA:{
if(!name.isEmpty())
js[name] = QString("insufficient_quota");
js["insufficient_quota"] = (QJsonObject)m_insufficient_quota;
}break;
case MountFolderError_ALREADY_MOUNTED:{
if(!name.isEmpty())
js[name] = QString("already_mounted");
}break;
case MountFolderError_NO_PERMISSION:{
if(!name.isEmpty())
js[name] = QString("no_permission");
}break;
case MountFolderError_NOT_MOUNTABLE:{
if(!name.isEmpty())
js[name] = QString("not_mountable");
}break;
case MountFolderError_OTHER:{
if(!name.isEmpty())
js[name] = QString("other");
}break;
}//switch
}
void MountFolderError::fromJson(const QJsonObject& js){
QString s = js[".tag"].toString();
if(s.compare("access_error") == 0){
m_tag = MountFolderError_ACCESS_ERROR;
m_access_error.fromJson(js["access_error"].toObject());
}
else if(s.compare("inside_shared_folder") == 0){
m_tag = MountFolderError_INSIDE_SHARED_FOLDER;
}
else if(s.compare("insufficient_quota") == 0){
m_tag = MountFolderError_INSUFFICIENT_QUOTA;
m_insufficient_quota.fromJson(js["insufficient_quota"].toObject());
}
else if(s.compare("already_mounted") == 0){
m_tag = MountFolderError_ALREADY_MOUNTED;
}
else if(s.compare("no_permission") == 0){
m_tag = MountFolderError_NO_PERMISSION;
}
else if(s.compare("not_mountable") == 0){
m_tag = MountFolderError_NOT_MOUNTABLE;
}
else if(s.compare("other") == 0){
m_tag = MountFolderError_OTHER;
}
}
QString MountFolderError::toString(bool multiline)const
{
QJsonObject js;
toJson(js, "MountFolderError");
QJsonDocument doc(js);
QString s(doc.toJson(multiline ? QJsonDocument::Indented : QJsonDocument::Compact));
return s;
}
std::unique_ptr<MountFolderError> MountFolderError::factory::create(const QByteArray& data)
{
QJsonDocument doc = QJsonDocument::fromJson(data);
QJsonObject js = doc.object();
std::unique_ptr<MountFolderError> rv = std::unique_ptr<MountFolderError>(new MountFolderError);
rv->fromJson(js);
return rv;
}
}//sharing
}//dropboxQt
| 29.669643 | 99 | 0.616611 | slashdotted |
9286be102837112c957c8b89fb5642cf1d8e72e7 | 3,631 | h++ | C++ | css/grammar/position.h++ | rubenvb/skui | 5bda2d73232eb7a763ba9d788c7603298767a7d7 | [
"MIT"
] | 19 | 2016-10-13T22:44:31.000Z | 2021-12-28T20:28:15.000Z | css/grammar/position.h++ | rubenvb/skui | 5bda2d73232eb7a763ba9d788c7603298767a7d7 | [
"MIT"
] | 1 | 2021-05-16T15:15:22.000Z | 2021-05-16T17:01:26.000Z | css/grammar/position.h++ | rubenvb/skui | 5bda2d73232eb7a763ba9d788c7603298767a7d7 | [
"MIT"
] | 4 | 2017-03-07T05:37:02.000Z | 2018-06-05T03:14:48.000Z | /**
* The MIT License (MIT)
*
* Copyright © 2019 Ruben Van Boxem
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
**/
#ifndef SKUI_CSS_GRAMMAR_POSITION_H
#define SKUI_CSS_GRAMMAR_POSITION_H
#include "css/length.h++"
#include "css/position.h++"
#include "css/grammar/as.h++"
#include "css/grammar/length.h++"
#include <core/debug.h++>
#include <boost/spirit/home/x3.hpp>
#include <boost/fusion/adapted/struct.hpp>
#include <boost/fusion/adapted/struct/adapt_struct_named.hpp>
BOOST_FUSION_ADAPT_STRUCT(skui::css::position,
x,
y)
BOOST_FUSION_ADAPT_STRUCT(skui::css::length_with_offset,
value,
offset)
namespace skui::css::grammar
{
namespace x3 = boost::spirit::x3;
constexpr auto swap_x_y = [](auto& context)
{
css::position& position = x3::_attr(context);
std::swap(position.x, position.y);
};
struct horizontal_relative_position_table : x3::symbols<css::length>
{
horizontal_relative_position_table();
} const horizontal_relative_position;
struct vertical_relative_position_table : x3::symbols<css::length>
{
vertical_relative_position_table();
} const vertical_relative_position;
const auto horizontal_position = x3::rule<struct horizontal_position, css::length_with_offset>{"horizontal_position"}
= horizontal_relative_position >> -length_percentage
| x3::lit('0') >> x3::attr(css::length{}) >> x3::attr(css::length{})
| length_percentage >> x3::attr(css::length{})
;
const auto vertical_position = x3::rule<struct vertical_position, css::length_with_offset>{"vertical_position"}
= vertical_relative_position >> -length_percentage
| x3::lit('0') >> x3::attr(css::length{}) >> x3::attr(css::length{})
| length_percentage >> x3::attr(css::length{})
;
//| vertical_relative_position
const auto position = x3::rule<struct position_, css::position>{"position"}
%= horizontal_position >> vertical_position
| (vertical_position >> horizontal_position)[swap_x_y]
| horizontal_position >> x3::attr(css::length_with_offset{{50, unit::percentage}, {}})
| (vertical_position >> x3::attr(css::length_with_offset{{50, unit::percentage}, {}}))[swap_x_y]
;
}
#endif
| 41.261364 | 119 | 0.645001 | rubenvb |
9287a02a7a544d3aaeafe4518ec15a307887a178 | 6,347 | cpp | C++ | app/parse_kml.cpp | JaviBonilla/SolarPILOT | c535313484018597e8029202e764ec8e834839a5 | [
"MIT"
] | 26 | 2018-03-21T17:26:44.000Z | 2022-02-07T05:55:47.000Z | app/parse_kml.cpp | JaviBonilla/SolarPILOT | c535313484018597e8029202e764ec8e834839a5 | [
"MIT"
] | 38 | 2018-03-09T17:54:49.000Z | 2022-01-28T16:28:29.000Z | app/parse_kml.cpp | JaviBonilla/SolarPILOT | c535313484018597e8029202e764ec8e834839a5 | [
"MIT"
] | 11 | 2018-03-17T09:36:51.000Z | 2022-02-02T10:13:47.000Z |
/*******************************************************************************************************
* Copyright 2018 Alliance for Sustainable Energy, LLC
*
* NOTICE: This software was developed at least in part by Alliance for Sustainable Energy, LLC
* ("Alliance") under Contract No. DE-AC36-08GO28308 with the U.S. Department of Energy and the U.S.
* The Government retains for itself and others acting on its behalf a nonexclusive, paid-up,
* irrevocable worldwide license in the software to reproduce, prepare derivative works, distribute
* copies to the public, perform publicly and display publicly, and to permit others to do so.
*
* 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, the above government
* rights notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, the above government
* rights notice, this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3. The entire corresponding source code of any redistribution, with or without modification, by a
* research entity, including but not limited to any contracting manager/operator of a United States
* National Laboratory, any institution of higher learning, and any non-profit organization, must be
* made publicly available under this license for as long as the redistribution is made available by
* the research entity.
*
* 4. Redistribution of this software, without modification, must refer to the software by the same
* designation. Redistribution of a modified version of this software (i) may not refer to the modified
* version by the same designation, or by any confusingly similar designation, and (ii) must refer to
* the underlying software originally provided by Alliance as "Solar Power tower Integrated Layout and
* Optimization Tool" or "SolarPILOT". Except to comply with the foregoing, the terms "Solar Power
* tower Integrated Layout and Optimization Tool", "SolarPILOT", or any confusingly similar
* designation may not be used to refer to any modified version of this software or any modified
* version of the underlying software originally provided by Alliance without the prior written consent
* of Alliance.
*
* 5. The name of the copyright holder, contributors, the United States Government, the United States
* Department of Energy, or any of their employees may not 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,
* CONTRIBUTORS, UNITED STATES GOVERNMENT OR UNITED STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR
* EMPLOYEES, BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************************************/
/*
Library for parsing KML files (Google Earth format), based on XML.
code.google.com/p/libkml/
https://developers.google.com/kml/documentation/kmlreference
*/
#include "parse_kml.h"
#include <wx/string.h>
#include <rapidxml.hpp>
#include "gui_util.h"
using namespace rapidxml;
void ParseKML(wxString &file, double &tower_lat, double &tower_lon, std::vector<sp_point> &poly)
{
/*
Parse the KML polygon and create a formatted polygon to be used by the bounds grid.
The format for the bounds grid is:
[POLY][P]x1,y1,z1[P]x2,y2,z2...
The "poly" vector is NOT CLEARED by this method. Be sure to clear it before calling, if needed.
*/
//We have to copy the file onto the heap as a char* since the xml parser points to permanent
//memory locations. The wxString buffers are temporary.
char *fstr = new char[file.size()+1];
strncpy(fstr, (const char*)file.mb_str(), file.size());
fstr[file.size()] = 0; //Null terminator
xml_document<> doc;
doc.parse<0>(fstr);
xml_node<> *node = doc.first_node()->first_node("Document")->first_node("Placemark");
double
tlatr = tower_lat*D2R,
tlonr = tower_lon*D2R,
r_earth = 6371009.; //Radius of the earth in meters
while(node != 0)
{
wxString coords = (std::string)node->
first_node("Polygon")->
first_node("outerBoundaryIs")->
first_node("LinearRing")->
first_node("coordinates")->value();
coords.Trim(false); //Remove leading tabs and newlines
coords.Trim(); //Remove trailing junk
//Construct the polygon
std::vector<std::string> pp = split(coords.ToStdString(), " ");
for(unsigned int i=0; i<pp.size(); i++)
{
//Convert point values into doubles
std::vector<std::string> ps = split(pp.at(i),",");
double
plat, plon;
to_double(ps.at(1), &plat);
to_double(ps.at(0), &plon);
plat *= D2R;
plon *= D2R;
//Convert degrees into meters
double dist = r_earth*acos( sin(tlatr)*sin(plat) + cos(tlatr)*cos(plat)*cos(tlonr - plon) );
double dy = (plat < tlatr ? -1. : 1.)*r_earth*acos( sin(tlatr)*sin(plat) + cos(tlatr)*cos(plat) );
double dx = (plon < tlonr ? -1. : 1.)*sqrt( pow(dist, 2) - pow(dy, 2) );
poly.push_back(sp_point(dx, dy, 0.));
}
//Update to the new sibling node
node = node->next_sibling();
}
delete [] fstr;
}
| 46.328467 | 110 | 0.676067 | JaviBonilla |
92881cb14b49dc3defa4400678c987491d0cbee3 | 714 | cpp | C++ | lucas/tep/2019-1/Contest4/f.cpp | medeiroslucas/lo-and-behold-pp | d2be16f9b108b501fd9fccf173e741c93350cee4 | [
"MIT"
] | 2 | 2019-09-09T00:34:40.000Z | 2019-09-09T17:35:19.000Z | lucas/tep/2019-1/Contest4/f.cpp | medeiroslucas/lo-and-behold-pp | d2be16f9b108b501fd9fccf173e741c93350cee4 | [
"MIT"
] | null | null | null | lucas/tep/2019-1/Contest4/f.cpp | medeiroslucas/lo-and-behold-pp | d2be16f9b108b501fd9fccf173e741c93350cee4 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
const double PI = acos(-1.0);
const double oo = 100000000;
int main(){
int N;
double max=-oo, min=oo, area;
pair<double, double> p, pontos;
cin >> N >> p.first >> p.second;
while(N--){
cin >> pontos.first >> pontos.second;
if(hypot(p.first - pontos.first, p.second - pontos.second) > max){
max = hypot(p.first - pontos.first, p.second - pontos.second);
}
if(hypot(p.first - pontos.first, p.second - pontos.second) < min){
min = hypot(p.first - pontos.first, p.second - pontos.second);
}
}
area = PI*(max*max - min*min);
printf("%.10lf\n", area);
return 0;
} | 21 | 74 | 0.556022 | medeiroslucas |
928946ea867daf7caf6944d0c51edfee2527dd3b | 1,712 | cpp | C++ | Tries/Tries_Creation.cpp | susantabiswas/placementPrep | 22a7574206ddc63eba89517f7b68a3d2f4d467f5 | [
"MIT"
] | 19 | 2018-12-02T05:59:44.000Z | 2021-07-24T14:11:54.000Z | Tries/Tries_Creation.cpp | susantabiswas/placementPrep | 22a7574206ddc63eba89517f7b68a3d2f4d467f5 | [
"MIT"
] | null | null | null | Tries/Tries_Creation.cpp | susantabiswas/placementPrep | 22a7574206ddc63eba89517f7b68a3d2f4d467f5 | [
"MIT"
] | 13 | 2019-04-25T16:20:00.000Z | 2021-09-06T19:50:04.000Z | #include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
//trie structure
struct TrieNode
{
struct TrieNode* child[26];
bool is_str_end;
};
//to create a trieNode type node
struct TrieNode* createNode()
{
struct TrieNode *t=new struct TrieNode;
if(t)
{
t->is_str_end=false;
for (int i = 0; i < 26; ++i)
{
t->child[i]=NULL;
}
return t;
}
else
return NULL;
}
//to insert a new character in the Trie ,if it is already present then ignore and
//keep on traversing else insert the key
void InsertNode(struct TrieNode *root,string word)
{
int index; //for storing the index of the character in a-z
struct TrieNode *t=root;
for(int i=0;i<word.length();i++)
{
index=word[i]-'a';
if(t->child[index]==NULL)
t->child[index]=createNode();
t=t->child[index];
}
//when finally the string end
t->is_str_end=true;
}
//searches the string in the Trie
bool searchString(struct TrieNode *root,string word)
{
int index;
struct TrieNode *t=root;
for (int i = 0; i <word.length(); ++i)
{
index=word[i]-'a';
if(t->child[index]==NULL)
{
return false;
}
t=t->child[index];
}
if(t!=NULL && t->is_str_end==true)
return true;
}
int main()
{
// Input keys (use only 'a' through 'z' and lower case)
string word[8] = {"the", "a", "there", "answer", "any",
"by", "bye", "their"};
struct TrieNode *root = createNode();
// Construct trie
for (int i = 0; i < sizeof(word)/sizeof(string); i++)
InsertNode(root, word[0]);
// Search for different keys
cout<<"them:"<<searchString(root,"thek")<<endl;
return 0;
}
| 19.906977 | 81 | 0.595794 | susantabiswas |
928a1b8acf955a585769bd23c02264da1badaafa | 11,662 | cpp | C++ | redgpu_memory_allocator_functions.cpp | procedural/redgpu_memory_allocator_dma | 4eedd04b9983cde624e91dd1ec4294ac2de73697 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | redgpu_memory_allocator_functions.cpp | procedural/redgpu_memory_allocator_dma | 4eedd04b9983cde624e91dd1ec4294ac2de73697 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | redgpu_memory_allocator_functions.cpp | procedural/redgpu_memory_allocator_dma | 4eedd04b9983cde624e91dd1ec4294ac2de73697 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | #include "redgpu_memory_allocator_functions.h"
REDGPU_DECLSPEC void REDGPU_API rmaDmaVkGetPhysicalDeviceProperties2(RedContext context, unsigned gpuIndex, VkPhysicalDevice physicalDevice, VkPhysicalDeviceProperties2 * pProperties) {
// NOTE(Constantine): Hardcoded for memorymanagement_vk.cpp:292
VkPhysicalDeviceMaintenance3Properties * maintenance3 = (VkPhysicalDeviceMaintenance3Properties *)pProperties->pNext;
maintenance3->maxMemoryAllocationSize = context->gpus[gpuIndex].maxMemoryAllocateBytesCount;
}
REDGPU_DECLSPEC void REDGPU_API rmaDmaVkGetPhysicalDeviceMemoryProperties(RedContext context, unsigned gpuIndex, VkPhysicalDevice physicalDevice, VkPhysicalDeviceMemoryProperties * pMemoryProperties) {
VkPhysicalDeviceMemoryProperties properties = {};
properties.memoryTypeCount = context->gpus[gpuIndex].memoryTypesCount;
properties.memoryHeapCount = context->gpus[gpuIndex].memoryHeapsCount;
for (unsigned i = 0; i < context->gpus[gpuIndex].memoryTypesCount; i += 1) {
RedMemoryType memoryType = context->gpus[gpuIndex].memoryTypes[i];
properties.memoryTypes[i].heapIndex = memoryType.memoryHeapIndex;
if (memoryType.isGpuVram == 1) {
properties.memoryTypes[i].propertyFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
}
if (memoryType.isCpuMappable == 1) {
properties.memoryTypes[i].propertyFlags |= VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
}
if (memoryType.isCpuCoherent == 1) {
properties.memoryTypes[i].propertyFlags |= VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
}
if (memoryType.isCpuCached == 1) {
properties.memoryTypes[i].propertyFlags |= VK_MEMORY_PROPERTY_HOST_CACHED_BIT;
}
}
for (unsigned i = 0; i < context->gpus[gpuIndex].memoryHeapsCount; i += 1) {
RedMemoryHeap memoryHeap = context->gpus[gpuIndex].memoryHeaps[i];
properties.memoryHeaps[i].size = memoryHeap.memoryBytesCount;
if (memoryHeap.isGpuVram == 1) {
properties.memoryHeaps[i].flags |= VK_MEMORY_HEAP_DEVICE_LOCAL_BIT;
}
}
pMemoryProperties[0] = properties;
}
REDGPU_DECLSPEC VkResult REDGPU_API rmaDmaVkAllocateMemory(RedContext context, unsigned gpuIndex, VkDevice device, const VkMemoryAllocateInfo * pAllocateInfo, const VkAllocationCallbacks * pAllocator, VkDeviceMemory * pMemory, const char * name) {
RedStatuses statuses = {};
if (context->gpus[gpuIndex].memoryTypes[pAllocateInfo->memoryTypeIndex].isCpuMappable == 1) {
// NOTE(Constantine): Pass array from DMA to RMA in future.
RedHandleArray array = 0;
redMemoryAllocateMappable(context, (RedHandleGpu)device, name, 0, array, pAllocateInfo->allocationSize, pAllocateInfo->memoryTypeIndex, 0, (RedHandleMemory *)pMemory, &statuses, 0, 0, 0);
} else {
redMemoryAllocate(context, (RedHandleGpu)device, name, pAllocateInfo->allocationSize, pAllocateInfo->memoryTypeIndex, 0, 0, 0, (RedHandleMemory *)pMemory, &statuses, 0, 0, 0);
}
return (VkResult)statuses.statusError;
}
REDGPU_DECLSPEC void REDGPU_API rmaDmaVkFreeMemory(RedContext context, unsigned gpuIndex, VkDevice device, VkDeviceMemory memory, const VkAllocationCallbacks * pAllocator) {
redMemoryFree(context, (RedHandleGpu)device, (RedHandleMemory)memory, 0, 0, 0);
}
REDGPU_DECLSPEC VkResult REDGPU_API rmaDmaVkMapMemory(RedContext context, unsigned gpuIndex, VkDevice device, VkDeviceMemory memory, VkDeviceSize offset, VkDeviceSize size, VkMemoryMapFlags flags, void ** ppData) {
RedStatuses statuses = {};
redMemoryMap(context, (RedHandleGpu)device, (RedHandleMemory)memory, offset, size, ppData, &statuses, 0, 0, 0);
return (VkResult)statuses.statusError;
}
REDGPU_DECLSPEC void REDGPU_API rmaDmaVkUnmapMemory(RedContext context, unsigned gpuIndex, VkDevice device, VkDeviceMemory memory) {
redMemoryUnmap(context, (RedHandleGpu)device, (RedHandleMemory)memory, 0, 0, 0);
}
REDGPU_DECLSPEC VkResult REDGPU_API rmaDmaVkBindBufferMemory2(RedContext context, unsigned gpuIndex, VkDevice device, uint32_t bindInfoCount, const VkBindBufferMemoryInfo * pBindInfos) {
RedStatuses statuses = {};
redMemorySet(context, (RedHandleGpu)device, bindInfoCount, (const RedMemoryArray *)pBindInfos, 0, 0, &statuses, 0, 0, 0);
return (VkResult)statuses.statusError;
}
REDGPU_DECLSPEC VkResult REDGPU_API rmaDmaVkBindImageMemory2(RedContext context, unsigned gpuIndex, VkDevice device, uint32_t bindInfoCount, const VkBindImageMemoryInfo * pBindInfos) {
RedStatuses statuses = {};
redMemorySet(context, (RedHandleGpu)device, 0, 0, bindInfoCount, (const RedMemoryImage *)pBindInfos, &statuses, 0, 0, 0);
return (VkResult)statuses.statusError;
}
REDGPU_DECLSPEC void REDGPU_API rmaDmaVkGetBufferMemoryRequirements2(RedContext context, unsigned gpuIndex, VkDevice device, const RedVkBuffer * pInfo, VkMemoryRequirements2 * pMemoryRequirements) {
pMemoryRequirements->memoryRequirements.size = pInfo->memoryBytesCount;
pMemoryRequirements->memoryRequirements.alignment = pInfo->memoryBytesAlignment;
pMemoryRequirements->memoryRequirements.memoryTypeBits = pInfo->memoryTypesSupported;
// NOTE(Constantine): Explicitly ignoring VkMemoryDedicatedRequirements in pMemoryRequirements->pNext.
}
REDGPU_DECLSPEC void REDGPU_API rmaDmaVkGetImageMemoryRequirements2(RedContext context, unsigned gpuIndex, VkDevice device, const RedVkImage * pInfo, VkMemoryRequirements2 * pMemoryRequirements) {
pMemoryRequirements->memoryRequirements.size = pInfo->memoryBytesCount;
pMemoryRequirements->memoryRequirements.alignment = pInfo->memoryBytesAlignment;
pMemoryRequirements->memoryRequirements.memoryTypeBits = pInfo->memoryTypesSupported;
// NOTE(Constantine): Explicitly ignoring VkMemoryDedicatedRequirements in pMemoryRequirements->pNext.
}
REDGPU_DECLSPEC VkResult REDGPU_API rmaDmaVkCreateBuffer(RedContext context, unsigned gpuIndex, VkDevice device, const VkBufferCreateInfo * pCreateInfo, const VkAllocationCallbacks * pAllocator, RedVkBuffer * pBuffer) {
RedStatuses statuses = {};
// NOTE(Constantine): Pass structuredBufferElementBytesCount from DMA to RMA in future.
uint64_t structuredBufferElementBytesCount = 0;
// NOTE(Constantine): Pass initialAccess from DMA to RMA in future.
RedAccessBitflags initialAccess = 0;
RedArray array = {};
redCreateArray(context, (RedHandleGpu)device, "REDGPU Memory Allocator DMA", (RedArrayType)pCreateInfo->usage, pCreateInfo->size, structuredBufferElementBytesCount, initialAccess, (pCreateInfo->sharingMode == VK_SHARING_MODE_CONCURRENT || pCreateInfo->queueFamilyIndexCount == 0) ? -1 : pCreateInfo->pQueueFamilyIndices[0], 0, &array, &statuses, 0, 0, 0);
RedVkBuffer * anArray = (RedVkBuffer *)&array;
pBuffer[0] = anArray[0];
return (VkResult)statuses.statusError;
}
REDGPU_DECLSPEC void REDGPU_API rmaDmaVkDestroyBuffer(RedContext context, unsigned gpuIndex, VkDevice device, VkBuffer buffer, const VkAllocationCallbacks * pAllocator) {
redDestroyArray(context, (RedHandleGpu)device, (RedHandleArray)buffer, 0, 0, 0);
}
REDGPU_DECLSPEC VkResult REDGPU_API rmaDmaVkCreateImage(RedContext context, unsigned gpuIndex, VkDevice device, const VkImageCreateInfo * pCreateInfo, const VkAllocationCallbacks * pAllocator, RedVkImage * pImage) {
RedStatuses statuses = {};
RedImageDimensions imageDimensions = RED_IMAGE_DIMENSIONS_2D;
if (pCreateInfo->imageType == VK_IMAGE_TYPE_1D) {
imageDimensions = RED_IMAGE_DIMENSIONS_1D;
} else if (pCreateInfo->imageType == VK_IMAGE_TYPE_2D && ((pCreateInfo->flags & VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT) == VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT)) {
imageDimensions = RED_IMAGE_DIMENSIONS_2D_WITH_TEXTURE_DIMENSIONS_CUBE_AND_CUBE_LAYERED;
} else if (pCreateInfo->imageType == VK_IMAGE_TYPE_2D) {
imageDimensions = RED_IMAGE_DIMENSIONS_2D;
} else if (pCreateInfo->imageType == VK_IMAGE_TYPE_3D && ((pCreateInfo->flags & VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT) == VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT)) {
imageDimensions = RED_IMAGE_DIMENSIONS_3D_WITH_TEXTURE_DIMENSIONS_2D_AND_2D_LAYERED;
} else if (pCreateInfo->imageType == VK_IMAGE_TYPE_3D) {
imageDimensions = RED_IMAGE_DIMENSIONS_3D;
}
RedAccessBitflags restrictToAccess = 0;
if ((pCreateInfo->usage & VK_IMAGE_USAGE_TRANSFER_SRC_BIT) == VK_IMAGE_USAGE_TRANSFER_SRC_BIT) {
restrictToAccess |= RED_ACCESS_BITFLAG_COPY_R;
}
if ((pCreateInfo->usage & VK_IMAGE_USAGE_TRANSFER_DST_BIT) == VK_IMAGE_USAGE_TRANSFER_DST_BIT) {
restrictToAccess |= RED_ACCESS_BITFLAG_COPY_W;
}
if ((pCreateInfo->usage & VK_IMAGE_USAGE_SAMPLED_BIT) == VK_IMAGE_USAGE_SAMPLED_BIT) {
restrictToAccess |= RED_ACCESS_BITFLAG_STRUCT_RESOURCE_NON_FRAGMENT_STAGE_R | RED_ACCESS_BITFLAG_STRUCT_RESOURCE_FRAGMENT_STAGE_R;
}
if ((pCreateInfo->usage & VK_IMAGE_USAGE_STORAGE_BIT) == VK_IMAGE_USAGE_STORAGE_BIT) {
restrictToAccess |= RED_ACCESS_BITFLAG_STRUCT_RESOURCE_W;
}
if ((pCreateInfo->usage & VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) == VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) {
restrictToAccess |= RED_ACCESS_BITFLAG_OUTPUT_COLOR_W;
}
if ((pCreateInfo->usage & VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) == VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
restrictToAccess |= RED_ACCESS_BITFLAG_OUTPUT_DEPTH_RW;
if ((RedFormat)pCreateInfo->format == RED_FORMAT_DEPTH_24_UINT_TO_FLOAT_0_1_STENCIL_8_UINT ||
(RedFormat)pCreateInfo->format == RED_FORMAT_DEPTH_32_FLOAT_STENCIL_8_UINT)
{
restrictToAccess |= RED_ACCESS_BITFLAG_OUTPUT_STENCIL_RW;
}
}
// NOTE(Constantine): Pass initialAccess from DMA to RMA in future.
RedAccessBitflags initialAccess = 0;
RedImage image = {};
redCreateImage(context, (RedHandleGpu)device, "REDGPU Memory Allocator DMA", imageDimensions, (RedFormat)pCreateInfo->format, pCreateInfo->extent.width, pCreateInfo->extent.height, pCreateInfo->extent.depth, pCreateInfo->mipLevels, pCreateInfo->arrayLayers, (RedMultisampleCountBitflag)pCreateInfo->samples, restrictToAccess, initialAccess, (pCreateInfo->sharingMode == VK_SHARING_MODE_CONCURRENT || pCreateInfo->queueFamilyIndexCount == 0) ? -1 : pCreateInfo->pQueueFamilyIndices[0], 0, &image, &statuses, 0, 0, 0);
RedVkImage * anImage = (RedVkImage *)ℑ
pImage[0] = anImage[0];
return (VkResult)statuses.statusError;
}
REDGPU_DECLSPEC void REDGPU_API rmaDmaVkDestroyImage(RedContext context, unsigned gpuIndex, VkDevice device, VkImage image, const VkAllocationCallbacks * pAllocator) {
redDestroyImage(context, (RedHandleGpu)device, (RedHandleImage)image, 0, 0, 0);
}
REDGPU_DECLSPEC void REDGPU_API rmaDmaVkCmdInsertDebugUtilsLabelEXT(RedContext context, unsigned gpuIndex, VkCommandBuffer commandBuffer, const VkDebugUtilsLabelEXT * pLabelInfo) {
RedCallProceduresAndAddresses callPAs;
redGetCallProceduresAndAddresses(context, context->gpus[gpuIndex].gpu, &callPAs, 0, 0, 0, 0);
redCallMark(callPAs.redCallMark, (RedHandleCalls)commandBuffer, pLabelInfo->pLabelName);
}
REDGPU_DECLSPEC void REDGPU_API rmaDmaVkCmdBeginDebugUtilsLabelEXT(RedContext context, unsigned gpuIndex, VkCommandBuffer commandBuffer, const VkDebugUtilsLabelEXT * pLabelInfo) {
RedCallProceduresAndAddresses callPAs;
redGetCallProceduresAndAddresses(context, context->gpus[gpuIndex].gpu, &callPAs, 0, 0, 0, 0);
redCallMarkSet(callPAs.redCallMarkSet, (RedHandleCalls)commandBuffer, pLabelInfo->pLabelName);
}
REDGPU_DECLSPEC void REDGPU_API rmaDmaVkCmdEndDebugUtilsLabelEXT(RedContext context, unsigned gpuIndex, VkCommandBuffer commandBuffer) {
RedCallProceduresAndAddresses callPAs;
redGetCallProceduresAndAddresses(context, context->gpus[gpuIndex].gpu, &callPAs, 0, 0, 0, 0);
redCallMarkEnd(callPAs.redCallMarkEnd, (RedHandleCalls)commandBuffer);
}
| 66.261364 | 518 | 0.799005 | procedural |
928af9ec5d4404c56d6ddffcaa048fc46f6a94ab | 1,347 | cpp | C++ | src/server/db/db.cpp | ETinyfish/TEST | 255014beb178878d8b0a466e0fd61fc26c1d8445 | [
"MIT"
] | null | null | null | src/server/db/db.cpp | ETinyfish/TEST | 255014beb178878d8b0a466e0fd61fc26c1d8445 | [
"MIT"
] | null | null | null | src/server/db/db.cpp | ETinyfish/TEST | 255014beb178878d8b0a466e0fd61fc26c1d8445 | [
"MIT"
] | 1 | 2021-06-30T05:55:32.000Z | 2021-06-30T05:55:32.000Z | #include "db.h"
#include <muduo/base/Logging.h>
// 数据库配置信息
static string server = "127.0.0.1";
static string user = "root";
static string password = "123";
static string dbname = "chat_server";
// 初始化数据库连接
MySQL::MySQL()
{
_conn = mysql_init(nullptr);
}
// 释放数据库连接资源
MySQL::~MySQL()
{
if (_conn != nullptr)
mysql_close(_conn);
}
// 连接数据库
bool MySQL::connect()
{
MYSQL *p = mysql_real_connect(_conn, server.c_str(), user.c_str(),
password.c_str(), dbname.c_str(), 3306, nullptr, 0);
if (p != nullptr)
{
// C和C++代码默认的编码字符是ASCII,如果不设置,从MySQL上拉下来的中文显示?
mysql_query(_conn, "set names gbk");
LOG_INFO << "connect mysql success!";
}
else
{
LOG_INFO << "connect mysql fail!";
}
return p;
}
// 更新操作
bool MySQL::update(string sql)
{
if (mysql_query(_conn, sql.c_str()))
{
LOG_INFO << __FILE__ << ":" << __LINE__ << ":"
<< sql << "更新失败!";
return false;
}
return true;
}
// 查询操作
MYSQL_RES *MySQL::query(string sql)
{
if (mysql_query(_conn, sql.c_str()))
{
LOG_INFO << __FILE__ << ":" << __LINE__ << ":"
<< sql << "查询失败!";
return nullptr;
}
return mysql_use_result(_conn);
}
// 获取连接
MYSQL* MySQL::getConnection()
{
return _conn;
} | 18.708333 | 86 | 0.550854 | ETinyfish |
928de761324af0f5ae218a0f5341e48bb0b33a4f | 2,131 | cc | C++ | ash/sysui/context_menu_mus.cc | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2019-01-28T08:09:58.000Z | 2021-11-15T15:32:10.000Z | ash/sysui/context_menu_mus.cc | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2016-07-11T15:19:20.000Z | 2017-04-02T20:38:55.000Z | ash/sysui/context_menu_mus.cc | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 6 | 2020-09-23T08:56:12.000Z | 2021-11-18T03:40:49.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 "ash/sysui/context_menu_mus.h"
#include "ash/common/shelf/shelf_types.h"
#include "ash/common/shelf/wm_shelf.h"
#include "ash/desktop_background/user_wallpaper_delegate.h"
#include "ash/shell.h"
#include "grit/ash_strings.h"
namespace ash {
ContextMenuMus::ContextMenuMus(WmShelf* wm_shelf)
: ui::SimpleMenuModel(nullptr),
wm_shelf_(wm_shelf),
alignment_menu_(wm_shelf) {
set_delegate(this);
AddCheckItemWithStringId(MENU_AUTO_HIDE,
IDS_ASH_SHELF_CONTEXT_MENU_AUTO_HIDE);
AddSubMenuWithStringId(MENU_ALIGNMENT_MENU,
IDS_ASH_SHELF_CONTEXT_MENU_POSITION, &alignment_menu_);
#if defined(OS_CHROMEOS)
AddItemWithStringId(MENU_CHANGE_WALLPAPER, IDS_AURA_SET_DESKTOP_WALLPAPER);
#endif
}
ContextMenuMus::~ContextMenuMus() {}
bool ContextMenuMus::IsCommandIdChecked(int command_id) const {
if (command_id == MENU_AUTO_HIDE)
return wm_shelf_->GetAutoHideBehavior() == SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS;
return false;
}
bool ContextMenuMus::IsCommandIdEnabled(int command_id) const {
Shell* shell = Shell::GetInstance();
if (command_id == MENU_CHANGE_WALLPAPER)
return shell->user_wallpaper_delegate()->CanOpenSetWallpaperPage();
return true;
}
bool ContextMenuMus::GetAcceleratorForCommandId(int command_id,
ui::Accelerator* accelerator) {
return false;
}
void ContextMenuMus::ExecuteCommand(int command_id, int event_flags) {
if (command_id == MENU_AUTO_HIDE) {
wm_shelf_->SetAutoHideBehavior(wm_shelf_->GetAutoHideBehavior() ==
SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS
? SHELF_AUTO_HIDE_BEHAVIOR_NEVER
: SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS);
} else if (command_id == MENU_CHANGE_WALLPAPER) {
Shell::GetInstance()->user_wallpaper_delegate()->OpenSetWallpaperPage();
}
}
} // namespace ash
| 34.934426 | 80 | 0.705303 | Wzzzx |
928e626c06d50a9f27688bf16d0ef3c097dd3c35 | 3,912 | hpp | C++ | src/dtl/bitmap/util/buffer.hpp | harald-lang/tree-encoded-bitmaps | a4ab056f2cefa7843b27c736833b08977b56649c | [
"Apache-2.0"
] | 29 | 2020-06-18T12:51:42.000Z | 2022-02-22T07:38:24.000Z | src/dtl/bitmap/util/buffer.hpp | marcellus-saputra/Thuja | 8443320a6d0e9a20bb6b665f0befc6988978cafd | [
"Apache-2.0"
] | null | null | null | src/dtl/bitmap/util/buffer.hpp | marcellus-saputra/Thuja | 8443320a6d0e9a20bb6b665f0befc6988978cafd | [
"Apache-2.0"
] | 2 | 2021-04-07T13:43:34.000Z | 2021-06-09T04:49:39.000Z | #pragma once
//===----------------------------------------------------------------------===//
#include <dtl/dtl.hpp>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <memory>
#include <type_traits>
//===----------------------------------------------------------------------===//
namespace dtl {
//===----------------------------------------------------------------------===//
/// A simple memory buffer which allows allocations without initialization.
template<
typename _word_type,
typename _alloc = std::allocator<_word_type>>
class buffer {
using word_type = _word_type;
static constexpr std::size_t word_bitlength = sizeof(word_type) * 8;
static constexpr uintptr_t cache_line_size = 64; // bytes
static constexpr auto elements_per_cache_line =
cache_line_size / sizeof(word_type);
/// The number of elements.
std::size_t size_;
/// Pointer to the buffer.
word_type* ptr_;
/// Cache line aligned pointer to the buffer.
word_type* aligned_ptr_;
/// The allocator.
_alloc allocator_;
static inline word_type*
get_aligned_ptr(word_type* ptr) {
const uintptr_t adjust_by =
(reinterpret_cast<uintptr_t>(ptr) % cache_line_size) == 0
? 0
: cache_line_size - (reinterpret_cast<uintptr_t>(ptr) % cache_line_size);
auto p = reinterpret_cast<word_type*>(
reinterpret_cast<uintptr_t>(ptr) + adjust_by);
return reinterpret_cast<word_type*>(
__builtin_assume_aligned(p, cache_line_size));
}
inline void
do_allocate() {
ptr_ = allocator_.allocate(size_ + elements_per_cache_line);
aligned_ptr_ = get_aligned_ptr(ptr_);
}
inline void
do_deallocate() {
if (ptr_ != nullptr) {
allocator_.deallocate(ptr_, size_ + elements_per_cache_line);
}
}
public:
/// C'tor
explicit buffer(std::size_t size, u1 init = true, const _alloc& alloc = _alloc())
: size_(size), ptr_(nullptr), allocator_(alloc) {
do_allocate();
if (init) {
std::memset(aligned_ptr_, 0, size_ * sizeof(word_type));
}
}
buffer(const buffer& other)
: size_(other.size_), ptr_(nullptr), aligned_ptr_(nullptr),
allocator_(other.allocator_) {
do_allocate();
std::memcpy(aligned_ptr_, other.aligned_ptr_, size_ * sizeof(word_type));
}
buffer(buffer&& other) noexcept
: size_(other.size_), ptr_(other.ptr_), aligned_ptr_(other.aligned_ptr_),
allocator_(std::move(other.allocator_)) {
other.ptr_ = nullptr;
other.aligned_ptr_ = nullptr;
}
buffer& operator=(const buffer& other) {
assert(ptr_ != other.ptr_);
if (size_ == other.size_) {
std::memcpy(aligned_ptr_, other.aligned_ptr_, size_ * sizeof(word_type));
}
else {
do_deallocate();
size_ = other.size_;
allocator_ = other.allocator_;
do_allocate();
std::memcpy(aligned_ptr_, other.aligned_ptr_, size_ * sizeof(word_type));
}
return *this;
}
buffer& operator=(buffer&& other) noexcept {
if (this != &other) {
do_deallocate();
size_ = other.size_;
allocator_ = std::move(other.allocator_);
ptr_ = other.ptr_;
aligned_ptr_ = other.aligned_ptr_;
other.ptr_ = nullptr;
other.aligned_ptr_ = nullptr;
}
return *this;
}
~buffer() noexcept {
do_deallocate();
}
inline std::size_t
size() const noexcept {
return size_;
}
/// Return a pointer to the buffer.
inline word_type*
data() noexcept {
return reinterpret_cast<word_type*>(
__builtin_assume_aligned(aligned_ptr_, cache_line_size));
}
/// Return a const pointer to the buffer.
inline const word_type*
data() const noexcept {
return reinterpret_cast<const word_type*>(
__builtin_assume_aligned(aligned_ptr_, cache_line_size));
}
};
//===----------------------------------------------------------------------===//
} // namespace dtl
| 28.764706 | 83 | 0.615798 | harald-lang |
928f19d3da027bd21bfeaa4efcc8f7acc0190ac1 | 4,032 | cc | C++ | cmd/pyxisd/main.cc | eLong-INF/pyxis | 304820eb72bd62d3c211c3423f62dc87b535bb3c | [
"BSD-3-Clause"
] | 9 | 2016-07-21T01:45:17.000Z | 2016-08-26T03:20:25.000Z | cmd/pyxisd/main.cc | eLong-opensource/pyxis | 304820eb72bd62d3c211c3423f62dc87b535bb3c | [
"BSD-3-Clause"
] | null | null | null | cmd/pyxisd/main.cc | eLong-opensource/pyxis | 304820eb72bd62d3c211c3423f62dc87b535bb3c | [
"BSD-3-Clause"
] | null | null | null | #include <pyxis/server/server.h>
#include <pyxis/rpc/server.h>
#include <pyxis/server/fake_raft.h>
#include <sofa/pbrpc/pbrpc.h>
#include <gflags/gflags.h>
#include <glog/logging.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/EventLoopThread.h>
#include <muduo/net/inspect/Inspector.h>
#include <raft/core/transporter/sofarpc.h>
#include <raft/core/server.h>
#include <toft/base/string/algorithm.h>
#include <toft/base/binary_version.h>
#include <boost/scoped_ptr.hpp>
DEFINE_string(pyxis_list, "", "address list of pyxis servers(host1:port1,host2:port2)");
DEFINE_string(pyxis_listen_addr, "0.0.0.0:7000", "pyxis listen address");
DEFINE_string(raft_listen_addr, "0.0.0.0:7001", "raft listen address");
DEFINE_int32(pprof, 9982, "port of pprof");
DEFINE_string(dbdir, "db", "leveldb dir");
DEFINE_int32(session_interval, 1000, "session check interval");
DEFINE_int32(max_timeout, 2 * 60 * 1000, "max session timeout");
DEFINE_int32(min_timeout, 5 * 1000, "max session timeout");
DEFINE_int32(rpc_channel_size, 1024, "rpc channel size");
// for raft
DEFINE_string(raft_list, "", "address list of raft servers(host1:port1,host2:port2)");
DEFINE_string(snapshotdir, "snapshot", "snapshot dir");
DEFINE_uint64(snapshot_size, 1000000, "commit log size to take snapshot.");
DEFINE_uint64(snapshot_interval, 3600 * 24, " take snapshot interval in second.");
DEFINE_int32(max_commit_size, 200, "max commit size in one loop");
DEFINE_string(raftlog, "raftlog", "raft log dir");
DEFINE_bool(force_flush, false, "force flush in raft log");
DEFINE_int32(election_timeout, 1000, "election timeout in ms");
DEFINE_int32(heartbeat_timeout, 50, "heartbeat timeout in ms");
DEFINE_int32(myid, 0, "my id");
int main(int argc, char* argv[])
{
toft::SetupBinaryVersion();
google::InitGoogleLogging(argv[0]);
google::ParseCommandLineFlags(&argc, &argv, true);
std::vector<std::string> raftList;
std::vector<std::string> pyxisList;
toft::SplitString(FLAGS_raft_list, ",", &raftList);
toft::SplitString(FLAGS_pyxis_list, ",", &pyxisList);
pyxis::Options options;
options.DBDir = FLAGS_dbdir;
options.SessionCheckInterval = FLAGS_session_interval;
options.MaxSessionTimeout = FLAGS_max_timeout;
options.MinSessionTimeout = FLAGS_min_timeout;
options.SnapshotDir = FLAGS_snapshotdir;
options.MyID = FLAGS_myid;
options.AddrList = pyxisList;
uint32_t myid = FLAGS_myid;
uint32_t myindex = myid - 1;
CHECK(myid > 0);
CHECK(myid <= pyxisList.size());
CHECK(myid <= raftList.size());
// 监控线程
boost::scoped_ptr<muduo::net::EventLoopThread> inspectThread;
boost::scoped_ptr<muduo::net::Inspector> inspector;
if (FLAGS_pprof != 0) {
inspectThread.reset(new muduo::net::EventLoopThread);
inspector.reset(new muduo::net::Inspector(inspectThread->startLoop(),
muduo::net::InetAddress(FLAGS_pprof),
"inspect"));
}
raft::sofarpc::Transporter trans;
raft::Options raft_options;
raft_options.MyID = FLAGS_myid;
raft_options.RaftLogDir = FLAGS_raftlog;
raft_options.SnapshotLogSize = FLAGS_snapshot_size;
raft_options.SnapshotInterval = FLAGS_snapshot_interval;
raft_options.ForceFlush = FLAGS_force_flush;
raft_options.MaxCommitSize = FLAGS_max_commit_size;
raft_options.HeartbeatTimeout = FLAGS_heartbeat_timeout;
raft_options.ElectionTimeout = FLAGS_election_timeout;
raft::Server raftServer(raft_options, &trans);
raft::sofarpc::RpcServer raftRpcServer(FLAGS_raft_listen_addr, raftServer.RpcEventChannel());
for (size_t i = 0; i < raftList.size(); i++) {
if (i == myindex) {
continue;
}
trans.AddPeer(raftList[i]);
raftServer.AddPeer(raftList[i]);
}
// raft初始化
pyxis::Server pyxisServer(options, &raftServer);
muduo::net::EventLoop loop;
pyxis::rpc::Server rpcServer(&loop, FLAGS_pyxis_listen_addr, &pyxisServer);
rpcServer.Start();
pyxisServer.Start();
raftRpcServer.Start();
raftServer.Start();
loop.loop();
return 0;
}
| 36 | 95 | 0.728423 | eLong-INF |
9293c46352416bbd95d09069fc83fffa2697e1e4 | 1,756 | cpp | C++ | tests/unit/resource_manager_tests.cpp | aaroncblack/Umpire | 5089a55aeed8b269112125e917f08b10e1797ae5 | [
"MIT"
] | null | null | null | tests/unit/resource_manager_tests.cpp | aaroncblack/Umpire | 5089a55aeed8b269112125e917f08b10e1797ae5 | [
"MIT"
] | null | null | null | tests/unit/resource_manager_tests.cpp | aaroncblack/Umpire | 5089a55aeed8b269112125e917f08b10e1797ae5 | [
"MIT"
] | null | null | null | //////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2018-2019, Lawrence Livermore National Security, LLC.
// Produced at the Lawrence Livermore National Laboratory
//
// Created by David Beckingsale, david@llnl.gov
// LLNL-CODE-747640
//
// All rights reserved.
//
// This file is part of Umpire.
//
// For details, see https://github.com/LLNL/Umpire
// Please also see the LICENSE file for MIT license.
//////////////////////////////////////////////////////////////////////////////
#include "gtest/gtest.h"
#include "umpire/ResourceManager.hpp"
TEST(ResourceManager, Constructor) {
umpire::ResourceManager& rm = umpire::ResourceManager::getInstance();
(void) rm;
SUCCEED();
}
TEST(ResourceManager, findAllocationRecord)
{
auto& rm = umpire::ResourceManager::getInstance();
auto alloc = rm.getAllocator("HOST");
const size_t size = 1024 * 1024;
const size_t offset = 1024;
char* ptr = static_cast<char*>(alloc.allocate(size));
const umpire::util::AllocationRecord* rec = rm.findAllocationRecord(ptr + offset);
ASSERT_EQ(ptr, rec->ptr);
alloc.deallocate(ptr);
ASSERT_THROW(rm.findAllocationRecord(nullptr), umpire::util::Exception);
}
TEST(ResourceManager, getAllocatorByName)
{
auto& rm = umpire::ResourceManager::getInstance();
EXPECT_NO_THROW({
auto alloc = rm.getAllocator("HOST");
UMPIRE_USE_VAR(alloc);
});
ASSERT_THROW(
rm.getAllocator("BANANA"),
umpire::util::Exception);
}
TEST(ResourceManager, getAllocatorById)
{
auto& rm = umpire::ResourceManager::getInstance();
EXPECT_NO_THROW({
auto alloc = rm.getAllocator(0);
UMPIRE_USE_VAR(alloc);
});
ASSERT_THROW(
rm.getAllocator(-4),
umpire::util::Exception);
}
| 24.054795 | 84 | 0.642369 | aaroncblack |
92944939250c28298b5f6815e0ada8e39adcf980 | 8,198 | hh | C++ | Project/headers/HelperFunctions.hh | anshuman1811/cs687-reinforcementlearning | cf30cc0ab2b0e515cd4b643fc55c60cc5f38a481 | [
"MIT"
] | null | null | null | Project/headers/HelperFunctions.hh | anshuman1811/cs687-reinforcementlearning | cf30cc0ab2b0e515cd4b643fc55c60cc5f38a481 | [
"MIT"
] | null | null | null | Project/headers/HelperFunctions.hh | anshuman1811/cs687-reinforcementlearning | cf30cc0ab2b0e515cd4b643fc55c60cc5f38a481 | [
"MIT"
] | null | null | null | #pragma once
#include <iostream> // For console i/o
#include <vector> // For vectors, not including linear algebra
#include <random> // For random number generation
#include <algorithm> // For min/max functions
// Additional libraries that you will have to download.
// First is Eigen, which we use for linear algebra: http://eigen.tuxfamily.org/index.php?title=Main_Page
#include <Eigen/Dense>
// Second is Boost, which we use for ibeta_inv: https://www.boost.org/
#include <boost/math/special_functions/beta.hpp>
// Typically these shouldn't be in a .hpp file.
using namespace std;
using namespace Eigen;
using namespace boost::math;
// This function returns the inverse of Student's t CDF using the degrees of
// freedom in nu for the corresponding probabilities in p. That is, it is
// a C++ implementation of Matlab's tinv function: https://www.mathworks.com/help/stats/tinv.html
// To see how this was created, see the "quantile" block here: https://www.boost.org/doc/libs/1_58_0/libs/math/doc/html/math_toolkit/dist_ref/dists/students_t_dist.html
double tinv(double p, unsigned int nu) {
double x = ibeta_inv((double)nu / 2.0, 0.5, 2.0 * min(p, 1.0 - p));
return sign(p - 0.5) * sqrt((double)nu * (1.0 - x) / x);
}
// Get the sample standard deviation of the vector v (an Eigen::VectorXd)
double stddev(const VectorXd& v) {
double mu = v.mean(), result = 0; // Get the sample mean
for (unsigned int i = 0; i < v.size(); i++)
result += (v[i] - mu) * (v[i] - mu); // Compute the sum of the squared differences between samples and the sample mean
result = sqrt(result / (v.size() - 1.0)); // Get the sample variance by dividing by the number of samples minus one, and then the sample standard deviation by taking the square root.
return result; // Return the value that we've computed.
}
// Assuming v holds i.i.d. samples of a random variable, compute
// a (1-delta)-confidence upper bound on the expected value of the random
// variable using Student's t-test. That is:
// sampleMean + sampleStandardDeviation/sqrt(n) * tinv(1-delta, n-1),
// where n is the number of points in v.
//
// If numPoints is provided, then ttestUpperBound predicts what its output would be if it were to
// be run using a new vector, v, containing numPoints values sampled from the same distribution as
// the points in v.
double ttestUpperBound(const VectorXd& v, const double& delta, const int numPoints = -1) {
unsigned int n = (numPoints == -1 ? (unsigned int)v.size() : (unsigned int)numPoints); // Set n to be numPoints if it was provided, and the number of points in v otherwise.
return v.mean() + (numPoints != -1 ? 2.0 : 1.0) * stddev(v) / sqrt((double)n) * tinv(1.0 - delta, n - 1u);
}
double ttestLowerBound(const VectorXd& v, const double& delta, const int numPoints = -1) {
unsigned int n = (numPoints == -1 ? (unsigned int)v.size() : (unsigned int)numPoints); // Set n to be numPoints if it was provided, and the number of points in v otherwise.
return v.mean() - (numPoints != -1 ? 2.0 : 1.0) * stddev(v) / sqrt((double)n) * tinv(1.0 - delta, n - 1u);
}
/*
This function implements CMA-ES (http://en.wikipedia.org/wiki/CMA-ES). Return
value is the minimizer / maximizer. This code is written for brevity, not clarity.
See the link above for a description of what this code is doing.
*/
VectorXd CMAES(
const VectorXd& initialMean, // Starting point of the search
const double& initialSigma, // Initial standard deviation of the search around initialMean
const unsigned int& numIterations, // Number of iterations to run before stopping
// f, below, is the function to be optimized. Its first argument is the solution, the middle arguments are variables required by f (listed below), and the last is a random number generator.
double(*f)(const VectorXd& theta, const void* params[], mt19937_64& generator),
const void* params[], // Parrameters of f other than theta
const bool& minimize, // If true, we will try to minimize f. Otherwise we will try to maximize f
mt19937_64& generator) // The random number generator to use
{
// Define all of the terms that we will use in the iterations
unsigned int N = (unsigned int)initialMean.size(), lambda = 4 + (unsigned int)floor(3.0 * log(N)), hsig;
double sigma = initialSigma, mu = lambda / 2.0, eigeneval = 0, chiN = pow(N, 0.5) * (1.0 - 1.0 / (4.0 * N) + 1.0 / (21.0 * N * N));
VectorXd xmean = initialMean, weights((unsigned int)mu);
for (unsigned int i = 0; i < (unsigned int)mu; i++)
weights[i] = i + 1;
weights = log(mu + 1.0 / 2.0) - weights.array().log();
mu = floor(mu);
weights = weights / weights.sum();
double mueff = weights.sum() * weights.sum() / weights.dot(weights), cc = (4.0 + mueff / N) / (N + 4.0 + 2.0 * mueff / N), cs = (mueff + 2.0) / (N + mueff + 5.0), c1 = 2.0 / ((N + 1.3) * (N + 1.3) + mueff), cmu = min(1.0 - c1, 2.0 * (mueff - 2.0 + 1.0 / mueff) / ((N + 2.0) * (N + 2.0) + mueff)), damps = 1.0 + 2.0 * max(0.0, sqrt((mueff - 1.0) / (N + 1.0)) - 1.0) + cs;
VectorXd pc = VectorXd::Zero(N), ps = VectorXd::Zero(N), D = VectorXd::Ones(N), DSquared = D, DInv = 1.0 / D.array(), xold, oneOverD;
for (unsigned int i = 0; i < DSquared.size(); i++)
DSquared[i] *= DSquared[i];
MatrixXd B = MatrixXd::Identity(N, N), C = B * DSquared.asDiagonal() * B.transpose(), invsqrtC = B * DInv.asDiagonal() * B.transpose(), arx(N, (int)lambda), repmat(xmean.size(), (int)(mu + .1)), artmp, arxSubMatrix(N, (int)(mu + .1));
vector<double> arfitness(lambda);
vector<unsigned int> arindex(lambda);
// Perform the iterations
for (unsigned int counteval = 0; counteval < numIterations;) {
cout << "Sampling Population" << endl;
// Sample the population
for (unsigned int k = 0; k < lambda; k++) {
normal_distribution<double> distribution(0, 1);
VectorXd randomVector(N);
for (unsigned int i = 0; i < N; i++)
randomVector[i] = D[i] * distribution(generator);
arx.col(k) = xmean + sigma * B * randomVector;
}
// Evaluate the population
vector<VectorXd> fInputs(lambda);
for (unsigned int i = 0; i < lambda; i++) {
cout << "Evaluating Candidate " << counteval+i << "/" << numIterations << endl;
fInputs[i] = arx.col(i);
cout << "Theta: " << fInputs[i].transpose() << endl;
arfitness[i] = (minimize ? 1 : -1) * f(fInputs[i], params, generator);
}
// Update the population distribution
counteval += lambda;
xold = xmean;
for (unsigned int i = 0; i < lambda; ++i)
arindex[i] = i;
std::sort(arindex.begin(), arindex.end(), [&arfitness](unsigned int i1, unsigned int i2) {return arfitness[i1] < arfitness[i2]; });
for (unsigned int col = 0; col < (unsigned int)mu; col++)
arxSubMatrix.col(col) = arx.col(arindex[col]);
xmean = arxSubMatrix * weights;
ps = (1.0 - cs) * ps + sqrt(cs * (2.0 - cs) * mueff) * invsqrtC * (xmean - xold) / sigma;
hsig = (ps.norm() / sqrt(1.0 - pow(1.0 - cs, 2.0 * counteval / lambda)) / (double)chiN < 1.4 + 2.0 / (N + 1.0) ? 1 : 0);
pc = (1 - cc) * pc + hsig * sqrt(cc * (2 - cc) * mueff) * (xmean - xold) / sigma;
for (unsigned int i = 0; i < repmat.cols(); i++)
repmat.col(i) = xold;
artmp = (1.0 / sigma) * (arxSubMatrix - repmat);
C = (1 - c1 - cmu) * C + c1 * (pc * pc.transpose() + (1u - hsig) * cc * (2 - cc) * C) + cmu * artmp * weights.asDiagonal() * artmp.transpose();
sigma = sigma * exp((cs / damps) * (ps.norm() / (double)chiN - 1.0));
if ((double)counteval - eigeneval > (double)lambda / (c1 + cmu) / (double)N / 10.0) {
eigeneval = counteval;
for (unsigned int r = 0; r < C.rows(); r++)
for (unsigned int c = r + 1; c < C.cols(); c++)
C(r, c) = C(c, r);
EigenSolver<MatrixXd> es(C);
D = C.eigenvalues().real();
B = es.eigenvectors().real();
D = D.array().sqrt();
for (unsigned int i = 0; i < B.cols(); i++)
B.col(i) = B.col(i).normalized();
oneOverD = 1.0 / D.array();
invsqrtC = B * oneOverD.asDiagonal() * B.transpose();
}
} // End loop over iterations
return arx.col(arindex[0]);
} | 58.978417 | 372 | 0.633081 | anshuman1811 |
92948fe246d6d0321a44e0e212486c4687854044 | 3,119 | cpp | C++ | depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qttools/src/assistant/qhelpconverter/outputpage.cpp | GrinCash/Grinc-core | 1377979453ba84082f70f9c128be38e57b65a909 | [
"MIT"
] | null | null | null | depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qttools/src/assistant/qhelpconverter/outputpage.cpp | GrinCash/Grinc-core | 1377979453ba84082f70f9c128be38e57b65a909 | [
"MIT"
] | null | null | null | depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qttools/src/assistant/qhelpconverter/outputpage.cpp | GrinCash/Grinc-core | 1377979453ba84082f70f9c128be38e57b65a909 | [
"MIT"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the Qt Assistant of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtCore/QFileInfo>
#include <QtCore/QDir>
#include <QtWidgets/QMessageBox>
#include "outputpage.h"
QT_BEGIN_NAMESPACE
OutputPage::OutputPage(QWidget *parent)
: QWizardPage(parent)
{
setTitle(tr("Output File Names"));
setSubTitle(tr("Specify the file names for the output files."));
setButtonText(QWizard::NextButton, tr("Convert..."));
m_ui.setupUi(this);
connect(m_ui.projectLineEdit, &QLineEdit::textChanged,
this, &QWizardPage::completeChanged);
connect(m_ui.collectionLineEdit, &QLineEdit::textChanged,
this, &QWizardPage::completeChanged);
registerField(QLatin1String("ProjectFileName"),
m_ui.projectLineEdit);
registerField(QLatin1String("CollectionFileName"),
m_ui.collectionLineEdit);
}
void OutputPage::setPath(const QString &path)
{
m_path = path;
}
void OutputPage::setCollectionComponentEnabled(bool enabled)
{
m_ui.collectionLineEdit->setEnabled(enabled);
m_ui.label_2->setEnabled(enabled);
}
bool OutputPage::isComplete() const
{
if (m_ui.projectLineEdit->text().isEmpty()
|| m_ui.collectionLineEdit->text().isEmpty())
return false;
return true;
}
bool OutputPage::validatePage()
{
return checkFile(m_ui.projectLineEdit->text(),
tr("Qt Help Project File"))
&& checkFile(m_ui.collectionLineEdit->text(),
tr("Qt Help Collection Project File"));
}
bool OutputPage::checkFile(const QString &fileName, const QString &title)
{
QFile fi(m_path + QDir::separator() + fileName);
if (!fi.exists())
return true;
if (QMessageBox::warning(this, title,
tr("The specified file %1 already exist.\n\nDo you want to remove it?")
.arg(fileName), tr("Remove"), tr("Cancel")) == 0) {
return fi.remove();
}
return false;
}
QT_END_NAMESPACE
| 31.826531 | 79 | 0.673934 | GrinCash |
92957e83fd0e8838a7f92589057c12265ed6de25 | 35,911 | cpp | C++ | src/ttauri/tokenizer.cpp | prollings/ttauri | 51aa748eb52b72a06038ffa12952523cf3d4f9b6 | [
"BSL-1.0"
] | null | null | null | src/ttauri/tokenizer.cpp | prollings/ttauri | 51aa748eb52b72a06038ffa12952523cf3d4f9b6 | [
"BSL-1.0"
] | null | null | null | src/ttauri/tokenizer.cpp | prollings/ttauri | 51aa748eb52b72a06038ffa12952523cf3d4f9b6 | [
"BSL-1.0"
] | null | null | null | // Copyright Take Vos 2019-2020.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
#include "tokenizer.hpp"
namespace tt {
enum class tokenizer_state_t: uint8_t {
Initial,
Name,
MinusOrPlus, // Could be the start of a number, or an operator starting with '+' or '-'.
Zero, // Could be part of a number with a base.
Dot, // Could be the start of a floating point number, or the '.' operator.
Number, // Could be some kind of number without a base.
DashAfterNumber, // Could be a date.
ColonAfterNumber, // Could be a time.
DashAfterInteger, // Integer followed by a operator starting with '-'
ColonAfterInteger, // Integer followed by a operator starting with ':'
Float,
Date,
Time,
DQuote, // Could be the start of a string, an empty string, or block string.
DoubleDQuote, // Is an empty string or a block string.
String,
StringEscape,
BlockString,
BlockStringDQuote,
BlockStringDoubleDQuote,
BlockStringCaptureDQuote,
BlockStringEscape,
Slash, // Could be the start of a LineComment, BlockComment, or an operator.
LineComment,
BlockComment,
BlockCommentMaybeEnd, // Found a '*' possibly end of comment.
OperatorFirstChar,
OperatorSecondChar,
OperatorThirdChar,
Sentinal
};
constexpr size_t NR_TOKENIZER_STATES = static_cast<size_t>(tokenizer_state_t::Sentinal);
enum class tokenizer_action_t: uint8_t {
Idle = 0x00,
Capture = 0x01, // Capture this character.
Start = 0x02, // Start the capture queue.
Read = 0x04, // Read next character, before processing next state. This will also advance the location.
Found = 0x08, // Token Found.
Tab = 0x10, // Move the location modulo 8 to the right.
LineFeed = 0x20, // Move to the next line.
Poison = 0x80, // Cleared.
};
constexpr uint16_t get_offset(tokenizer_state_t state, char c = '\0') noexcept {
return (static_cast<uint16_t>(state) << 8) | static_cast<uint8_t>(c);
}
constexpr tokenizer_action_t operator|(tokenizer_action_t lhs, tokenizer_action_t rhs)
{
return static_cast<tokenizer_action_t>(static_cast<uint8_t>(lhs) | static_cast<uint8_t>(rhs));
}
constexpr tokenizer_action_t operator|(tokenizer_action_t lhs, char rhs)
{
switch (rhs) {
case '\n': return lhs | tokenizer_action_t::LineFeed;
case '\f': return lhs | tokenizer_action_t::LineFeed;
case '\t': return lhs | tokenizer_action_t::Tab;
default: return lhs | tokenizer_action_t::Idle;
}
}
constexpr bool operator>=(tokenizer_action_t lhs, tokenizer_action_t rhs)
{
return (static_cast<uint8_t>(lhs) & static_cast<uint8_t>(rhs)) == static_cast<uint8_t>(rhs);
}
struct tokenizer_transition_t {
tokenizer_state_t next;
tokenizer_action_t action;
char c;
tokenizer_name_t name;
constexpr tokenizer_transition_t(
char c,
tokenizer_state_t next = tokenizer_state_t::Initial,
tokenizer_action_t action = tokenizer_action_t::Idle,
tokenizer_name_t name = tokenizer_name_t::NotAssigned
) :
next(next), action(action), c(c), name(name) {}
constexpr tokenizer_transition_t() :
next(tokenizer_state_t::Initial), action(tokenizer_action_t::Idle), c('\0'), name(tokenizer_name_t::NotAssigned) {}
};
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_Name()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
if (isNameNext(c) || c == '-') {
transition.next = tokenizer_state_t::Name;
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Capture;
} else {
transition.next = tokenizer_state_t::Initial;
transition.action = tokenizer_action_t::Found;
transition.name = tokenizer_name_t::Name;
}
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_MinusOrPlus()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
if (c == '0') {
transition.next = tokenizer_state_t::Zero;
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Capture;
} else if (isDigit(c) || c == '.') {
transition.next = tokenizer_state_t::Number;
} else {
transition.next = tokenizer_state_t::OperatorSecondChar;
}
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_Dot()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
if (isDigit(c)) {
transition.next = tokenizer_state_t::Float;
} else {
transition.next = tokenizer_state_t::Initial;
transition.action = tokenizer_action_t::Found;
transition.name = tokenizer_name_t::Operator;
}
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_Zero()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
if (c == 'x' || c == 'X' || c == 'd' || c == 'D' || c == 'o' || c == 'O' || c == 'b' || c == 'B') {
transition.next = tokenizer_state_t::Number;
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Capture;
} else {
transition.next = tokenizer_state_t::Number;
}
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_Number()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
if (isDigit(c)) {
transition.next = tokenizer_state_t::Number;
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Capture;
} else if (c == '_' || c == '\'') {
transition.next = tokenizer_state_t::Number;
transition.action = tokenizer_action_t::Read;
} else if (c == '.') {
transition.next = tokenizer_state_t::Float;
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Capture;
} else if (c == '-') {
transition.next = tokenizer_state_t::DashAfterNumber;
transition.action = tokenizer_action_t::Read;
} else if (c == ':') {
transition.next = tokenizer_state_t::ColonAfterNumber;
transition.action = tokenizer_action_t::Read;
} else {
transition.next = tokenizer_state_t::Initial;
transition.action = tokenizer_action_t::Found;
transition.name = tokenizer_name_t::IntegerLiteral;
}
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_DashAfterNumber()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {'-'};
if (isDigit(c)) {
transition.next = tokenizer_state_t::Date;
transition.action = tokenizer_action_t::Capture;
} else {
transition.next = tokenizer_state_t::DashAfterInteger;
transition.action = tokenizer_action_t::Found;
transition.name = tokenizer_name_t::IntegerLiteral;
}
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_ColonAfterNumber()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {':'};
if (isDigit(c)) {
transition.next = tokenizer_state_t::Time;
transition.action = tokenizer_action_t::Capture;
} else {
transition.next = tokenizer_state_t::ColonAfterInteger;
transition.action = tokenizer_action_t::Found;
transition.name = tokenizer_name_t::IntegerLiteral;
}
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_DashAfterInteger()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
tokenizer_transition_t transition = {'-'};
transition.next = tokenizer_state_t::OperatorSecondChar;
transition.action = tokenizer_action_t::Start | tokenizer_action_t::Capture;
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_ColonAfterInteger()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
tokenizer_transition_t transition = {':'};
transition.next = tokenizer_state_t::OperatorSecondChar;
transition.action = tokenizer_action_t::Start | tokenizer_action_t::Capture;
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_Date()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
if (isDigit(c) || c == '-') {
transition.next = tokenizer_state_t::Date;
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Capture;
} else {
transition.next = tokenizer_state_t::Initial;
transition.action = tokenizer_action_t::Found;
transition.name = tokenizer_name_t::DateLiteral;
}
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_Time()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
if (isDigit(c) || c == ':' || c == '.') {
transition.next = tokenizer_state_t::Time;
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Capture;
} else {
transition.next = tokenizer_state_t::Initial;
transition.action = tokenizer_action_t::Found;
transition.name = tokenizer_name_t::TimeLiteral;
}
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_Float()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
if (isDigit(c) || c == 'e' || c == 'E' || c == '-') {
transition.next = tokenizer_state_t::Float;
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Capture;
} else if (c == '_' || c == '\'') {
transition.next = tokenizer_state_t::Float;
transition.action = tokenizer_action_t::Read;
} else {
transition.next = tokenizer_state_t::Initial;
transition.action = tokenizer_action_t::Found;
transition.name = tokenizer_name_t::FloatLiteral;
}
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_Slash()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
if (c == '/') {
transition.next = tokenizer_state_t::LineComment;
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Start;
} else if (c == '*') {
transition.next = tokenizer_state_t::BlockComment;
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Start;
} else {
transition.next = tokenizer_state_t::OperatorSecondChar;
}
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_LineComment()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
if (c == '\0') {
transition.next = tokenizer_state_t::Initial;
} else if (isLinefeed(c)) {
transition.next = tokenizer_state_t::Initial;
transition.action = tokenizer_action_t::Read | c;
} else {
transition.next = tokenizer_state_t::LineComment;
transition.action = tokenizer_action_t::Read | c;
}
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_BlockComment()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
if (c == '\0') {
transition.next = tokenizer_state_t::Initial;
transition.action = tokenizer_action_t::Found;
transition.name = tokenizer_name_t::ErrorEOTInBlockComment;
} else if (c == '*') {
transition.next = tokenizer_state_t::BlockCommentMaybeEnd;
transition.action = tokenizer_action_t::Read;
} else {
transition.next = tokenizer_state_t::BlockComment;
transition.action = tokenizer_action_t::Read | c;
}
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_BlockCommentMaybeEnd()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
if (c == '\0') {
transition.next = tokenizer_state_t::Initial;
transition.action = tokenizer_action_t::Found;
transition.name = tokenizer_name_t::ErrorEOTInBlockComment;
} else if (c == '/') {
transition.next = tokenizer_state_t::Initial;
transition.action = tokenizer_action_t::Read;
} else if (c == '*') {
transition.next = tokenizer_state_t::BlockCommentMaybeEnd;
transition.action = tokenizer_action_t::Read;
} else {
transition.next = tokenizer_state_t::BlockComment;
transition.action = tokenizer_action_t::Read | c;
}
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_DQuote()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
if (c == '"') {
transition.next = tokenizer_state_t::DoubleDQuote;
transition.action = tokenizer_action_t::Read;
} else {
transition.next = tokenizer_state_t::String;
}
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_DoubleDQuote()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
if (c == '"') {
transition.next = tokenizer_state_t::BlockString;
transition.action = tokenizer_action_t::Read;
} else {
// Empty string.
transition.next = tokenizer_state_t::Initial;
transition.action = tokenizer_action_t::Found;
transition.name = tokenizer_name_t::StringLiteral;
}
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_String()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
if (c == '\0') {
transition.next = tokenizer_state_t::Initial;
transition.action = tokenizer_action_t::Found;
transition.name = tokenizer_name_t::ErrorEOTInString;
} else if (isLinefeed(c)) {
transition.next = tokenizer_state_t::Initial;
transition.action = tokenizer_action_t::Found | tokenizer_action_t::Read | tokenizer_action_t::Capture | tokenizer_action_t::Start | c;
transition.name = tokenizer_name_t::ErrorLFInString;
} else if (c == '\\') {
transition.next = tokenizer_state_t::StringEscape;
transition.action = tokenizer_action_t::Read;
} else if (c == '"') {
transition.next = tokenizer_state_t::Initial;
transition.action = tokenizer_action_t::Found | tokenizer_action_t::Read;
transition.name = tokenizer_name_t::StringLiteral;
} else {
transition.next = tokenizer_state_t::String;
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Capture | c;
}
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_StringEscape()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
switch (c) {
case '\0':
transition.next = tokenizer_state_t::Initial;
transition.action = tokenizer_action_t::Found;
transition.name = tokenizer_name_t::ErrorEOTInString;
r[i] = transition;
continue;
case 'a': transition.c = '\a'; break;
case 'b': transition.c = '\b'; break;
case 'f': transition.c = '\f'; break;
case 'n': transition.c = '\n'; break;
case 'r': transition.c = '\r'; break;
case 't': transition.c = '\t'; break;
case 'v': transition.c = '\v'; break;
}
transition.next = tokenizer_state_t::String;
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Capture;
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_BlockString()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
if (c == '\0') {
transition.next = tokenizer_state_t::Initial;
transition.action = tokenizer_action_t::Found;
transition.name = tokenizer_name_t::ErrorEOTInString;
} else if (c == '"') {
transition.next = tokenizer_state_t::BlockStringDQuote;
transition.action = tokenizer_action_t::Read;
} else if (isWhitespace(c)) {
transition.next = tokenizer_state_t::BlockString;
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Capture | c;
} else if (c == '\\') {
transition.next = tokenizer_state_t::BlockStringEscape;
transition.action = tokenizer_action_t::Read;
} else {
transition.next = tokenizer_state_t::BlockString;
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Capture;
}
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_BlockStringDQuote()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
if (c == '"') {
transition.next = tokenizer_state_t::BlockStringDoubleDQuote;
transition.action = tokenizer_action_t::Read;
} else {
transition.next = tokenizer_state_t::BlockString;
transition.action = tokenizer_action_t::Capture;
transition.c = '"';
}
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_BlockStringDoubleDQuote()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
if (c == '"') {
transition.next = tokenizer_state_t::Initial;
transition.action = tokenizer_action_t::Found | tokenizer_action_t::Read;
transition.name = tokenizer_name_t::StringLiteral;
} else {
transition.next = tokenizer_state_t::BlockStringCaptureDQuote;
transition.action = tokenizer_action_t::Capture;
transition.c = '"';
}
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_BlockStringCaptureDQuote()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
transition.next = tokenizer_state_t::BlockString;
transition.action = tokenizer_action_t::Capture;
transition.c = '"';
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_BlockStringEscape()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
switch (c) {
case '\0':
transition.next = tokenizer_state_t::Initial;
transition.action = tokenizer_action_t::Found;
transition.name = tokenizer_name_t::ErrorEOTInString;
r[i] = transition;
continue;
case 'a': transition.c = '\a'; break;
case 'b': transition.c = '\b'; break;
case 'f': transition.c = '\f'; break;
case 'n': transition.c = '\n'; break;
case 'r': transition.c = '\r'; break;
case 't': transition.c = '\t'; break;
case 'v': transition.c = '\v'; break;
}
transition.next = tokenizer_state_t::BlockString;
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Capture;
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_OperatorThirdChar()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
switch (c) {
case '>':
case '=':
transition.next = tokenizer_state_t::Initial;
transition.action = tokenizer_action_t::Found | tokenizer_action_t::Read | tokenizer_action_t::Capture;
transition.name = tokenizer_name_t::Operator;
break;
default:
transition.next = tokenizer_state_t::Initial;
transition.action = tokenizer_action_t::Found;
transition.name = tokenizer_name_t::Operator;
}
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_OperatorSecondChar()
{
#define LAST_CHAR\
transition.next = tokenizer_state_t::Initial;\
transition.action = tokenizer_action_t::Found | tokenizer_action_t::Read | tokenizer_action_t::Capture;\
transition.name = tokenizer_name_t::Operator
#define MORE_CHARS\
transition.next = tokenizer_state_t::OperatorThirdChar;\
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Capture;
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
switch (c) {
case '=': MORE_CHARS; break; // Possible: <=>
case '<': MORE_CHARS; break; // Possible: <<=
case '>': MORE_CHARS; break; // Possible: >>=
case '-': LAST_CHAR; break;
case '+': LAST_CHAR; break;
case '*': LAST_CHAR; break;
case '&': LAST_CHAR; break;
case '|': LAST_CHAR; break;
case '^': LAST_CHAR; break;
default:
transition.next = tokenizer_state_t::Initial;
transition.action = tokenizer_action_t::Found;
transition.name = tokenizer_name_t::Operator;
}
r[i] = transition;
}
return r;
#undef LAST_CHAR
#undef MORE_CHARS
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_OperatorFirstChar()
{
#define LAST_CHAR\
transition.next = tokenizer_state_t::Initial;\
transition.action = tokenizer_action_t::Found | tokenizer_action_t::Read | tokenizer_action_t::Capture;\
transition.name = tokenizer_name_t::Operator
#define MORE_CHARS\
transition.next = tokenizer_state_t::OperatorSecondChar;\
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Capture;
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
switch (c) {
case '.': LAST_CHAR; break;
case ';': LAST_CHAR; break;
case ',': LAST_CHAR; break;
case '(': LAST_CHAR; break;
case ')': LAST_CHAR; break;
case '[': LAST_CHAR; break;
case ']': LAST_CHAR; break;
case '{': LAST_CHAR; break;
case '}': LAST_CHAR; break;
case '?': LAST_CHAR; break;
case '@': LAST_CHAR; break;
case '$': LAST_CHAR; break;
case '~': LAST_CHAR; break;
case '!': MORE_CHARS; break; // Possible: !=
case '<': MORE_CHARS; break; // Possible: <=>, <=, <-, <<, <>, <<=
case '>': MORE_CHARS; break; // Possible: >=, >>, >>=
case '=': MORE_CHARS; break; // Possible: ==, =>
case '+': MORE_CHARS; break; // Possible: ++, +=
case '-': MORE_CHARS; break; // Possible: --, ->, -=
case '*': MORE_CHARS; break; // Possible: **
case '%': MORE_CHARS; break; // Possible: %=
case '/': MORE_CHARS; break; // Possible: /=
case '|': MORE_CHARS; break; // Possible: ||, |=
case '&': MORE_CHARS; break; // Possible: &&, &=
case '^': MORE_CHARS; break; // Possible: ^=
case ':': MORE_CHARS; break; // Possible: :=
default:
// If we don't recognize the operator, it means this character is invalid.
transition.next = tokenizer_state_t::Initial;
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Capture;
transition.name = tokenizer_name_t::ErrorInvalidCharacter;
}
r[i] = transition;
}
return r;
#undef LAST_CHAR
#undef MORE_CHARS
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_Initial()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
if (c == '\0') {
transition.next = tokenizer_state_t::Initial;
transition.action = tokenizer_action_t::Found;
transition.name = tokenizer_name_t::End;
} else if (isNameFirst(c)) {
transition.next = tokenizer_state_t::Name;
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Capture | tokenizer_action_t::Start;
} else if (c == '-' || c == '+') {
transition.next = tokenizer_state_t::MinusOrPlus;
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Capture | tokenizer_action_t::Start;
} else if (c == '0') {
transition.next = tokenizer_state_t::Zero;
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Capture | tokenizer_action_t::Start;
} else if (isDigit(c)) {
transition.next = tokenizer_state_t::Number;
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Capture | tokenizer_action_t::Start;
} else if (c == '.') {
transition.next = tokenizer_state_t::Dot;
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Capture | tokenizer_action_t::Start;
} else if (c == '"') {
transition.next = tokenizer_state_t::DQuote;
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Start;
} else if (isWhitespace(c)) {
transition.next = tokenizer_state_t::Initial;
transition.action = tokenizer_action_t::Read | c;
} else if (c == '#') {
transition.next = tokenizer_state_t::LineComment;
transition.action = tokenizer_action_t::Read;
} else if (c == '/') {
transition.next = tokenizer_state_t::Slash;
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Capture | tokenizer_action_t::Start;
} else {
transition.next = tokenizer_state_t::OperatorFirstChar;
}
r[i] = transition;
}
return r;
}
constexpr size_t TRANSITION_TABLE_SIZE = NR_TOKENIZER_STATES * 256;
using transitionTable_t = std::array<tokenizer_transition_t,TRANSITION_TABLE_SIZE>;
constexpr transitionTable_t calculateTransitionTable()
{
#define CALCULATE_SUB_TABLE(x)\
i = get_offset(tokenizer_state_t::x);\
for (ttlet t: calculateTransitionTable_ ## x()) { r[i++] = t; }
transitionTable_t r{};
// Poisson the table, to make sure all sub tables have been initialized.
for (size_t i = 0; i < r.size(); i++) {
r[i].action = tokenizer_action_t::Poison;
}
size_t i = 0;
CALCULATE_SUB_TABLE(Initial);
CALCULATE_SUB_TABLE(Name);
CALCULATE_SUB_TABLE(MinusOrPlus);
CALCULATE_SUB_TABLE(Zero);
CALCULATE_SUB_TABLE(Dot);
CALCULATE_SUB_TABLE(Number);
CALCULATE_SUB_TABLE(DashAfterNumber);
CALCULATE_SUB_TABLE(ColonAfterNumber);
CALCULATE_SUB_TABLE(DashAfterInteger);
CALCULATE_SUB_TABLE(ColonAfterInteger);
CALCULATE_SUB_TABLE(Date);
CALCULATE_SUB_TABLE(Time);
CALCULATE_SUB_TABLE(Float);
CALCULATE_SUB_TABLE(DQuote);
CALCULATE_SUB_TABLE(DoubleDQuote);
CALCULATE_SUB_TABLE(String);
CALCULATE_SUB_TABLE(StringEscape);
CALCULATE_SUB_TABLE(BlockString);
CALCULATE_SUB_TABLE(BlockStringDQuote);
CALCULATE_SUB_TABLE(BlockStringDoubleDQuote);
CALCULATE_SUB_TABLE(BlockStringCaptureDQuote);
CALCULATE_SUB_TABLE(BlockStringEscape);
CALCULATE_SUB_TABLE(Slash);
CALCULATE_SUB_TABLE(LineComment);
CALCULATE_SUB_TABLE(BlockComment);
CALCULATE_SUB_TABLE(BlockCommentMaybeEnd);
CALCULATE_SUB_TABLE(OperatorFirstChar);
CALCULATE_SUB_TABLE(OperatorSecondChar);
CALCULATE_SUB_TABLE(OperatorThirdChar);
return r;
#undef CALCULATE_SUB_TABLE
}
constexpr bool optimizeTransitionTableOnce(transitionTable_t &r)
{
bool foundOptimization = false;
for (size_t i = 0; i < r.size(); i++) {
auto &transition = r[i];
if (transition.action == tokenizer_action_t::Idle) {
foundOptimization = true;
transition = r[get_offset(transition.next, static_cast<char>(i & 0xff))];
}
}
return foundOptimization;
}
constexpr transitionTable_t optimizeTransitionTable(transitionTable_t transitionTable)
{
for (int i = 0; i < 10; i++) {
if (!optimizeTransitionTableOnce(transitionTable)) {
break;
}
}
return transitionTable;
}
constexpr bool checkTransitionTable(transitionTable_t const &r)
{
for (size_t i = 0; i < r.size(); i++) {
if (r[i].action >= tokenizer_action_t::Poison) {
return false;
}
}
return true;
}
constexpr transitionTable_t buildTransitionTable()
{
constexpr auto transitionTable = calculateTransitionTable();
static_assert(checkTransitionTable(transitionTable), "Not all entries in transition table where assigned.");
return optimizeTransitionTable(transitionTable);
}
constexpr transitionTable_t transitionTable = buildTransitionTable();
struct tokenizer {
using iterator = typename std::string_view::const_iterator;
tokenizer_state_t state;
iterator index;
iterator end;
parse_location location;
parse_location captureLocation;
tokenizer(iterator begin, iterator end) :
state(tokenizer_state_t::Initial), index(begin), end(end) {}
/*! Parse a token.
*/
[[nodiscard]] token_t getNextToken() {
auto token = token_t{};
auto transition = tokenizer_transition_t{};
while (index != end) {
transition = transitionTable[get_offset(state, *index)];
state = transition.next;
auto action = transition.action;
if (action >= tokenizer_action_t::Start) {
token.location = location;
token.value.clear();
}
if (action >= tokenizer_action_t::Capture) {
token.value += transition.c;
}
if (action >= tokenizer_action_t::Read) {
if (action >= tokenizer_action_t::LineFeed) {
location.increment_line();
} else if (action >= tokenizer_action_t::Tab) {
location.tab_column();
} else {
location.increment_column();
}
++index;
}
if (action >= tokenizer_action_t::Found) {
token.name = transition.name;
return token;
}
}
// Complete the token at the current state. Or an end-token at the initial state.
if (state == tokenizer_state_t::Initial) {
// Mark the current offset as the position of the end-token.
token.location = location;
token.value.clear();
}
transition = transitionTable[get_offset(state)];
state = transition.next;
token.name = transition.name;
return token;
}
/*! Parse all tokens.
*/
[[nodiscard]] std::vector<token_t> getTokens() noexcept {
std::vector<token_t> r;
tokenizer_name_t token_name;
do {
ttlet token = getNextToken();
token_name = token.name;
r.push_back(std::move(token));
} while (token_name != tokenizer_name_t::End);
return r;
}
};
[[nodiscard]] std::vector<token_t> parseTokens(std::string_view::const_iterator first, std::string_view::const_iterator last) noexcept
{
return tokenizer(first, last).getTokens();
}
[[nodiscard]] std::vector<token_t> parseTokens(std::string_view text) noexcept
{
return parseTokens(text.cbegin(), text.cend());
}
}
| 34.266221 | 147 | 0.621147 | prollings |
92973dda4203cd24ca131457c4d824ecb2cbf27f | 453 | cpp | C++ | window-move-1.cpp | ADITYA-CS/ncurse | f6a9ce3b5e024b76338ab92ae966daf63eb53bc2 | [
"MIT"
] | null | null | null | window-move-1.cpp | ADITYA-CS/ncurse | f6a9ce3b5e024b76338ab92ae966daf63eb53bc2 | [
"MIT"
] | null | null | null | window-move-1.cpp | ADITYA-CS/ncurse | f6a9ce3b5e024b76338ab92ae966daf63eb53bc2 | [
"MIT"
] | null | null | null | #include <ncurses.h>
#define TSIZE 18
int main() {
WINDOW *b;
int maxx, maxy, y, x;
initscr();
bkgd('.');
refresh();
getmaxyx(stdscr, maxy, maxx);
x = (maxx-TSIZE) >> 1;
b = newwin(1, TSIZE, 0, x);
waddstr(b, "I'm getting sick!");
for(y=0; y < maxy; y++){
mvwin(b, y, x);
wrefresh(b);
touchline(stdscr,y-1,1);
refresh();
getch();
}
endwin();
return 0;
}
| 15.1 | 36 | 0.470199 | ADITYA-CS |
929b034d7a728376039d65f9d0e175ff419fa453 | 3,037 | cpp | C++ | tools/Database/src/DataRecordFileV2.cpp | yaoyuan0553/PatentTagging | 8f086588e48e3ece24079bd32596b67cd6e37a94 | [
"MIT"
] | 2 | 2019-08-13T12:31:08.000Z | 2019-08-27T20:33:16.000Z | tools/Database/src/DataRecordFileV2.cpp | yaoyuan0553/PatentTagging | 8f086588e48e3ece24079bd32596b67cd6e37a94 | [
"MIT"
] | null | null | null | tools/Database/src/DataRecordFileV2.cpp | yaoyuan0553/PatentTagging | 8f086588e48e3ece24079bd32596b67cd6e37a94 | [
"MIT"
] | 1 | 2019-09-10T02:18:00.000Z | 2019-09-10T02:18:00.000Z | //
// Created by yuan on 9/2/19.
//
#include "DataRecordFileV2.h"
using namespace std;
DataRecordFileV2::DataRecordFileV2(uint64_t sizeToAllocate) :
buf_((char*)checkMalloc(max(sizeToAllocate, FILE_HEAD_SIZE))),
capacity_(max(sizeToAllocate, FILE_HEAD_SIZE))
{
numBytes() = FILE_HEAD_SIZE;
numRecords() = FILE_HEAD_SIZE;
// nBytes_ = FILE_HEAD_SIZE; // only 12 bytes are used
// nRecords_ = 0;
}
DataRecordFileV2::~DataRecordFileV2()
{
free(buf_);
}
void DataRecordFileV2::reserve(size_t newSize)
{
// if not larger, do nothing
if (newSize <= capacity_) return;
capacity_ = newSize;
buf_ = (char*)realloc(buf_, capacity_);
if (!buf_)
PSYS_FATAL("realloc()");
}
void DataRecordFileV2::shrink(size_t newSize)
{
// if not smaller, do nothing
if (newSize >= capacity_) return;
// can't be smaller than file head
capacity_ = max(newSize, FILE_HEAD_SIZE);
buf_ = (char*)realloc(buf_, capacity_);
if (!buf_)
PSYS_FATAL("realloc()");
}
DataRecordFileWriter::DataRecordFileWriter(size_t maxFileSize) :
DataRecordFileV2(maxFileSize), curBuf_(buf()), maxFileSize_(maxFileSize)
{
obtainBinId();
}
void DataRecordFileWriter::writeToFile(const char*)
{
}
/***********************************************
* DataRecordFileReader *
***********************************************/
DataRecordFileReader::DataRecordFileReader(const char* dataFilename) :
DataRecordFileV2(), filename_(dataFilename)
{
openDataFile();
}
void DataRecordFileReader::openDataFile()
{
fileHandle_ = open(filename_.c_str(), O_RDONLY);
if (fileHandle_ == -1)
PSYS_FATAL("failed to open (open()) [%s]", filename_.c_str());
// note: pread() doesn't change the file pointer offset
if (pread(fileHandle_, buf(), FILE_HEAD_SIZE, 0) == -1)
PSYS_FATAL("error reading (pread()) header of file [%s]", filename_.c_str());
}
DataRecordFileReader::~DataRecordFileReader()
{
closeDataFile();
}
void DataRecordFileReader::closeDataFile()
{
if (close(fileHandle_) == -1)
PSYS_FATAL("failed to close (close()) [%s]", filename_.c_str());
}
bool DataRecordFileReader::getDataRecordAtOffset(uint64_t offset, DataRecordV2* dataRecord) const
{
try {
if (allDataLoaded_)
*dataRecord = DataRecordV2(buf(), offset, numBytes());
else
*dataRecord = DataRecordV2(fileHandle_, offset, numBytes());
}
catch (ObjectConstructionFailure& ocf) {
fprintf(stderr, "DataRecord failed to construct: %s\n", ocf.what());
return false;
}
return true;
}
void DataRecordFileReader::loadAllData()
{
reserve(numBytes());
if (pread(fileHandle_, buf() + FILE_HEAD_SIZE, numBytes() - FILE_HEAD_SIZE, FILE_HEAD_SIZE) == -1)
PSYS_FATAL("error reading (pread()) file [%s]", filename_.c_str());
allDataLoaded_ = true;
}
void DataRecordFileReader::freeAllData()
{
shrink(FILE_HEAD_SIZE);
allDataLoaded_ = false;
}
| 25.308333 | 102 | 0.643727 | yaoyuan0553 |
929c9124c54184211afececa21d22ef6b9b03edc | 8,663 | cpp | C++ | tests/unit/src/common/stream_channel.cpp | WeiDaiWD/APSI | b799d7a21d69867c07e91a3fd610f13e17cf91f5 | [
"MIT"
] | 72 | 2021-05-04T11:25:58.000Z | 2022-03-31T07:32:57.000Z | tests/unit/src/common/stream_channel.cpp | WeiDaiWD/APSI | b799d7a21d69867c07e91a3fd610f13e17cf91f5 | [
"MIT"
] | 16 | 2021-05-06T07:58:34.000Z | 2022-03-28T22:54:51.000Z | tests/unit/src/common/stream_channel.cpp | WeiDaiWD/APSI | b799d7a21d69867c07e91a3fd610f13e17cf91f5 | [
"MIT"
] | 13 | 2021-05-04T06:44:40.000Z | 2022-03-16T03:12:54.000Z | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
// STD
#include <string>
#include <thread>
#include <utility>
// SEAL
#include "seal/keygenerator.h"
#include "seal/publickey.h"
// APSI
#include "apsi/network/stream_channel.h"
#include "apsi/powers.h"
#include "apsi/util/utils.h"
// Google Test
#include "gtest/gtest.h"
using namespace std;
using namespace seal;
using namespace apsi;
using namespace apsi::network;
namespace APSITests {
namespace {
shared_ptr<PSIParams> get_params()
{
static shared_ptr<PSIParams> params = nullptr;
if (!params) {
PSIParams::ItemParams item_params;
item_params.felts_per_item = 8;
PSIParams::TableParams table_params;
table_params.hash_func_count = 3;
table_params.max_items_per_bin = 16;
table_params.table_size = 512;
PSIParams::QueryParams query_params;
query_params.query_powers = { 1, 3, 5 };
size_t pmd = 4096;
PSIParams::SEALParams seal_params;
seal_params.set_poly_modulus_degree(pmd);
seal_params.set_coeff_modulus(CoeffModulus::Create(pmd, { 40, 40 }));
seal_params.set_plain_modulus(65537);
params =
make_shared<PSIParams>(item_params, table_params, query_params, seal_params);
}
return params;
}
shared_ptr<CryptoContext> get_context()
{
static shared_ptr<CryptoContext> context = nullptr;
if (!context) {
context = make_shared<CryptoContext>(*get_params());
KeyGenerator keygen(*context->seal_context());
context->set_secret(keygen.secret_key());
RelinKeys rlk;
keygen.create_relin_keys(rlk);
context->set_evaluator(move(rlk));
}
return context;
}
} // namespace
class StreamChannelTests : public ::testing::Test {
protected:
StreamChannelTests()
{}
~StreamChannelTests()
{}
};
TEST_F(StreamChannelTests, SendReceiveParms)
{
stringstream stream1;
stringstream stream2;
StreamChannel svr(/* istream */ stream1, /* ostream */ stream2);
StreamChannel clt(/* istream */ stream2, /* ostream */ stream1);
unique_ptr<SenderOperation> sop = make_unique<SenderOperationParms>();
// Send a parms operation
clt.send(move(sop));
sop = svr.receive_operation(get_context()->seal_context());
ASSERT_NE(nullptr, sop);
ASSERT_EQ(SenderOperationType::sop_parms, sop->type());
// Create a parms response
auto rsop_parms = make_unique<SenderOperationResponseParms>();
rsop_parms->params = make_unique<PSIParams>(*get_params());
unique_ptr<SenderOperationResponse> rsop = move(rsop_parms);
svr.send(move(rsop));
// Receive the parms response
rsop = clt.receive_response(SenderOperationType::sop_parms);
rsop_parms.reset(dynamic_cast<SenderOperationResponseParms *>(rsop.release()));
// We received valid parameters
ASSERT_EQ(get_params()->item_bit_count(), rsop_parms->params->item_bit_count());
ASSERT_EQ(svr.bytes_sent(), clt.bytes_received());
ASSERT_EQ(svr.bytes_received(), clt.bytes_sent());
}
TEST_F(StreamChannelTests, SendReceiveOPRFTest)
{
stringstream stream1;
stringstream stream2;
StreamChannel svr(/* istream */ stream1, /* ostream */ stream2);
StreamChannel clt(/* istream */ stream2, /* ostream */ stream1);
// Fill a data buffer
vector<unsigned char> oprf_data(256);
for (size_t i = 0; i < oprf_data.size(); i++) {
oprf_data[i] = static_cast<unsigned char>(i);
}
auto sop_oprf = make_unique<SenderOperationOPRF>();
sop_oprf->data = oprf_data;
unique_ptr<SenderOperation> sop = move(sop_oprf);
// Send an OPRF operation
clt.send(move(sop));
// Receive the operation
sop = svr.receive_operation(get_context()->seal_context());
ASSERT_EQ(SenderOperationType::sop_oprf, sop->type());
sop_oprf.reset(dynamic_cast<SenderOperationOPRF *>(sop.release()));
// Validate the data
ASSERT_EQ(256, sop_oprf->data.size());
for (size_t i = 0; i < sop_oprf->data.size(); i++) {
ASSERT_EQ(static_cast<char>(sop_oprf->data[i]), static_cast<char>(i));
}
// Create an OPRF response
auto rsop_oprf = make_unique<SenderOperationResponseOPRF>();
rsop_oprf->data = oprf_data;
unique_ptr<SenderOperationResponse> rsop = move(rsop_oprf);
svr.send(move(rsop));
// Receive the OPRF response
rsop = clt.receive_response(SenderOperationType::sop_oprf);
rsop_oprf.reset(dynamic_cast<SenderOperationResponseOPRF *>(rsop.release()));
// Validate the data
ASSERT_EQ(256, rsop_oprf->data.size());
for (size_t i = 0; i < rsop_oprf->data.size(); i++) {
ASSERT_EQ(static_cast<char>(rsop_oprf->data[i]), static_cast<char>(i));
}
ASSERT_EQ(svr.bytes_sent(), clt.bytes_received());
ASSERT_EQ(svr.bytes_received(), clt.bytes_sent());
}
TEST_F(StreamChannelTests, SendReceiveQuery)
{
stringstream stream1;
stringstream stream2;
StreamChannel svr(/* istream */ stream1, /* ostream */ stream2);
StreamChannel clt(/* istream */ stream2, /* ostream */ stream1);
auto sop_query = make_unique<SenderOperationQuery>();
sop_query->relin_keys = *get_context()->relin_keys();
sop_query->data[0].push_back(get_context()->encryptor()->encrypt_zero_symmetric());
sop_query->data[123].push_back(get_context()->encryptor()->encrypt_zero_symmetric());
unique_ptr<SenderOperation> sop = move(sop_query);
// Send a query operation
clt.send(move(sop));
// Receive the operation
sop = svr.receive_operation(get_context()->seal_context());
ASSERT_EQ(SenderOperationType::sop_query, sop->type());
sop_query.reset(dynamic_cast<SenderOperationQuery *>(sop.release()));
// Are we able to extract the relinearization keys?
ASSERT_NO_THROW(auto rlk = sop_query->relin_keys.extract_if_local());
// Check for query ciphertexts
ASSERT_EQ(2, sop_query->data.size());
ASSERT_FALSE(sop_query->data.at(0).empty());
ASSERT_EQ(1, sop_query->data[0].size());
auto query_ct0 = sop_query->data[0][0].extract_if_local();
ASSERT_FALSE(sop_query->data.at(123).empty());
ASSERT_EQ(1, sop_query->data[123].size());
auto query_ct123 = sop_query->data[123][0].extract_if_local();
// Create a query response
auto rsop_query = make_unique<SenderOperationResponseQuery>();
rsop_query->package_count = 2;
unique_ptr<SenderOperationResponse> rsop = move(rsop_query);
svr.send(move(rsop));
// Receive the query response
rsop = clt.receive_response(SenderOperationType::sop_query);
rsop_query.reset(dynamic_cast<SenderOperationResponseQuery *>(rsop.release()));
// Validate the data
ASSERT_EQ(2, rsop_query->package_count);
// Send two ResultPackages
auto rp = make_unique<ResultPackage>();
rp->bundle_idx = 0;
rp->label_byte_count = 0;
rp->nonce_byte_count = 0;
rp->psi_result = query_ct0;
svr.send(move(rp));
rp = make_unique<ResultPackage>();
rp->bundle_idx = 123;
rp->label_byte_count = 80;
rp->nonce_byte_count = 4;
rp->psi_result = query_ct123;
rp->label_result.push_back(query_ct123);
svr.send(move(rp));
// Receive two packages
rp = clt.receive_result(get_context()->seal_context());
ASSERT_EQ(0, rp->bundle_idx);
ASSERT_EQ(0, rp->label_byte_count);
ASSERT_EQ(0, rp->bundle_idx);
ASSERT_TRUE(rp->label_result.empty());
rp = clt.receive_result(get_context()->seal_context());
ASSERT_EQ(123, rp->bundle_idx);
ASSERT_EQ(80, rp->label_byte_count);
ASSERT_EQ(4, rp->nonce_byte_count);
ASSERT_EQ(1, rp->label_result.size());
ASSERT_EQ(svr.bytes_sent(), clt.bytes_received());
ASSERT_EQ(svr.bytes_received(), clt.bytes_sent());
}
} // namespace APSITests
| 34.791165 | 97 | 0.62184 | WeiDaiWD |
92a19ff157a16ed176e06a96c8483de43e7e9d8c | 944 | cpp | C++ | QuickGUI/src/QuickGUIOgreEquivalents.cpp | VisualEntertainmentAndTechnologies/VENT-QuickGUI | 7c687193001bcf914bd4a9947644915091ea8723 | [
"Unlicense"
] | 3 | 2017-01-12T19:22:01.000Z | 2017-05-06T09:55:39.000Z | QuickGUI/src/QuickGUIOgreEquivalents.cpp | VisualEntertainmentAndTechnologies/VENT-QuickGUI | 7c687193001bcf914bd4a9947644915091ea8723 | [
"Unlicense"
] | null | null | null | QuickGUI/src/QuickGUIOgreEquivalents.cpp | VisualEntertainmentAndTechnologies/VENT-QuickGUI | 7c687193001bcf914bd4a9947644915091ea8723 | [
"Unlicense"
] | null | null | null | #include "QuickGUIOgreEquivalents.h"
namespace QuickGUI
{
const Vector2 Vector2::ZERO( 0, 0 );
const Vector3 Vector3::ZERO( 0, 0, 0 );
bool ColourValue::operator==(const ColourValue& rhs) const
{
return (r == rhs.r &&
g == rhs.g &&
b == rhs.b &&
a == rhs.a);
}
//---------------------------------------------------------------------
bool ColourValue::operator!=(const ColourValue& rhs) const
{
return !(*this == rhs);
}
const ColourValue ColourValue::ZERO = ColourValue(0.0,0.0,0.0,0.0);
const ColourValue ColourValue::Black = ColourValue(0.0,0.0,0.0);
const ColourValue ColourValue::White = ColourValue(1.0,1.0,1.0);
const ColourValue ColourValue::Red = ColourValue(1.0,0.0,0.0);
const ColourValue ColourValue::Green = ColourValue(0.0,1.0,0.0);
const ColourValue ColourValue::Blue = ColourValue(0.0,0.0,1.0);
}
| 32.551724 | 76 | 0.555085 | VisualEntertainmentAndTechnologies |
92a418fadf9b8d9424d20df7b0066158eedf5d88 | 11,026 | hpp | C++ | common/cxx/config_cxx/include/config_cxx/yaml_wrapper.hpp | csitarichie/someip_cyclone_dds_bridge | 2ccaaa6e2484a938b08562497431df61ab23769f | [
"MIT"
] | null | null | null | common/cxx/config_cxx/include/config_cxx/yaml_wrapper.hpp | csitarichie/someip_cyclone_dds_bridge | 2ccaaa6e2484a938b08562497431df61ab23769f | [
"MIT"
] | null | null | null | common/cxx/config_cxx/include/config_cxx/yaml_wrapper.hpp | csitarichie/someip_cyclone_dds_bridge | 2ccaaa6e2484a938b08562497431df61ab23769f | [
"MIT"
] | null | null | null | #include <memory>
#include <string>
#include <variant>
#include <vector>
#include "adstutil_cxx/compiler_diagnostics.hpp"
ADST_DISABLE_CLANG_WARNING("unused-parameter")
#include <adstutil_cxx/static_string.hpp>
ADST_RESTORE_CLANG_WARNING()
#include "adstutil_cxx/error_handler.hpp"
struct yaml_parser_s;
using yaml_parser_t = yaml_parser_s;
namespace sstr = ak_toolkit::static_str;
namespace adst::common {
/**
* Parse a YAML document and give access to the fields.
*/
class YamlWrapper
{
// not copyable or movable
YamlWrapper(const YamlWrapper&) = delete;
YamlWrapper(YamlWrapper&&) = delete;
YamlWrapper& operator=(const YamlWrapper&) = delete;
YamlWrapper& operator=(YamlWrapper&&) = delete;
public:
/**
* Creates Yaml object which provides access path key type of representation of the file.
*
* In case both static doc and file name is provided then file is read first if file does not exists or null
* than static doc is used if both is NULL or file can not be read and static doc is NULL error is called.
*
* @param onErrorCallBack Error callback. This function will typically never return (e.g. by calling exit/abort).
* @param staticDoc if it is not NULL and file can not be read or NULL then reads from the Static Doc.
* @param fileName if it is not NULL wrapper reads from file if file exists.
*
*/
explicit YamlWrapper(const OnErrorCallBack& onErrorCallBack, const std::string& staticDoc,
const std::string& fileName);
~YamlWrapper() = default;
/**
* Getter for floating point values. The function has to be called with a specific type
* template. In floating point case e.g. ''getValue<double>''.
*
* @param accessPath See details at getValueImpl.
* @param separator See details at getValueImpl.
* @return Pair of which the first is a valid/invalid bool flag and the second is the actual data.
*/
template <typename T, typename std::enable_if<std::is_floating_point<T>::value, T>::type* = nullptr>
std::pair<bool, T> getValue(const std::string& accessPath, const char separator = '/') const
{
char* id;
auto val = getValueImpl(accessPath, separator);
T ret = strtof(val, &id);
return std::make_pair(*id == '\0', ret);
}
/**
* Getter for signed integer (not bool) values. See above for details.
*/
template <typename T,
typename std::enable_if<
std::is_integral<T>::value && std::is_signed<T>::value && !std::is_same<T, bool>::value, T>::type = 0>
std::pair<bool, T> getValue(const std::string& accessPath, const char separator = '/') const
{
char* id;
auto val = getValueImpl(accessPath, separator);
T ret = strtol(val, &id, 0);
return std::make_pair(*id == '\0', ret);
}
/**
* Getter for unsigned integer (not bool) values. See above for details.
*/
template <typename T, typename std::enable_if<std::is_integral<T>::value && std::is_unsigned<T>::value &&
!std::is_same<T, bool>::value,
T>::type = 0>
std::pair<bool, T> getValue(const std::string& accessPath, const char separator = '/') const
{
char* id;
auto val = getValueImpl(accessPath, separator);
T ret = strtoul(val, &id, 0);
return std::make_pair(*id == '\0', ret);
}
/**
* Getter for boolean type values. Internally, this getter accepts true, True and 1 as true, and
* false, False and 0 as false. See :cpp:func:`YamlWrapper::getValueImpl` for more details.
*/
template <typename T, typename std::enable_if<std::is_same<T, bool>::value, T>::type = 0>
std::pair<bool, T> getValue(const std::string& accessPath, const char separator = '/') const
{
auto value = std::string{getValueImpl(accessPath, separator)};
if (value == "true" || value == "True" || value == "1") {
return std::make_pair<bool, T>(true, true);
}
if (value == "false" || value == "False" || value == "0") {
return std::make_pair<bool, T>(true, false);
}
return std::make_pair<bool, T>(false, false);
}
/**
* Getter for string values. This function can be used for any value type. See above for
* details.
*/
template <typename T, typename = typename std::enable_if<std::is_same<T, std::string>::value>::type>
std::pair<bool, const T> getValue(const std::string& accessPath, const char separator = '/') const
{
auto retStr = getValueImpl(accessPath, separator);
return std::make_pair((retStr == std::string{NOT_FOUND}) ? false : true, std::string{retStr});
}
private:
/**
* Abstract base class for every YAML node. All other nodes derive from this. Each node may have
* a key which is used to identify the exact node. The key can be empty and a number too in case
* of sequence elements.
*/
class YamlNode
{
protected:
/**
* enum class for each types of nodes. The root node is always a DOC. Other nodes follow obviously.
*/
enum class Type
{
VALUE,
SEQUENCE,
MAPPING,
DOC
};
private:
// not copyable or movable
YamlNode(const YamlNode&) = delete;
YamlNode(YamlNode&&) = delete;
YamlNode& operator=(const YamlNode&) = delete;
YamlNode& operator=(YamlNode&&) = delete;
/// The wrapper constuctor needs access to the fields.
friend class YamlWrapper;
const Type type_; /// The type of the node. See above
const std::string value_; /// At scalars this is the real value, at other cases it's "<ClassName>Value"
protected:
/// The parent of the node in case of MAPPING and SEQUENCE type nodes.
YamlNode& parent_;
/// The children of the node if this is a MAPPING or a SEQUENCE type node.
std::vector<std::unique_ptr<YamlNode>> children_;
/// The name (key) of the node which can be used to identify the node.
const std::string name_;
public:
/**
* The more common constructor needs a parent node, a key, a type and a value.
*
* @param aParent Parent node.
* @param aName Name (key) which will be used for identification.
* @param aType Type of the node.
* @param aValue Value of the node, which is most meaningful in case of scalars (leaf nodes).
*/
explicit YamlNode(YamlNode& aParent, const std::string& aName, Type aType, const std::string& aValue)
: type_(aType)
, value_(aValue)
, parent_(aParent)
, name_(aName)
{
}
/**
* Construct a root node. Sets the type to DOC and the parent to
* itself. This is because the root node is the parent of itself (we
* cannot have a reference to NULL).
*/
explicit YamlNode()
: type_(Type::DOC)
, value_("YamlDocValue")
, parent_(*this)
{
}
/**
* Getter function for the node key.
*
* @return Node key.
*/
const std::string& getKey() const
{
return name_;
}
/**
* Getter function for the node type.
*
* @return Node type.
*/
Type getType() const
{
return type_;
}
/**
* Getter function for the the node value.
*
* @return the value of the node
*/
const std::string& getValue() const
{
return value_;
}
virtual ~YamlNode() = 0;
}; // class YamlNode
/**
* Concrete class for the doc (root) node. Shall not be used for other node types.
*/
class YamlDoc : public YamlNode
{
public:
explicit YamlDoc()
: YamlNode()
{
}
};
/**
* The mapping node. This is not an actual std::map but represents a YAML mapping. A mapping
* node's children can be VALUE, MAPPING or SEQUENCE type nodes. Searching on it takes O(n)
* time, where n is the number of elements.
*/
class YamlMapping : public YamlNode
{
public:
explicit YamlMapping(YamlNode& aParent, const std::string& aName)
: YamlNode(aParent, aName, YamlNode::Type::MAPPING, "YamlMappingValue")
{
}
};
/**
* The sequence node. It's child nodes are stored in order and can be VALUE, MAPPING and
* SEQUENCE type nodes.
*/
class YamlSequence : public YamlNode
{
public:
explicit YamlSequence(YamlNode& aParent, const std::string& aName)
: YamlNode(aParent, aName, YamlNode::Type::SEQUENCE, "YamlSequenceValue")
{
}
};
/**
* The value node. Actual VALUEs are stored in this type of nodes.
*/
class YamlValue : public YamlNode
{
public:
explicit YamlValue(YamlNode& aParent, const std::string& aName, const std::string& aValue)
: YamlNode(aParent, aName, YamlNode::Type::VALUE, aValue)
{
}
};
/**
* Retrieves node value as string from the node tree. This is the core functionality for
* accessing node values (since internally all node values are represented as strings).
*
* @param accessPath Access path to the node. Nested maps should be searched with their
* respective keys, sequences should be searched by index.
* @param separator Separator which is used between access path elements for nested node
* searching.
*/
const char* getValueImpl(const std::string& accessPath, char separator) const;
/**
* Parse the YAML doc from file and create the node tree.
* @param fileName path to the file to read.
* @return true in case of success otherwise false
*/
bool initFromFile(const std::string& fileName);
/**
* Parse the YAML doc from static 0 terminated c string and create the node tree.
* @param builtInDoc the compiled in config doc useful for tests where no extra file is provided.
* @return true in case of success otherwise false
*/
bool initFromConstString(const std::string& builtInDoc);
bool parse(yaml_parser_t* parser);
/// The root node. All other nodes are children of this node.
std::unique_ptr<YamlNode> root_ = std::make_unique<YamlDoc>();
/// Used as node value in case the actual node cannot be found.
static constexpr auto NOT_FOUND = sstr::literal("Not Found");
/// Default error callback function.
const OnErrorCallBack& onErrorCallBack_;
};
inline YamlWrapper::YamlNode::~YamlNode()
{
}
} // namespace adst::common
| 34.782334 | 120 | 0.605024 | csitarichie |
92a53706f39c6deaa856a91f2610f5040a94c679 | 941 | cc | C++ | third_party/webrtc/src/chromium/src/mojo/converters/transform/transform_type_converters.cc | bopopescu/webrtc-streaming-node | 727a441204344ff596401b0253caac372b714d91 | [
"MIT"
] | 8 | 2016-02-08T11:59:31.000Z | 2020-05-31T15:19:54.000Z | third_party/webrtc/src/chromium/src/mojo/converters/transform/transform_type_converters.cc | bopopescu/webrtc-streaming-node | 727a441204344ff596401b0253caac372b714d91 | [
"MIT"
] | 1 | 2021-05-05T11:11:31.000Z | 2021-05-05T11:11:31.000Z | third_party/webrtc/src/chromium/src/mojo/converters/transform/transform_type_converters.cc | bopopescu/webrtc-streaming-node | 727a441204344ff596401b0253caac372b714d91 | [
"MIT"
] | 7 | 2016-02-09T09:28:14.000Z | 2020-07-25T19:03:36.000Z | // Copyright 2015 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 "mojo/converters/transform/transform_type_converters.h"
namespace mojo {
// static
TransformPtr TypeConverter<TransformPtr, gfx::Transform>::Convert(
const gfx::Transform& input) {
std::vector<float> storage(16);
input.matrix().asRowMajorf(&storage[0]);
mojo::Array<float> matrix;
matrix.Swap(&storage);
TransformPtr transform(Transform::New());
transform->matrix = matrix.Pass();
return transform.Pass();
}
// static
gfx::Transform TypeConverter<gfx::Transform, TransformPtr>::Convert(
const TransformPtr& input) {
if (input.is_null())
return gfx::Transform();
gfx::Transform transform(gfx::Transform::kSkipInitialization);
transform.matrix().setRowMajorf(&input->matrix.storage()[0]);
return transform;
}
} // namespace mojo
| 29.40625 | 73 | 0.730074 | bopopescu |
92a5c7f2a916af5dad02a0129e148cf91381964f | 21,312 | cpp | C++ | src/S2LP.cpp | cparata/S2-LP | 620eb9026749425bd8bf8cd8929711aae8f831fd | [
"BSD-3-Clause"
] | 4 | 2020-06-10T00:10:36.000Z | 2021-07-04T16:12:41.000Z | src/S2LP.cpp | cparata/S2-LP | 620eb9026749425bd8bf8cd8929711aae8f831fd | [
"BSD-3-Clause"
] | 3 | 2021-04-16T15:50:28.000Z | 2021-09-15T14:59:51.000Z | src/S2LP.cpp | cparata/S2-LP | 620eb9026749425bd8bf8cd8929711aae8f831fd | [
"BSD-3-Clause"
] | 5 | 2020-03-25T09:39:02.000Z | 2022-03-09T18:48:10.000Z | /**
******************************************************************************
* @file S2LP.cpp
* @author SRA
* @version V1.0.0
* @date March 2020
* @brief Implementation of a S2-LP sub-1GHz transceiver.
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2020 STMicroelectronics</center></h2>
*
* 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 STMicroelectronics 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.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "S2LP.h"
/* Defines -------------------------------------------------------------------*/
#define HEADER_WRITE_MASK 0x00 /*!< Write mask for header byte*/
#define HEADER_READ_MASK 0x01 /*!< Read mask for header byte*/
#define HEADER_ADDRESS_MASK 0x00 /*!< Address mask for header byte*/
#define HEADER_COMMAND_MASK 0x80 /*!< Command mask for header byte*/
#define S2LP_CMD_SIZE 2
#define BUILT_HEADER(add_comm, w_r) (add_comm | w_r) /*!< macro to build the header byte*/
#define WRITE_HEADER BUILT_HEADER(HEADER_ADDRESS_MASK, HEADER_WRITE_MASK) /*!< macro to build the write header byte*/
#define READ_HEADER BUILT_HEADER(HEADER_ADDRESS_MASK, HEADER_READ_MASK) /*!< macro to build the read header byte*/
#define COMMAND_HEADER BUILT_HEADER(HEADER_COMMAND_MASK, HEADER_WRITE_MASK) /*!< macro to build the command header byte*/
#define LINEAR_FIFO_ADDRESS 0xFF /*!< Linear FIFO address*/
/* Class Implementation ------------------------------------------------------*/
/** Constructor
* @param spi object of the instance of the spi peripheral
* @param csn the spi chip select pin
* @param sdn the shutdown pin
* @param irqn the pin to receive IRQ event
* @param frequency the base carrier frequency in Hz
* @param xtalFrequency the crystal oscillator frequency
* @param paInfo information about external power amplifier
* @param irq_gpio the S2-LP gpio used to receive the IRQ events
* @param my_addr address of the device
* @param multicast_addr multicast address
* @param broadcast_addr broadcast address
*/
S2LP::S2LP(SPIClass *spi, int csn, int sdn, int irqn, uint32_t frequency, uint32_t xtalFrequency, PAInfo_t paInfo, S2LPGpioPin irq_gpio, uint8_t my_addr, uint8_t multicast_addr, uint8_t broadcast_addr) : dev_spi(spi), csn_pin(csn), sdn_pin(sdn), irq_pin(irqn), lFrequencyBase(frequency), s_lXtalFrequency(xtalFrequency), s_paInfo(paInfo), irq_gpio_selected(irq_gpio), my_address(my_addr), multicast_address(multicast_addr), broadcast_address(broadcast_addr)
{
Callback<void()>::func = std::bind(&S2LP::S2LPIrqHandler, this);
irq_handler = static_cast<S2LPEventHandler>(Callback<void()>::callback);
memset((void *)&g_xStatus, 0, sizeof(S2LPStatus));
s_cWMbusSubmode = WMBUS_SUBMODE_NOT_CONFIGURED;
current_event_callback = NULL;
nr_of_irq_disabled = 0;
xTxDoneFlag = RESET;
memset((void *)vectcRxBuff, 0, FIFO_SIZE*sizeof(uint8_t));
memset((void *)vectcTxBuff, 0, FIFO_SIZE*sizeof(uint8_t));
cRxData = 0;
is_waiting_for_read = false;
is_bypass_enabled = false;
}
/**
* @brief Initialize the S2-LP library.
* @param None.
* @retval None.
*/
void S2LP::begin(void)
{
pinMode(csn_pin, OUTPUT);
digitalWrite(csn_pin, HIGH);
pinMode(sdn_pin, OUTPUT);
/* Shutdown the S2-LP */
digitalWrite(sdn_pin, HIGH);
delay(1);
digitalWrite(sdn_pin, LOW);
delay(1);
/* S2-LP soft reset */
S2LPCmdStrobeSres();
SGpioInit xGpioIRQ={
irq_gpio_selected,
S2LP_GPIO_MODE_DIGITAL_OUTPUT_LP,
S2LP_GPIO_DIG_OUT_IRQ
};
S2LPGpioInit(&xGpioIRQ);
SRadioInit xRadioInit = {
lFrequencyBase, /* base carrier frequency */
MOD_2FSK, /* modulation type */
38400, /* data rate */
20000, /* frequency deviation */
100000 /* bandwidth */
};
S2LPRadioInit(&xRadioInit);
S2LPRadioSetMaxPALevel(S_DISABLE);
if(s_paInfo.paRfRangeExtender == RANGE_EXT_NONE)
{
S2LPRadioSetPALeveldBm(7, 12);
} else
{
/* in case we are using a board with external PA, the S2LPRadioSetPALeveldBm will be not functioning because
the output power is affected by the amplification of this external component.
Set the raw register. */
/* For example, paLevelValue=0x25 will give about 19dBm on a STEVAL FKI-915V1 */
S2LPSpiWriteRegisters(PA_POWER8_ADDR, 1, &s_paInfo.paLevelValue);
if(s_paInfo.paRfRangeExtender == RANGE_EXT_SKYWORKS_SE2435L)
{
S2LPGpioInit(&s_paInfo.paSignalCSD_S2LP);
S2LPGpioInit(&s_paInfo.paSignalCPS_S2LP);
S2LPGpioInit(&s_paInfo.paSignalCTX_S2LP);
} else if(s_paInfo.paRfRangeExtender == RANGE_EXT_SKYWORKS_SKY66420)
{
pinMode(s_paInfo.paSignalCSD_MCU, OUTPUT);
pinMode(s_paInfo.paSignalCPS_MCU, OUTPUT);
pinMode(s_paInfo.paSignalCTX_MCU, OUTPUT);
}
}
S2LPRadioSetPALevelMaxIndex(7);
PktBasicInit xBasicInit={
16, /* Preamble length */
32, /* Sync length */
0x88888888, /* Sync word */
S_ENABLE, /* Variable length */
S_DISABLE, /* Extended length field */
PKT_CRC_MODE_8BITS, /* CRC mode */
S_ENABLE, /* Enable address */
S_DISABLE, /* Enable FEC */
S_ENABLE /* Enable Whitening */
};
S2LPPktBasicInit(&xBasicInit);
PktBasicAddressesInit xAddressInit={
S_ENABLE, /* Filtering my address */
my_address, /* My address */
S_ENABLE, /* Filtering multicast address */
multicast_address, /* Multicast address */
S_ENABLE, /* Filtering broadcast address */
broadcast_address /* broadcast address */
};
S2LPPktBasicAddressesInit(&xAddressInit);
SCsmaInit xCsmaInit={
S_ENABLE, /* Persistent mode enable/disable */
CSMA_PERIOD_64TBIT, /* CS Period */
3, /* CS Timeout */
5, /* Max number of backoffs */
0xFA21, /* BU counter seed */
32 /* CU prescaler */
};
S2LPCsmaInit(&xCsmaInit);
S2LPPacketHandlerSetRxPersistentMode(S_ENABLE);
SRssiInit xSRssiInit = {
.cRssiFlt = 14,
.xRssiMode = RSSI_STATIC_MODE,
.cRssiThreshdBm = -60,
};
S2LPRadioRssiInit(&xSRssiInit);
S2LPManagementRcoCalibration();
/* Enable PQI */
S2LPRadioSetPqiCheck(0x00);
S2LPRadioSetPqiCheck(S_ENABLE);
/* S2LP IRQs enable */
S2LPGpioIrqDeInit(NULL);
S2LPGpioIrqConfig(RX_DATA_READY,S_ENABLE);
S2LPGpioIrqConfig(TX_DATA_SENT , S_ENABLE);
/* clear FIFO if needed */
S2LPCmdStrobeFlushRxFifo();
/* Set infinite Timeout */
S2LPTimerSetRxTimerCounter(0);
S2LPTimerSetRxTimerStopCondition(ANY_ABOVE_THRESHOLD);
/* IRQ registers blanking */
S2LPGpioIrqClearStatus();
uint8_t tmp = 0x90;
S2LPSpiWriteRegisters(0x76, 1, &tmp);
if(s_paInfo.paRfRangeExtender == RANGE_EXT_SKYWORKS_SKY66420)
{
FEM_Operation_SKY66420(FEM_RX);
}
/* Go to RX state */
S2LPCmdStrobeCommand(CMD_RX);
attachInterrupt(irq_pin, irq_handler, FALLING);
}
/**
* @brief DeInitialize the S2-LP library.
* @param None.
* @retval None.
*/
void S2LP::end(void)
{
/* Shutdown the S2-LP */
digitalWrite(sdn_pin, HIGH);
delay(1);
digitalWrite(sdn_pin, LOW);
delay(1);
/* S2-LP soft reset */
S2LPCmdStrobeSres();
/* Detach S2-LP IRQ */
detachInterrupt(irq_pin);
/* Reset CSN pin */
pinMode(csn_pin, INPUT);
/* Reset SDN pin */
pinMode(sdn_pin, INPUT);
/* Reset CSD, CPS and CTX if it is needed */
if(s_paInfo.paRfRangeExtender == RANGE_EXT_SKYWORKS_SKY66420)
{
pinMode(s_paInfo.paSignalCSD_MCU, INPUT);
pinMode(s_paInfo.paSignalCPS_MCU, INPUT);
pinMode(s_paInfo.paSignalCTX_MCU, INPUT);
}
/* Reset all internal variables */
memset((void *)&g_xStatus, 0, sizeof(S2LPStatus));
s_cWMbusSubmode = WMBUS_SUBMODE_NOT_CONFIGURED;
current_event_callback = NULL;
nr_of_irq_disabled = 0;
xTxDoneFlag = RESET;
memset((void *)vectcRxBuff, 0, FIFO_SIZE*sizeof(uint8_t));
memset((void *)vectcTxBuff, 0, FIFO_SIZE*sizeof(uint8_t));
cRxData = 0;
is_waiting_for_read = false;
is_bypass_enabled = false;
}
/**
* @brief Attach the callback for Receive event.
* @param func the Receive callback.
* @retval None.
*/
void S2LP::attachS2LPReceive(S2LPEventHandler func)
{
current_event_callback = func;
}
/**
* @brief Send the payload packet.
* @param payload pointer to the data to be sent.
* @param payload_len length in bytes of the payload data.
* @param dest_addr destination address.
* @param use_csma_ca should CSMA/CA be enabled for transmission.
* @retval zero in case of success, non-zero error code otherwise.
* @note the maximum payload size allowed is 128 bytes
*/
uint8_t S2LP::send(uint8_t *payload, uint8_t payload_len, uint8_t dest_addr, bool use_csma_ca)
{
uint32_t start_time;
uint32_t current_time;
if(payload_len > FIFO_SIZE)
{
return 1;
}
disableS2LPIrq();
/* Go to Ready mode */
if(S2LPSetReadyState())
{
enableS2LPIrq();
return 1;
}
S2LPPktBasicSetPayloadLength(payload_len);
S2LPSetRxSourceReferenceAddress(dest_addr);
if(use_csma_ca)
{
S2LPCsma(S_ENABLE);
}
/* Flush TX FIFO */
S2LPCmdStrobeCommand(CMD_FLUSHTXFIFO);
memcpy(vectcTxBuff, payload, payload_len);
S2LPSpiWriteFifo(payload_len, vectcTxBuff);
/* IRQ registers blanking */
S2LPGpioIrqClearStatus();
enableS2LPIrq();
uint8_t tmp=0x9C;
S2LPSpiWriteRegisters(0x76,1,&tmp);
if(s_paInfo.paRfRangeExtender == RANGE_EXT_SKYWORKS_SKY66420)
{
FEM_Operation_SKY66420(FEM_TX);
}
S2LPCmdStrobeCommand(CMD_TX);
start_time = millis();
/* wait for TX done */
do
{
current_time = millis();
} while(!xTxDoneFlag && (current_time - start_time) <= 1000);
if(use_csma_ca)
{
S2LPCsma(S_DISABLE);
}
if(!is_waiting_for_read)
{
uint8_t tmp = 0x90;
S2LPSpiWriteRegisters(0x76, 1, &tmp);
if(s_paInfo.paRfRangeExtender == RANGE_EXT_SKYWORKS_SKY66420)
{
FEM_Operation_SKY66420(FEM_RX);
}
/* Return to RX state */
S2LPCmdStrobeCommand(CMD_RX);
}
disableS2LPIrq();
/* Timeout case */
if(!xTxDoneFlag)
{
enableS2LPIrq();
return 1;
}
xTxDoneFlag = RESET;
enableS2LPIrq();
return 0;
}
/**
* @brief Get the payload size of the received packet.
* @param None.
* @retval the payload size of the received packet.
*/
uint8_t S2LP::getRecvPayloadLen(void)
{
return cRxData;
}
/**
* @brief Read the payload packet.
* @param payload pointer to the data to be sent.
* @param payload_len length in bytes of the payload data.
* @retval the number of read bytes.
* @note the maximum payload size allowed is 128 bytes
*/
uint8_t S2LP::read(uint8_t *payload, uint8_t payload_len)
{
uint8_t ret_val = cRxData;
disableS2LPIrq();
if(payload_len < cRxData)
{
enableS2LPIrq();
return 0;
}
memcpy(payload, vectcRxBuff, cRxData);
cRxData = 0;
is_waiting_for_read = false;
uint8_t tmp = 0x90;
S2LPSpiWriteRegisters(0x76, 1, &tmp);
if(s_paInfo.paRfRangeExtender == RANGE_EXT_SKYWORKS_SKY66420)
{
FEM_Operation_SKY66420(FEM_RX);
}
/* Return to RX state */
S2LPCmdStrobeCommand(CMD_RX);
enableS2LPIrq();
return ret_val;
}
/**
* @brief Sets the channel number.
* @param cChannel the channel number.
* @retval None.
*/
void S2LP::setRadioChannel(uint8_t cChannel)
{
return S2LPRadioSetChannel(cChannel);
}
/**
* @brief Returns the actual channel number.
* @param None.
* @retval uint8_t Actual channel number.
*/
uint8_t S2LP::getRadioChannel(void)
{
return S2LPRadioGetChannel();
}
/**
* @brief Set the channel space factor in channel space register.
* The channel spacing step is computed as F_Xo/32768.
* @param fChannelSpace the channel space expressed in Hz.
* @retval None.
*/
void S2LP::setRadioChannelSpace(uint32_t lChannelSpace)
{
return S2LPRadioSetChannelSpace(lChannelSpace);
}
/**
* @brief Return the channel space register.
* @param None.
* @retval uint32_t Channel space. The channel space is: CS = channel_space_factor x XtalFrequency/2^15
* where channel_space_factor is the CHSPACE register value.
*/
uint32_t S2LP::getRadioChannelSpace(void)
{
return S2LPRadioGetChannelSpace();
}
/**
* @brief Set the Ready state.
* @param None.
* @retval zero in case of success, non-zero error code otherwise.
*/
uint8_t S2LP::S2LPSetReadyState(void)
{
uint8_t ret_val = 0;
uint32_t start_time;
uint32_t current_time;
S2LPCmdStrobeCommand(CMD_SABORT);
start_time = millis();
do
{
S2LPRefreshStatus();
current_time = millis();
} while(g_xStatus.MC_STATE != MC_STATE_READY && (current_time - start_time) <= 1000);
if((current_time - start_time) > 1000)
{
ret_val = 1;
}
return ret_val;
}
S2LPCutType S2LP::S2LPManagementGetCut(void)
{
uint8_t tmp;
/* Read Cut version from S2LP register */
S2LPSpiReadRegisters(0xF1, 1, &tmp);
return (S2LPCutType)tmp;
}
/**
* @brief IRQ Handler.
* @param None.
* @retval None.
*/
void S2LP::S2LPIrqHandler(void)
{
S2LPIrqs xIrqStatus;
/* Get the IRQ status */
S2LPGpioIrqGetStatus(&xIrqStatus);
/* Check the SPIRIT TX_DATA_SENT IRQ flag */
if(xIrqStatus.IRQ_TX_DATA_SENT)
{
/* set the tx_done_flag to manage the event in the send() */
xTxDoneFlag = SET;
}
/* Check the S2LP RX_DATA_READY IRQ flag */
if(xIrqStatus.IRQ_RX_DATA_READY)
{
/* Get the RX FIFO size */
cRxData = S2LPFifoReadNumberBytesRxFifo();
/* Read the RX FIFO */
S2LPSpiReadFifo(cRxData, vectcRxBuff);
/* Flush the RX FIFO */
S2LPCmdStrobeFlushRxFifo();
is_waiting_for_read = true;
/* Call application callback */
if(current_event_callback)
{
current_event_callback();
}
}
}
/**
* @brief Disable the S2LP interrupts.
* @param None.
* @retval None.
*/
void S2LP::disableS2LPIrq(void)
{
if(nr_of_irq_disabled == 0)
{
detachInterrupt(irq_pin);
}
nr_of_irq_disabled++;
}
/**
* @brief Enable the S2LP interrupts.
* @param None.
* @retval None.
*/
void S2LP::enableS2LPIrq(void)
{
if(nr_of_irq_disabled > 0)
{
nr_of_irq_disabled--;
if(nr_of_irq_disabled == 0)
{
attachInterrupt(irq_pin, irq_handler, FALLING);
}
}
}
/**
* @brief Commands for external PA of type SKY66420.
* @param operation the command to be executed.
* @retval None.
*/
void S2LP::FEM_Operation_SKY66420(FEM_OperationType operation)
{
switch (operation)
{
case FEM_SHUTDOWN:
{
/* Puts CSD high to turn on PA */
digitalWrite(s_paInfo.paSignalCSD_MCU, LOW);
/* Puts CTX high to go in TX state DON'T CARE */
digitalWrite(s_paInfo.paSignalCTX_MCU, HIGH);
/* No Bypass mode select DON'T CARE */
digitalWrite(s_paInfo.paSignalCPS_MCU, HIGH);
break;
}
case FEM_TX_BYPASS:
{
/* Puts CSD high to turn on PA */
digitalWrite(s_paInfo.paSignalCSD_MCU, HIGH);
/* Puts CTX high to go in TX state */
digitalWrite(s_paInfo.paSignalCTX_MCU, HIGH);
/* Bypass mode select */
digitalWrite(s_paInfo.paSignalCPS_MCU, LOW);
break;
}
case FEM_TX:
{
/* Puts CSD high to turn on PA */
digitalWrite(s_paInfo.paSignalCSD_MCU, HIGH);
/* Puts CTX high to go in TX state */
digitalWrite(s_paInfo.paSignalCTX_MCU, HIGH);
/* No Bypass mode select DON'T CARE */
digitalWrite(s_paInfo.paSignalCPS_MCU, HIGH);
break;
}
case FEM_RX:
{
/* Puts CSD high to turn on PA */
digitalWrite(s_paInfo.paSignalCSD_MCU, HIGH);
/* Puts CTX low */
digitalWrite(s_paInfo.paSignalCTX_MCU, LOW);
/* Check Bypass mode */
if (is_bypass_enabled)
{
digitalWrite(s_paInfo.paSignalCPS_MCU, LOW);
} else
{
digitalWrite(s_paInfo.paSignalCPS_MCU, HIGH);
}
break;
}
default:
/* Error */
break;
}
}
/**
* @brief Write single or multiple registers.
* @param cRegAddress: base register's address to be write
* @param cNbBytes: number of registers and bytes to be write
* @param pcBuffer: pointer to the buffer of values have to be written into registers
* @retval Device status
*/
S2LPStatus S2LP::S2LPSpiWriteRegisters(uint8_t cRegAddress, uint8_t cNbBytes, uint8_t* pcBuffer )
{
uint8_t header[S2LP_CMD_SIZE]={WRITE_HEADER,cRegAddress};
S2LPStatus status;
SpiSendRecv( header, pcBuffer, cNbBytes );
((uint8_t*)&status)[1]=header[0];
((uint8_t*)&status)[0]=header[1];
return status;
}
/**
* @brief Read single or multiple registers.
* @param cRegAddress: base register's address to be read
* @param cNbBytes: number of registers and bytes to be read
* @param pcBuffer: pointer to the buffer of registers' values read
* @retval Device status
*/
S2LPStatus S2LP::S2LPSpiReadRegisters(uint8_t cRegAddress, uint8_t cNbBytes, uint8_t* pcBuffer )
{
uint8_t header[S2LP_CMD_SIZE]={READ_HEADER,cRegAddress};
S2LPStatus status;
SpiSendRecv( header, pcBuffer, cNbBytes );
((uint8_t*)&status)[1]=header[0];
((uint8_t*)&status)[0]=header[1];
return status;
}
/**
* @brief Send a command
* @param cCommandCode: command code to be sent
* @retval Device status
*/
S2LPStatus S2LP::S2LPSpiCommandStrobes(uint8_t cCommandCode)
{
uint8_t header[S2LP_CMD_SIZE]={COMMAND_HEADER,cCommandCode};
S2LPStatus status;
SpiSendRecv( header, NULL, 0 );
((uint8_t*)&status)[1]=header[0];
((uint8_t*)&status)[0]=header[1];
return status;
}
/**
* @brief Write data into TX FIFO.
* @param cNbBytes: number of bytes to be written into TX FIFO
* @param pcBuffer: pointer to data to write
* @retval Device status
*/
S2LPStatus S2LP::S2LPSpiWriteFifo(uint8_t cNbBytes, uint8_t* pcBuffer)
{
uint8_t header[S2LP_CMD_SIZE]={WRITE_HEADER,LINEAR_FIFO_ADDRESS};
S2LPStatus status;
SpiSendRecv( header, pcBuffer, cNbBytes );
((uint8_t*)&status)[1]=header[0];
((uint8_t*)&status)[0]=header[1];
return status;
}
/**
* @brief Read data from RX FIFO.
* @param cNbBytes: number of bytes to read from RX FIFO
* @param pcBuffer: pointer to data read from RX FIFO
* @retval Device status
*/
S2LPStatus S2LP::S2LPSpiReadFifo(uint8_t cNbBytes, uint8_t* pcBuffer)
{
uint8_t header[S2LP_CMD_SIZE]={READ_HEADER,LINEAR_FIFO_ADDRESS};
S2LPStatus status;
SpiSendRecv( header, pcBuffer, cNbBytes );
((uint8_t*)&status)[1]=header[0];
((uint8_t*)&status)[0]=header[1];
return status;
}
/**
* @brief Basic SPI function to send/receive data.
* @param pcHeader: pointer to header to be sent
* @param pcBuffer: pointer to data to be sent/received
* @param cNbBytes: number of bytes to send/receive
* @retval Device status
*/
void S2LP::SpiSendRecv(uint8_t *pcHeader, uint8_t *pcBuffer, uint16_t cNbBytes)
{
disableS2LPIrq();
dev_spi->beginTransaction(SPISettings(8000000, MSBFIRST, SPI_MODE0));
digitalWrite(csn_pin, LOW);
dev_spi->transfer(pcHeader, S2LP_CMD_SIZE);
if(cNbBytes)
{
dev_spi->transfer(pcBuffer, cNbBytes);
}
digitalWrite(csn_pin, HIGH);
enableS2LPIrq();
}
/**
* @brief Management of RCO calibration.
* @param None.
* @retval None.
*/
void S2LP::S2LPManagementRcoCalibration(void)
{
uint8_t tmp[2],tmp2;
S2LPSpiReadRegisters(0x6D, 1, &tmp2);
tmp2 |= 0x01;
S2LPSpiWriteRegisters(0x6D, 1, &tmp2);
S2LPSpiCommandStrobes(0x63);
delay(100);
S2LPSpiCommandStrobes(0x62);
do
{
S2LPSpiReadRegisters(0x8D, 1, tmp);
}
while((tmp[0]&0x10)==0);
S2LPSpiReadRegisters(0x94, 2, tmp);
S2LPSpiReadRegisters(0x6F, 1, &tmp2);
tmp[1]=(tmp[1]&0x80)|(tmp2&0x7F);
S2LPSpiWriteRegisters(0x6E, 2, tmp);
S2LPSpiReadRegisters(0x6D, 1, &tmp2);
tmp2 &= 0xFE;
S2LPSpiWriteRegisters(0x6D, 1, &tmp2);
}
| 25.801453 | 457 | 0.680133 | cparata |
92ab368c5a42a6994494b3535c97511d109ad44e | 8,755 | cc | C++ | src/CCA/Components/Wasatch/Coal/CharOxidation/FirstOrderArrhenius/FirstOrderInterface.cc | abagusetty/Uintah | fa1bf819664fa6f09c5a7cd076870a40816d35c9 | [
"MIT"
] | 3 | 2020-06-10T08:21:31.000Z | 2020-06-23T18:33:16.000Z | src/CCA/Components/Wasatch/Coal/CharOxidation/FirstOrderArrhenius/FirstOrderInterface.cc | abagusetty/Uintah | fa1bf819664fa6f09c5a7cd076870a40816d35c9 | [
"MIT"
] | null | null | null | src/CCA/Components/Wasatch/Coal/CharOxidation/FirstOrderArrhenius/FirstOrderInterface.cc | abagusetty/Uintah | fa1bf819664fa6f09c5a7cd076870a40816d35c9 | [
"MIT"
] | 2 | 2019-12-30T05:48:30.000Z | 2020-02-12T16:24:16.000Z | #include "FirstOrderInterface.h"
#include <stdexcept>
#include <sstream>
#include <CCA/Components/Wasatch/TimeStepper.h>
#include <CCA/Components/Wasatch/Coal/CharOxidation/LangmuirHinshelwood/CharOxidation.h>
#include <CCA/Components/Wasatch/Coal/CharOxidation/CO2andCO_RHS.h>
#include <CCA/Components/Wasatch/Coal/CharOxidation/O2RHS.h>
#include <CCA/Components/Wasatch/Coal/CharOxidation/CharRHS.h>
#include <CCA/Components/Wasatch/Coal/CharOxidation/H2andH2ORHS.h>
#include <CCA/Components/Wasatch/Coal/Devolatilization/CPD/c0_fun.h>
#include <CCA/Components/Wasatch/Coal/CoalData.h>
#include "FirstOrderArrhenius.h"
using std::ostringstream;
using std::endl;
namespace FOA{
using CHAR::CharModel;
using CHAR::CharGasSpecies;
using CHAR::CharOxidationData;
using WasatchCore::GraphCategories;
//------------------------------------------------------------------
template< typename FieldT >
FirstOrderInterface<FieldT>::
FirstOrderInterface( WasatchCore::GraphCategories& gc,
const Tag& pDiamTag,
const Tag& pTempTag,
const Tag& gTempTag,
const Tag& co2MassFracTag,
const Tag& coMassFracTag,
const Tag& o2MassFracTag,
const Tag& h2MassFracTag,
const Tag& h2oMassFracTag,
const Tag& ch4MassFracTag,
const Tag& mixMWTag,
const Tag& pDensTag,
const Tag& gPressTag,
const Tag& pMassTag,
const Tag& initPrtmassTag,
const Coal::CoalType coalType,
const DEV::DevModel dvmodel )
: gc_ ( gc ),
pTempTag_ ( pTempTag ),
gTempTag_ ( gTempTag ),
mixMWTag_ ( mixMWTag ),
pDensTag_ ( pDensTag ),
gPressTag_ ( gPressTag ),
pDiamTag_ ( pDiamTag ),
pMassTag_ ( pMassTag ),
pMass0Tag_ ( initPrtmassTag ),
o2MassFracTag_ ( o2MassFracTag ),
h2oMassFracTag_( h2oMassFracTag ),
h2MassFracTag_ ( h2MassFracTag ),
co2MassFracTag_( co2MassFracTag ),
coMassFracTag_ ( coMassFracTag ),
ch4MassFracTag_( ch4MassFracTag ),
o2_rhsTag_ ( Coal::StringNames::self().char_o2_rhs, STATE_NONE ),
h2_rhsTag_ ( Coal::StringNames::self().char_h2_rhs, STATE_NONE ),
h2o_rhsTag_ ( Coal::StringNames::self().char_h2o_rhs, STATE_NONE ),
ch4_rhsTag_ ( Coal::StringNames::self().char_ch4_rhs, STATE_NONE ),
co2_rhsTag_ ( Coal::StringNames::self().char_co2_rhs, STATE_NONE ),
co_rhsTag_ ( Coal::StringNames::self().char_co_rhs, STATE_NONE ),
initDevChar_ ( dvmodel == DEV::CPDM ),
charModel_ ( CHAR::FIRST_ORDER ),
charData_ ( coalType ),
firstOrderData_( coalType ),
sNames_ ( Coal::StringNames::self() )
{
proc0cout << "Setting up char model: "
<< CHAR::char_model_name(charModel_)
<< std::endl;
parse_equations();
set_tags();
register_expressions();
}
//------------------------------------------------------------------
template< typename FieldT >
void
FirstOrderInterface<FieldT>::
parse_equations()
{
proc0cout << "Parsing equations...\n";
// Get initial mass fraction of char within coal volatiles
double c0 = 0.0;
if( initDevChar_ ){
c0 = CPD::c0_fun(charData_.get_C(), charData_.get_O());
}
// Calculate initial mass fraction of char within coal
double char0 = charData_.get_fixed_C()+ charData_.get_vm()*c0;
proc0cout << std::endl
<< "Initial char mass fraction in coal volatiles is : "
<< charData_.get_vm()*c0
<< std::endl
<< "Initial mass fraction of char in coal is : "
<< char0 << std::endl;
charEqn_ = new Coal::CoalEquation( sNames_.char_mass, pMassTag_, char0, gc_ );
eqns_.clear();
eqns_.push_back( charEqn_ );
}
//------------------------------------------------------------------
template< typename FieldT >
void
FirstOrderInterface<FieldT>::
set_tags()
{
charMassTag_ = charEqn_->solution_variable_tag();
charMass_rhsTag_ = charEqn_->rhs_tag();
oxidation_rhsTag_ = Tag( sNames_.char_oxid_rhs, STATE_NONE );
heteroCo2Tag_ = Tag( sNames_.char_gasifco2, STATE_NONE );
heteroH2oTag_ = Tag( sNames_.char_gasifh2o, STATE_NONE );
co2CoRatioTag_ = Tag( sNames_.char_coco2ratio,STATE_NONE );
speciesSrcTags_.clear();
speciesSrcTags_.push_back( co2_rhsTag_ );
speciesSrcTags_.push_back( co_rhsTag_ );
speciesSrcTags_.push_back( o2_rhsTag_ );
speciesSrcTags_.push_back( h2_rhsTag_ );
speciesSrcTags_.push_back( h2o_rhsTag_ );
// order here matters: [ CO2, CO, O2, H2, H2O, CH4 ]
massFracTags_.clear();
massFracTags_.push_back( co2MassFracTag_ );
massFracTags_.push_back( coMassFracTag_ );
massFracTags_.push_back( o2MassFracTag_ );
massFracTags_.push_back( h2MassFracTag_ );
massFracTags_.push_back( h2oMassFracTag_ );
massFracTags_.push_back( ch4MassFracTag_ );
co2CoTags_.clear();
co2CoTags_.push_back( co2_rhsTag_ );
co2CoTags_.push_back( co_rhsTag_ );
char_co2coTags_.clear();
char_co2coTags_.push_back( oxidation_rhsTag_ );
char_co2coTags_.push_back( co2CoRatioTag_ );
h2andh2o_rhsTags_.clear();
h2andh2o_rhsTags_.push_back( h2_rhsTag_ );
h2andh2o_rhsTags_.push_back( h2o_rhsTag_ );
}
//------------------------------------------------------------------
template< typename FieldT >
void
FirstOrderInterface<FieldT>::
register_expressions()
{
proc0cout << "Registering expressions...\n";
Expr::ExpressionFactory& factory = *(gc_[WasatchCore::ADVANCE_SOLUTION]->exprFactory);
factory.register_expression( new typename Expr::ConstantExpr<FieldT>::Builder(ch4_rhsTag_, 0));
oxidationRHSID_ = factory.register_expression( new typename CHAR::CharOxidation <FieldT>::
Builder( char_co2coTags_, pDiamTag_, pTempTag_, gTempTag_, o2MassFracTag_, mixMWTag_, pDensTag_,
charMassTag_, gPressTag_, pMass0Tag_, charData_, charModel_) );
gasifID_ = factory.register_expression( new typename FirstOrderArrhenius<FieldT>::
Builder( Expr::tag_list(heteroH2oTag_,heteroCo2Tag_),
massFracTags_,
gPressTag_,mixMWTag_, gTempTag_, pTempTag_, charMassTag_,
pDiamTag_,charData_, firstOrderData_) );
h2Andh2oRHSID_ = factory.register_expression( new typename CHAR::H2andH2ORHS <FieldT>::
Builder( h2andh2o_rhsTags_, heteroH2oTag_) );
co2coRHSID_ = factory.register_expression( new typename CHAR::CO2andCO_RHS <FieldT>::
Builder( co2CoTags_, oxidation_rhsTag_, co2CoRatioTag_, heteroCo2Tag_, heteroH2oTag_) );
o2RHSID_ = factory.register_expression( new typename O2RHS <FieldT>::
Builder( o2_rhsTag_, oxidation_rhsTag_, co2CoRatioTag_) );
charRHSID_ = factory.register_expression( new typename CHAR::CharRHS <FieldT>::
Builder( charMass_rhsTag_, oxidation_rhsTag_, heteroCo2Tag_, heteroH2oTag_) );
}
//------------------------------------------------------------------
template< typename FieldT >
const Tag
FirstOrderInterface<FieldT>::
gas_species_src_tag( const CharGasSpecies spec ) const
{
if( spec == CHAR::O2 ) return o2_rhsTag_;
if( spec == CHAR::CO2 ) return co2_rhsTag_;
if( spec == CHAR::CO ) return co_rhsTag_;
if( spec == CHAR::H2 ) return h2_rhsTag_;
if( spec == CHAR::H2O ) return h2o_rhsTag_;
return Tag();
}
//==========================================================================
// Explicit template instantiation for supported versions of this expression
template class FirstOrderInterface< SpatialOps::Particle::ParticleField >;
//==========================================================================
} // namespace FOA
| 41.29717 | 147 | 0.573158 | abagusetty |
92adc71f2c9fac6874e4cedb1a4e66e8cad98c97 | 5,094 | cc | C++ | media/audio/win/audio_device_listener_win_unittest.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | media/audio/win/audio_device_listener_win_unittest.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | media/audio/win/audio_device_listener_win_unittest.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright (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/win/audio_device_listener_win.h"
#include <memory>
#include <string>
#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/strings/utf_string_conversions.h"
#include "base/system/system_monitor.h"
#include "base/test/simple_test_tick_clock.h"
#include "base/test/task_environment.h"
#include "base/win/scoped_com_initializer.h"
#include "media/audio/audio_manager.h"
#include "media/audio/audio_unittest_util.h"
#include "media/audio/win/core_audio_util_win.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using base::win::ScopedCOMInitializer;
namespace media {
constexpr char kFirstTestDevice[] = "test_device_0";
constexpr char kSecondTestDevice[] = "test_device_1";
class AudioDeviceListenerWinTest
: public testing::Test,
public base::SystemMonitor::DevicesChangedObserver {
public:
AudioDeviceListenerWinTest() {
DCHECK(com_init_.Succeeded());
if (!CoreAudioUtil::IsSupported())
return;
system_monitor_.AddDevicesChangedObserver(this);
output_device_listener_ = std::make_unique<AudioDeviceListenerWin>(
base::BindRepeating(&AudioDeviceListenerWinTest::OnDeviceChange,
base::Unretained(this)));
tick_clock_.Advance(base::Seconds(12345));
output_device_listener_->tick_clock_ = &tick_clock_;
}
AudioDeviceListenerWinTest(const AudioDeviceListenerWinTest&) = delete;
AudioDeviceListenerWinTest& operator=(const AudioDeviceListenerWinTest&) =
delete;
~AudioDeviceListenerWinTest() override {
system_monitor_.RemoveDevicesChangedObserver(this);
}
void AdvanceLastDeviceChangeTime() {
tick_clock_.Advance(AudioDeviceListenerWin::kDeviceChangeLimit +
base::Milliseconds(1));
}
// Simulate a device change where no output devices are available.
bool SimulateNullDefaultOutputDeviceChange() {
auto result = output_device_listener_->OnDefaultDeviceChanged(
static_cast<EDataFlow>(eConsole), static_cast<ERole>(eRender), nullptr);
task_environment_.RunUntilIdle();
return result == S_OK;
}
bool SimulateDefaultOutputDeviceChange(const char* new_device_id) {
auto result = output_device_listener_->OnDefaultDeviceChanged(
static_cast<EDataFlow>(eConsole), static_cast<ERole>(eRender),
base::ASCIIToWide(new_device_id).c_str());
task_environment_.RunUntilIdle();
return result == S_OK;
}
MOCK_METHOD0(OnDeviceChange, void());
MOCK_METHOD1(OnDevicesChanged, void(base::SystemMonitor::DeviceType));
private:
ScopedCOMInitializer com_init_;
base::test::TaskEnvironment task_environment_;
base::SystemMonitor system_monitor_;
base::SimpleTestTickClock tick_clock_;
std::unique_ptr<AudioDeviceListenerWin> output_device_listener_;
};
// Simulate a device change events and ensure we get the right callbacks.
TEST_F(AudioDeviceListenerWinTest, OutputDeviceChange) {
ABORT_AUDIO_TEST_IF_NOT(CoreAudioUtil::IsSupported());
EXPECT_CALL(*this, OnDeviceChange()).Times(1);
EXPECT_CALL(*this, OnDevicesChanged(base::SystemMonitor::DEVTYPE_AUDIO))
.Times(1);
ASSERT_TRUE(SimulateDefaultOutputDeviceChange(kFirstTestDevice));
testing::Mock::VerifyAndClear(this);
AdvanceLastDeviceChangeTime();
EXPECT_CALL(*this, OnDeviceChange()).Times(1);
EXPECT_CALL(*this, OnDevicesChanged(base::SystemMonitor::DEVTYPE_AUDIO))
.Times(1);
ASSERT_TRUE(SimulateDefaultOutputDeviceChange(kSecondTestDevice));
// Since it occurs too soon, the second device event shouldn't call
// OnDeviceChange(), but it should notify OnDevicesChanged().
EXPECT_CALL(*this, OnDeviceChange()).Times(0);
EXPECT_CALL(*this, OnDevicesChanged(base::SystemMonitor::DEVTYPE_AUDIO))
.Times(1);
ASSERT_TRUE(SimulateDefaultOutputDeviceChange(kSecondTestDevice));
}
// Ensure that null output device changes don't crash. Simulates the situation
// where we have no output devices.
TEST_F(AudioDeviceListenerWinTest, NullOutputDeviceChange) {
ABORT_AUDIO_TEST_IF_NOT(CoreAudioUtil::IsSupported());
EXPECT_CALL(*this, OnDeviceChange()).Times(1);
EXPECT_CALL(*this, OnDevicesChanged(base::SystemMonitor::DEVTYPE_AUDIO))
.Times(1);
ASSERT_TRUE(SimulateNullDefaultOutputDeviceChange());
testing::Mock::VerifyAndClear(this);
AdvanceLastDeviceChangeTime();
EXPECT_CALL(*this, OnDeviceChange()).Times(1);
EXPECT_CALL(*this, OnDevicesChanged(base::SystemMonitor::DEVTYPE_AUDIO))
.Times(1);
ASSERT_TRUE(SimulateDefaultOutputDeviceChange(kFirstTestDevice));
// Since it occurs too soon, the second device event shouldn't call
// OnDeviceChange(), but it should notify OnDevicesChanged().
testing::Mock::VerifyAndClear(this);
EXPECT_CALL(*this, OnDevicesChanged(base::SystemMonitor::DEVTYPE_AUDIO))
.Times(1);
ASSERT_TRUE(SimulateNullDefaultOutputDeviceChange());
}
} // namespace media
| 36.647482 | 80 | 0.76384 | zealoussnow |
92ae06733548a7f8dd9a19cf96c8f449bd64a0c3 | 35,275 | cpp | C++ | Parser/src/parser.cpp | nuua-io/Nuua | d74bec22d09d25f2bc0ced8d7c9a154ff84a874d | [
"MIT"
] | 43 | 2018-11-17T02:08:09.000Z | 2022-03-03T14:50:02.000Z | Parser/src/parser.cpp | nuua-io/Nuua | d74bec22d09d25f2bc0ced8d7c9a154ff84a874d | [
"MIT"
] | 2 | 2019-08-07T03:16:51.000Z | 2021-05-17T03:05:08.000Z | Parser/src/parser.cpp | nuua-io/Nuua | d74bec22d09d25f2bc0ced8d7c9a154ff84a874d | [
"MIT"
] | 3 | 2019-01-07T18:43:35.000Z | 2021-07-21T12:12:23.000Z | /**
* |-------------|
* | Nuua Parser |
* |-------------|
*
* Copyright 2019 Erik Campobadal <soc@erik.cat>
* https://nuua.io
*/
#include "../include/parser.hpp"
#include "../../Lexer/include/lexer.hpp"
#include "../../Logger/include/logger.hpp"
#include <filesystem>
#include <algorithm>
#define CURRENT() (*(this->current))
#define PREVIOUS() (*(this->current - 1))
#define CHECK(token) (this->current->type == token)
#define CHECK_AT(token, n) ((this->current + n)->type == token)
#define NEXT() (this->current++)
#define ADVANCE(n) (this->current += n)
#define IS_AT_END() (CHECK(TOKEN_EOF))
#define LOOKAHEAD(n) (*(this->current + n))
#define LINE() (this->current->line)
#define COL() (this->current->column)
#define PLINE() ((this->current - 1)->line)
#define PCOL() ((this->current - 1)->column)
#define ADD_LOG(msg) logger->add_entity(this->file, LINE(), COL(), msg)
#define ADD_PREV_LOG(msg) logger->add_entity(this->file, PLINE(), PCOL(), msg)
#define ADD_LOG_PAR(line, col, msg) logger->add_entity(this->file, line, col, msg)
#define EXPECT_NEW_LINE() if (!this->match_any({{ TOKEN_NEW_LINE, TOKEN_EOF }})) { \
ADD_LOG("Expected a new line or EOF but got '" + CURRENT().to_string() + "'."); exit(logger->crash()); }
#define NEW_NODE(type, ...) (std::make_shared<type>(this->file, PLINE(), PCOL(), __VA_ARGS__))
// Stores the parsing file stack, to avoid
// cyclic imports.
static std::vector<const std::string *> file_stack;
#define PREVENT_CYCLIC(file_ptr) \
{ \
if (std::find(file_stack.begin(), file_stack.end(), file_ptr) != file_stack.end()) { \
ADD_LOG("Cyclic import detected. Can't use '" + *file_ptr + "'. Cyclic imports are not available in nuua."); \
exit(logger->crash()); \
} \
}
// Stores the relation between a file_name and the
// parsed Abstract Syntax Tree and the pointer to the
// original long lived file name string.
// Acts as a temporal cache to avoid re-parsing a file.
static std::unordered_map<
std::string,
std::pair<
std::shared_ptr<std::vector<std::shared_ptr<Statement>>>,
std::shared_ptr<const std::string>
>
> parsed_files;
Token *Parser::consume(const TokenType type, const std::string &message)
{
if (this->current->type == type) return NEXT();
ADD_LOG(message);
exit(logger->crash());
}
bool Parser::match(const TokenType token)
{
if (CHECK(token)) {
if (token != TOKEN_EOF) NEXT();
return true;
}
return false;
}
bool Parser::match_any(const std::vector<TokenType> &tokens)
{
for (const TokenType &token : tokens) {
if (CHECK(token)) {
if (token != TOKEN_EOF) NEXT();
return true;
}
}
return false;
}
/* GRAMMAR RULES */
/*
primary -> "false"
| "true"
| INTEGER
| FLOAT
| STRING
| IDENTIFIER
| LIST
| DICTIONARY
| OBJECT
| "(" expression ")"
*/
std::shared_ptr<Expression> Parser::primary()
{
if (this->match(TOKEN_FALSE)) return NEW_NODE(Boolean, false);
if (this->match(TOKEN_TRUE)) return NEW_NODE(Boolean, true);
if (this->match(TOKEN_INTEGER)) return NEW_NODE(Integer, std::stoll(PREVIOUS().to_string()));
if (this->match(TOKEN_FLOAT)) return NEW_NODE(Float, std::stof(PREVIOUS().to_string()));
if (this->match(TOKEN_STRING)) return NEW_NODE(String, PREVIOUS().to_string());
if (this->match(TOKEN_IDENTIFIER)) {
const std::string name = PREVIOUS().to_string();
// It can be an object.
if (this->match(TOKEN_BANG)) {
// It's an object.
this->consume(TOKEN_LEFT_BRACE, "Expected '{' at the start of the object creation.");
std::unordered_map<std::string, std::shared_ptr<Expression>> arguments;
this->object_arguments(arguments);
this->consume(TOKEN_RIGHT_BRACE, "Expected '}' at the end of the object creation.");
return NEW_NODE(Object, name, arguments);
}
return NEW_NODE(Variable, name);
}
if (this->match(TOKEN_LEFT_SQUARE)) {
std::vector<std::shared_ptr<Expression> > values;
if (this->match(TOKEN_RIGHT_SQUARE)) return NEW_NODE(List, values);
for (;;) {
if (IS_AT_END()) {
ADD_LOG("Unfinished list, Expecting ']' after the last list element.");
exit(logger->crash());
}
values.push_back(std::move(expression()));
if (this->match(TOKEN_RIGHT_SQUARE)) break;
this->consume(TOKEN_COMMA, "Expected ',' after a list element");
}
return NEW_NODE(List, values);
}
if (this->match(TOKEN_LEFT_BRACE)) {
std::unordered_map<std::string, std::shared_ptr<Expression>> values;
std::vector<std::string> keys;
if (this->match(TOKEN_RIGHT_BRACE)) return NEW_NODE(Dictionary, values, keys);
for (;;) {
if (IS_AT_END()) {
ADD_LOG("Unfinished dictionary, Expecting '}' after the last dictionary element.");
exit(logger->crash());
}
std::shared_ptr<Expression> key = this->expression();
if (key->rule != RULE_VARIABLE) {
ADD_LOG("Expected an identifier as a key");
exit(logger->crash());
}
this->consume(TOKEN_COLON, "Expected ':' after dictionary key");
std::string name = std::static_pointer_cast<Variable>(key)->name;
values[name] = this->expression();
keys.push_back(name);
if (this->match(TOKEN_RIGHT_BRACE)) break;
this->consume(TOKEN_COMMA, "Expected ',' after dictionary element");
}
return NEW_NODE(Dictionary, values, keys);
}
if (this->match(TOKEN_LEFT_PAREN)) {
std::shared_ptr<Expression> value = this->expression();
this->consume(TOKEN_RIGHT_PAREN, "Expected ')' after a group expression");
return NEW_NODE(Group, value);
}
/*
if (this->match(TOKEN_STICK)) {
std::vector<std::shared_ptr<Statement> > parameters = this->parameters();
if (!this->match(TOKEN_STICK)) {
parameters = this->parameters();
this->consume(TOKEN_STICK, "Expected '|' after the closure parameters");
}
std::string return_type;
if (this->match(TOKEN_COLON)) return_type = this->type(false);
std::vector<std::shared_ptr<Statement> > body;
if (this->match(TOKEN_RIGHT_ARROW)) {
body.push_back(NEW_NODE(Return, this->expression()));
} else if (this->match(TOKEN_BIG_RIGHT_ARROW)) {
body.push_back(this->statement(false));
} else if (this->match(TOKEN_LEFT_BRACE)) {
EXPECT_NEW_LINE();
body = this->body();
this->consume(TOKEN_RIGHT_BRACE, "Expected '}' after closure body.");
} else {
ADD_LOG("Unknown token found after closure. Expected '->', '=>' or '{'.");
exit(logger->crash());
}
return NEW_NODE(Closure, parameters, return_type, body);
}
*/
ADD_LOG("Expected an expression but got '" + CURRENT().to_string() + "'");
exit(logger->crash());
}
/*
unary_postfix -> primary unary_p*;
unary_p -> "[" expression "]"
| slice
| "(" arguments? ")"
| '.' IDENTIFIER;
slice -> "[" expression? ":" expression? (":" expression?)? "]"
arguments -> expression ("," expression)*;
*/
std::shared_ptr<Expression> Parser::unary_postfix()
{
std::shared_ptr<Expression> result = this->primary();
while (this->match_any({{ TOKEN_LEFT_SQUARE, TOKEN_LEFT_PAREN, TOKEN_DOT }})) {
Token op = PREVIOUS();
switch (op.type) {
case TOKEN_LEFT_SQUARE: {
std::shared_ptr<Expression> start = std::shared_ptr<Expression>();
std::shared_ptr<Expression> end = std::shared_ptr<Expression>();
std::shared_ptr<Expression> step = std::shared_ptr<Expression>();
if (this->match(TOKEN_COLON)) goto parser_is_slice1;
start = this->expression();
if (this->match(TOKEN_COLON)) {
// It's a Slice, not an access and the start index is already calculated.
parser_is_slice1:
if (this->match(TOKEN_RIGHT_SQUARE)) goto parser_finish_slice;
if (this->match(TOKEN_COLON)) goto parser_get_slice_step;
end = this->expression();
if (this->match(TOKEN_RIGHT_SQUARE)) goto parser_finish_slice;
this->consume(TOKEN_COLON, "Expected ':' or ']' after slice end index");
parser_get_slice_step:
if (this->match(TOKEN_RIGHT_SQUARE)) goto parser_finish_slice;
step = this->expression();
this->consume(TOKEN_RIGHT_SQUARE, "Expected ']' after a slice step");
parser_finish_slice:
result = NEW_NODE(Slice, result, start, end, step);
break;
}
this->consume(TOKEN_RIGHT_SQUARE, "Expected ']' after the access index");
result = NEW_NODE(Access, result, start);
break;
}
case TOKEN_LEFT_PAREN: {
std::vector<std::shared_ptr<Expression>> arguments = this->arguments();
this->consume(TOKEN_RIGHT_PAREN, "Expected ')' after function arguments.");
result = NEW_NODE(Call, result, arguments);
break;
}
case TOKEN_DOT: {
std::string prop = this->consume(TOKEN_IDENTIFIER, "Expected an identifier after '.' in an access to an object property.")->to_string();
result = NEW_NODE(Property, result, prop);
break;
}
default: {
ADD_LOG("Invalid unary postfix operator");
exit(logger->crash());
};
}
}
return result;
}
/*
unary_prefix -> ("!" | "+" | "-") unary_prefix
| unary_postfix;
*/
std::shared_ptr<Expression> Parser::unary_prefix()
{
if (this->match_any({{ TOKEN_BANG, TOKEN_PLUS, TOKEN_MINUS }})) {
Token op = PREVIOUS();
std::shared_ptr<Expression> expr = this->unary_prefix();
return NEW_NODE(Unary, op, expr);
}
return this->unary_postfix();
}
/*
cast -> unary_prefix ("as" type)*;
*/
std::shared_ptr<Expression> Parser::cast()
{
std::shared_ptr<Expression> result = this->unary_prefix();
while (this->match(TOKEN_AS)) {
std::shared_ptr<Type> type = this->type();
result = NEW_NODE(Cast, result, type);
}
return result;
}
/*
multiplication -> cast (("/" | "*") cast)*;
*/
std::shared_ptr<Expression> Parser::multiplication()
{
std::shared_ptr<Expression> result = this->cast();
while (this->match_any({{ TOKEN_SLASH, TOKEN_STAR /* , TOKEN_PERCENT */ }})) {
Token op = PREVIOUS();
std::shared_ptr<Expression> expr = this->cast();
result = NEW_NODE(Binary, result, op, expr);
}
return result;
}
/*
addition -> multiplication (("-" | "+") multiplication)*;
*/
std::shared_ptr<Expression> Parser::addition()
{
std::shared_ptr<Expression> result = this->multiplication();
while (this->match_any({{ TOKEN_MINUS, TOKEN_PLUS }})) {
Token op = PREVIOUS();
std::shared_ptr<Expression> expr = this->multiplication();
result = NEW_NODE(Binary, result, op, expr);
}
return result;
}
/*
comparison -> addition ((">" | ">=" | "<" | "<=") addition)*;
*/
std::shared_ptr<Expression> Parser::comparison()
{
std::shared_ptr<Expression> result = this->addition();
while (this->match_any({{ TOKEN_HIGHER, TOKEN_HIGHER_EQUAL, TOKEN_LOWER, TOKEN_LOWER_EQUAL }})) {
Token op = PREVIOUS();
std::shared_ptr<Expression> expr = this->addition();
result = NEW_NODE(Binary, result, op, expr);
}
return result;
}
/*
equality -> comparison (("!=" | "==") comparison)*;
*/
std::shared_ptr<Expression> Parser::equality()
{
std::shared_ptr<Expression> result = this->comparison();
while (this->match_any({{ TOKEN_BANG_EQUAL, TOKEN_EQUAL_EQUAL }})) {
Token op = PREVIOUS();
std::shared_ptr<Expression> expr = this->comparison();
result = NEW_NODE(Binary, result, op, expr);
}
return result;
}
/*
logical_and -> equality ("and" equality)*;
*/
std::shared_ptr<Expression> Parser::logical_and()
{
std::shared_ptr<Expression> result = this->equality();
while (this->match(TOKEN_AND)) {
Token op = PREVIOUS();
std::shared_ptr<Expression> expr = this->equality();
result = NEW_NODE(Logical, result, op, expr);
}
return result;
}
/*
logical_or -> logical_and ("or" logical_and)*;
*/
std::shared_ptr<Expression> Parser::logical_or()
{
std::shared_ptr<Expression> result = this->logical_and();
while (this->match(TOKEN_OR)) {
Token op = PREVIOUS();
std::shared_ptr<Expression> expr = this->logical_and();
result = NEW_NODE(Logical, result, op, expr);
}
return result;
}
/*
range -> logical_or ((".." | "...") logical_or)*;
*/
std::shared_ptr<Expression> Parser::range()
{
std::shared_ptr<Expression> result = this->logical_or();
while (this->match_any({{ TOKEN_DOUBLE_DOT, TOKEN_TRIPLE_DOT }})) {
const bool inclusive = PREVIOUS().type == TOKEN_DOUBLE_DOT ? false : true;
std::shared_ptr<Expression> right = this->expression();
result = NEW_NODE(Range, result, right, inclusive);
}
return result;
}
/*
assignment -> range ("=" range)*;
*/
std::shared_ptr<Expression> Parser::assignment()
{
std::shared_ptr<Expression> result = this->range();
while (this->match(TOKEN_EQUAL)) {
std::shared_ptr<Expression> expr = this->range();
result = NEW_NODE(Assign, result, expr);
}
return result;
}
/*
expression -> assignment;
*/
std::shared_ptr<Expression> Parser::expression()
{
return this->assignment();
}
/*
variable_declaration -> IDENTIFIER ":" ("=" expression)?;
*/
std::shared_ptr<Statement> Parser::variable_declaration()
{
std::string variable = this->consume(TOKEN_IDENTIFIER, "Expected an identifier in a declaration statement")->to_string();
this->consume(TOKEN_COLON, "Expected ':' after identifier in a declaration statement");
std::shared_ptr<Type> type = this->type();
std::shared_ptr<Expression> initializer;
if (this->match(TOKEN_EQUAL)) initializer = this->expression();
if (!type && !initializer) {
ADD_LOG("A variable without type and initializer can't be declared. At least one is expected.");
exit(logger->crash());
}
return NEW_NODE(Declaration, variable, type, initializer);
}
/*
expression_statement -> expression;
*/
std::shared_ptr<Statement> Parser::expression_statement()
{
std::shared_ptr<Expression> expr = this->expression();
return NEW_NODE(ExpressionStatement, expr);
}
/*
use_declaration -> "use" STRING
| "use" IDENTIFIER ("," IDENTIFIER)* "from" STRING;
*/
std::shared_ptr<Statement> Parser::use_declaration()
{
std::vector<std::string> targets;
std::string module;
if (CHECK(TOKEN_IDENTIFIER)) {
targets.push_back(this->consume(TOKEN_IDENTIFIER, "Expected an identifier after 'use'")->to_string()); // The message is redundant.
while (this->match(TOKEN_COMMA)) targets.push_back(this->consume(TOKEN_IDENTIFIER, "Expected an identifier after ','")->to_string());
this->consume(TOKEN_FROM, "Expected 'from' after the import target");
module = this->consume(TOKEN_STRING, "Expected an identifier after 'from'")->to_string();
} else {
module = this->consume(TOKEN_STRING, "Expected an identifier or 'string' after 'use'")->to_string();
}
Parser::format_path(module, this->file);
std::shared_ptr<Use> use;
// Parse the contents of the target.
if (parsed_files.find(module) == parsed_files.end()) {
use = NEW_NODE(Use, targets, std::make_shared<std::string>(module));
PREVENT_CYCLIC(use->module.get());
use->code = std::make_shared<std::vector<std::shared_ptr<Statement>>>();
Parser(use->module).parse(use->code);
} else {
use = NEW_NODE(Use, targets, parsed_files[module].second);
PREVENT_CYCLIC(use->module.get());
use->code = parsed_files[module].first;
}
return use;
}
/*
export_declaration -> "export" top_level_declaration
*/
std::shared_ptr<Statement> Parser::export_declaration()
{
std::shared_ptr<Statement> stmt = this->top_level_declaration(false);
if (stmt->rule == RULE_EXPORT) {
ADD_LOG("Can't export an export. Does that even make sense?.");
exit(logger->crash());
}
// printf("CURRENT: %s\n", CURRENT().to_string().c_str());
return NEW_NODE(Export, stmt);
}
/*
fun_declaration -> "fun" IDENTIFIER "(" parameters? ")" (":" type)? ("->" expression "\n" | "=>" statement | "{" "\n" statement* "}" "\n");
parameters -> variable_declaration ("," variable_declaration)*;
*/
std::shared_ptr<Statement> Parser::fun_declaration()
{
std::string name = this->consume(TOKEN_IDENTIFIER, "Expected an identifier (function name) after 'fun'.")->to_string();
this->consume(TOKEN_LEFT_PAREN, "Expected '(' after the function name.");
std::vector<std::shared_ptr<Declaration>> parameters;
if (!this->match(TOKEN_RIGHT_PAREN)) {
this->parameters(¶meters);
this->consume(TOKEN_RIGHT_PAREN, "Expected ')' after the function parameters");
}
std::shared_ptr<Type> return_type;
if (this->match(TOKEN_COLON)) return_type = this->type(false);
std::vector<std::shared_ptr<Statement> > body;
if (this->match(TOKEN_RIGHT_ARROW)) {
body.push_back(std::move(NEW_NODE(Return, this->expression())));
} else if (this->match(TOKEN_BIG_RIGHT_ARROW)) {
body.push_back(std::move(this->statement(false)));
} else if (this->match(TOKEN_LEFT_BRACE)) {
EXPECT_NEW_LINE();
body = this->body();
this->consume(TOKEN_RIGHT_BRACE, "Expected '}' after function body.");
} else {
ADD_LOG("Unknown token found after function. Expected '->', '=>' or '{'.");
exit(logger->crash());
}
return std::make_shared<Function>(NEW_NODE(FunctionValue, name, parameters, return_type, body));
}
/*
print_statement -> "print" expression;
*/
std::shared_ptr<Statement> Parser::print_statement()
{
std::shared_ptr<Expression> expr = this->expression();
return NEW_NODE(Print, expr);
}
/*
if_statement -> "if" expression ("=>" statement | "{" "\n" statement* "}");
*/
std::shared_ptr<Statement> Parser::if_statement()
{
std::shared_ptr<Expression> condition = this->expression();
std::vector<std::shared_ptr<Statement> > then_branch, else_branch;
// Then branch
if (this->match(TOKEN_LEFT_BRACE)) {
EXPECT_NEW_LINE();
then_branch = this->body();
this->consume(TOKEN_RIGHT_BRACE, "Expected '}' after 'if' body.");
} else if (this->match(TOKEN_BIG_RIGHT_ARROW)) {
then_branch.push_back(std::move(this->statement(false)));
} else {
ADD_LOG("Expected '{' or '=>' after 'if' condition.");
exit(logger->crash());
}
// Else branch
if (this->match(TOKEN_ELIF)) {
else_branch.push_back(std::move(this->if_statement()));
} else if (CHECK(TOKEN_NEW_LINE) && CHECK_AT(TOKEN_ELIF, 1)) {
ADVANCE(2); // Consume the two tokens.
else_branch.push_back(std::move(this->if_statement()));
} else if (this->match(TOKEN_ELSE)) {
if (this->match(TOKEN_LEFT_BRACE)) {
EXPECT_NEW_LINE();
else_branch = this->body();
this->consume(TOKEN_RIGHT_BRACE, "Expected '}' after 'else' body.");
} else if (this->match(TOKEN_BIG_RIGHT_ARROW)) {
else_branch.push_back(std::move(this->statement(false)));
} else {
ADD_LOG("Expected '{' or '=>' after 'else'.");
exit(logger->crash());
}
} else if (CHECK(TOKEN_NEW_LINE) && CHECK_AT(TOKEN_ELSE, 1)) {
ADVANCE(2); // Consume the two tokens.
if (this->match(TOKEN_LEFT_BRACE)) {
EXPECT_NEW_LINE();
else_branch = this->body();
this->consume(TOKEN_RIGHT_BRACE, "Expected '}' after 'else' body.");
} else if (this->match(TOKEN_BIG_RIGHT_ARROW)) {
else_branch.push_back(std::move(this->statement(false)));
} else {
ADD_LOG("Expected '{' or '=>' after 'else'.");
exit(logger->crash());
}
}
return NEW_NODE(If, condition, then_branch, else_branch);
}
std::shared_ptr<Statement> Parser::while_statement()
{
std::shared_ptr<Expression> condition = this->expression();
std::vector<std::shared_ptr<Statement> > body;
if (this->match(TOKEN_LEFT_BRACE)) {
EXPECT_NEW_LINE();
body = this->body();
this->consume(TOKEN_RIGHT_BRACE, "Expected '}' after 'while' body.");
} else if (this->match(TOKEN_BIG_RIGHT_ARROW)) {
body.push_back(std::move(this->statement(false)));
} else {
ADD_LOG("Expected '{' or '=>' after 'while' condition.");
exit(logger->crash());
}
return NEW_NODE(While, condition, body);
}
/*
for_statement -> "for" IDENTIFIER ("," IDENTIFIER)? "in" expression ("=>" statement | "{" "\n" statement* "}" "\n");
*/
std::shared_ptr<Statement> Parser::for_statement()
{
std::string index, variable = this->consume(TOKEN_IDENTIFIER, "Expected identifier after 'for'")->to_string();
if (this->match(TOKEN_COMMA)) {
index = this->consume(TOKEN_IDENTIFIER, "Expected identifier as the optional second identifier in 'for'")->to_string();
}
this->consume(TOKEN_IN, "Expected 'in' after 'for' identifier/s.");
std::shared_ptr<Expression> iterator = this->expression();
std::vector<std::shared_ptr<Statement> > body;
if (this->match(TOKEN_LEFT_BRACE)) {
EXPECT_NEW_LINE();
body = this->body();
this->consume(TOKEN_RIGHT_BRACE, "Expected '}' after 'for' body.");
} else if (this->match(TOKEN_BIG_RIGHT_ARROW)) {
body.push_back(std::move(this->statement(false)));
} else {
ADD_LOG("Expected '{' or '=>' after 'for' iterator.");
exit(logger->crash());
}
return NEW_NODE(For, variable, index, iterator, body);
}
/*
return_statement -> "return" expression?;
*/
std::shared_ptr<Statement> Parser::return_statement()
{
if (CHECK(TOKEN_NEW_LINE) || CHECK(TOKEN_EOF)) {
return NEW_NODE(Return, nullptr);
}
std::shared_ptr<Expression> expr = this->expression();
return NEW_NODE(Return, expr);
}
std::shared_ptr<Statement> Parser::delete_statement()
{
std::shared_ptr<Expression> expr = this->expression();
return NEW_NODE(Delete, expr);
}
std::shared_ptr<Statement> Parser::class_statement()
{
std::string name = this->consume(TOKEN_IDENTIFIER, "Expected identifier after 'class'.")->to_string();
this->consume(TOKEN_LEFT_BRACE, "Expected '{' after 'class' name.");
std::vector<std::shared_ptr<Statement> > body = this->class_body();
this->consume(TOKEN_RIGHT_BRACE, "Expected '}' after 'class' body.");
return NEW_NODE(Class, name, body);
}
/*
statement -> variable_declaration "\n"?
| if_statement "\n"
| while_statement "\n"
| for_statement "\n"
| return_statement "\n"
| delete_statement "\n"
| print_statement "\n"
| expression_statement "\n"?;
*/
std::shared_ptr<Statement> Parser::statement(bool new_line)
{
std::shared_ptr<Statement> result;
// Remove blank lines
while (this->match(TOKEN_NEW_LINE));
// Save the current line / column.
line_t line = LINE();
column_t column = COL();
// Check what type of statement we're parsing.
if (CHECK(TOKEN_IDENTIFIER) && LOOKAHEAD(1).type == TOKEN_COLON) {
ADD_LOG("Parsing variable declaration");
result = this->variable_declaration();
} else if (this->match(TOKEN_IF)) {
ADD_PREV_LOG("Parsing if declaration");
result = this->if_statement();
} else if (this->match(TOKEN_WHILE)) {
ADD_PREV_LOG("Parsing while statement");
result = this->while_statement();
} else if (this->match(TOKEN_FOR)) {
ADD_PREV_LOG("Parsing for statement");
result = this->for_statement();
} else if (this->match(TOKEN_RETURN)) {
ADD_PREV_LOG("Parsing return statement");
result = this->return_statement();
} else if (this->match(TOKEN_DELETE)) {
ADD_PREV_LOG("Parsing delete statement");
result = this->delete_statement();
} else if (this->match(TOKEN_PRINT)) {
ADD_PREV_LOG("Parsing print statement");
result = this->print_statement();
} else {
ADD_LOG("Parsing expression");
result = this->expression_statement();
}
if (new_line) EXPECT_NEW_LINE();
logger->pop_entity();
// Set the line / column to overwrite the ones in the node.
result->line = line;
result->column = column;
return result;
}
/*
top_level_declaration -> use_declaration "\n"
| export_declaration "\n"
| class_declaration "\n"
| fun_declaration "\n";
*/
std::shared_ptr<Statement> Parser::top_level_declaration(const bool expect_new_line)
{
std::shared_ptr<Statement> result;
// Save the current line / column.
line_t line = LINE();
column_t column = COL();
if (this->match(TOKEN_USE)) {
ADD_PREV_LOG("Parsing 'use' declaration");
result = this->use_declaration();
} else if (this->match(TOKEN_EXPORT)) {
ADD_PREV_LOG("Parsing 'export' declaration");
result = this->export_declaration();
} else if (this->match(TOKEN_CLASS)) {
ADD_PREV_LOG("Parsing 'class' declaration");
result = this->class_statement();
} else if (this->match(TOKEN_FUN)) {
ADD_PREV_LOG("Parsing 'fun' declaration");
result = this->fun_declaration();
// Set the line / column to overwrite the ones in the node.
// MUST BE SET ON THE INNER VALUE
std::static_pointer_cast<Function>(result)->value->line = line;
std::static_pointer_cast<Function>(result)->value->column = column;
} else {
//printf("CURRENT: %zu\n", CURRENT().);
ADD_LOG("Unknown top level declaration. Expected 'use', 'export', 'class' or 'fun'. But got '" + CURRENT().to_type_string() + "'");
exit(logger->crash());
}
if (expect_new_line) EXPECT_NEW_LINE();
logger->pop_entity();
// Set the line / column to overwrite the ones in the node.
result->line = line;
result->column = column;
return result;
}
std::shared_ptr<Statement> Parser::class_body_declaration()
{
std::shared_ptr<Statement> result;
// Remove blank lines
while (this->match(TOKEN_NEW_LINE));
// Save the current line / column.
line_t line = LINE();
column_t column = COL();
if (CHECK(TOKEN_IDENTIFIER) && LOOKAHEAD(1).type == TOKEN_COLON) {
ADD_LOG("Parsing variable declaration");
result = this->variable_declaration();
} else if (this->match(TOKEN_FUN)) {
ADD_PREV_LOG("Parsing 'fun' declaration");
result = this->fun_declaration();
// Set the line / column to overwrite the ones in the node.
// MUST BE SET ON THE INNER VALUE
std::static_pointer_cast<Function>(result)->value->line = line;
std::static_pointer_cast<Function>(result)->value->column = column;
} else {
ADD_LOG("Invalid class block declaration. Expected 'fun' or variable declaration. But got '" + CURRENT().to_string() + "'");
exit(logger->crash());
}
EXPECT_NEW_LINE();
logger->pop_entity();
// Set the line / column to overwrite the ones in the node.
result->line = line;
result->column = column;
return result;
}
void Parser::parameters(std::vector<std::shared_ptr<Declaration>> *dest)
{
if (!CHECK(TOKEN_RIGHT_PAREN)) {
do {
std::shared_ptr<Statement> parameter = this->statement(false);
if (parameter->rule != RULE_DECLARATION) {
ADD_LOG_PAR(parameter->line, parameter->column, "Invalid argument when defining the function. Expected a variable declaration.");
exit(logger->crash());
}
// Disallow parameter initializors.
std::shared_ptr<Declaration> dec = std::static_pointer_cast<Declaration>(parameter);
if (dec->initializer) {
ADD_LOG_PAR(dec->initializer->line, dec->initializer->column, "Function parameters are not allowed to have initializers.");
exit(logger->crash());
}
dest->push_back(std::move(dec));
} while (this->match(TOKEN_COMMA));
}
}
void Parser::object_arguments(std::unordered_map<std::string, std::shared_ptr<Expression>> &arguments)
{
if (!CHECK(TOKEN_RIGHT_BRACE)) {
do {
std::string key = this->consume(TOKEN_IDENTIFIER, "Expected an identifier to set the object argument")->to_string();
this->consume(TOKEN_COLON, "Expected ':' after the argument identifier");
arguments[key] = std::move(this->expression());
} while (this->match(TOKEN_COMMA));
}
}
std::vector<std::shared_ptr<Expression>> Parser::arguments()
{
std::vector<std::shared_ptr<Expression>> arguments;
if (!CHECK(TOKEN_RIGHT_PAREN)) {
do arguments.push_back(std::move(this->expression()));
while (this->match(TOKEN_COMMA));
}
return arguments;
}
std::vector<std::shared_ptr<Statement>> Parser::body()
{
std::vector<std::shared_ptr<Statement>> body;
while (!IS_AT_END()) {
// Remove blank lines.
while (this->match(TOKEN_NEW_LINE));
if (IS_AT_END()) {
ADD_LOG("Unterminated body. Must use '}' to terminate the body.");
exit(logger->crash());
}
// Check if the body ended.
if (CHECK(TOKEN_RIGHT_BRACE)) break;
// Push a new statement into the body.
body.push_back(std::move(this->statement()));
}
return body;
}
std::vector<std::shared_ptr<Statement> > Parser::class_body()
{
std::vector<std::shared_ptr<Statement> > body;
while (!IS_AT_END() && !CHECK(TOKEN_RIGHT_BRACE)) {
body.push_back(std::move(this->class_body_declaration()));
}
return body;
}
/*
type -> "[" type "]"
| "{" type "}"
| "(" type ("," type)* ("->" type)? ")"
| IDENTIFIER;
*/
std::shared_ptr<Type> Parser::type(bool optional)
{
if (this->match(TOKEN_LEFT_SQUARE)) {
// List type.
std::shared_ptr<Type> inner_type = this->type();
std::shared_ptr<Type> type = std::make_shared<Type>(VALUE_LIST, inner_type);
this->consume(TOKEN_RIGHT_SQUARE, "A list type needs to end with ']'");
return type;
} else if (this->match(TOKEN_LEFT_BRACE)) {
// Dict type.
std::shared_ptr<Type> inner_type = this->type();
std::shared_ptr<Type> type = std::make_shared<Type>(VALUE_DICT, inner_type);
this->consume(TOKEN_RIGHT_BRACE, "A dictionary type needs to end with '}'");
return type;
} else if (this->match(TOKEN_LEFT_PAREN)) {
// Function type.
if (this->match(TOKEN_RIGHT_PAREN)) {
// Empty function (no paramenters or return type)
return std::make_shared<Type>(VALUE_FUN);
} else if (this->match(TOKEN_RIGHT_ARROW)) {
// Function without arguments and only a return type.
std::shared_ptr<Type> type = this->type();
this->consume(TOKEN_RIGHT_PAREN, "A function type needs to end with ')'");
return std::make_shared<Type>(VALUE_FUN, type);
}
// The function have arguments (+ return)?
std::shared_ptr<Type> type = std::make_shared<Type>(VALUE_FUN);
// Add the parameters.
do type->parameters.push_back(std::move(this->type()));
while (this->match(TOKEN_COMMA));
// Add the return type if needed.
if (this->match(TOKEN_RIGHT_ARROW)) type->inner_type = this->type();
this->consume(TOKEN_RIGHT_PAREN, "A function type needs to end with ')'");
return type;
} else if (CHECK(TOKEN_IDENTIFIER)) {
// Other types (native + custom).
std::string type = this->consume(TOKEN_IDENTIFIER, "Expected an identifier as a type.")->to_string();
return std::make_shared<Type>(type);
} else if (optional && (CHECK(TOKEN_NEW_LINE) || CHECK(TOKEN_EQUAL))) return std::shared_ptr<Type>();
ADD_LOG("Unknown type token expected.");
exit(logger->crash());
}
/*
program -> top_level_declaration*;
*/
void Parser::parse(std::shared_ptr<std::vector<std::shared_ptr<Statement>>> &code)
{
// Add the file we are going to parse to the file_stack.
file_stack.push_back(this->file.get());
// Prepare the token list.
std::unique_ptr<std::vector<Token>> tokens = std::make_unique<std::vector<Token>>();
Lexer lexer = Lexer(this->file);
// Scan the tokens.
lexer.scan(tokens);
if (logger->show_tokens) Token::debug_tokens(*tokens);
this->current = &tokens->front();
while (!IS_AT_END()) {
// Remove blank lines
while (this->match(TOKEN_NEW_LINE));
if (IS_AT_END()) break;
// Add the TLD.
code->push_back(std::move(this->top_level_declaration()));
}
// Check the code size to avoid empty files.
if (code->size() == 0) {
logger->add_entity(this->file, 0, 0, "Empty file detected, you might need to check the file or make sure it's not empty.");
exit(logger->crash());
}
parsed_files[*this->file] = std::make_pair(code, this->file);
}
Parser::Parser(const char *file)
{
std::string source = std::string(file);
Parser::format_path(source);
this->file = std::move(std::make_shared<const std::string>(std::string(source)));
}
void Parser::format_path(std::string &path, const std::shared_ptr<const std::string> &parent)
{
// Add the final .nu if needed.
if (path.length() <= 3 || path.substr(path.length() - 3) != ".nu") path.append(".nu");
// Join the parent if needed.
std::filesystem::path f;
// Path if local file
if (parent) f = std::filesystem::path(*parent).remove_filename().append(path);
else f = path;
// Cehck if path exists
if (!std::filesystem::exists(std::filesystem::absolute(f))) {
// Check if path exists on std lib.
f = std::filesystem::path(logger->executable_path).remove_filename().append("Lib").append(path);
if (!std::filesystem::exists(std::filesystem::absolute(f))) {
// Well... No module exists with that name.
logger->add_entity(std::shared_ptr<const std::string>(), 0, 0, "Module " + path + " not found in any path.");
exit(logger->crash());
}
}
path = std::filesystem::absolute(f).string();
}
#undef CURRENT
#undef PREVIOUS
#undef CHECK
#undef CHECK_AT
#undef NEXT
#undef ADVANCE
#undef IS_AT_END
#undef LOOKAHEAD
#undef LINE
#undef COL
#undef PLINE
#undef PCOL
#undef ADD_LOG
#undef ADD_LOG_PAR
#undef ADD_PREV_LOG
#undef EXPECT_NEW_LINE
#undef NEW_NODE
| 36.744792 | 152 | 0.619731 | nuua-io |
92aed95a9b30612cc232672044221fd85a6aafac | 507 | cpp | C++ | ITP1/q31.cpp | felixny/AizuOnline | 8ff399d60077e08961845502d4a99244da580cd2 | [
"MIT"
] | null | null | null | ITP1/q31.cpp | felixny/AizuOnline | 8ff399d60077e08961845502d4a99244da580cd2 | [
"MIT"
] | null | null | null | ITP1/q31.cpp | felixny/AizuOnline | 8ff399d60077e08961845502d4a99244da580cd2 | [
"MIT"
] | null | null | null | // ITP1_9_C
#include <iostream>
#include <string>
using namespace std;
int main() {
string taro;
string hanako;
int n;
int pointH = 0;
int pointT = 0;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> taro >> hanako;
if (taro > hanako) {
pointT += 3;
} else if (taro < hanako) {
pointH += 3;
} else if (taro == hanako) {
pointT += 1;
pointH += 1;
}
}
cout << pointT << " " << pointH << endl;
return 0;
}
/* 3
cat dog
fish fish
lion tiger */ | 14.485714 | 42 | 0.506903 | felixny |
92aefa42e0b83866da1087676db09d5e1193f50d | 3,598 | cc | C++ | system_manager.cc | rockchip-linux/LibIPCProtocol | 6fe4cb96c761253f4002db1f3be71b24dc946cd2 | [
"BSD-3-Clause"
] | 1 | 2021-06-28T00:25:02.000Z | 2021-06-28T00:25:02.000Z | system_manager.cc | rockchip-linux/LibIPCProtocol | 6fe4cb96c761253f4002db1f3be71b24dc946cd2 | [
"BSD-3-Clause"
] | null | null | null | system_manager.cc | rockchip-linux/LibIPCProtocol | 6fe4cb96c761253f4002db1f3be71b24dc946cd2 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2020 Fuzhou Rockchip Electronics Co., Ltd. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <assert.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <unistd.h>
#include <glib.h>
#include <dbus-c++/dbus.h>
#include "json-c/json.h"
#include "system_manager.h"
#include "system_manager_proxy.h"
#include "dbus_connection.h"
#include "libipcpro_log_control.h"
extern int ipc_pro_log_ctl;
#define SYSTEMMANAGER_DBUSSEND_1(FUNC) \
dbus_mutex_lock(); \
try { \
DBus::Connection conn = get_dbus_conn(); \
DBusSystemManager* system_manager_proxy_ = new DBusSystemManager(conn, SYSTEM_MANAGER_PATH, SYSTEM_MANAGER, SYSTEM_MANAGER_INTERFACE); \
system_manager_proxy_->FUNC(); \
delete system_manager_proxy_; \
} catch (DBus::Error err) { \
ipc_pro_log_ctl && printf("DBus::Error - %s\n", err.what()); \
} \
dbus_mutex_unlock(); \
return NULL;
#define SYSTEMMANAGER_DBUSSEND_2(FUNC) \
char *ret = NULL; \
dbus_mutex_lock(); \
try { \
DBus::Connection conn = get_dbus_conn(); \
DBusSystemManager* system_manager_proxy_ = new DBusSystemManager(conn, SYSTEM_MANAGER_PATH, SYSTEM_MANAGER, SYSTEM_MANAGER_INTERFACE); \
auto config = system_manager_proxy_->FUNC(json); \
ret = g_strdup(config.c_str()); \
delete system_manager_proxy_; \
} catch (DBus::Error err) { \
ipc_pro_log_ctl && printf("DBus::Error - %s\n", err.what()); \
} \
dbus_mutex_unlock(); \
return ret;
char *dbus_system_reboot(void)
{
SYSTEMMANAGER_DBUSSEND_1(Reboot);
}
char *dbus_system_factory_reset(void)
{
SYSTEMMANAGER_DBUSSEND_1(FactoryReset);
}
char *dbus_system_export_db(char *json)
{
SYSTEMMANAGER_DBUSSEND_2(ExportDB);
}
char *dbus_system_import_db(char *json)
{
SYSTEMMANAGER_DBUSSEND_2(ImportDB);
}
char *dbus_system_export_log(char *json)
{
SYSTEMMANAGER_DBUSSEND_2(ExportLog);
}
char *dbus_system_upgrade(char *json)
{
SYSTEMMANAGER_DBUSSEND_2(Upgrade);
}
extern "C" char *system_reboot(void)
{
return dbus_system_reboot();
}
extern "C" char *system_factory_reset(void)
{
return dbus_system_factory_reset();
}
extern "C" char *system_export_db(const char *path)
{
char *ret = NULL;
json_object *j_cfg = json_object_new_object();
json_object_object_add(j_cfg, "sPath", json_object_new_string(path));
ret = dbus_system_export_db((char *)json_object_to_json_string(j_cfg));
json_object_put(j_cfg);
return ret;
}
extern "C" char *system_import_db(const char *path)
{
char *ret = NULL;
json_object *j_cfg = json_object_new_object();
json_object_object_add(j_cfg, "sPath", json_object_new_string(path));
ret = dbus_system_import_db((char *)json_object_to_json_string(j_cfg));
json_object_put(j_cfg);
return ret;
}
extern "C" char *system_export_log(const char *path)
{
char *ret = NULL;
json_object *j_cfg = json_object_new_object();
json_object_object_add(j_cfg, "sPath", json_object_new_string(path));
ret = dbus_system_export_log((char *)json_object_to_json_string(j_cfg));
json_object_put(j_cfg);
return ret;
}
extern "C" char *system_upgrade(const char *path)
{
char *ret = NULL;
json_object *j_cfg = json_object_new_object();
json_object_object_add(j_cfg, "sPath", json_object_new_string(path));
ret = dbus_system_upgrade((char *)json_object_to_json_string(j_cfg));
json_object_put(j_cfg);
return ret;
} | 26.455882 | 144 | 0.708727 | rockchip-linux |
92afb8f5a6bb59ea6ce6450390bd7c9ec35b7188 | 760 | cpp | C++ | test/test_mex.cpp | torfinnberset/mex-it | d4ce2a14231d05191d309d2e6951a0defc8254d3 | [
"MIT"
] | 31 | 2015-01-26T16:57:47.000Z | 2022-03-14T07:58:02.000Z | test/test_mex.cpp | torfinnberset/mex-it | d4ce2a14231d05191d309d2e6951a0defc8254d3 | [
"MIT"
] | 4 | 2015-04-03T09:03:37.000Z | 2019-11-10T23:37:32.000Z | test/test_mex.cpp | torfinnberset/mex-it | d4ce2a14231d05191d309d2e6951a0defc8254d3 | [
"MIT"
] | 10 | 2015-09-20T07:40:07.000Z | 2022-03-11T09:53:33.000Z | #include "mex_function.h"
#include "mex-it.h"
#include <iostream>
using namespace mex_binding;
using namespace std;
int main() {
int nrhs = 3;
int nlhs = 1;
double x=3.0;
double y=4.0;
double z=5.0;
mxArray *in1 = mxCreateDoubleScalar(x);
mxArray *in2 = mxCreateDoubleScalar(y);
mxArray *in3 = mxCreateDoubleScalar(z);
mxArray *out1 = mxCreateDoubleScalar(-1.0);
const mxArray *prhs[nrhs];
mxArray *plhs[nlhs];
prhs[0] = in1;
prhs[1] = in2;
prhs[2] = in3;
plhs[0] = out1;
call_mex_function(mex_function, nlhs, plhs, nrhs, prhs);
double result = mxGetScalar(plhs[0]);
assert(result == 35);
#ifdef DEBUG
cout << __FILE__ << " => mex_function: result of (" << x << " + " << y << ") * " << z << " is: " << result << endl;
#endif
}
| 18.095238 | 116 | 0.635526 | torfinnberset |
92b14af0a634c5f42bc749b1dbd63e44c84b052c | 871 | cpp | C++ | poprithms/tests/tests/memory/alias/tensor/color_0.cpp | graphcore/poprithms | 9975a6a343891e3c5f8968a9507261c1185029ed | [
"MIT"
] | 24 | 2020-07-06T17:11:30.000Z | 2022-01-01T07:39:12.000Z | poprithms/tests/tests/memory/alias/tensor/color_0.cpp | graphcore/poprithms | 9975a6a343891e3c5f8968a9507261c1185029ed | [
"MIT"
] | null | null | null | poprithms/tests/tests/memory/alias/tensor/color_0.cpp | graphcore/poprithms | 9975a6a343891e3c5f8968a9507261c1185029ed | [
"MIT"
] | 2 | 2020-07-15T12:33:22.000Z | 2021-07-27T06:07:16.000Z | // Copyright (c) 2020 Graphcore Ltd. All rights reserved.
#include <algorithm>
#include <iostream>
#include <poprithms/error/error.hpp>
#include <poprithms/memory/alias/graph.hpp>
namespace {
using namespace poprithms::memory::alias;
using namespace poprithms::memory::nest;
void test0() {
Graph g;
auto alloc = g.tensor(g.allocate({50}, Color(7)));
auto sliced = alloc.slice({7}, {17});
if (sliced.containsColor({5}) || !sliced.containsColor({7})) {
throw poprithms::test::error("Sliced of the wrong color in test0");
}
auto alloc2 = g.tensor(g.allocate({50}, Color(10)));
auto cat = sliced.concat({alloc2}, 0, 0);
if (cat.containsColor({5}) || !cat.containsColor({7}) ||
!cat.containsColor({10})) {
throw poprithms::test::error("Sliced of the wrong color in test0");
}
}
} // namespace
int main() {
test0();
return 0;
}
| 23.540541 | 71 | 0.657865 | graphcore |