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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ad9c6825a96c1b09f45c58d1bd81ce77443d5dae
| 196
|
cpp
|
C++
|
tests/test_model.cpp
|
shakfu/prolog
|
9d6621e3e723b0bd899bd963fe4a4125cf57671c
|
[
"Unlicense"
] | null | null | null |
tests/test_model.cpp
|
shakfu/prolog
|
9d6621e3e723b0bd899bd963fe4a4125cf57671c
|
[
"Unlicense"
] | null | null | null |
tests/test_model.cpp
|
shakfu/prolog
|
9d6621e3e723b0bd899bd963fe4a4125cf57671c
|
[
"Unlicense"
] | null | null | null |
#include "doctest.h"
#include "model/vehicle.hpp"
TEST_CASE("testing vehicle") {
model::Vehicle v;
v.brand = "x";
v.cost = 10.0;
v.weight = 5.0;
CHECK(v.cost_per_kg() == 2.0);
}
| 14
| 34
| 0.591837
|
shakfu
|
ad9db69271a9151979b183ac511aa504315c42c6
| 1,106
|
cpp
|
C++
|
c++/dp/MiniSqaureCut.cpp
|
Nk095291/pepcoding
|
fb57f8fa58c155d38bdbc47824f547e24c0804b6
|
[
"MIT"
] | 1
|
2020-04-24T05:45:44.000Z
|
2020-04-24T05:45:44.000Z
|
c++/dp/MiniSqaureCut.cpp
|
Nk095291/pepcoding
|
fb57f8fa58c155d38bdbc47824f547e24c0804b6
|
[
"MIT"
] | null | null | null |
c++/dp/MiniSqaureCut.cpp
|
Nk095291/pepcoding
|
fb57f8fa58c155d38bdbc47824f547e24c0804b6
|
[
"MIT"
] | null | null | null |
#include<iostream>
#include<vector>
#include<climits>
using namespace std;
int solve(vector<vector<int>>&res, int b,int l){
if(l<=0||b<=0)
return 0;
if(l==b)
return 0;
if(res[b][l]!=INT_MAX)
return res[b][l];
for(int i =1;i<=min(b,l);i++){
int p1v=solve(res,b-i,i);
int p2v=solve(res,b,l-i);
int p1h=solve(res,i,l-i);
int p2h=solve(res,b-i,l);
res[b][l]=min((p1h+p2h+1),(p1v+p2v+1));
}
return res[b][l];
}
int solve2(vector<vector<int>>&res, int b,int l){
if(l==0||b==0)
return 0;
if(l==b)
return 1;
if(res[b][l]!=0)
return res[b][l];
int mymin=INT_MAX;
for(int i =1;i<=min(b,l);i++){
int p1v=solve(res,b-i,i);
int p2v=solve(res,b,l-i);
int c1=p1v+p2v+1;
int p1h=solve(res,i,l-i);
int p2h=solve(res,b-i,l);
int c2 =p1h+p2h+1;
mymin=min(mymin,min(c1,c2));
}
res[b][l]=mymin;
return mymin;
}
int main(){
vector<vector<int>>res(31,vector<int>(36+1,INT_MAX));
cout<<solve(res,30,36);
}
| 21.269231
| 57
| 0.507233
|
Nk095291
|
ada146d03ec82a7927462795c75ab534000fad54
| 451
|
cpp
|
C++
|
Arrays - Reverse array/Arrays - Reverse array/Source.cpp
|
CHList/CS-305
|
731a192fb8ef38bde2e845733d43fd63e4129695
|
[
"MIT"
] | null | null | null |
Arrays - Reverse array/Arrays - Reverse array/Source.cpp
|
CHList/CS-305
|
731a192fb8ef38bde2e845733d43fd63e4129695
|
[
"MIT"
] | null | null | null |
Arrays - Reverse array/Arrays - Reverse array/Source.cpp
|
CHList/CS-305
|
731a192fb8ef38bde2e845733d43fd63e4129695
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
void reverseArray(int [], int);
int main() {
const int size = 6;
int list[size] = { 1,6,7,9,2,5 };
reverseArray(list, size);
cout << list[0];
for (int i = 1; i < size; i++) {
cout << "," << list[i];
}
cout << endl;
return 0;
}
void reverseArray(int list[], int size) {
int temp = 0;
for (int i = 1; i <= size/2; i++) {
temp = list[size-i];
list[size - i] = list[i-1];
list[i-1] = temp;
}
}
| 18.791667
| 41
| 0.552106
|
CHList
|
ada2e2c33c4a1f6ea0a55e19426f4182afc20be6
| 1,115
|
cpp
|
C++
|
03-composition-references/1-reference/assign_a_reference.cpp
|
nofar88/cpp-5782
|
473c68627fc0908fdef8956caf1e1d2267c9417b
|
[
"MIT"
] | 14
|
2021-01-30T16:36:18.000Z
|
2022-03-30T17:24:44.000Z
|
03-composition-references/1-reference/assign_a_reference.cpp
|
dimastar2310/cpp-5781
|
615ba07e0841522df74384f380172557f5e305a7
|
[
"MIT"
] | 1
|
2022-03-02T20:55:14.000Z
|
2022-03-02T20:55:14.000Z
|
03-composition-references/1-reference/assign_a_reference.cpp
|
dimastar2310/cpp-5781
|
615ba07e0841522df74384f380172557f5e305a7
|
[
"MIT"
] | 16
|
2021-03-02T11:13:41.000Z
|
2021-07-09T14:18:15.000Z
|
/**
* Demonstrates assigning values to references in C++.
*
* @author Erel Segal-Halevi
* @since 2018-02
*/
#include <iostream>
using namespace std;
int main() {
int* p1;
//int& r1; // compile error
int num = 1, num2 = 999;
cout << "Pointer:" << endl;
int* pnum = #
cout << "pnum = " << pnum << " " << *pnum << " " << num << endl;
(*pnum) = 2;
cout << "pnum = " << pnum << " " << *pnum << " " << num << endl;
pnum = &num2;
cout << "pnum = " << pnum << " " << *pnum << " " << num << endl;
pnum += 4; // unsafe
cout << "pnum = " << pnum << " " << *pnum << " " << num << endl << endl;
cout << "Reference:" << endl;
int& rnum = num;
cout << "rnum = " << &rnum << " " << rnum << " " << num << endl;
rnum = 3; // Here a reference is like a pointer
cout << "rnum = " << &rnum << " " << rnum << " " << num << endl;
rnum = num2; // Here a reference is unlike a pointer
cout << "rnum = " << &rnum << " " << rnum << " " << num << endl;
rnum += 4;
cout << "rnum = " << &rnum << " " << rnum << " " << num << endl << endl;
}
| 30.135135
| 76
| 0.442152
|
nofar88
|
ada55c5ef838ebe62e9bdce02ea66a59bd917970
| 2,347
|
cc
|
C++
|
chrome/chrome_cleaner/mojom/typemaps/string16_embedded_nulls_mojom_traits.cc
|
sarang-apps/darshan_browser
|
173649bb8a7c656dc60784d19e7bb73e07c20daa
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null |
chrome/chrome_cleaner/mojom/typemaps/string16_embedded_nulls_mojom_traits.cc
|
sarang-apps/darshan_browser
|
173649bb8a7c656dc60784d19e7bb73e07c20daa
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null |
chrome/chrome_cleaner/mojom/typemaps/string16_embedded_nulls_mojom_traits.cc
|
sarang-apps/darshan_browser
|
173649bb8a7c656dc60784d19e7bb73e07c20daa
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null |
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/chrome_cleaner/mojom/typemaps/string16_embedded_nulls_mojom_traits.h"
namespace mojo {
using chrome_cleaner::mojom::NullValueDataView;
using chrome_cleaner::mojom::String16EmbeddedNullsDataView;
using chrome_cleaner::String16EmbeddedNulls;
// static
bool StructTraits<NullValueDataView, nullptr_t>::Read(NullValueDataView data,
nullptr_t* value) {
*value = nullptr;
return true;
}
// static
base::span<const uint16_t>
UnionTraits<String16EmbeddedNullsDataView, String16EmbeddedNulls>::value(
const String16EmbeddedNulls& str) {
DCHECK_EQ(String16EmbeddedNullsDataView::Tag::VALUE, GetTag(str));
// This should only be called by Mojo to get the data to be send through the
// pipe. When called by Mojo in this case, str will outlive the returned span.
return base::make_span(str.CastAsUInt16Array(), str.size());
}
// static
nullptr_t
UnionTraits<String16EmbeddedNullsDataView, String16EmbeddedNulls>::null_value(
const chrome_cleaner::String16EmbeddedNulls& str) {
DCHECK_EQ(String16EmbeddedNullsDataView::Tag::NULL_VALUE, GetTag(str));
return nullptr;
}
// static
chrome_cleaner::mojom::String16EmbeddedNullsDataView::Tag
UnionTraits<String16EmbeddedNullsDataView, String16EmbeddedNulls>::GetTag(
const chrome_cleaner::String16EmbeddedNulls& str) {
return str.size() == 0 ? String16EmbeddedNullsDataView::Tag::NULL_VALUE
: String16EmbeddedNullsDataView::Tag::VALUE;
}
// static
bool UnionTraits<String16EmbeddedNullsDataView, String16EmbeddedNulls>::Read(
String16EmbeddedNullsDataView str_view,
String16EmbeddedNulls* out) {
if (str_view.is_null_value()) {
*out = String16EmbeddedNulls();
return true;
}
ArrayDataView<uint16_t> view;
str_view.GetValueDataView(&view);
// Note: Casting is intentional, since the data view represents the string as
// a uint16_t array, whereas String16EmbeddedNulls's constructor expects
// a wchar_t array.
*out = String16EmbeddedNulls(reinterpret_cast<const wchar_t*>(view.data()),
view.size());
return true;
}
} // namespace mojo
| 34.514706
| 86
| 0.737963
|
sarang-apps
|
ada5da0873736248a9ef99e8067522d738188fd2
| 838
|
cpp
|
C++
|
UbiGame_Blank/Source/Game/Util/WallManager.cpp
|
AdrienPringle/HTN-team-brain-damage
|
f234bd1e46bd83f5c2a8af5535d3e795e0b8d985
|
[
"MIT"
] | null | null | null |
UbiGame_Blank/Source/Game/Util/WallManager.cpp
|
AdrienPringle/HTN-team-brain-damage
|
f234bd1e46bd83f5c2a8af5535d3e795e0b8d985
|
[
"MIT"
] | null | null | null |
UbiGame_Blank/Source/Game/Util/WallManager.cpp
|
AdrienPringle/HTN-team-brain-damage
|
f234bd1e46bd83f5c2a8af5535d3e795e0b8d985
|
[
"MIT"
] | null | null | null |
#include "WallManager.h"
#include "GameEngine/GameEngineMain.h"
#include "Game/GameEntities/WallEntity.h"
using namespace Game;
WallManager* WallManager::sm_instance = nullptr;
WallManager::WallManager(){
wasMouseDown = true;
}
WallManager::~WallManager(){
}
void WallManager::Update(){
//spawn wall on mouse down
if(!sf::Mouse::isButtonPressed(sf::Mouse::Left)){
wasMouseDown = false;
} else if (!wasMouseDown) {
wasMouseDown = true;
SpawnWall();
}
}
void WallManager::SpawnWall(){
sf::RenderWindow *window = GameEngine::GameEngineMain::GetInstance()->GetRenderWindow();
sf::Vector2f mousePos = sf::Vector2f(sf::Mouse::getPosition(*window));
WallEntity* wall = new WallEntity();
wall->SetPos(mousePos);
GameEngine::GameEngineMain::GetInstance()->AddEntity(wall);
}
| 23.942857
| 92
| 0.689737
|
AdrienPringle
|
adad1ee2fe75ed250ac64d745fa10f209da9c2a0
| 735
|
cpp
|
C++
|
ESOData/Filesystem/DataFileHeader.cpp
|
FloorBelow/ESOData
|
eb35a95ec64d56c5842c4df85bc844e06fc72582
|
[
"MIT"
] | 1
|
2021-12-20T02:46:34.000Z
|
2021-12-20T02:46:34.000Z
|
ESOData/Filesystem/DataFileHeader.cpp
|
rekiofoldhome/ESOData
|
3c176110e7fa37fcff0b74b0bf0649f7251e59ed
|
[
"MIT"
] | null | null | null |
ESOData/Filesystem/DataFileHeader.cpp
|
rekiofoldhome/ESOData
|
3c176110e7fa37fcff0b74b0bf0649f7251e59ed
|
[
"MIT"
] | 1
|
2021-06-10T03:00:46.000Z
|
2021-06-10T03:00:46.000Z
|
#include <ESOData/Filesystem/DataFileHeader.h>
#include <ESOData/Serialization/SerializationStream.h>
#include <stdexcept>
namespace esodata {
SerializationStream &operator <<(SerializationStream &stream, const DataFileHeader &header) {
stream << DataFileHeader::Signature;
stream << header.version;
stream << header.unknown;
stream << header.headerSize;
return stream;
}
SerializationStream &operator >>(SerializationStream &stream, DataFileHeader &header) {
uint32_t signature;
stream >> signature;
if (signature != DataFileHeader::Signature)
throw std::runtime_error("Bad DAT file signature");
stream >> header.version;
stream >> header.unknown;
stream >> header.headerSize;
return stream;
}
}
| 24.5
| 94
| 0.742857
|
FloorBelow
|
adb86ae40f02307ae6ef47ba88df07ccb71ad290
| 3,225
|
hpp
|
C++
|
src/xml/Xml.hpp
|
Yousazoe/Solar
|
349c75f7a61b1727aa0c6d581cf75124b2502a57
|
[
"Apache-2.0"
] | 1
|
2021-08-07T13:02:01.000Z
|
2021-08-07T13:02:01.000Z
|
src/xml/Xml.hpp
|
Yousazoe/Solar
|
349c75f7a61b1727aa0c6d581cf75124b2502a57
|
[
"Apache-2.0"
] | null | null | null |
src/xml/Xml.hpp
|
Yousazoe/Solar
|
349c75f7a61b1727aa0c6d581cf75124b2502a57
|
[
"Apache-2.0"
] | null | null | null |
#pragma once
#include<../thirdparty/tinyxml/tinyxml.h>
#include<memory>
#include<fstream>
namespace tutorial
{
class XMLAttribute
{
public:
XMLAttribute() : _attrib(nullptr) {}
XMLAttribute(TiXmlAttribute *attrib) : _attrib(attrib) {}
bool is_empty() const { return _attrib == nullptr; }
const char* name() const { return _attrib->Name(); }
const char* value() const { return _attrib->Value(); }
XMLAttribute next_attrib() { return XMLAttribute(_attrib->Next()); }
protected:
TiXmlAttribute* _attrib;
};
class XMLNode
{
public:
XMLNode() = default;
XMLNode(TiXmlElement* node) : _node(node) {}
public:
TiXmlElement* get_xml_node() { return _node; }
bool is_empty() const { return _node == nullptr; }
const char* name() const { return _node->Value(); }
XMLNode first_child() const { return XMLNode(_node->FirstChildElement()); }
XMLNode next_sibling() const { return XMLNode(_node->NextSiblingElement()); }
XMLNode first_child(const char* name) const { return XMLNode(_node->FirstChildElement(name)); }
XMLNode next_sibling(const char* name) const { return XMLNode(_node->NextSiblingElement(name)); }
XMLAttribute first_attrib() { return XMLAttribute(_node->FirstAttribute()); }
const char* attribute(const char* name, const char* defValue = "") const
{
const char *attrib = _node->Attribute(name);
return attrib != nullptr ? attrib : defValue;
}
void attribute(const char* name, float* value, const float& default) const
{
double v = default;
_node->Attribute(name, &v);
*value = (float)v;
}
void attribute(const char* name, int* value, const int& default) const
{
_node->Attribute(name, value);
}
size_t child_node_count(const char *name = nullptr) const
{
size_t numNodes = 0u;
TiXmlElement *node1 = _node->FirstChildElement(name);
while (node1)
{
++numNodes;
node1 = node1->NextSiblingElement(name);
}
return numNodes;
}
operator bool() const { return !is_empty(); }
protected:
TiXmlElement* _node = nullptr;
};
class XMLDoc
{
public:
XMLDoc() { }
~XMLDoc() {
_doc.Clear();
}
public:
bool has_error() const;
XMLNode get_root_node();
void parse_string(const char* text);
void parse_buffer(const char* charbuf, size_t size);
bool parse_file(const char* file_name);
private:
TiXmlDocument _doc;
std::unique_ptr<char[]> buf;
};
inline bool XMLDoc::has_error() const
{
return _doc.RootElement() == nullptr;
}
inline XMLNode XMLDoc::get_root_node()
{
return XMLNode(_doc.RootElement());
}
inline void XMLDoc::parse_string(const char* text)
{
_doc.Parse(text);
}
inline void XMLDoc::parse_buffer(const char* charbuf, size_t size)
{
buf.reset(new char[size + 1]);
memcpy(buf.get(), charbuf, size);
buf[size] = '\0';
parse_string(buf.get());
}
inline bool XMLDoc::parse_file(const char* file_name)
{
std::fstream f(file_name, std::ios::in | std::ios::binary);
if (!f.is_open())
return false;
f.seekg(0, std::ios::end);
auto size = (size_t)f.tellg();
f.seekg(0, std::ios::beg);
buf.reset(new char[size + 1]);
f.read(buf.get(), size);
buf[size] = '\0';
f.close();
parse_string(buf.get());
return true;
}
}
| 23.201439
| 99
| 0.671628
|
Yousazoe
|
adbc18e69243df5c6ea4b52bfeae1e38d8b83f58
| 6,237
|
cpp
|
C++
|
levelManager.cpp
|
LEpigeon888/IndevBuggedGame
|
c99f9bc64d3b52fca830be4a79fb81dbdb8f97d7
|
[
"Zlib"
] | null | null | null |
levelManager.cpp
|
LEpigeon888/IndevBuggedGame
|
c99f9bc64d3b52fca830be4a79fb81dbdb8f97d7
|
[
"Zlib"
] | null | null | null |
levelManager.cpp
|
LEpigeon888/IndevBuggedGame
|
c99f9bc64d3b52fca830be4a79fb81dbdb8f97d7
|
[
"Zlib"
] | null | null | null |
#include <fstream>
#include <utility>
#include "blockManager.hpp"
#include "eventManager.hpp"
#include "global.hpp"
#include "levelManager.hpp"
#include "utilities.hpp"
void LevelManager::setBlockHere(std::map<Point, std::unique_ptr<Block>>& currentMap, BlockId idOfBlock, int xBlock,
int yBlock)
{
auto block = BlockManager::createBlock(idOfBlock);
block->setPosition({xBlock * SIZE_BLOCK, yBlock * SIZE_BLOCK});
currentMap[Point(xBlock, yBlock)] = std::move(block);
}
void LevelManager::loadLevelFromFile(LevelInfo& currentLevel, std::string filePath)
{
size_t spacePos;
std::string currentLine;
std::string currentType;
std::string firstWordOfLine;
std::ifstream file;
file.open("resources/" + filePath);
while (std::getline(file, currentLine))
{
spacePos = currentLine.find(' ');
firstWordOfLine = currentLine.substr(0, spacePos);
if (spacePos == std::string::npos)
{
currentLine.clear();
}
else
{
currentLine.erase(0, spacePos + 1);
}
if (firstWordOfLine == "GAME_VERSION")
{
currentLevel.initialGameVersion = VersionNumber(currentLine);
}
else if (firstWordOfLine == "NEXT_LEVEL")
{
currentLevel.nextLevelName = currentLine;
}
else if (firstWordOfLine == "SIZE_OF_LEVEL")
{
currentLevel.limitOfGame.top = 0;
currentLevel.limitOfGame.left = 0;
currentLevel.limitOfGame.width = Utilities::stringToInt(Utilities::readFirstString(currentLine));
currentLevel.limitOfGame.height = Utilities::stringToInt(Utilities::readFirstString(currentLine));
}
else if (firstWordOfLine == "PLAYER_POSITION")
{
currentLevel.playerStartPosition.x = Utilities::stringToInt(Utilities::readFirstString(currentLine));
currentLevel.playerStartPosition.y = Utilities::stringToInt(Utilities::readFirstString(currentLine));
}
else if (firstWordOfLine == "NEW_BLOCK")
{
BlockId idOfBlock = BlockManager::stringBlockId(Utilities::readFirstString(currentLine));
int posX = Utilities::stringToInt(Utilities::readFirstString(currentLine));
int posY = Utilities::stringToInt(Utilities::readFirstString(currentLine));
setBlockHere(currentLevel.mapOfGame, idOfBlock, posX, posY);
}
else if (firstWordOfLine == "NEW_EVENT")
{
std::string nameOfEvent = Utilities::readFirstString(currentLine);
int posX = Utilities::stringToInt(Utilities::readFirstString(currentLine));
int posY = Utilities::stringToInt(Utilities::readFirstString(currentLine));
int sizeX = Utilities::stringToInt(Utilities::readFirstString(currentLine));
int sizeY = Utilities::stringToInt(Utilities::readFirstString(currentLine));
currentLevel.listOfEvent.emplace_back(
EventManager::createEvent(nameOfEvent, sf::IntRect{posX, posY, sizeX, sizeY}, currentLine));
}
}
file.close();
}
void LevelManager::loadBasicLevelFromFile(BasicLevelInfo& currentLevel, std::string filePath)
{
size_t spacePos;
std::string currentLine;
std::string currentType;
std::string firstWordOfLine;
std::ifstream file;
file.open("resources/" + filePath);
while (std::getline(file, currentLine))
{
spacePos = currentLine.find(' ');
firstWordOfLine = currentLine.substr(0, spacePos);
if (spacePos == std::string::npos)
{
currentLine.clear();
}
else
{
currentLine.erase(0, spacePos + 1);
}
if (firstWordOfLine == "SIZE_OF_LEVEL")
{
currentLevel.limitOfGame.top = 0;
currentLevel.limitOfGame.left = 0;
currentLevel.limitOfGame.width = Utilities::stringToInt(Utilities::readFirstString(currentLine));
currentLevel.limitOfGame.height = Utilities::stringToInt(Utilities::readFirstString(currentLine));
}
else if (firstWordOfLine == "PLAYER_POSITION")
{
currentLevel.playerStartPosition.x = Utilities::stringToInt(Utilities::readFirstString(currentLine));
currentLevel.playerStartPosition.y = Utilities::stringToInt(Utilities::readFirstString(currentLine));
}
else if (firstWordOfLine == "NEW_BLOCK")
{
BasicBlock newBlock;
newBlock.id = BlockManager::stringBlockId(Utilities::readFirstString(currentLine));
int posX = Utilities::stringToInt(Utilities::readFirstString(currentLine));
int posY = Utilities::stringToInt(Utilities::readFirstString(currentLine));
newBlock.sprite.setSize(sf::Vector2f(SIZE_BLOCK, SIZE_BLOCK));
newBlock.sprite.setPosition(SIZE_BLOCK * posX, SIZE_BLOCK * posY);
newBlock.sprite.setFillColor(BlockManager::getColorOfBlock(newBlock.id));
currentLevel.mapOfGame[Point(posX, posY)] = std::move(newBlock);
}
else
{
std::string newLine = firstWordOfLine;
if (!currentLine.empty())
{
newLine += " " + currentLine;
}
currentLevel.otherLines.push_back(newLine);
}
}
file.close();
}
void LevelManager::saveBasicLevel(BasicLevelInfo& currentLevel, std::string levelName)
{
std::ofstream file;
file.open("resources/" + levelName);
file << "SIZE_OF_LEVEL " << currentLevel.limitOfGame.width << " " << currentLevel.limitOfGame.height << std::endl;
file << "PLAYER_POSITION " << currentLevel.playerStartPosition.x << " " << currentLevel.playerStartPosition.y
<< std::endl;
for (auto& currentLevelIte : currentLevel.mapOfGame)
{
file << "NEW_BLOCK " << BlockManager::blockIdToString(currentLevelIte.second.id) << " "
<< currentLevelIte.first.first << " " << currentLevelIte.first.second << std::endl;
}
for (std::string& line : currentLevel.otherLines)
{
file << line << std::endl;
}
file.close();
}
| 36.473684
| 118
| 0.636364
|
LEpigeon888
|
adbecc30a0fe5a2dbe4ac91abdf0b678606a2c3f
| 955
|
cpp
|
C++
|
src/mxml/parsing/MordentHandler.cpp
|
dkun7944/mxml
|
6450e7cab88eb6ee0ac469f437047072e1868ea4
|
[
"MIT"
] | 18
|
2016-05-22T00:55:28.000Z
|
2021-03-29T08:44:23.000Z
|
src/mxml/parsing/MordentHandler.cpp
|
dkun7944/mxml
|
6450e7cab88eb6ee0ac469f437047072e1868ea4
|
[
"MIT"
] | 6
|
2017-05-17T13:20:09.000Z
|
2018-10-22T20:00:57.000Z
|
src/mxml/parsing/MordentHandler.cpp
|
dkun7944/mxml
|
6450e7cab88eb6ee0ac469f437047072e1868ea4
|
[
"MIT"
] | 14
|
2016-05-12T22:54:34.000Z
|
2021-10-19T12:43:16.000Z
|
// Copyright © 2016 Venture Media Labs.
//
// This file is part of mxml. The full mxml copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
#include "MordentHandler.h"
#include "EmptyPlacementHandler.h"
namespace mxml {
using dom::Mordent;
static const char* kPlacementAttribute = "placement";
static const char* kLongAttribute = "long";
void MordentHandler::startElement(const lxml::QName& qname, const AttributeMap& attributes) {
_result.reset(new Mordent());
auto placement = attributes.find(kPlacementAttribute);
if (placement != attributes.end())
_result->setPlacement(presentOptional(EmptyPlacementHandler::placementFromString(placement->second)));
auto longv = attributes.find(kLongAttribute);
if (longv != attributes.end())
_result->setLong(longv->second == "yes");
}
} // namespace
| 30.806452
| 110
| 0.736126
|
dkun7944
|
adbfd05a98256bf85511a02bd842b3c4af93c5bb
| 2,714
|
cpp
|
C++
|
NES/Mapper/Mapper068.cpp
|
chittleskuny/virtuanes
|
f2528f24108ebde6c2e123920423d95e086d86bc
|
[
"MIT"
] | null | null | null |
NES/Mapper/Mapper068.cpp
|
chittleskuny/virtuanes
|
f2528f24108ebde6c2e123920423d95e086d86bc
|
[
"MIT"
] | null | null | null |
NES/Mapper/Mapper068.cpp
|
chittleskuny/virtuanes
|
f2528f24108ebde6c2e123920423d95e086d86bc
|
[
"MIT"
] | null | null | null |
//////////////////////////////////////////////////////////////////////////
// Mapper068 SunSoft (After Burner II) //
//////////////////////////////////////////////////////////////////////////
void Mapper068::Reset()
{
reg[0] = reg[1] = reg[2] = reg[3] = 0;
coin = 0;
SetPROM_32K_Bank( 0, 1, PROM_8K_SIZE-2, PROM_8K_SIZE-1 );
}
#if 0
BYTE Mapper068::ExRead( WORD addr )
{
if( addr == 0x4020 ) {
DEBUGOUT( "RD $4020:%02X\n", coin );
return coin;
}
return addr>>8;
}
void Mapper068::ExWrite( WORD addr, BYTE data )
{
if( addr == 0x4020 ) {
DEBUGOUT( "WR $4020:%02X\n", data );
coin = data;
}
}
#endif
void Mapper068::Write( WORD addr, BYTE data )
{
switch( addr & 0xF000 ) {
case 0x8000:
SetVROM_2K_Bank( 0, data );
break;
case 0x9000:
SetVROM_2K_Bank( 2, data );
break;
case 0xA000:
SetVROM_2K_Bank( 4, data );
break;
case 0xB000:
SetVROM_2K_Bank( 6, data );
break;
case 0xC000:
reg[2] = data;
SetBank();
break;
case 0xD000:
reg[3] = data;
SetBank();
break;
case 0xE000:
reg[0] = (data & 0x10)>>4;
reg[1] = data & 0x03;
SetBank();
break;
case 0xF000:
SetPROM_16K_Bank( 4, data );
break;
}
}
void Mapper068::SetBank()
{
if( reg[0] ) {
switch( reg[1] ) {
case 0:
SetVROM_1K_Bank( 8, (INT)reg[2]+0x80 );
SetVROM_1K_Bank( 9, (INT)reg[3]+0x80 );
SetVROM_1K_Bank( 10, (INT)reg[2]+0x80 );
SetVROM_1K_Bank( 11, (INT)reg[3]+0x80 );
break;
case 1:
SetVROM_1K_Bank( 8, (INT)reg[2]+0x80 );
SetVROM_1K_Bank( 9, (INT)reg[2]+0x80 );
SetVROM_1K_Bank( 10, (INT)reg[3]+0x80 );
SetVROM_1K_Bank( 11, (INT)reg[3]+0x80 );
break;
case 2:
SetVROM_1K_Bank( 8, (INT)reg[2]+0x80 );
SetVROM_1K_Bank( 9, (INT)reg[2]+0x80 );
SetVROM_1K_Bank( 10, (INT)reg[2]+0x80 );
SetVROM_1K_Bank( 11, (INT)reg[2]+0x80 );
break;
case 3:
SetVROM_1K_Bank( 8, (INT)reg[3]+0x80 );
SetVROM_1K_Bank( 9, (INT)reg[3]+0x80 );
SetVROM_1K_Bank( 10, (INT)reg[3]+0x80 );
SetVROM_1K_Bank( 11, (INT)reg[3]+0x80 );
break;
}
} else {
switch( reg[1] ) {
case 0:
SetVRAM_Mirror( VRAM_VMIRROR );
break;
case 1:
SetVRAM_Mirror( VRAM_HMIRROR );
break;
case 2:
SetVRAM_Mirror( VRAM_MIRROR4L );
break;
case 3:
SetVRAM_Mirror( VRAM_MIRROR4H );
break;
}
}
}
void Mapper068::SaveState( LPBYTE p )
{
p[0] = reg[0];
p[1] = reg[1];
p[2] = reg[2];
p[3] = reg[3];
}
void Mapper068::LoadState( LPBYTE p )
{
reg[0] = p[0];
reg[1] = p[1];
reg[2] = p[2];
reg[3] = p[3];
}
| 20.876923
| 75
| 0.51437
|
chittleskuny
|
adccb5f1b156054bc25860aecc8c8c7d649bfd59
| 14,637
|
cpp
|
C++
|
Source/Client/IM-Client/IMClient/HttpDownloader.cpp
|
InstantBusinessNetwork/IBN
|
bbcf47de56bfc52049eeb2e46677642a28f38825
|
[
"MIT"
] | 21
|
2015-07-22T15:22:41.000Z
|
2021-03-23T05:40:44.000Z
|
Source/Client/IM-Client/IMClient/HttpDownloader.cpp
|
InstantBusinessNetwork/IBN
|
bbcf47de56bfc52049eeb2e46677642a28f38825
|
[
"MIT"
] | 11
|
2015-10-19T07:54:10.000Z
|
2021-09-01T08:47:56.000Z
|
Source/Client/IM-Client/IMClient/HttpDownloader.cpp
|
InstantBusinessNetwork/IBN
|
bbcf47de56bfc52049eeb2e46677642a28f38825
|
[
"MIT"
] | 16
|
2015-07-22T15:23:09.000Z
|
2022-01-17T10:49:43.000Z
|
// HttpDownloader.cpp: implementation of the CHttpDownloader class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "HttpDownloader.h"
#include "Resource.h"
#include "GlobalFunction.h"
#include "atlenc.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CHttpDownloader::CHttpDownloader()
{
m_hInternet = 0;
m_hConnect = 0;
m_hRequest = 0;
m_longAbort = FALSE;
m_pStream = NULL;
m_hWnd = NULL;
m_nMessage = 0;
m_dwTotalSize = 0;
m_dwDownloaded = 0;
m_dwTimeout = 60000;
m_dwConnectRetryCount = 3;
m_ProxyType = GetOptionInt(IDS_NETOPTIONS, IDS_ACCESSTYPE, INTERNET_OPEN_TYPE_PRECONFIG);
m_ProxyName.Format(_T("http=http://%s:%s"), GetOptionString(IDS_NETOPTIONS, IDS_PROXYNAME, _T("")), GetOptionString(IDS_NETOPTIONS, IDS_PROXYPORT, _T("")));
// m_UseFireWall = GetOptionInt(IDS_NETOPTIONS, IDS_USEFIREWALL, FALSE);
// m_FireWallUser = GetOptionString(IDS_NETOPTIONS, IDS_FIREWALLUSER, "");
// m_FireWallPass = GetOptionString(IDS_NETOPTIONS, IDS_FIREWALLPASS, "");
m_hEvent = ::CreateEvent(NULL, TRUE, TRUE, NULL);
}
CHttpDownloader::~CHttpDownloader()
{
Clear();
if(m_pStream)
{
m_pStream->Release();
m_pStream = NULL;
}
CloseHandle(m_hEvent);
}
HRESULT CHttpDownloader::ConnectToServer(_bstr_t &strBuffer)
{
BOOL bResult;
DWORD dwStatus;
DWORD nTimeoutCounter;
_bstr_t strMethod;
_bstr_t strUrl = m_request.url;
LPCTSTR szProxyName = NULL;
if(m_ProxyType == INTERNET_OPEN_TYPE_PROXY)
szProxyName = m_ProxyName;
//// InternetOpen \\\\
if(!m_hInternet)
m_hInternet = InternetOpen(_T("McHttpDownloader"), m_ProxyType, szProxyName, NULL, INTERNET_FLAG_ASYNC);
if(!m_hInternet)
{
strBuffer = _T("InternetOpen failed");
return E_FAIL;
}
InternetSetStatusCallback(m_hInternet, (INTERNET_STATUS_CALLBACK)CallbackFunc);
//// InternetOpen ////
if(m_longAbort > 0)
return E_ABORT;
//// InternetConnect \\\\
if(!m_hConnect)
{
m_hConnect = InternetConnect(m_hInternet, m_request.server, (short)m_request.port, NULL, NULL, INTERNET_SERVICE_HTTP, NULL, (DWORD)&m_context);
}
if(m_hConnect == NULL)
{
strBuffer = _T("InternetConnect failed");
return INET_E_CANNOT_CONNECT;
}
//// InternetConnect ////
nTimeoutCounter = 0;
NewConnect:
strMethod = _T("GET");
strBuffer = _T("");
//// OpenRequest \\\\
if(m_hRequest)
{
::InternetCloseHandle(m_hRequest);
m_hRequest = NULL;
}
if(m_longAbort > 0)
return E_ABORT;
DWORD dwFlags =
INTERNET_FLAG_KEEP_CONNECTION |
INTERNET_FLAG_NO_CACHE_WRITE |
INTERNET_FLAG_RELOAD |
INTERNET_FLAG_PRAGMA_NOCACHE |
INTERNET_FLAG_NO_UI |
INTERNET_FLAG_NO_COOKIES |
INTERNET_FLAG_IGNORE_CERT_CN_INVALID |
INTERNET_FLAG_NO_AUTO_REDIRECT |
INTERNET_FLAG_HYPERLINK |
(m_request.bUseSSL ?
(INTERNET_FLAG_SECURE/*|
INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS|
INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP*/)
:
0);
m_context.op = HTTP_DOWNLOADER_OP_OPEN_REQUEST;
m_hRequest = HttpOpenRequest(m_hConnect, strMethod, strUrl, _T("HTTP/1.1"), NULL, NULL, dwFlags, (DWORD)&m_context);
if(m_hRequest == NULL)
{
strBuffer = _T("HttpOpenRequest failed");
return E_FAIL;
}
if(m_ProxyType == INTERNET_OPEN_TYPE_PROXY)
{
if(GetOptionInt(IDS_NETOPTIONS,IDS_USEFIREWALL,0))
{
CString fireWallUser = GetOptionString(IDS_NETOPTIONS, IDS_FIREWALLUSER, _T(""));
CString fireWallPass = GetOptionString(IDS_NETOPTIONS, IDS_FIREWALLPASS, _T(""));
//////////////////////////////////////////////////////////////////////////
int HeaderLen = ATL::ProxyAuthorizationStringGetRequiredLength(fireWallUser, fireWallPass);
LPTSTR strHeader = new TCHAR[HeaderLen+1];
ZeroMemory(strHeader,HeaderLen+1);
HRESULT hr = ATL::ProxyAuthorizationString(fireWallUser, fireWallPass, strHeader, &HeaderLen);
ASSERT(hr==S_OK);
HttpAddRequestHeaders(m_hRequest, strHeader, HeaderLen, HTTP_ADDREQ_FLAG_ADD );
delete []strHeader;
//////////////////////////////////////////////////////////////////////////
}
}
//// OpenRequest ////
NewRequest:
if(m_longAbort > 0)
return E_ABORT;
m_context.op = HTTP_DOWNLOADER_OP_SEND_REQUEST;
bResult = HttpSendRequest(m_hRequest, NULL , 0, (LPVOID)(BYTE*)(LPCTSTR)strBuffer, lstrlen(strBuffer));
if(!bResult && 997 == GetLastError()) // Overlapped I/O operation is in progress.
bResult = WaitForComplete(m_dwTimeout); // Resolve host name, connect, send request, receive response.
if(!bResult)
{
DWORD dwErrCode = GetLastError();
// ATLTRACE("Send Request error = %d \r\n",dwErrCode);
if(dwErrCode == 6) // The handle is invalid.
goto NewConnect;
if(dwErrCode == ERROR_INTERNET_TIMEOUT) // timeout
{
if(++nTimeoutCounter < m_dwConnectRetryCount)
goto NewConnect;
else
{
strBuffer = _T("Timeout");
return E_FAIL;//INET_E_CONNECTION_TIMEOUT;
}
}
strBuffer = _T("SendRequest failed");
return E_FAIL;
}
dwStatus = GetHttpStatus();
if(dwStatus == 401 || dwStatus == 407) // Denied or Proxy asks password
{
if(ERROR_INTERNET_FORCE_RETRY ==
InternetErrorDlg(GetDesktopWindow(), m_hRequest,
ERROR_INTERNET_INCORRECT_PASSWORD,
FLAGS_ERROR_UI_FILTER_FOR_ERRORS |
FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS |
FLAGS_ERROR_UI_FLAGS_GENERATE_DATA,
NULL))
{
goto NewRequest;
}
}
if(dwStatus != 200) // Not OK
{
strBuffer = _T("SendRequest returned with error");
return INET_E_CANNOT_CONNECT;
}
return S_OK;
}
DWORD CHttpDownloader::GetHttpStatus()
{
LPVOID lpOutBuffer = new char[4];
DWORD dwSize = 4;
DWORD Status = 0;
DWORD err = 0;
BOOL bResult;
ret:
m_context.op = HTTP_DOWNLOADER_OP_GET_STATUS;
bResult = HttpQueryInfo(m_hRequest, HTTP_QUERY_STATUS_CODE, (LPVOID)lpOutBuffer, &dwSize, NULL);
if(!bResult&&997 == GetLastError())
WaitForComplete(m_dwTimeout);
if(!bResult)
{
err = GetLastError();
if(err == ERROR_HTTP_HEADER_NOT_FOUND)
{
return false; //throw();
}
else
{
if (err == ERROR_INSUFFICIENT_BUFFER)
{
if(lpOutBuffer!=NULL)
delete[] lpOutBuffer;
lpOutBuffer = new char[dwSize];
goto ret;
}
else
{
return Status; //throw();
}
}
}
else
{
// ATLTRACE("HTTP STATUS - %s \r\n", lpOutBuffer);
Status = atol((char*)lpOutBuffer);
delete[] lpOutBuffer;
lpOutBuffer = NULL;
return Status;
}
}
HRESULT CHttpDownloader::WorkFunction()
{
HRESULT hr;
_bstr_t strBuffer;
strBuffer = _T("");
if(m_longAbort > 0)
{
hr = E_ABORT;
goto EndWorkFunc;
}
if(m_request.pCritSect)
EnterCriticalSection(m_request.pCritSect);
if(m_longAbort > 0)
{
hr = E_ABORT;
goto EndWorkFunc;
}
hr = ConnectToServer(strBuffer);
if(FAILED(hr))
goto EndWorkFunc;
hr = ReadData(strBuffer);
if(FAILED(hr) || m_dwDownloaded < m_dwTotalSize)
{
strBuffer = _T("Cannot read data");
goto EndWorkFunc;
}
EndWorkFunc:
// TRACE(_T("HTTP OPERATION = %d\n"), m_context.op);
Clear();
if(m_pStream)
{
LARGE_INTEGER li = {0, 0};
hr = m_pStream->Seek(li, STREAM_SEEK_SET, NULL);
}
if(m_request.pCritSect)
{
try
{
LeaveCriticalSection(m_request.pCritSect);
}
catch(...)
{
// MCTRACE(0, _T("LeaveCriticalSection(%08x)"), m_request.pCritSect);
}
}
return hr;
}
HRESULT CHttpDownloader::ReadData(_bstr_t &strBuffer)
{
HRESULT hr = E_FAIL;
IStream *pStream = NULL;
INTERNET_BUFFERS ib ={0};
ULONG ulWritten;
BOOL bResult;
DWORD dwErr;
TCHAR buf[32];
DWORD dwBufferLength;
TCHAR *szNULL = _T("\x0");
// Get file size
dwBufferLength = 32*sizeof(TCHAR);
if(::HttpQueryInfo(m_hRequest, HTTP_QUERY_CONTENT_LENGTH, buf, &dwBufferLength, NULL))
{
m_dwTotalSize = _tcstoul(buf, &szNULL, 10);
if(m_hWnd != NULL && m_nMessage != 0)
::PostMessage(m_hWnd, m_nMessage, m_dwDownloaded, m_dwTotalSize);
}
//Check MD5 hash
if(m_request.md5 != NULL && _tcslen(m_request.md5) >= 22)
{
dwBufferLength = 32*sizeof(TCHAR);
if(::HttpQueryInfo(m_hRequest, HTTP_QUERY_CONTENT_MD5, buf, &dwBufferLength, NULL))
{
if(0 == _tcsnicmp(m_request.md5, buf, 22))
{
if(m_hWnd != NULL && m_nMessage != 0)
::PostMessage(m_hWnd, m_nMessage, m_dwTotalSize, m_dwTotalSize);
}
return S_OK;
}
}
hr = CreateStreamOnHGlobal(NULL, TRUE, &pStream);
if(FAILED(hr))
{
return hr;
}
ib.lpcszHeader = NULL;
ib.dwHeadersLength = NULL;
ib.lpvBuffer = new TCHAR[COMMAND_BUFF_SIZE_PART];
ib.dwBufferLength = COMMAND_BUFF_SIZE_PART;
ib.dwStructSize = sizeof(ib);
do
{
ib.dwBufferLength = COMMAND_BUFF_SIZE_PART;
if(m_longAbort > 0)
{
hr = E_ABORT;
break;
}
m_context.op = HTTP_DOWNLOADER_OP_READ_DATA;
bResult = InternetReadFileEx(m_hRequest, &ib, IRF_ASYNC | IRF_USE_CONTEXT, (DWORD)&m_context);
dwErr = GetLastError();
if(!bResult && dwErr == 997) // Overlapped I/O operation is in progress.
{
bResult = WaitForComplete(m_dwTimeout);
if(bResult)
continue;
}
if(bResult)
{
if(ib.dwBufferLength)
{
hr = pStream->Write(ib.lpvBuffer, ib.dwBufferLength, &ulWritten);
if(FAILED(hr))
{
strBuffer = _T("Cannot write to stream");
break;
}
m_dwDownloaded += ib.dwBufferLength;
if(m_hWnd != NULL && m_nMessage != 0)
::PostMessage(m_hWnd, m_nMessage, m_dwDownloaded, m_dwTotalSize);
}
}
else
{
hr = E_FAIL;
break;
}
// Sleep(1);
} while(ib.dwBufferLength);
if(ib.lpvBuffer)
{
delete[] ib.lpvBuffer;
ib.lpvBuffer = NULL;
}
if(SUCCEEDED(hr) && pStream)
{
m_pStream = pStream;
return hr;
}
else
{
if(pStream)
pStream->Release();
pStream = NULL;
}
return hr;
}
HRESULT CHttpDownloader::Load(LPCTSTR szUrl, IStream **ppStream, LPCTSTR szMD5)
{
HRESULT hr = E_FAIL;
m_longAbort = 0;
Clear();
*ppStream = NULL;
m_dwDownloaded = 0;
m_dwTotalSize = 0;
m_request.md5 = szMD5;
hr = ParseUrl(szUrl);
if(SUCCEEDED(hr))
{
if(m_pStream)
{
m_pStream->Release();
m_pStream = NULL;
}
m_context.op = HTTP_DOWNLOADER_OP_IDLE;
m_context.hEvent = m_hEvent;
SetEvent(m_hEvent);
hr = WorkFunction();
if(SUCCEEDED(hr))
{
m_pStream->AddRef();
*ppStream = m_pStream;
}
}
return hr;
}
HRESULT CHttpDownloader::ParseUrl(LPCTSTR szUrlIn)
{
if(!lstrlen(szUrlIn))
return INET_E_INVALID_URL;
URL_COMPONENTS uc;
memset(&uc, 0, sizeof(uc));
uc.dwStructSize = sizeof(uc);
TCHAR szServer[1024];
TCHAR szUrl[1024];
// TCHAR szScheme[1024];
uc.lpszHostName = szServer;
uc.dwHostNameLength = sizeof(szServer);
uc.lpszUrlPath = szUrl;
uc.dwUrlPathLength = sizeof(szUrl);
// uc.lpszScheme =szScheme;
// uc.dwSchemeLength = sizeof(szScheme);
if(!InternetCrackUrl(szUrlIn, lstrlen(szUrlIn), 0, &uc))
return INET_E_INVALID_URL;
if(uc.nScheme==INTERNET_SCHEME_HTTPS)
m_request.bUseSSL = TRUE;
if(lstrlen(szServer))
m_request.server = szServer;
if(uc.nPort != 0)
m_request.port = uc.nPort;
if(lstrlen(szUrl))
m_request.url = szUrl;
return S_OK;
}
void CHttpDownloader::EnableProgress(HWND hWnd, UINT nMessage)
{
m_hWnd = hWnd;
m_nMessage = nMessage;
}
void CHttpDownloader::Abort()
{
InterlockedExchange(&m_longAbort, 1);
Clear();
SetEvent(m_hEvent);
}
void CHttpDownloader::Clear()
{
if(m_hRequest)
{
InternetCloseHandle(m_hRequest);
m_hRequest = NULL;
}
if(m_hConnect)
{
InternetCloseHandle(m_hConnect);
m_hConnect = NULL;
}
if(m_hInternet)
{
InternetCloseHandle(m_hInternet);
m_hInternet = NULL;
}
}
void __stdcall CHttpDownloader::CallbackFunc(HINTERNET hInternet, DWORD dwContext, DWORD dwInternetStatus, LPVOID lpvStatusInformation, DWORD dwStatusInformationLength)
{
// TRACE(_T("INTERNET CALLBACK %08x %08x %d\n"), hInternet, dwContext, dwInternetStatus);
if(IsBadWritePtr((LPVOID)dwContext,sizeof(CHttpDownloader :: HttpDownloaderContext)))
return;
CHttpDownloader::HttpDownloaderContext *pContext = (CHttpDownloader::HttpDownloaderContext*)dwContext;
INTERNET_ASYNC_RESULT* pINTERNET_ASYNC_RESULT = NULL;
BOOL bRetVal = FALSE;
switch (dwInternetStatus)
{
case INTERNET_STATUS_REQUEST_COMPLETE:
pINTERNET_ASYNC_RESULT = (INTERNET_ASYNC_RESULT*)lpvStatusInformation;
if(pINTERNET_ASYNC_RESULT->dwError!=ERROR_INTERNET_OPERATION_CANCELLED)
{
pContext->dwError = pINTERNET_ASYNC_RESULT->dwError;
bRetVal = SetEvent(pContext->hEvent);
}
break;
/*
case INTERNET_STATUS_RESPONSE_RECEIVED:
if(pContext)
{
if(pContext->op == HTTP_DOWNLOADER_OP_READ_DATA)
SetEvent(pContext->hEvent);
}
break;*/
case INTERNET_STATUS_RESOLVING_NAME:
case INTERNET_STATUS_NAME_RESOLVED:
case INTERNET_STATUS_CONNECTING_TO_SERVER:
case INTERNET_STATUS_CONNECTED_TO_SERVER:
case INTERNET_STATUS_SENDING_REQUEST:
case INTERNET_STATUS_REQUEST_SENT:
case INTERNET_STATUS_RECEIVING_RESPONSE:
case INTERNET_STATUS_CTL_RESPONSE_RECEIVED:
case INTERNET_STATUS_PREFETCH:
case INTERNET_STATUS_CLOSING_CONNECTION:
case INTERNET_STATUS_CONNECTION_CLOSED:
case INTERNET_STATUS_HANDLE_CREATED:
case INTERNET_STATUS_HANDLE_CLOSING:
case INTERNET_STATUS_REDIRECT:
case INTERNET_STATUS_INTERMEDIATE_RESPONSE:
case INTERNET_STATUS_STATE_CHANGE:
default:
break;
}
}
BOOL CHttpDownloader::WaitForComplete(DWORD dwMilliseconds)
{
ResetEvent(m_hEvent);
DWORD dw = WaitForSingleObject(m_hEvent, dwMilliseconds);
//TRACE("\r\n == after WaitForSingleObject == \r\n");
if(m_longAbort > 0)
{
// TRACE(_T("WaitForComplete: ABORTED, OP = %d\n"), m_context.op);
SetLastError(ERROR_INTERNET_CONNECTION_ABORTED);
return FALSE;
}
if(dw == WAIT_TIMEOUT)
{
// TRACE(_T("WaitForComplete: TIMEOUT, OP = %d\n"), m_context.op);
SetLastError(ERROR_INTERNET_TIMEOUT);
return FALSE;
}
if(m_context.dwError != ERROR_SUCCESS)
return FALSE;
return (dw == WAIT_OBJECT_0);
}
| 23.27027
| 169
| 0.662909
|
InstantBusinessNetwork
|
adccb8a5662a5de17434c419c0a66ffe388f5e52
| 1,012
|
cc
|
C++
|
stl/containers/map/unordered_map.cc
|
curoky/dumbo
|
d0aae7b239a552ff670795ae51c3452c9e28f63d
|
[
"Apache-2.0"
] | null | null | null |
stl/containers/map/unordered_map.cc
|
curoky/dumbo
|
d0aae7b239a552ff670795ae51c3452c9e28f63d
|
[
"Apache-2.0"
] | null | null | null |
stl/containers/map/unordered_map.cc
|
curoky/dumbo
|
d0aae7b239a552ff670795ae51c3452c9e28f63d
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright 2019 curoky(cccuroky@gmail.com).
*
* 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 <catch2/catch.hpp> // for AssertionHandler, operator""_catch_sr, SourceLineInfo, StringRef, REQUIRE, TEST_CASE
#include <algorithm> // for max
#include <unordered_map> // for unordered_map, pair
TEST_CASE("[UnorderedMap]: insert when exists") {
std::unordered_map<int, int> mp = {{1, 1}};
REQUIRE(mp.emplace(1, 2).second == false);
REQUIRE(mp.emplace(2, 2).second == true);
}
| 37.481481
| 120
| 0.720356
|
curoky
|
add35b5bbe2b0962674ac0b421017a86f1f02314
| 8,813
|
cc
|
C++
|
common/cpp/src/google_smart_card_common/pp_var_utils/extraction.cc
|
swapnil119/chromeos_smart_card_connector
|
c01ec7e9aad61ede90f1eeaf8554540ede988d2d
|
[
"Apache-2.0"
] | 1
|
2021-10-18T03:23:18.000Z
|
2021-10-18T03:23:18.000Z
|
common/cpp/src/google_smart_card_common/pp_var_utils/extraction.cc
|
AdrianaDJ/chromeos_smart_card_connector
|
63bcbc1ce293779efbe99a63edfbc824d96719fc
|
[
"Apache-2.0"
] | 1
|
2021-02-23T22:37:22.000Z
|
2021-02-23T22:37:22.000Z
|
common/cpp/src/google_smart_card_common/pp_var_utils/extraction.cc
|
AdrianaDJ/chromeos_smart_card_connector
|
63bcbc1ce293779efbe99a63edfbc824d96719fc
|
[
"Apache-2.0"
] | 1
|
2021-04-15T17:09:55.000Z
|
2021-04-15T17:09:55.000Z
|
// Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <google_smart_card_common/pp_var_utils/extraction.h>
#include <cstring>
#include <google_smart_card_common/numeric_conversions.h>
namespace google_smart_card {
namespace {
constexpr char kErrorWrongType[] =
"Expected a value of type \"%s\", instead got: %s";
template <typename T>
bool VarAsInteger(const pp::Var& var,
const char* type_name,
T* result,
std::string* error_message) {
int64_t integer;
if (var.is_int()) {
integer = var.AsInt();
} else if (var.is_double()) {
if (!CastDoubleToInt64(var.AsDouble(), &integer, error_message))
return false;
} else {
*error_message = FormatPrintfTemplate(kErrorWrongType, kIntegerJsTypeTitle,
DebugDumpVar(var).c_str());
return false;
}
return CastInteger(integer, type_name, result, error_message);
}
} // namespace
bool VarAs(const pp::Var& var, int8_t* result, std::string* error_message) {
return VarAsInteger(var, "int8_t", result, error_message);
}
bool VarAs(const pp::Var& var, uint8_t* result, std::string* error_message) {
return VarAsInteger(var, "uint8_t", result, error_message);
}
bool VarAs(const pp::Var& var, int16_t* result, std::string* error_message) {
return VarAsInteger(var, "int16_t", result, error_message);
}
bool VarAs(const pp::Var& var, uint16_t* result, std::string* error_message) {
return VarAsInteger(var, "uint16_t", result, error_message);
}
bool VarAs(const pp::Var& var, int32_t* result, std::string* error_message) {
return VarAsInteger(var, "int32_t", result, error_message);
}
bool VarAs(const pp::Var& var, uint32_t* result, std::string* error_message) {
return VarAsInteger(var, "uint32_t", result, error_message);
}
bool VarAs(const pp::Var& var, int64_t* result, std::string* error_message) {
return VarAsInteger(var, "int64_t", result, error_message);
}
bool VarAs(const pp::Var& var, uint64_t* result, std::string* error_message) {
return VarAsInteger(var, "uint64_t", result, error_message);
}
bool VarAs(const pp::Var& var, long* result, std::string* error_message) {
return VarAsInteger(var, "long", result, error_message);
}
bool VarAs(const pp::Var& var,
unsigned long* result,
std::string* error_message) {
return VarAsInteger(var, "unsigned long", result, error_message);
}
bool VarAs(const pp::Var& var, float* result, std::string* error_message) {
double double_value;
if (!VarAs(var, &double_value, error_message))
return false;
*result = static_cast<float>(double_value);
return true;
}
bool VarAs(const pp::Var& var, double* result, std::string* error_message) {
if (!var.is_number()) {
*error_message = FormatPrintfTemplate(kErrorWrongType, kIntegerJsTypeTitle,
DebugDumpVar(var).c_str());
return false;
}
*result = var.AsDouble();
return true;
}
bool VarAs(const pp::Var& var, bool* result, std::string* error_message) {
if (!var.is_bool()) {
*error_message = FormatPrintfTemplate(kErrorWrongType, kBooleanJsTypeTitle,
DebugDumpVar(var).c_str());
return false;
}
*result = var.AsBool();
return true;
}
bool VarAs(const pp::Var& var,
std::string* result,
std::string* error_message) {
if (!var.is_string()) {
*error_message = FormatPrintfTemplate(kErrorWrongType, kStringJsTypeTitle,
DebugDumpVar(var).c_str());
return false;
}
*result = var.AsString();
return true;
}
bool VarAs(const pp::Var& var,
pp::Var* result,
std::string* /*error_message*/) {
*result = var;
return true;
}
bool VarAs(const pp::Var& var,
pp::VarArray* result,
std::string* error_message) {
if (!var.is_array()) {
*error_message = FormatPrintfTemplate(kErrorWrongType, kArrayJsTypeTitle,
DebugDumpVar(var).c_str());
return false;
}
*result = pp::VarArray(var);
return true;
}
bool VarAs(const pp::Var& var,
pp::VarArrayBuffer* result,
std::string* error_message) {
if (!var.is_array_buffer()) {
*error_message = FormatPrintfTemplate(
kErrorWrongType, kArrayBufferJsTypeTitle, DebugDumpVar(var).c_str());
return false;
}
*result = pp::VarArrayBuffer(var);
return true;
}
bool VarAs(const pp::Var& var,
pp::VarDictionary* result,
std::string* error_message) {
if (!var.is_dictionary()) {
*error_message = FormatPrintfTemplate(
kErrorWrongType, kDictionaryJsTypeTitle, DebugDumpVar(var).c_str());
return false;
}
*result = pp::VarDictionary(var);
return true;
}
bool VarAs(const pp::Var& var,
pp::Var::Null* /*result*/,
std::string* error_message) {
if (!var.is_null()) {
*error_message = FormatPrintfTemplate(kErrorWrongType, kNullJsTypeTitle,
DebugDumpVar(var).c_str());
return false;
}
return true;
}
namespace internal {
std::vector<uint8_t> GetVarArrayBufferData(pp::VarArrayBuffer var) {
std::vector<uint8_t> result(var.ByteLength());
if (!result.empty()) {
std::memcpy(&result[0], var.Map(), result.size());
var.Unmap();
}
return result;
}
} // namespace internal
int GetVarDictSize(const pp::VarDictionary& var) {
return GetVarArraySize(var.GetKeys());
}
int GetVarArraySize(const pp::VarArray& var) {
return static_cast<int>(var.GetLength());
}
bool GetVarDictValue(const pp::VarDictionary& var,
const std::string& key,
pp::Var* result,
std::string* error_message) {
if (!var.HasKey(key)) {
*error_message =
FormatPrintfTemplate("The dictionary has no key \"%s\"", key.c_str());
return false;
}
*result = var.Get(key);
return true;
}
pp::Var GetVarDictValue(const pp::VarDictionary& var, const std::string& key) {
pp::Var result;
std::string error_message;
if (!GetVarDictValue(var, key, &result, &error_message))
GOOGLE_SMART_CARD_LOG_FATAL << error_message;
return result;
}
VarDictValuesExtractor::VarDictValuesExtractor(const pp::VarDictionary& var)
: var_(var) {
const std::vector<std::string> keys =
VarAs<std::vector<std::string>>(var_.GetKeys());
not_requested_keys_.insert(keys.begin(), keys.end());
}
bool VarDictValuesExtractor::GetSuccess(std::string* error_message) const {
if (failed_) {
*error_message = error_message_;
return false;
}
return true;
}
bool VarDictValuesExtractor::GetSuccessWithNoExtraKeysAllowed(
std::string* error_message) const {
if (!GetSuccess(error_message))
return false;
if (!not_requested_keys_.empty()) {
std::string unexpected_keys_dump;
for (const std::string& key : not_requested_keys_) {
if (!unexpected_keys_dump.empty())
unexpected_keys_dump += ", ";
unexpected_keys_dump += '"' + key + '"';
}
*error_message =
FormatPrintfTemplate("The dictionary contains unexpected keys: %s",
unexpected_keys_dump.c_str());
return false;
}
return true;
}
void VarDictValuesExtractor::CheckSuccess() const {
std::string error_message;
if (!GetSuccess(&error_message))
GOOGLE_SMART_CARD_LOG_FATAL << error_message;
}
void VarDictValuesExtractor::CheckSuccessWithNoExtraKeysAllowed() const {
std::string error_message;
if (!GetSuccessWithNoExtraKeysAllowed(&error_message))
GOOGLE_SMART_CARD_LOG_FATAL << error_message;
}
void VarDictValuesExtractor::AddRequestedKey(const std::string& key) {
not_requested_keys_.erase(key);
}
void VarDictValuesExtractor::ProcessFailedExtraction(
const std::string& key,
const std::string& extraction_error_message) {
if (failed_) {
// We could concatenate all occurred errors, but storing of the first error
// only should be enough.
return;
}
error_message_ = FormatPrintfTemplate(
"Failed to extract the dictionary value with key \"%s\": %s", key.c_str(),
extraction_error_message.c_str());
failed_ = true;
}
} // namespace google_smart_card
| 30.181507
| 80
| 0.666969
|
swapnil119
|
add80978f49c3218f7ec8dd60422cf62bb0cd10f
| 51,310
|
cpp
|
C++
|
source/TrickHLA/Interaction.cpp
|
jiajlin/TrickHLA
|
ae704b97049579e997593ae6d8dd016010b8fa1e
|
[
"NASA-1.3"
] | null | null | null |
source/TrickHLA/Interaction.cpp
|
jiajlin/TrickHLA
|
ae704b97049579e997593ae6d8dd016010b8fa1e
|
[
"NASA-1.3"
] | null | null | null |
source/TrickHLA/Interaction.cpp
|
jiajlin/TrickHLA
|
ae704b97049579e997593ae6d8dd016010b8fa1e
|
[
"NASA-1.3"
] | null | null | null |
/*!
@file TrickHLA/Interaction.cpp
@ingroup TrickHLA
@brief This class represents an HLA Interaction that is managed by Trick.
@copyright Copyright 2019 United States Government as represented by the
Administrator of the National Aeronautics and Space Administration.
No copyright is claimed in the United States under Title 17, U.S. Code.
All Other Rights Reserved.
\par<b>Responsible Organization</b>
Simulation and Graphics Branch, Mail Code ER7\n
Software, Robotics & Simulation Division\n
NASA, Johnson Space Center\n
2101 NASA Parkway, Houston, TX 77058
@tldh
@trick_link_dependency{DebugHandler.cpp}
@trick_link_dependency{Federate.cpp}
@trick_link_dependency{Int64Interval.cpp}
@trick_link_dependency{Int64Time.cpp}
@trick_link_dependency{Interaction.cpp}
@trick_link_dependency{InteractionHandler.cpp}
@trick_link_dependency{InteractionItem.cpp}
@trick_link_dependency{Manager.cpp}
@trick_link_dependency{MutexLock.cpp}
@trick_link_dependency{MutexProtection.cpp}
@trick_link_dependency{Parameter.cpp}
@trick_link_dependency{ParameterItem.cpp}
@trick_link_dependency{Types.cpp}
@revs_title
@revs_begin
@rev_entry{Dan Dexter, L3 Titan Group, DSES, Aug 2006, --, Initial implementation.}
@rev_entry{Dan Dexter, NASA ER7, TrickHLA, March 2019, --, Version 2 origin.}
@rev_entry{Edwin Z. Crues, NASA ER7, TrickHLA, March 2019, --, Version 3 rewrite.}
@revs_end
*/
// System include files.
#include <cstdlib>
#include <iostream>
#include <sstream>
// Trick include files.
#include "trick/exec_proto.h"
#include "trick/message_proto.h"
// TrickHLA include files.
#include "TrickHLA/Constants.hh"
#include "TrickHLA/DebugHandler.hh"
#include "TrickHLA/Federate.hh"
#include "TrickHLA/Int64Interval.hh"
#include "TrickHLA/Int64Time.hh"
#include "TrickHLA/Interaction.hh"
#include "TrickHLA/InteractionHandler.hh"
#include "TrickHLA/InteractionItem.hh"
#include "TrickHLA/Manager.hh"
#include "TrickHLA/MutexLock.hh"
#include "TrickHLA/MutexProtection.hh"
#include "TrickHLA/Parameter.hh"
#include "TrickHLA/ParameterItem.hh"
#include "TrickHLA/StringUtilities.hh"
#include "TrickHLA/Types.hh"
// C++11 deprecated dynamic exception specifications for a function so we need
// to silence the warnings coming from the IEEE 1516 declared functions.
// This should work for both GCC and Clang.
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated"
// HLA include files.
#include RTI1516_HEADER
#pragma GCC diagnostic pop
using namespace std;
using namespace RTI1516_NAMESPACE;
using namespace TrickHLA;
/*!
* @job_class{initialization}
*/
Interaction::Interaction()
: FOM_name( NULL ),
publish( false ),
subscribe( false ),
preferred_order( TRANSPORT_SPECIFIED_IN_FOM ),
param_count( 0 ),
parameters( NULL ),
handler( NULL ),
mutex(),
changed( false ),
received_as_TSO( false ),
time( 0.0 ),
manager( NULL ),
user_supplied_tag_size( 0 ),
user_supplied_tag_capacity( 0 ),
user_supplied_tag( NULL )
{
return;
}
/*!
* @job_class{shutdown}
*/
Interaction::~Interaction()
{
// Remove this interaction from the federation execution.
remove();
if ( user_supplied_tag != NULL ) {
if ( TMM_is_alloced( (char *)user_supplied_tag ) ) {
TMM_delete_var_a( user_supplied_tag );
}
user_supplied_tag = NULL;
user_supplied_tag_size = 0;
}
// Make sure we destroy the mutex.
(void)mutex.unlock();
}
/*!
* @job_class{initialization}
*/
void Interaction::initialize(
Manager *trickhla_mgr )
{
TRICKHLA_VALIDATE_FPU_CONTROL_WORD;
if ( trickhla_mgr == NULL ) {
send_hs( stderr, "Interaction::initialize():%d Unexpected NULL Trick-HLA-Manager!%c",
__LINE__, THLA_NEWLINE );
exec_terminate( __FILE__, "Interaction::initialize() Unexpected NULL Trick-HLA-Manager!" );
return;
}
this->manager = trickhla_mgr;
// Make sure we have a valid object FOM name.
if ( ( FOM_name == NULL ) || ( *FOM_name == '\0' ) ) {
ostringstream errmsg;
errmsg << "Interaction::initialize():" << __LINE__
<< " Missing Interaction FOM Name."
<< " Please check your input or modified-data files to make sure the"
<< " Interaction FOM name is correctly specified." << THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
exec_terminate( __FILE__, (char *)errmsg.str().c_str() );
}
// TODO: Get the preferred order by parsing the FOM.
//
// Do a quick bounds check on the 'preferred_order' value.
if ( ( preferred_order < TRANSPORT_FIRST_VALUE ) || ( preferred_order > TRANSPORT_LAST_VALUE ) ) {
ostringstream errmsg;
errmsg << "Interaction::initialize():" << __LINE__
<< " For Interaction '"
<< FOM_name << "', the 'preferred_order' is not valid and must be one"
<< " of TRANSPORT_SPECIFIED_IN_FOM, TRANSPORT_TIMESTAMP_ORDER or"
<< " TRANSPORT_RECEIVE_ORDER. Please check your input or modified-data"
<< " files to make sure the 'preferred_order' is correctly specified."
<< THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
exec_terminate( __FILE__, (char *)errmsg.str().c_str() );
}
// If we have an parameter count but no parameters then let the user know.
if ( ( param_count > 0 ) && ( parameters == NULL ) ) {
ostringstream errmsg;
errmsg << "Interaction::initialize():" << __LINE__
<< " For Interaction '"
<< FOM_name << "', the 'param_count' is " << param_count
<< " but no 'parameters' are specified. Please check your input or"
<< " modified-data files to make sure the Interaction Parameters are"
<< " correctly specified." << THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
exec_terminate( __FILE__, (char *)errmsg.str().c_str() );
}
// If we have parameters but the parameter-count is invalid then let
// the user know.
if ( ( param_count <= 0 ) && ( parameters != NULL ) ) {
ostringstream errmsg;
errmsg << "Interaction::initialize():" << __LINE__
<< " For Interaction '"
<< FOM_name << "', the 'param_count' is " << param_count
<< " but 'parameters' have been specified. Please check your input"
<< " or modified-data files to make sure the Interaction Parameters"
<< " are correctly specified." << THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
exec_terminate( __FILE__, (char *)errmsg.str().c_str() );
}
// Reset the TrickHLA Parameters count if it is negative or if there
// are no attributes.
if ( ( param_count < 0 ) || ( parameters == NULL ) ) {
param_count = 0;
}
// We must have an interaction handler specified, otherwise we can not
// process the interaction.
if ( handler == NULL ) {
ostringstream errmsg;
errmsg << "Interaction::initialize():" << __LINE__
<< " An Interaction-Handler for"
<< " 'handler' was not specified for the '" << FOM_name << "'"
<< " interaction. Please check your input or modified-data files to"
<< " make sure an Interaction-Handler is correctly specified."
<< THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
exec_terminate( __FILE__, (char *)errmsg.str().c_str() );
}
// Initialize the Interaction-Handler.
handler->initialize_callback( this );
TRICKHLA_VALIDATE_FPU_CONTROL_WORD;
}
void Interaction::set_user_supplied_tag(
unsigned char *tag,
size_t tag_size )
{
if ( tag_size > user_supplied_tag_capacity ) {
user_supplied_tag_capacity = tag_size;
if ( user_supplied_tag == NULL ) {
user_supplied_tag = (unsigned char *)TMM_declare_var_1d( "char", (int)user_supplied_tag_capacity );
} else {
user_supplied_tag = (unsigned char *)TMM_resize_array_1d_a( user_supplied_tag, (int)user_supplied_tag_capacity );
}
}
user_supplied_tag_size = tag_size;
if ( tag != NULL ) {
memcpy( user_supplied_tag, tag, user_supplied_tag_size );
} else {
memset( user_supplied_tag, 0, user_supplied_tag_size );
}
}
/*!
* @details Called from the virtual destructor.
* @job_class{shutdown}
*/
void Interaction::remove() // RETURN: -- None.
{
// Only remove the Interaction if the manager has not been shutdown.
if ( is_shutdown_called() ) {
// Get the RTI-Ambassador and check for NULL.
RTIambassador *rti_amb = get_RTI_ambassador();
if ( rti_amb != NULL ) {
if ( is_publish() ) {
// Macro to save the FPU Control Word register value.
TRICKHLA_SAVE_FPU_CONTROL_WORD;
// Un-publish the Interaction.
try {
if ( DebugHandler::show( DEBUG_LEVEL_2_TRACE, DEBUG_SOURCE_INTERACTION ) ) {
send_hs( stdout, "Interaction::remove():%d Unpublish Interaction '%s'.%c",
__LINE__, get_FOM_name(), THLA_NEWLINE );
}
rti_amb->unpublishInteractionClass( get_class_handle() );
} catch ( RTI1516_EXCEPTION &e ) {
string rti_err_msg;
StringUtilities::to_string( rti_err_msg, e.what() );
send_hs( stderr, "Interaction::remove():%d Unpublish Interaction '%s' exception '%s'%c",
__LINE__, get_FOM_name(), rti_err_msg.c_str(), THLA_NEWLINE );
}
// Macro to restore the saved FPU Control Word register value.
TRICKHLA_RESTORE_FPU_CONTROL_WORD;
TRICKHLA_VALIDATE_FPU_CONTROL_WORD;
}
// Un-subscribe from the Interaction
unsubscribe_from_interaction();
}
}
}
void Interaction::setup_preferred_order_with_RTI()
{
// Just return if the user wants to use the default preferred order
// specified in the FOM. Return if the interaction is not published since
// we can only change the preferred order for publish interactions.
if ( ( preferred_order == TRANSPORT_SPECIFIED_IN_FOM ) || !is_publish() ) {
return;
}
RTIambassador *rti_amb = get_RTI_ambassador();
if ( rti_amb == NULL ) {
send_hs( stderr, "Interaction::setup_preferred_order_with_RTI():%d Unexpected NULL RTIambassador.%c",
__LINE__, THLA_NEWLINE );
return;
}
if ( DebugHandler::show( DEBUG_LEVEL_2_TRACE, DEBUG_SOURCE_INTERACTION ) ) {
send_hs( stdout, "Interaction::setup_preferred_order_with_RTI():%d \
Published Interaction '%s' Preferred-Order:%s%c",
__LINE__, get_FOM_name(),
( preferred_order == TRANSPORT_TIMESTAMP_ORDER ? "TIMESTAMP" : "RECEIVE" ),
THLA_NEWLINE );
}
// Macro to save the FPU Control Word register value.
TRICKHLA_SAVE_FPU_CONTROL_WORD;
// Change the preferred order.
try {
switch ( preferred_order ) {
case TRANSPORT_RECEIVE_ORDER: {
rti_amb->changeInteractionOrderType( this->class_handle,
RTI1516_NAMESPACE::RECEIVE );
break;
}
case TRANSPORT_TIMESTAMP_ORDER:
default: {
rti_amb->changeInteractionOrderType( this->class_handle,
RTI1516_NAMESPACE::TIMESTAMP );
break;
}
}
} catch ( RTI1516_NAMESPACE::InteractionClassNotPublished &e ) {
// Macro to restore the saved FPU Control Word register value.
TRICKHLA_RESTORE_FPU_CONTROL_WORD;
TRICKHLA_VALIDATE_FPU_CONTROL_WORD;
ostringstream errmsg;
errmsg << "Interaction::setup_preferred_order_with_RTI():" << __LINE__
<< " EXCEPTION: InteractionClassNotPublished for Interaction '"
<< get_FOM_name() << "'" << THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
exec_terminate( __FILE__, (char *)errmsg.str().c_str() );
} catch ( RTI1516_NAMESPACE::FederateNotExecutionMember &e ) {
// Macro to restore the saved FPU Control Word register value.
TRICKHLA_RESTORE_FPU_CONTROL_WORD;
TRICKHLA_VALIDATE_FPU_CONTROL_WORD;
ostringstream errmsg;
errmsg << "Interaction::setup_preferred_order_with_RTI():" << __LINE__
<< " EXCEPTION: FederateNotExecutionMember for Interaction '"
<< get_FOM_name() << "'" << THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
exec_terminate( __FILE__, (char *)errmsg.str().c_str() );
} catch ( RTI1516_NAMESPACE::InteractionClassNotDefined &e ) {
// Macro to restore the saved FPU Control Word register value.
TRICKHLA_RESTORE_FPU_CONTROL_WORD;
TRICKHLA_VALIDATE_FPU_CONTROL_WORD;
ostringstream errmsg;
errmsg << "Interaction::setup_preferred_order_with_RTI():" << __LINE__
<< " EXCEPTION: InteractionClassNotDefined for Interaction '"
<< get_FOM_name() << "'" << THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
exec_terminate( __FILE__, (char *)errmsg.str().c_str() );
} catch ( RTI1516_NAMESPACE::RestoreInProgress &e ) {
// Macro to restore the saved FPU Control Word register value.
TRICKHLA_RESTORE_FPU_CONTROL_WORD;
TRICKHLA_VALIDATE_FPU_CONTROL_WORD;
ostringstream errmsg;
errmsg << "Interaction::setup_preferred_order_with_RTI():" << __LINE__
<< " EXCEPTION: RestoreInProgress for Interaction '"
<< get_FOM_name() << "'" << THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
exec_terminate( __FILE__, (char *)errmsg.str().c_str() );
} catch ( RTI1516_NAMESPACE::RTIinternalError &e ) {
// Macro to restore the saved FPU Control Word register value.
TRICKHLA_RESTORE_FPU_CONTROL_WORD;
TRICKHLA_VALIDATE_FPU_CONTROL_WORD;
ostringstream errmsg;
errmsg << "Interaction::setup_preferred_order_with_RTI():" << __LINE__
<< " EXCEPTION: RTIinternalError for Interaction '"
<< get_FOM_name() << "'" << THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
exec_terminate( __FILE__, (char *)errmsg.str().c_str() );
} catch ( RTI1516_NAMESPACE::SaveInProgress &e ) {
// Macro to restore the saved FPU Control Word register value.
TRICKHLA_RESTORE_FPU_CONTROL_WORD;
TRICKHLA_VALIDATE_FPU_CONTROL_WORD;
ostringstream errmsg;
errmsg << "Interaction::setup_preferred_order_with_RTI():" << __LINE__
<< " EXCEPTION: SaveInProgress for Interaction '"
<< get_FOM_name() << "'" << THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
exec_terminate( __FILE__, (char *)errmsg.str().c_str() );
} catch ( RTI1516_NAMESPACE::NotConnected &e ) {
// Macro to restore the saved FPU Control Word register value.
TRICKHLA_RESTORE_FPU_CONTROL_WORD;
TRICKHLA_VALIDATE_FPU_CONTROL_WORD;
ostringstream errmsg;
errmsg << "Interaction::setup_preferred_order_with_RTI():" << __LINE__
<< " EXCEPTION: NotConnected for Interaction '"
<< get_FOM_name() << "'" << THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
exec_terminate( __FILE__, (char *)errmsg.str().c_str() );
} catch ( RTI1516_EXCEPTION &e ) {
// Macro to restore the saved FPU Control Word register value.
TRICKHLA_RESTORE_FPU_CONTROL_WORD;
TRICKHLA_VALIDATE_FPU_CONTROL_WORD;
string rti_err_msg;
StringUtilities::to_string( rti_err_msg, e.what() );
ostringstream errmsg;
errmsg << "Interaction::setup_preferred_order_with_RTI():" << __LINE__
<< " RTI1516_EXCEPTION for Interaction '" << get_FOM_name()
<< "' with error '" << rti_err_msg << "'" << THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
exec_terminate( __FILE__, (char *)errmsg.str().c_str() );
}
// Macro to restore the saved FPU Control Word register value.
TRICKHLA_RESTORE_FPU_CONTROL_WORD;
TRICKHLA_VALIDATE_FPU_CONTROL_WORD;
}
void Interaction::publish_interaction()
{
// The RTI must be ready and the flag must be set to publish.
if ( !is_publish() ) {
return;
}
RTIambassador *rti_amb = get_RTI_ambassador();
if ( rti_amb == NULL ) {
send_hs( stderr, "Interaction::publish_interaction():%d Unexpected NULL RTIambassador.%c",
__LINE__, THLA_NEWLINE );
return;
}
if ( DebugHandler::show( DEBUG_LEVEL_2_TRACE, DEBUG_SOURCE_INTERACTION ) ) {
send_hs( stdout, "Interaction::publish_interaction():%d Interaction '%s'.%c",
__LINE__, get_FOM_name(), THLA_NEWLINE );
}
// Macro to save the FPU Control Word register value.
TRICKHLA_SAVE_FPU_CONTROL_WORD;
// Publish the Interaction
try {
rti_amb->publishInteractionClass( this->class_handle );
} catch ( RTI1516_NAMESPACE::FederateNotExecutionMember &e ) {
// Macro to restore the saved FPU Control Word register value.
TRICKHLA_RESTORE_FPU_CONTROL_WORD;
TRICKHLA_VALIDATE_FPU_CONTROL_WORD;
ostringstream errmsg;
errmsg << "Interaction::publish_interaction():" << __LINE__
<< " EXCEPTION: FederateNotExecutionMember for Interaction '"
<< get_FOM_name() << "'" << THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
exec_terminate( __FILE__, (char *)errmsg.str().c_str() );
} catch ( RTI1516_NAMESPACE::InteractionClassNotDefined &e ) {
// Macro to restore the saved FPU Control Word register value.
TRICKHLA_RESTORE_FPU_CONTROL_WORD;
TRICKHLA_VALIDATE_FPU_CONTROL_WORD;
ostringstream errmsg;
errmsg << "Interaction::publish_interaction():" << __LINE__
<< " EXCEPTION: InteractionClassNotDefined for Interaction '"
<< get_FOM_name() << "'" << THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
exec_terminate( __FILE__, (char *)errmsg.str().c_str() );
} catch ( RTI1516_NAMESPACE::RestoreInProgress &e ) {
// Macro to restore the saved FPU Control Word register value.
TRICKHLA_RESTORE_FPU_CONTROL_WORD;
TRICKHLA_VALIDATE_FPU_CONTROL_WORD;
ostringstream errmsg;
errmsg << "Interaction::publish_interaction():" << __LINE__
<< " EXCEPTION: RestoreInProgress for Interaction '"
<< get_FOM_name() << "'" << THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
exec_terminate( __FILE__, (char *)errmsg.str().c_str() );
} catch ( RTI1516_NAMESPACE::RTIinternalError &e ) {
// Macro to restore the saved FPU Control Word register value.
TRICKHLA_RESTORE_FPU_CONTROL_WORD;
TRICKHLA_VALIDATE_FPU_CONTROL_WORD;
ostringstream errmsg;
errmsg << "Interaction::publish_interaction():" << __LINE__
<< " EXCEPTION: RTIinternalError for Interaction '"
<< get_FOM_name() << "'" << THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
exec_terminate( __FILE__, (char *)errmsg.str().c_str() );
} catch ( RTI1516_NAMESPACE::SaveInProgress &e ) {
// Macro to restore the saved FPU Control Word register value.
TRICKHLA_RESTORE_FPU_CONTROL_WORD;
TRICKHLA_VALIDATE_FPU_CONTROL_WORD;
ostringstream errmsg;
errmsg << "Interaction::publish_interaction():" << __LINE__
<< " EXCEPTION: SaveInProgress for Interaction '"
<< get_FOM_name() << "'" << THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
exec_terminate( __FILE__, (char *)errmsg.str().c_str() );
} catch ( RTI1516_NAMESPACE::NotConnected &e ) {
// Macro to restore the saved FPU Control Word register value.
TRICKHLA_RESTORE_FPU_CONTROL_WORD;
TRICKHLA_VALIDATE_FPU_CONTROL_WORD;
ostringstream errmsg;
errmsg << "Interaction::publish_interaction():" << __LINE__
<< " EXCEPTION: NotConnected for Interaction '"
<< get_FOM_name() << "'" << THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
exec_terminate( __FILE__, (char *)errmsg.str().c_str() );
} catch ( RTI1516_EXCEPTION &e ) {
// Macro to restore the saved FPU Control Word register value.
TRICKHLA_RESTORE_FPU_CONTROL_WORD;
TRICKHLA_VALIDATE_FPU_CONTROL_WORD;
string rti_err_msg;
StringUtilities::to_string( rti_err_msg, e.what() );
ostringstream errmsg;
errmsg << "Interaction::publish_interaction():" << __LINE__
<< " RTI1516_EXCEPTION for Interaction '" << get_FOM_name()
<< "' with error '" << rti_err_msg << "'" << THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
exec_terminate( __FILE__, (char *)errmsg.str().c_str() );
}
// Macro to restore the saved FPU Control Word register value.
TRICKHLA_RESTORE_FPU_CONTROL_WORD;
TRICKHLA_VALIDATE_FPU_CONTROL_WORD;
}
void Interaction::unpublish_interaction()
{
RTIambassador *rti_amb = get_RTI_ambassador();
if ( rti_amb == NULL ) {
send_hs( stderr, "Interaction::unpublish_interaction():%d Unexpected NULL RTIambassador.%c",
__LINE__, THLA_NEWLINE );
return;
}
// Subscribe to the interaction.
if ( is_publish() ) {
if ( DebugHandler::show( DEBUG_LEVEL_2_TRACE, DEBUG_SOURCE_INTERACTION ) ) {
send_hs( stdout, "Interaction::unpublish_interaction():%d Interaction '%s'%c",
__LINE__, get_FOM_name(), THLA_NEWLINE );
}
// Macro to save the FPU Control Word register value.
TRICKHLA_SAVE_FPU_CONTROL_WORD;
try {
rti_amb->unpublishInteractionClass( this->class_handle );
} catch ( RTI1516_NAMESPACE::InteractionClassNotDefined &e ) {
// Macro to restore the saved FPU Control Word register value.
TRICKHLA_RESTORE_FPU_CONTROL_WORD;
TRICKHLA_VALIDATE_FPU_CONTROL_WORD;
ostringstream errmsg;
errmsg << "Interaction::unpublish_interaction():" << __LINE__
<< " EXCEPTION: InteractionClassNotDefined for Interaction '"
<< get_FOM_name() << "'" << THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
exec_terminate( __FILE__, (char *)errmsg.str().c_str() );
} catch ( RTI1516_NAMESPACE::FederateNotExecutionMember &e ) {
// Macro to restore the saved FPU Control Word register value.
TRICKHLA_RESTORE_FPU_CONTROL_WORD;
TRICKHLA_VALIDATE_FPU_CONTROL_WORD;
ostringstream errmsg;
errmsg << "Interaction::unpublish_interaction():" << __LINE__
<< " EXCEPTION: FederateNotExecutionMember for Interaction '"
<< get_FOM_name() << "'" << THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
exec_terminate( __FILE__, (char *)errmsg.str().c_str() );
} catch ( RTI1516_NAMESPACE::SaveInProgress &e ) {
// Macro to restore the saved FPU Control Word register value.
TRICKHLA_RESTORE_FPU_CONTROL_WORD;
TRICKHLA_VALIDATE_FPU_CONTROL_WORD;
ostringstream errmsg;
errmsg << "Interaction::unpublish_interaction():" << __LINE__
<< " EXCEPTION: SaveInProgress for Interaction '"
<< get_FOM_name() << "'" << THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
exec_terminate( __FILE__, (char *)errmsg.str().c_str() );
} catch ( RTI1516_NAMESPACE::RestoreInProgress &e ) {
// Macro to restore the saved FPU Control Word register value.
TRICKHLA_RESTORE_FPU_CONTROL_WORD;
TRICKHLA_VALIDATE_FPU_CONTROL_WORD;
ostringstream errmsg;
errmsg << "Interaction::unpublish_interaction():" << __LINE__
<< " EXCEPTION: RestoreInProgress for Interaction '"
<< get_FOM_name() << "'" << THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
exec_terminate( __FILE__, (char *)errmsg.str().c_str() );
} catch ( RTI1516_NAMESPACE::NotConnected &e ) {
// Macro to restore the saved FPU Control Word register value.
TRICKHLA_RESTORE_FPU_CONTROL_WORD;
TRICKHLA_VALIDATE_FPU_CONTROL_WORD;
ostringstream errmsg;
errmsg << "Interaction::unpublish_interaction():" << __LINE__
<< " EXCEPTION: NotConnected for Interaction '"
<< get_FOM_name() << "'" << THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
exec_terminate( __FILE__, (char *)errmsg.str().c_str() );
} catch ( RTI1516_NAMESPACE::RTIinternalError &e ) {
// Macro to restore the saved FPU Control Word register value.
TRICKHLA_RESTORE_FPU_CONTROL_WORD;
TRICKHLA_VALIDATE_FPU_CONTROL_WORD;
ostringstream errmsg;
errmsg << "Interaction::unpublish_interaction():" << __LINE__
<< " EXCEPTION: RTIinternalError for Interaction '"
<< get_FOM_name() << "'" << THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
exec_terminate( __FILE__, (char *)errmsg.str().c_str() );
} catch ( RTI1516_EXCEPTION &e ) {
// Macro to restore the saved FPU Control Word register value.
TRICKHLA_RESTORE_FPU_CONTROL_WORD;
TRICKHLA_VALIDATE_FPU_CONTROL_WORD;
string rti_err_msg;
StringUtilities::to_string( rti_err_msg, e.what() );
ostringstream errmsg;
errmsg << "Interaction::unpublish_interaction():" << __LINE__
<< " RTI1516_EXCEPTION for Interaction '" << get_FOM_name()
<< "' with error '" << rti_err_msg << "'" << THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
exec_terminate( __FILE__, (char *)errmsg.str().c_str() );
}
// Macro to restore the saved FPU Control Word register value.
TRICKHLA_RESTORE_FPU_CONTROL_WORD;
TRICKHLA_VALIDATE_FPU_CONTROL_WORD;
}
}
void Interaction::subscribe_to_interaction()
{
// Get the RTI-Ambassador.
RTIambassador *rti_amb = get_RTI_ambassador();
if ( rti_amb == NULL ) {
send_hs( stderr, "Interaction::subscribe_to_interaction():%d Unexpected NULL RTIambassador.%c",
__LINE__, THLA_NEWLINE );
return;
}
// Subscribe to the interaction.
if ( is_subscribe() ) {
if ( DebugHandler::show( DEBUG_LEVEL_2_TRACE, DEBUG_SOURCE_INTERACTION ) ) {
send_hs( stdout, "Interaction::subscribe_to_interaction():%d Interaction '%s'%c",
__LINE__, get_FOM_name(), THLA_NEWLINE );
}
// Macro to save the FPU Control Word register value.
TRICKHLA_SAVE_FPU_CONTROL_WORD;
try {
rti_amb->subscribeInteractionClass( this->class_handle, true );
} catch ( RTI1516_NAMESPACE::FederateNotExecutionMember &e ) {
// Macro to restore the saved FPU Control Word register value.
TRICKHLA_RESTORE_FPU_CONTROL_WORD;
TRICKHLA_VALIDATE_FPU_CONTROL_WORD;
ostringstream errmsg;
errmsg << "Interaction::subscribe_to_interaction():" << __LINE__
<< " EXCEPTION: FederateNotExecutionMember for Interaction '"
<< get_FOM_name() << "'" << THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
exec_terminate( __FILE__, (char *)errmsg.str().c_str() );
} catch ( RTI1516_NAMESPACE::FederateServiceInvocationsAreBeingReportedViaMOM &e ) {
// Macro to restore the saved FPU Control Word register value.
TRICKHLA_RESTORE_FPU_CONTROL_WORD;
TRICKHLA_VALIDATE_FPU_CONTROL_WORD;
ostringstream errmsg;
errmsg << "Interaction::subscribe_to_interaction():" << __LINE__
<< " EXCEPTION: FederateServiceInvocationsAreBeingReportedViaMOM for Interaction '"
<< get_FOM_name() << "'" << THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
exec_terminate( __FILE__, (char *)errmsg.str().c_str() );
} catch ( RTI1516_NAMESPACE::InteractionClassNotDefined &e ) {
// Macro to restore the saved FPU Control Word register value.
TRICKHLA_RESTORE_FPU_CONTROL_WORD;
TRICKHLA_VALIDATE_FPU_CONTROL_WORD;
ostringstream errmsg;
errmsg << "Interaction::subscribe_to_interaction():" << __LINE__
<< " EXCEPTION: InteractionClassNotDefined for Interaction '"
<< get_FOM_name() << "'" << THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
exec_terminate( __FILE__, (char *)errmsg.str().c_str() );
} catch ( RTI1516_NAMESPACE::RestoreInProgress &e ) {
// Macro to restore the saved FPU Control Word register value.
TRICKHLA_RESTORE_FPU_CONTROL_WORD;
TRICKHLA_VALIDATE_FPU_CONTROL_WORD;
ostringstream errmsg;
errmsg << "Interaction::subscribe_to_interaction():" << __LINE__
<< " EXCEPTION: RestoreInProgress for Interaction '"
<< get_FOM_name() << "'" << THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
exec_terminate( __FILE__, (char *)errmsg.str().c_str() );
} catch ( RTI1516_NAMESPACE::RTIinternalError &e ) {
// Macro to restore the saved FPU Control Word register value.
TRICKHLA_RESTORE_FPU_CONTROL_WORD;
TRICKHLA_VALIDATE_FPU_CONTROL_WORD;
ostringstream errmsg;
errmsg << "Interaction::subscribe_to_interaction():" << __LINE__
<< " EXCEPTION: RTIinternalError for Interaction '"
<< get_FOM_name() << "'" << THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
exec_terminate( __FILE__, (char *)errmsg.str().c_str() );
} catch ( RTI1516_NAMESPACE::SaveInProgress &e ) {
// Macro to restore the saved FPU Control Word register value.
TRICKHLA_RESTORE_FPU_CONTROL_WORD;
TRICKHLA_VALIDATE_FPU_CONTROL_WORD;
ostringstream errmsg;
errmsg << "Interaction::subscribe_to_interaction():" << __LINE__
<< " EXCEPTION: SaveInProgress for Interaction '"
<< get_FOM_name() << "'" << THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
exec_terminate( __FILE__, (char *)errmsg.str().c_str() );
} catch ( RTI1516_NAMESPACE::NotConnected &e ) {
// Macro to restore the saved FPU Control Word register value.
TRICKHLA_RESTORE_FPU_CONTROL_WORD;
TRICKHLA_VALIDATE_FPU_CONTROL_WORD;
ostringstream errmsg;
errmsg << "Interaction::subscribe_to_interaction():" << __LINE__
<< " EXCEPTION: NotConnected for Interaction '"
<< get_FOM_name() << "'" << THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
exec_terminate( __FILE__, (char *)errmsg.str().c_str() );
} catch ( RTI1516_EXCEPTION &e ) {
// Macro to restore the saved FPU Control Word register value.
TRICKHLA_RESTORE_FPU_CONTROL_WORD;
TRICKHLA_VALIDATE_FPU_CONTROL_WORD;
string rti_err_msg;
StringUtilities::to_string( rti_err_msg, e.what() );
ostringstream errmsg;
errmsg << "Interaction::subscribe_to_interaction():" << __LINE__
<< " RTI1516_EXCEPTION for Interaction '" << get_FOM_name()
<< "' with error '" << rti_err_msg << "'" << THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
exec_terminate( __FILE__, (char *)errmsg.str().c_str() );
}
// Macro to restore the saved FPU Control Word register value.
TRICKHLA_RESTORE_FPU_CONTROL_WORD;
TRICKHLA_VALIDATE_FPU_CONTROL_WORD;
}
}
void Interaction::unsubscribe_from_interaction()
{
// Get the RTI-Ambassador.
RTIambassador *rti_amb = get_RTI_ambassador();
if ( rti_amb == NULL ) {
send_hs( stderr, "Interaction::unsubscribe_from_interaction():%d Unexpected NULL RTIambassador.%c",
__LINE__, THLA_NEWLINE );
return;
}
// Make sure we only unsubscribe an interaction that was subscribed to.
if ( is_subscribe() ) {
if ( DebugHandler::show( DEBUG_LEVEL_2_TRACE, DEBUG_SOURCE_INTERACTION ) ) {
send_hs( stdout, "Interaction::unsubscribe_from_interaction():%d Interaction '%s'%c",
__LINE__, get_FOM_name(), THLA_NEWLINE );
}
// Macro to save the FPU Control Word register value.
TRICKHLA_SAVE_FPU_CONTROL_WORD;
try {
rti_amb->unsubscribeInteractionClass( this->class_handle );
} catch ( RTI1516_NAMESPACE::InteractionClassNotDefined &e ) {
// Macro to restore the saved FPU Control Word register value.
TRICKHLA_RESTORE_FPU_CONTROL_WORD;
TRICKHLA_VALIDATE_FPU_CONTROL_WORD;
ostringstream errmsg;
errmsg << "Interaction::unsubscribe_from_interaction():" << __LINE__
<< " EXCEPTION: InteractionClassNotDefined for Interaction '"
<< get_FOM_name() << "'" << THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
exec_terminate( __FILE__, (char *)errmsg.str().c_str() );
} catch ( RTI1516_NAMESPACE::FederateNotExecutionMember &e ) {
// Macro to restore the saved FPU Control Word register value.
TRICKHLA_RESTORE_FPU_CONTROL_WORD;
TRICKHLA_VALIDATE_FPU_CONTROL_WORD;
ostringstream errmsg;
errmsg << "Interaction::unsubscribe_from_interaction():" << __LINE__
<< " EXCEPTION: FederateNotExecutionMember for Interaction '"
<< get_FOM_name() << "'" << THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
exec_terminate( __FILE__, (char *)errmsg.str().c_str() );
} catch ( RTI1516_NAMESPACE::SaveInProgress &e ) {
// Macro to restore the saved FPU Control Word register value.
TRICKHLA_RESTORE_FPU_CONTROL_WORD;
TRICKHLA_VALIDATE_FPU_CONTROL_WORD;
ostringstream errmsg;
errmsg << "Interaction::unsubscribe_from_interaction():" << __LINE__
<< " EXCEPTION: SaveInProgress for Interaction '"
<< get_FOM_name() << "'" << THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
exec_terminate( __FILE__, (char *)errmsg.str().c_str() );
} catch ( RTI1516_NAMESPACE::RestoreInProgress &e ) {
// Macro to restore the saved FPU Control Word register value.
TRICKHLA_RESTORE_FPU_CONTROL_WORD;
TRICKHLA_VALIDATE_FPU_CONTROL_WORD;
ostringstream errmsg;
errmsg << "Interaction::unsubscribe_from_interaction():" << __LINE__
<< " EXCEPTION: RestoreInProgress for Interaction '"
<< get_FOM_name() << "'" << THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
exec_terminate( __FILE__, (char *)errmsg.str().c_str() );
} catch ( RTI1516_NAMESPACE::NotConnected &e ) {
// Macro to restore the saved FPU Control Word register value.
TRICKHLA_RESTORE_FPU_CONTROL_WORD;
TRICKHLA_VALIDATE_FPU_CONTROL_WORD;
ostringstream errmsg;
errmsg << "Interaction::unsubscribe_from_interaction():" << __LINE__
<< " EXCEPTION: NotConnected for Interaction '"
<< get_FOM_name() << "'" << THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
exec_terminate( __FILE__, (char *)errmsg.str().c_str() );
} catch ( RTI1516_NAMESPACE::RTIinternalError &e ) {
// Macro to restore the saved FPU Control Word register value.
TRICKHLA_RESTORE_FPU_CONTROL_WORD;
TRICKHLA_VALIDATE_FPU_CONTROL_WORD;
ostringstream errmsg;
errmsg << "Interaction::unsubscribe_from_interaction():" << __LINE__
<< " EXCEPTION: RTIinternalError for Interaction '"
<< get_FOM_name() << "'" << THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
exec_terminate( __FILE__, (char *)errmsg.str().c_str() );
} catch ( RTI1516_EXCEPTION &e ) {
// Macro to restore the saved FPU Control Word register value.
TRICKHLA_RESTORE_FPU_CONTROL_WORD;
TRICKHLA_VALIDATE_FPU_CONTROL_WORD;
string rti_err_msg;
StringUtilities::to_string( rti_err_msg, e.what() );
ostringstream errmsg;
errmsg << "Interaction::unsubscribe_from_interaction():" << __LINE__
<< " RTI1516_EXCEPTION for Interaction '" << get_FOM_name()
<< "' with error '" << rti_err_msg << "'" << THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
exec_terminate( __FILE__, (char *)errmsg.str().c_str() );
}
// Macro to restore the saved FPU Control Word register value.
TRICKHLA_RESTORE_FPU_CONTROL_WORD;
TRICKHLA_VALIDATE_FPU_CONTROL_WORD;
}
}
bool Interaction::send(
RTI1516_USERDATA const &the_user_supplied_tag )
{
// RTI must be ready and the flag must be set to publish.
if ( !is_publish() ) {
return ( false );
}
// Macro to save the FPU Control Word register value.
TRICKHLA_SAVE_FPU_CONTROL_WORD;
// Get the Trick-Federate.
Federate *trick_fed = get_federate();
// Get the RTI-Ambassador.
RTIambassador *rti_amb = get_RTI_ambassador();
if ( rti_amb == NULL ) {
send_hs( stderr, "Interaction::send():%d As Receive-Order: Unexpected NULL RTIambassador.%c",
__LINE__, THLA_NEWLINE );
return ( false );
}
ParameterHandleValueMap param_values_map;
// For thread safety, lock here to avoid corrupting the parameters and use
// braces to create scope for the mutex-protection to auto unlock the mutex.
{
// When auto_unlock_mutex goes out of scope it automatically unlocks the
// mutex even if there is an exception.
MutexProtection auto_unlock_mutex( &mutex );
// Add all the parameter values to the map.
for ( int i = 0; i < param_count; i++ ) {
param_values_map[parameters[i].get_parameter_handle()] = parameters[i].get_encoded_parameter_value();
}
// Release mutex lock as auto_unlock_mutex goes out of scope
}
if ( DebugHandler::show( DEBUG_LEVEL_2_TRACE, DEBUG_SOURCE_INTERACTION ) ) {
send_hs( stdout, "Interaction::send():%d As Receive-Order: Interaction '%s'%c",
__LINE__, get_FOM_name(), THLA_NEWLINE );
}
bool successfuly_sent = false;
try {
// RECEIVE_ORDER with no timestamp.
// Do not send any interactions if federate save / restore has begun (see
// IEEE-1516.1-2000 sections 4.12, 4.20)
if ( trick_fed->should_publish_data() ) {
// This call returns an event retraction handle but we
// don't support event retraction so no need to store it.
(void)rti_amb->sendInteraction( this->class_handle,
param_values_map,
the_user_supplied_tag );
successfuly_sent = true;
}
} catch ( RTI1516_EXCEPTION &e ) {
string rti_err_msg;
StringUtilities::to_string( rti_err_msg, e.what() );
send_hs( stderr, "Interaction::send():%d As Receive-Order: Interaction '%s' with exception '%s'%c",
__LINE__, get_FOM_name(), rti_err_msg.c_str(), THLA_NEWLINE );
}
// Macro to restore the saved FPU Control Word register value.
TRICKHLA_RESTORE_FPU_CONTROL_WORD;
TRICKHLA_VALIDATE_FPU_CONTROL_WORD;
// Free the memory used in the parameter values map.
param_values_map.clear();
return ( successfuly_sent );
}
bool Interaction::send(
double send_HLA_time,
RTI1516_USERDATA const &the_user_supplied_tag )
{
// RTI must be ready and the flag must be set to publish.
if ( !is_publish() ) {
return ( false );
}
// Macro to save the FPU Control Word register value.
TRICKHLA_SAVE_FPU_CONTROL_WORD;
RTIambassador *rti_amb = get_RTI_ambassador();
if ( rti_amb == NULL ) {
send_hs( stderr, "Interaction::send():%d Unexpected NULL RTIambassador.%c",
__LINE__, THLA_NEWLINE );
return ( false );
}
ParameterHandleValueMap param_values_map;
// For thread safety, lock here to avoid corrupting the parameters and use
// braces to create scope for the mutex-protection to auto unlock the mutex.
{
// When auto_unlock_mutex goes out of scope it automatically unlocks the
// mutex even if there is an exception.
MutexProtection auto_unlock_mutex( &mutex );
// Add all the parameter values to the map.
for ( int i = 0; i < param_count; i++ ) {
if ( DebugHandler::show( DEBUG_LEVEL_7_TRACE, DEBUG_SOURCE_INTERACTION ) ) {
send_hs( stdout, "Interaction::send():%d Adding '%s' to parameter map.%c",
__LINE__, parameters[i].get_FOM_name(), THLA_NEWLINE );
}
param_values_map[parameters[i].get_parameter_handle()] = parameters[i].get_encoded_parameter_value();
}
// auto_unlock_mutex unlocks the mutex here as it goes out of scope.
}
// Update the timestamp.
time.set( send_HLA_time );
// Get the Trick-Federate.
Federate *trick_fed = get_federate();
// Determine if the interaction should be sent with a timestamp.
// See IEEE 1516.1-2010 Section 6.12.
bool send_with_timestamp = trick_fed->in_time_regulating_state()
&& ( preferred_order != TRANSPORT_RECEIVE_ORDER );
bool successfuly_sent = false;
try {
// Do not send any interactions if federate save or restore has begun (see
// IEEE-1516.1-2000 sections 4.12, 4.20)
if ( trick_fed->should_publish_data() ) {
// The message will only be sent as TSO if our Federate is in the HLA Time
// Regulating state and the interaction prefers timestamp order.
// See IEEE-1516.1-2000, Sections 6.6 and 8.1.1.
if ( send_with_timestamp ) {
if ( DebugHandler::show( DEBUG_LEVEL_2_TRACE, DEBUG_SOURCE_INTERACTION ) ) {
send_hs( stdout, "Interaction::send():%d As Timestamp-Order: Interaction '%s' sent for time %lf seconds.%c",
__LINE__, get_FOM_name(), time.get_time_in_seconds(), THLA_NEWLINE );
}
// This call returns an event retraction handle but we
// don't support event retraction so no need to store it.
// Send in Timestamp Order.
(void)rti_amb->sendInteraction( this->class_handle,
param_values_map,
the_user_supplied_tag,
time.get() );
successfuly_sent = true;
} else {
if ( DebugHandler::show( DEBUG_LEVEL_2_TRACE, DEBUG_SOURCE_INTERACTION ) ) {
send_hs( stdout, "Interaction::send():%d As Receive-Order: \
Interaction '%s' is time-regulating:%s, preferred-order:%s.%c",
__LINE__, get_FOM_name(),
( trick_fed->in_time_regulating_state() ? "Yes" : "No" ),
( ( preferred_order == TRANSPORT_RECEIVE_ORDER ) ? "receive" : "timestamp" ),
THLA_NEWLINE );
}
// Send in Receive Order (i.e. with no timestamp).
(void)rti_amb->sendInteraction( this->class_handle,
param_values_map,
the_user_supplied_tag );
successfuly_sent = true;
}
}
} catch ( RTI1516_NAMESPACE::InvalidLogicalTime &e ) {
// Macro to restore the saved FPU Control Word register value.
TRICKHLA_RESTORE_FPU_CONTROL_WORD;
TRICKHLA_VALIDATE_FPU_CONTROL_WORD;
string rti_err_msg;
StringUtilities::to_string( rti_err_msg, e.what() );
ostringstream errmsg;
errmsg << "Interaction::send():" << __LINE__ << " As "
<< ( send_with_timestamp ? "Timestamp Order" : "Receive Order" )
<< ", InvalidLogicalTime exception for " << get_FOM_name()
<< " time=" << time.get_time_in_seconds() << " ("
<< time.get_time_in_micros() << " microseconds)"
<< " error message:'" << rti_err_msg.c_str() << "'" << THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
} catch ( RTI1516_EXCEPTION &e ) {
string rti_err_msg;
StringUtilities::to_string( rti_err_msg, e.what() );
ostringstream errmsg;
errmsg << "Interaction::send():" << __LINE__ << " As "
<< ( send_with_timestamp ? "Timestamp Order" : "Receive Order" )
<< ", Interaction '" << get_FOM_name() << "' with exception '"
<< rti_err_msg.c_str() << "'" << THLA_ENDL;
send_hs( stderr, (char *)errmsg.str().c_str() );
}
// Macro to restore the saved FPU Control Word register value.
TRICKHLA_RESTORE_FPU_CONTROL_WORD;
TRICKHLA_VALIDATE_FPU_CONTROL_WORD;
// Free the memory used in the parameter values map.
param_values_map.clear();
return ( successfuly_sent );
}
void Interaction::process_interaction()
{
// The Interaction data must have changed and the RTI must be ready.
if ( !is_changed() ) {
return;
}
// For thread safety, lock here to avoid corrupting the parameters and use
// braces to create scope for the mutex-protection to auto unlock the mutex.
{
// When auto_unlock_mutex goes out of scope it automatically unlocks the
// mutex even if there is an exception.
MutexProtection auto_unlock_mutex( &mutex );
// Check the change flag again now that we have the lock on the mutex.
if ( !is_changed() ) { // cppcheck-suppress [identicalConditionAfterEarlyExit]
return;
}
if ( DebugHandler::show( DEBUG_LEVEL_5_TRACE, DEBUG_SOURCE_INTERACTION ) ) {
string handle_str;
StringUtilities::to_string( handle_str, class_handle );
if ( received_as_TSO ) {
send_hs( stdout, "Interaction::process_interaction():%d ID:%s, FOM_name:'%s', HLA time:%G, Timestamp-Order%c",
__LINE__, handle_str.c_str(), get_FOM_name(),
time.get_time_in_seconds(), THLA_NEWLINE );
} else {
send_hs( stdout, "Interaction::process_interaction():%d ID:%s, FOM_name:'%s', Receive-Order%c",
__LINE__, handle_str.c_str(), get_FOM_name(), THLA_NEWLINE );
}
}
// Unpack all the parameter data.
for ( int i = 0; i < param_count; i++ ) {
parameters[i].unpack_parameter_buffer();
}
mark_unchanged();
// Unlock the mutex as the auto_unlock_mutex goes out of scope.
}
// Call the users interaction handler (callback) so that they can
// continue processing the interaction.
if ( handler != NULL ) {
if ( user_supplied_tag_size > 0 ) {
handler->receive_interaction( RTI1516_USERDATA( user_supplied_tag, user_supplied_tag_size ) );
} else {
handler->receive_interaction( RTI1516_USERDATA( 0, 0 ) );
}
}
}
void Interaction::extract_data(
InteractionItem *interaction_item )
{
// Must be set to subscribe to the interaction and the interaction item
// is not null, otherwise just return.
if ( !is_subscribe() || ( interaction_item == NULL ) ) {
return;
}
if ( DebugHandler::show( DEBUG_LEVEL_7_TRACE, DEBUG_SOURCE_INTERACTION ) ) {
string handle_str;
StringUtilities::to_string( handle_str, class_handle );
send_hs( stdout, "Interaction::extract_data():%d ID:%s, FOM_name:'%s'%c",
__LINE__, handle_str.c_str(), get_FOM_name(), THLA_NEWLINE );
}
if ( interaction_item->is_timestamp_order() ) {
// Update the timestamp.
time.set( interaction_item->time );
// Received in Timestamp Order (TSO).
received_as_TSO = true;
} else {
// Receive Order (RO), not Timestamp Order (TSO).
received_as_TSO = false;
}
// For thread safety, lock here to avoid corrupting the parameters.
// When auto_unlock_mutex goes out of scope it automatically unlocks the
// mutex even if there is an exception.
MutexProtection auto_unlock_mutex( &mutex );
// Extract the user supplied tag.
if ( interaction_item->user_supplied_tag_size > 0 ) {
set_user_supplied_tag( interaction_item->user_supplied_tag, interaction_item->user_supplied_tag_size );
mark_changed();
} else {
set_user_supplied_tag( (unsigned char *)NULL, 0 );
}
// Process all the parameter-items in the queue.
while ( !interaction_item->parameter_queue.empty() ) {
ParameterItem *param_item = static_cast< ParameterItem * >( interaction_item->parameter_queue.front() );
// Determine if we have a valid parameter-item.
if ( ( param_item != NULL ) && ( param_item->index >= 0 ) && ( param_item->index < param_count ) ) {
if ( DebugHandler::show( DEBUG_LEVEL_7_TRACE, DEBUG_SOURCE_INTERACTION ) ) {
send_hs( stdout, "Interaction::extract_data():%d Decoding '%s' from parameter map.%c",
__LINE__, parameters[param_item->index].get_FOM_name(),
THLA_NEWLINE );
}
// Extract the parameter data for the given parameter-item.
parameters[param_item->index].extract_data( param_item->size, param_item->data );
// Mark the interaction as changed.
mark_changed();
}
// Now that we extracted the data from the parameter-item remove it
// from the queue.
interaction_item->parameter_queue.pop();
}
// Unlock the mutex as auto_unlock_mutex goes out of scope.
}
void Interaction::mark_unchanged()
{
this->changed = false;
// Clear the change flag for each of the attributes as well.
for ( int i = 0; i < param_count; i++ ) {
parameters[i].mark_unchanged();
}
}
/*!
* @details If the manager does not exist, -1.0 seconds is assigned to the returned object.
*/
Int64Interval Interaction::get_fed_lookahead() const
{
Int64Interval i;
if ( manager != NULL ) {
i = manager->get_fed_lookahead();
} else {
i = Int64Interval( -1.0 );
}
return i;
}
/*!
* @details If the manager does not exist, MAX_LOGICAL_TIME_SECONDS is assigned
* to the returned object.
*/
Int64Time Interaction::get_granted_fed_time() const
{
Int64Time t;
if ( manager != NULL ) {
t = manager->get_granted_fed_time();
} else {
t = Int64Time( MAX_LOGICAL_TIME_SECONDS );
}
return t;
}
Federate *Interaction::get_federate()
{
return ( ( this->manager != NULL ) ? this->manager->get_federate() : NULL );
}
RTIambassador *Interaction::get_RTI_ambassador()
{
return ( ( this->manager != NULL ) ? this->manager->get_RTI_ambassador()
: static_cast< RTI1516_NAMESPACE::RTIambassador * >( NULL ) );
}
bool Interaction::is_shutdown_called() const
{
return ( ( this->manager != NULL ) ? this->manager->is_shutdown_called() : false );
}
| 40.982428
| 123
| 0.638823
|
jiajlin
|
adda4a644ee7c2c8bbc263e13622a455a0d36f54
| 111
|
cpp
|
C++
|
dll/common/Engine/Math/Ray3D.cpp
|
kbinani/dxrip
|
ef170fd895c6d9bb6c05bc2026e9fa9bcd0b1908
|
[
"MIT"
] | 4
|
2015-09-23T14:12:07.000Z
|
2021-10-04T21:03:32.000Z
|
dll/common/Engine/Math/Ray3D.cpp
|
kbinani/dxrip
|
ef170fd895c6d9bb6c05bc2026e9fa9bcd0b1908
|
[
"MIT"
] | null | null | null |
dll/common/Engine/Math/Ray3D.cpp
|
kbinani/dxrip
|
ef170fd895c6d9bb6c05bc2026e9fa9bcd0b1908
|
[
"MIT"
] | 2
|
2018-06-26T14:59:11.000Z
|
2021-09-01T01:50:20.000Z
|
/*
Ray3D.cpp
Written by Matthew Fisher
a 3D ray represented by an origin point and a direction vector.
*/
| 18.5
| 64
| 0.72973
|
kbinani
|
addc2b8b55dc4dcf0b78935062600f696c73c88e
| 10,750
|
cpp
|
C++
|
Src/GUI/FrTabControl.cpp
|
VladGordienko28/FluorineEngine-I
|
31114c41884d41ec60d04dba7965bc83be47d229
|
[
"MIT"
] | null | null | null |
Src/GUI/FrTabControl.cpp
|
VladGordienko28/FluorineEngine-I
|
31114c41884d41ec60d04dba7965bc83be47d229
|
[
"MIT"
] | null | null | null |
Src/GUI/FrTabControl.cpp
|
VladGordienko28/FluorineEngine-I
|
31114c41884d41ec60d04dba7965bc83be47d229
|
[
"MIT"
] | null | null | null |
/*=============================================================================
FrTabControl.cpp: Tab control widget.
Copyright Jul.2016 Vlad Gordienko.
=============================================================================*/
#include "GUI.h"
/*-----------------------------------------------------------------------------
WTabPage implementation.
-----------------------------------------------------------------------------*/
// Whether fade tab, if it not in focus.
#define FADE_TAB 0
//
// Tab page constructor.
//
WTabPage::WTabPage( WContainer* InOwner, WWindow* InRoot )
: WContainer( InOwner, InRoot ),
Color( COLOR_SteelBlue ),
TabWidth( 70 ),
TabControl( nullptr )
{
Align = AL_Client;
Padding = TArea( 0, 0, 0, 0 );
}
//
// Tab page repaint.
//
void WTabPage::OnPaint( CGUIRenderBase* Render )
{
WContainer::OnPaint( Render );
#if 0
// Debug draw.
Render->DrawRegion
(
ClientToWindow( TPoint( 0, 0 ) ),
Size,
Color * COLOR_CornflowerBlue,
Color * COLOR_CornflowerBlue,
BPAT_Diagonal
);
#endif
}
//
// Close the tab page.
//
void WTabPage::Close( Bool bForce )
{
assert(TabControl != nullptr);
TabControl->CloseTabPage( TabControl->Pages.FindItem(this), bForce );
}
/*-----------------------------------------------------------------------------
WTabControl implementation.
-----------------------------------------------------------------------------*/
//
// Tabs control constructor.
//
WTabControl::WTabControl( WContainer* InOwner, WWindow* InRoot )
: WContainer( InOwner, InRoot ),
Pages(),
iActive( -1 ),
iHighlight( -1 ),
iCross( -1 ),
DragPage( nullptr ),
bWasDrag( false ),
bOverflow( false )
{
// Grab some place for header.
Padding = TArea( 21, 0, 0, 0 );
Align = AL_Client;
// Overflow popup menu.
Popup = new WPopupMenu( this, InRoot );
}
//
// Draw a tab control.
//
void WTabControl::OnPaint( CGUIRenderBase* Render )
{
// Call parent.
WContainer::OnPaint( Render );
// Precompute.
TPoint Base = ClientToWindow(TPoint::Zero);
Integer TextY = Base.Y + (19-Root->Font1->Height) / 2;
Integer XWalk = Base.X;
// Draw a master bar.
Render->DrawRegion
(
Base,
TSize( Size.Width, 20 ),
GUI_COLOR_PANEL,
/*GUI_COLOR_PANEL_BORDER*/GUI_COLOR_PANEL,
BPAT_Solid
);
// Draw headers.
TColor ActiveColor;
Integer iPage;
for( iPage=0; iPage<Pages.Num(); iPage++ )
{
WTabPage* Page = Pages[iPage];
// Test, maybe list overflow.
if( XWalk+Page->TabWidth >= Base.X+Size.Width-15 )
break;
// Special highlight required?
if( iPage == iActive || iPage == iHighlight )
{
TColor DrawColor = iPage == iActive ? Page->Color : TColor( 0x1d, 0x1d, 0x1d, 0xff ) + Page->Color;
TColor DarkColor = DrawColor * TColor( 0xdd, 0xdd, 0xdd, 0xff );
// Fade color, if not in focus.
if( iPage == iActive )
{
#if FADE_TAB
if( !IsChildFocused() )
DrawColor = TColor( 0x50, 0x50, 0x50, 0xff )+DrawColor*0.35f;
#endif
ActiveColor = DrawColor;
}
Render->DrawRegion
(
TPoint( XWalk, Base.Y ),
TSize( Page->TabWidth, 19 ),
DrawColor,
DrawColor,
BPAT_Solid
);
// Highlight selected cross.
if( iCross == iPage )
Render->DrawRegion
(
TPoint( XWalk+Page->TabWidth - 21, Base.Y + 3 ),
TSize( 13, 13 ),
DarkColor,
DarkColor,
BPAT_Solid
);
// Draw cross.
Render->DrawPicture
(
TPoint( XWalk+Page->TabWidth - 20, Base.Y + 4 ),
TSize( 11, 11 ),
TPoint( 0, 11 ),
TSize( 11, 11 ),
Root->Icons
);
}
// Draw tab title.
Render->DrawText
(
TPoint( XWalk + 5, TextY ),
Page->Caption,
GUI_COLOR_TEXT,
//COLOR_White,
Root->Font1
);
// To next.
XWalk+= Page->TabWidth;
}
// Draw a little marker if list overflow.
if( bOverflow = iPage < Pages.Num() )
{
TPoint Cursor = Root->MousePos;
TPoint Start = TPoint( Base.X+Size.Width-14, Base.Y+3 );
if( Cursor.X>=Start.X && Cursor.Y>=Start.Y && Cursor.X<=Start.X+14 && Cursor.Y<=Start.Y+14 )
Render->DrawRegion
(
Start,
TSize( 14, 14 ),
GUI_COLOR_BUTTON_HIGHLIGHT,
GUI_COLOR_BUTTON_HIGHLIGHT,
BPAT_Solid
);
Render->DrawPicture
(
TPoint( Base.X+Size.Width-10, Base.Y+9 ),
TSize( 7, 4 ),
TPoint( 0, 32 ),
TSize( 7, 4 ),
Root->Icons
);
}
// Draw a tiny color bar according to active page.
if( iActive != -1 )
{
WTabPage* Active = Pages[iActive];
Render->DrawRegion
(
TPoint( Base.X, Base.Y + 19 ),
TSize( Size.Width, 2 ),
ActiveColor,
ActiveColor,
BPAT_Solid
);
}
}
//
// Return the active page, if
// no page active return nullptr.
//
WTabPage* WTabControl::GetActivePage()
{
return iActive!=-1 && iActive<Pages.Num() ? Pages[iActive] : nullptr;
}
//
// Add a new tab and activate it.
//
Integer WTabControl::AddTabPage( WTabPage* Page )
{
Integer iNew = Pages.Push(Page);
Page->TabControl = this;
ActivateTabPage( iNew );
return iNew;
}
//
// Close tab by its index.
//
void WTabControl::CloseTabPage( Integer iPage, Bool bForce )
{
assert(iPage>=0 && iPage<Pages.Num());
WTabPage* P = Pages[iPage];
// Is tab prepared for DIE?
if( bForce || P->OnQueryClose() )
{
Pages.RemoveShift(iPage);
if( Pages.Num() )
{
// Open new item or just close.
if( iActive == iPage )
{
// Open new one.
ActivateTabPage( Pages.Num()-1 );
iHighlight = -1;
}
else
{
// Save selection.
iActive = iActive > iPage ? iActive-1 : iActive;
}
}
else
{
// Nothing to open, all tabs are closed.
iHighlight = iActive = -1;
}
// Destroy widget.
delete P;
}
}
//
// Mouse click on tabs bar.
//
void WTabControl::OnMouseUp( EMouseButton Button, Integer X, Integer Y )
{
WContainer::OnMouseUp( Button, X, Y );
iCross = XYToCross( X, Y );
// Close tab if cross pressed.
if( !bWasDrag &&
Button == MB_Left &&
iCross != -1 )
{
CloseTabPage(iCross);
}
// Close tab via middle button.
if( Button == MB_Middle )
{
Integer iPage = XToIndex(X);
if( iPage != -1 )
CloseTabPage(iPage);
}
// No more drag.
DragPage = nullptr;
bWasDrag = false;
}
//
// When mouse hover tabs bar.
//
void WTabControl::OnMouseMove( EMouseButton Button, Integer X, Integer Y )
{
WContainer::OnMouseMove( Button, X, Y );
if( !DragPage )
{
// No drag, just highlight.
iHighlight = XToIndex( X );
iCross = XYToCross( X, Y );
}
else
{
// Process tab drag.
Integer XWalk = 0;
for( Integer i=0; i<Pages.Num(); i++ )
if( Pages[i] != DragPage )
XWalk += Pages[i]->TabWidth;
else
break;
while( X < XWalk )
{
Integer iDrag = Pages.FindItem( DragPage );
if( iDrag <= 0 ) break;
XWalk -= Pages[iDrag-1]->TabWidth;
Pages.Swap( iDrag, iDrag-1 );
}
while( X > XWalk+DragPage->TabWidth )
{
Integer iDrag = Pages.FindItem( DragPage );
if( iDrag >= Pages.Num()-1 ) break;
XWalk += Pages[iDrag+1]->TabWidth;
Pages.Swap( iDrag, iDrag+1 );
}
// Refresh highlight.
iActive = iHighlight = Pages.FindItem( DragPage );
bWasDrag = true;
}
}
//
// When mouse press tabs bar.
//
void WTabControl::OnMouseDown( EMouseButton Button, Integer X, Integer Y )
{
WContainer::OnMouseDown( Button, X, Y );
// Test maybe clicked on little triangle.
if( bOverflow && Button==MB_Left && X > Size.Width-14 )
{
// Setup popup and show it.
Popup->Items.Empty();
for( Integer i=0; i<Pages.Num(); i++ )
Popup->AddItem( Pages[i]->Caption, WIDGET_EVENT(WTabControl::PopupPageClick), true );
Popup->Show( TPoint( Size.Width, 20 ) );
return;
}
Integer iClicked = XToIndex(X);
iCross = XYToCross( X, Y );
// Activate pressed.
if( iCross == -1 &&
iClicked != -1 &&
iClicked != iActive &&
!DragPage &&
Button != MB_Middle )
{
ActivateTabPage( iClicked );
}
// Prepare to drag active page.
bWasDrag = false;
if( Button == MB_Left && iActive != -1 )
DragPage = Pages[iActive];
}
//
// Activate an iPage.
//
void WTabControl::ActivateTabPage( Integer iPage )
{
assert(iPage>=0 && iPage<Pages.Num());
// Hide all.
for( Integer i=0; i<Pages.Num(); i++ )
Pages[i]->bVisible = false;
// Show and activate.
Pages[iPage]->bVisible = true;
Pages[iPage]->OnOpen();
iActive = iPage;
// Realign.
AlignChildren();
//Pages[iPage]->AlignChildren();
Pages[iPage]->WidgetProc( WPE_Resize, TWidProcParms() );
// Make it focused.
Root->SetFocused( this );
}
//
// Activate an Page.
//
void WTabControl::ActivateTabPage( WTabPage* Page )
{
Integer iPage = Pages.FindItem( Page );
assert(iPage != -1);
ActivateTabPage( iPage );
}
//
// When mouse leave tabs.
//
void WTabControl::OnMouseLeave()
{
WContainer::OnMouseLeave();
// No highlight any more.
iHighlight = -1;
iCross = -1;
}
//
// Convert mouse X to tab index, if mouse outside
// any tabs return -1.
//
Integer WTabControl::XToIndex( Integer InX )
{
Integer XWalk = 0;
for( Integer i=0; i<Pages.Num(); i++ )
{
WTabPage* Page = Pages[i];
if( XWalk+Page->TabWidth > Size.Width-15 )
break;
if( ( InX >= XWalk ) &&
( InX <= XWalk + Page->TabWidth ) )
return i;
XWalk += Page->TabWidth;
}
return -1;
}
//
// Figure out index of close cross on tab.
// It no cross around - return -1.
//
Integer WTabControl::XYToCross( Integer InX, Integer InY )
{
Integer XWalk = 0;
for( Integer i=0; i<Pages.Num(); i++ )
{
WTabPage* Page = Pages[i];
if( XWalk+Page->TabWidth > Size.Width-15 )
break;
if( ( InX > XWalk+Page->TabWidth-20 ) &&
( InX < XWalk+Page->TabWidth-5 ) &&
( InY > 4 && InY < 15 ) )
return i;
XWalk += Page->TabWidth;
}
return -1;
}
//
// Page selected.
//
void WTabControl::PopupPageClick( WWidget* Sender )
{
// Figure out chosen page.
WTabPage* Chosen = nullptr;
for( Integer i=0; i<Popup->Items.Num(); i++ )
if( Popup->Items[i].bChecked )
{
Chosen = Pages[i];
break;
}
assert(Chosen);
// Carousel pages, to make chosen first.
while( Pages[0] != Chosen )
{
WTabPage* First = Pages[0];
for( Integer i=0; i<Pages.Num()-1; i++ )
Pages[i] = Pages[i+1];
Pages[Pages.Num()-1] = First;
}
// Make first page active now.
ActivateTabPage( 0 );
}
//
// Tab control has been activated.
//
void WTabControl::OnActivate()
{
WContainer::OnActivate();
// Pages switching failure :(
#if 0
// Activate selected page.
WTabPage* Page = GetActivePage();
if( Page )
Root->SetFocused( Page );
#endif
}
/*-----------------------------------------------------------------------------
The End.
-----------------------------------------------------------------------------*/
| 19.265233
| 102
| 0.574233
|
VladGordienko28
|
addceae60277af9d0efb17f388335e133ab6e685
| 880
|
cpp
|
C++
|
samples/sample37.cpp
|
AjayBrahmakshatriya/mirror-cpp
|
f19fdfbfdc3f333a5e20f88374b87a3509dd1af7
|
[
"MIT"
] | null | null | null |
samples/sample37.cpp
|
AjayBrahmakshatriya/mirror-cpp
|
f19fdfbfdc3f333a5e20f88374b87a3509dd1af7
|
[
"MIT"
] | null | null | null |
samples/sample37.cpp
|
AjayBrahmakshatriya/mirror-cpp
|
f19fdfbfdc3f333a5e20f88374b87a3509dd1af7
|
[
"MIT"
] | null | null | null |
// Include the headers
#include "blocks/c_code_generator.h"
#include "builder/static_var.h"
#include "builder/dyn_var.h"
#include "blocks/extract_cuda.h"
#include <iostream>
// Include the BuildIt types
using builder::dyn_var;
using builder::static_var;
static void bar(dyn_var<int*> buffer) {
builder::annotate(CUDA_KERNEL);
for (dyn_var<int> cta = 0; cta < 128; cta = cta + 1) {
for (dyn_var<int> tid = 0; tid < 512; tid = tid + 1) {
dyn_var<int> thread_id = cta * 512 + tid;
buffer[thread_id] = 0;
}
}
}
int main(int argc, char* argv[]) {
builder::builder_context context;
auto ast = context.extract_function_ast(bar, "bar");
auto new_decls = block::extract_cuda_from(block::to<block::func_decl>(ast)->body);
for (auto a: new_decls)
block::c_code_generator::generate_code(a, std::cout, 0);
block::c_code_generator::generate_code(ast, std::cout, 0);
}
| 28.387097
| 83
| 0.7
|
AjayBrahmakshatriya
|
adddaedc9a8c59629f3f2fd012503ac9d6c83d26
| 336
|
cpp
|
C++
|
net.ssa/Dima/bge.root/bge/bge/ui.cpp
|
ixray-team/xray-vss-archive
|
b245c8601dcefb505b4b51f58142da6769d4dc92
|
[
"Linux-OpenIB"
] | 1
|
2022-03-26T17:00:19.000Z
|
2022-03-26T17:00:19.000Z
|
Dima/bge.root/bge/bge/ui.cpp
|
ixray-team/xray-vss-archive
|
b245c8601dcefb505b4b51f58142da6769d4dc92
|
[
"Linux-OpenIB"
] | null | null | null |
Dima/bge.root/bge/bge/ui.cpp
|
ixray-team/xray-vss-archive
|
b245c8601dcefb505b4b51f58142da6769d4dc92
|
[
"Linux-OpenIB"
] | 1
|
2022-03-26T17:00:21.000Z
|
2022-03-26T17:00:21.000Z
|
////////////////////////////////////////////////////////////////////////////
// Module : ui.cpp
// Created : 12.11.2004
// Modified : 12.11.2004
// Author : Dmitriy Iassenev
// Description : User interface
////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "ui.h"
| 30.545455
| 77
| 0.330357
|
ixray-team
|
ade07f5f3e86790ca6d9be1a00bce643a4edcc95
| 109
|
cpp
|
C++
|
Engine/src/Engine/Graphics/renderers/RenderAPI.cpp
|
AustinLynes/Arcana-Tools
|
ce585d552e30174c4c629a9ea05e7f83947499a5
|
[
"Apache-2.0"
] | null | null | null |
Engine/src/Engine/Graphics/renderers/RenderAPI.cpp
|
AustinLynes/Arcana-Tools
|
ce585d552e30174c4c629a9ea05e7f83947499a5
|
[
"Apache-2.0"
] | null | null | null |
Engine/src/Engine/Graphics/renderers/RenderAPI.cpp
|
AustinLynes/Arcana-Tools
|
ce585d552e30174c4c629a9ea05e7f83947499a5
|
[
"Apache-2.0"
] | null | null | null |
#include "RenderAPI.h"
namespace ArcanaTools {
RenderAPI::API RenderAPI::s_API = RenderAPI::API::OPENGL;
}
| 18.166667
| 58
| 0.743119
|
AustinLynes
|
ade1d45bdeffb800948221a346afcac788e4ec1f
| 2,740
|
cpp
|
C++
|
codes/CF/CF_911F.cpp
|
chessbot108/solved-problems
|
0945be829a8ea9f0d5896c89331460d70d076691
|
[
"MIT"
] | 2
|
2021-03-07T03:34:02.000Z
|
2021-03-09T01:22:21.000Z
|
codes/CF/CF_911F.cpp
|
chessbot108/solved-problems
|
0945be829a8ea9f0d5896c89331460d70d076691
|
[
"MIT"
] | 1
|
2021-03-27T15:01:23.000Z
|
2021-03-27T15:55:34.000Z
|
codes/CF/CF_911F.cpp
|
chessbot108/solved-problems
|
0945be829a8ea9f0d5896c89331460d70d076691
|
[
"MIT"
] | 1
|
2021-03-27T05:02:33.000Z
|
2021-03-27T05:02:33.000Z
|
//here take a cat
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <string>
#include <utility>
#include <cmath>
#include <cassert>
#include <algorithm>
#include <vector>
#include <random>
#include <chrono>
#include <queue>
#include <set>
#define ll long long
#define lb long double
#define pii pair<int, int>
#define pb push_back
#define mp make_pair
#define ins insert
#define cont continue
#define pow2(n) (1 << (n))
#define LC(n) (((n) << 1) + 1)
#define RC(n) (((n) << 1) + 2)
#define add(a, b) (((a)%mod + (b)%mod)%mod)
#define mul(a, b) (((a)%mod * (b)%mod)%mod)
#define init(arr, val) memset(arr, val, sizeof(arr))
#define bckt(arr, val, sz) memset(arr, val, sizeof(arr[0]) * (sz))
#define uid(a, b) uniform_int_distribution<int>(a, b)(rng)
#define tern(a, b, c) ((a) ? (b) : (c))
#define feq(a, b) (fabs(a - b) < eps)
#define moo printf
#define oom scanf
#define mool puts("")
#define orz assert
#define fll fflush(stdout)
const lb eps = 1e-9;
const ll mod = 1e9 + 7, ll_max = (ll)1e18;
const int MX = 2e5 +10, int_max = 0x3f3f3f3f;
using namespace std;
mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
struct node{
int u, w;
node(){};
node(int a, int b){ u=a, w=b; }
bool operator < (const node& b) const{
return w < b.w; //HMMMM
}
};
int dep[MX], dist[MX][5], vis[MX], par[MX], deg[MX];
int n;
priority_queue<node> pq;
vector<int> adj[MX];
vector<pair<pii, int>> ans;
void dfs(int u, int p, int d, int op){
par[u] = p;
dep[u] = d;
dist[u][op] = max(d, dist[u][op]);
for(int v : adj[u]){
if(v != p) dfs(v, u, d + 1, op);
}
}
void mark(int x){
if(!x || vis[x]) return ;
vis[x] = 1;
mark(par[x]);
}
int far(int x, int op){
dfs(x, 0, 0, op);
for(int i = 1; i<=n; i++){
if(dep[i] > dep[x]) x = i;
}
return x;
}
int main(){
cin.tie(0) -> sync_with_stdio(0);
cin >> n;
for(int i = 0; i<n-1; i++){
int a, b; cin >> a >> b;
adj[a].pb(b);
adj[b].pb(a);
}
int d1 = far(1, 0), d2 = far(d1, 1); far(d2, 2);
mark(d1); mark(d2);
for(int i = 1; i<=n; i++){
deg[i] = adj[i].size();
if(deg[i] == 1) pq.push(node(i, max(dist[i][1], dist[i][2])));
}
ll res = 0ll;
while(!pq.empty()){
node cur = pq.top(); pq.pop();
int u = cur.u, w = cur.w, v = tern(dist[u][1] > dist[u][2], d1, d2), p = par[u];
if(vis[u]) cont;
ans.pb(mp(mp(u, v), u));
res += w;
deg[p]--;
if(deg[p] == 1){
pq.push(node(p, max(dist[p][1], dist[p][2])));
}
}
for(; d1 != d2; d1 = par[d1]){
ans.pb(mp(mp(d1, d2), d1));
res += (ll)dep[d1];
}
moo("%lld\n", res);
for(const auto& e : ans){
moo("%d %d %d\n", e.first.first, e.first.second, e.second);
}
return 0;
}
| 21.92
| 84
| 0.55438
|
chessbot108
|
ade3670799690a1349db18a566faae2cb72a5f12
| 4,634
|
cpp
|
C++
|
src/dev/mcdaly/12BarTensegrity/tensionsensor.cpp
|
wvat/NTRTsim
|
0443cbd542e12e23c04adf79ea0d8d003c428baa
|
[
"Apache-2.0"
] | 148
|
2015-01-08T22:44:00.000Z
|
2022-03-19T18:42:48.000Z
|
src/dev/mcdaly/12BarTensegrity/tensionsensor.cpp
|
wvat/NTRTsim
|
0443cbd542e12e23c04adf79ea0d8d003c428baa
|
[
"Apache-2.0"
] | 107
|
2015-01-02T16:41:42.000Z
|
2021-06-14T22:09:19.000Z
|
src/dev/mcdaly/12BarTensegrity/tensionsensor.cpp
|
wvat/NTRTsim
|
0443cbd542e12e23c04adf79ea0d8d003c428baa
|
[
"Apache-2.0"
] | 86
|
2015-01-06T07:02:36.000Z
|
2022-02-28T17:36:14.000Z
|
/*
* Copyright © 2012, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The NASA Tensegrity Robotics Toolkit (NTRT) v1 platform is licensed
* under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
/**
* @file RPModel.cpp
* @brief Contains the implementation of class RocketPower.
* @author Brian Cera, based on code from Kyunam Kim
* @version 1.0.0
* $Id$
*/
// This module
//#include "RPModel.h"
// This library
#include "core/tgBasicActuator.h"
#include "core/tgRod.h"
#include "tgcreator/tgBuildSpec.h"
#include "tgcreator/tgBasicActuatorInfo.h"
#include "tgcreator/tgRodInfo.h"
#include "tgcreator/tgStructure.h"
#include "tgcreator/tgStructureInfo.h"
// The Bullet Physics library
#include "LinearMath/btVector3.h"
// The C++ Standard Library
#include <stdexcept>
#include <iostream>
#include <fstream>
namespace
{
// see tgBasicActuator and tgRod for a descripton of these rod parameters
// (specifically, those related to the motor moving the strings.)
// NOTE that any parameter that depends on units of length will scale
// with the current gravity scaling. E.g., with gravity as 98.1,
// the length units below are in decimeters.
// Note: This current model of the SUPERball rod is 1.5m long by 3 cm radius,
// which is 0.00424 m^3.
// For SUPERball v1.5, mass = 3.5kg per strut, which comes out to
// 0.825 kg / (decimeter^3).
// similarly, frictional parameters are for the tgRod objects.
//const double sf = 20;//scaling factor with respect to meter scale. E.g., centimeter scale is achieved by setting sf = 100
//const double length_scale = 0.25; //1 makes 4 m long rods
// In meter scale, the robot is too small, while in centimeter scale, the robot rotates freely (free energy!)
// Also, don't forget to change gravity scale in AppThruster.cpp and T6Thruster.cpp!
const struct Config
{
double density;
double radius;
double stiffness;
double damping;
double rod_length;
double rod_space;
double friction;
double rollFriction;
double restitution;
double pretension;
bool hist;
double maxTens;
double targetVelocity;
}
c =
{
2700/pow(sf,3),//0.688, // density (kg / length^3)
0.0254*sf,//0.31, // radius (length)
600,//1192.5*10,//613.0, // stiffness (kg / sec^2) was 1500
500, // damping (kg / sec)
4*sf*length_scale, // rod_length (length)
.02*sf, // rod_space (length)
0.99, // friction (unitless)
0.1, // rollFriction (unitless)
0.0, // restitution (?)
150*sf, //610, // pretension -> set to 4 * 613, the previous value of the rest length controller
0, // History logging (boolean)
300*sf, // maxTens
.02, //sf, // targetVelocity
// Use the below values for earlier versions of simulation.
// 1.006,
// 0.31,
// 300000.0,
// 3000.0,
// 15.0,
// 7.5,
};
} // namespace
RPModel::RPModel() : tgModel()
{
}
RPModel::~RPModel()
{
}
void RPModel::setup(tgWorld& world)
{
allAbstractMarkers=tgCast::filter<tgModel, abstractMarker> (getDescendants());
}
void RPModel::step(double dt)
{
// Precondition
if (dt <= 0.0)
{
throw std::invalid_argument("dt is not positive");
}
else
{
// Notify observers (controllers) of the step so that they can take action
notifyStep(dt);
tgModel::step(dt); // Step any children
}
for(int k=1;k<36;k++){
std::cout << allActuators[k]->getTension() << " ";
}
std::cout << std::endl;
}
void RPModel::onVisit(tgModelVisitor& r)
{
tgModel::onVisit(r);
}
const std::vector<tgBasicActuator*>& RPModel::getAllActuators() const
{
return allActuators;
}
const std::vector<tgRod*>& RPModel::getAllRods() const
{
return allRods;
}
const std::vector<tgBaseRigid*>& RPModel::getAllBaseRigids() const
{
return allBaseRigids;
}
const std::vector<abstractMarker*>& RPModel::getAllAbstractMarkers() const
{
return allAbstractMarkers;
}
void RPModel::teardown()
{
notifyTeardown();
tgModel::teardown();
}
| 26.632184
| 125
| 0.67609
|
wvat
|
ade50fce87017a1c81f10895ab73bae9171ceb65
| 196
|
cpp
|
C++
|
src/main/cpp/miscar/Fix.cpp
|
MisCar/libmiscar
|
b7da8ea84f1183ce4a8c5b51bcb29bea7052f7b2
|
[
"BSD-3-Clause"
] | null | null | null |
src/main/cpp/miscar/Fix.cpp
|
MisCar/libmiscar
|
b7da8ea84f1183ce4a8c5b51bcb29bea7052f7b2
|
[
"BSD-3-Clause"
] | null | null | null |
src/main/cpp/miscar/Fix.cpp
|
MisCar/libmiscar
|
b7da8ea84f1183ce4a8c5b51bcb29bea7052f7b2
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright (c) MisCar 1574
#include "miscar/Fix.h"
#include <cmath>
double miscar::Fix(double value, double range) {
return (std::abs(value) < range) ? 0 : (value - range) / (1 - range);
}
| 19.6
| 71
| 0.637755
|
MisCar
|
ade5137afabf9677c83d62a9053a95abc5ccfb16
| 5,038
|
cpp
|
C++
|
LAVFilters/decoder/LAVVideo/VideoInputPin.cpp
|
lcmftianci/licodeanalysis
|
62e2722eba1b75ef82f7c1328585873d08bb41cc
|
[
"Apache-2.0"
] | 2
|
2019-11-17T14:01:21.000Z
|
2019-12-24T14:29:45.000Z
|
LAVFilters/decoder/LAVVideo/VideoInputPin.cpp
|
lcmftianci/licodeanalysis
|
62e2722eba1b75ef82f7c1328585873d08bb41cc
|
[
"Apache-2.0"
] | null | null | null |
LAVFilters/decoder/LAVVideo/VideoInputPin.cpp
|
lcmftianci/licodeanalysis
|
62e2722eba1b75ef82f7c1328585873d08bb41cc
|
[
"Apache-2.0"
] | 3
|
2019-08-28T14:37:01.000Z
|
2020-06-17T16:46:32.000Z
|
/*
* Copyright (C) 2010-2019 Hendrik Leppkes
* http://www.1f0.de
*
* 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; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "stdafx.h"
#include "VideoInputPin.h"
#include "ILAVDynamicAllocator.h"
CVideoInputPin::CVideoInputPin(TCHAR* pObjectName, CLAVVideo* pFilter, HRESULT* phr, LPWSTR pName)
: CDeCSSTransformInputPin(pObjectName, pFilter, phr, pName)
, m_pLAVVideo(pFilter)
{
}
STDMETHODIMP CVideoInputPin::NonDelegatingQueryInterface(REFIID riid, void** ppv)
{
CheckPointer(ppv, E_POINTER);
return
QI(IPinSegmentEx)
__super::NonDelegatingQueryInterface(riid, ppv);
}
STDMETHODIMP CVideoInputPin::NotifyAllocator(IMemAllocator * pAllocator, BOOL bReadOnly)
{
HRESULT hr = __super::NotifyAllocator(pAllocator, bReadOnly);
m_bDynamicAllocator = FALSE;
if (SUCCEEDED(hr) && pAllocator) {
ILAVDynamicAllocator *pDynamicAllocator = nullptr;
if (SUCCEEDED(pAllocator->QueryInterface(&pDynamicAllocator))) {
m_bDynamicAllocator = pDynamicAllocator->IsDynamicAllocator();
}
SafeRelease(&pDynamicAllocator);
}
return hr;
}
STDMETHODIMP CVideoInputPin::EndOfSegment()
{
CAutoLock lck(&m_pLAVVideo->m_csReceive);
HRESULT hr = CheckStreaming();
if (S_OK == hr) {
hr = m_pLAVVideo->EndOfSegment();
}
return hr;
}
// IKsPropertySet
STDMETHODIMP CVideoInputPin::Set(REFGUID PropSet, ULONG Id, LPVOID pInstanceData, ULONG InstanceLength, LPVOID pPropertyData, ULONG DataLength)
{
if(PropSet != AM_KSPROPSETID_TSRateChange) {
return __super::Set(PropSet, Id, pInstanceData, InstanceLength, pPropertyData, DataLength);
}
switch(Id) {
case AM_RATE_SimpleRateChange: {
AM_SimpleRateChange* p = (AM_SimpleRateChange*)pPropertyData;
if (!m_CorrectTS) {
return E_PROP_ID_UNSUPPORTED;
}
CAutoLock cAutoLock(&m_csRateLock);
m_ratechange = *p;
}
break;
case AM_RATE_UseRateVersion: {
WORD* p = (WORD*)pPropertyData;
if (*p > 0x0101) {
return E_PROP_ID_UNSUPPORTED;
}
}
break;
case AM_RATE_CorrectTS: {
LONG* p = (LONG*)pPropertyData;
m_CorrectTS = *p;
}
break;
default:
return E_PROP_ID_UNSUPPORTED;
}
return S_OK;
}
STDMETHODIMP CVideoInputPin::Get(REFGUID PropSet, ULONG Id, LPVOID pInstanceData, ULONG InstanceLength, LPVOID pPropertyData, ULONG DataLength, ULONG* pBytesReturned)
{
if(PropSet != AM_KSPROPSETID_TSRateChange) {
return __super::Get(PropSet, Id, pInstanceData, InstanceLength, pPropertyData, DataLength, pBytesReturned);
}
switch(Id) {
case AM_RATE_SimpleRateChange: {
AM_SimpleRateChange* p = (AM_SimpleRateChange*)pPropertyData;
CAutoLock cAutoLock(&m_csRateLock);
*p = m_ratechange;
*pBytesReturned = sizeof(AM_SimpleRateChange);
}
break;
case AM_RATE_MaxFullDataRate: {
AM_MaxFullDataRate* p = (AM_MaxFullDataRate*)pPropertyData;
*p = 2 * 10000;
*pBytesReturned = sizeof(AM_MaxFullDataRate);
}
break;
case AM_RATE_QueryFullFrameRate: {
AM_QueryRate* p = (AM_QueryRate*)pPropertyData;
p->lMaxForwardFullFrame = 2 * 10000;
p->lMaxReverseFullFrame = 0;
*pBytesReturned = sizeof(AM_QueryRate);
}
break;
case AM_RATE_QueryLastRateSegPTS: {
//REFERENCE_TIME* p = (REFERENCE_TIME*)pPropertyData;
return E_PROP_ID_UNSUPPORTED;
}
break;
default:
return E_PROP_ID_UNSUPPORTED;
}
return S_OK;
}
STDMETHODIMP CVideoInputPin::QuerySupported(REFGUID PropSet, ULONG Id, ULONG* pTypeSupport)
{
if(PropSet != AM_KSPROPSETID_TSRateChange) {
return __super::QuerySupported(PropSet, Id, pTypeSupport);
}
switch (Id) {
case AM_RATE_SimpleRateChange:
*pTypeSupport = KSPROPERTY_SUPPORT_GET | KSPROPERTY_SUPPORT_SET;
break;
case AM_RATE_MaxFullDataRate:
*pTypeSupport = KSPROPERTY_SUPPORT_GET;
break;
case AM_RATE_UseRateVersion:
*pTypeSupport = KSPROPERTY_SUPPORT_SET;
break;
case AM_RATE_QueryFullFrameRate:
*pTypeSupport = KSPROPERTY_SUPPORT_GET;
break;
case AM_RATE_QueryLastRateSegPTS:
*pTypeSupport = KSPROPERTY_SUPPORT_GET;
break;
case AM_RATE_CorrectTS:
*pTypeSupport = KSPROPERTY_SUPPORT_SET;
break;
default:
return E_PROP_ID_UNSUPPORTED;
}
return S_OK;
}
| 29.121387
| 166
| 0.708615
|
lcmftianci
|
ade52bb499f53d45cc0770a06faa187155e32b1f
| 14,504
|
cpp
|
C++
|
Axis.Physalis/application/parsing/parsers/StepParser.cpp
|
renato-yuzup/axis-fem
|
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
|
[
"MIT"
] | 2
|
2021-07-23T08:49:54.000Z
|
2021-07-29T22:07:30.000Z
|
Axis.Physalis/application/parsing/parsers/StepParser.cpp
|
renato-yuzup/axis-fem
|
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
|
[
"MIT"
] | null | null | null |
Axis.Physalis/application/parsing/parsers/StepParser.cpp
|
renato-yuzup/axis-fem
|
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
|
[
"MIT"
] | null | null | null |
#include "StepParser.hpp"
#include "SnapshotParser.hpp"
#include "ResultCollectorParser.hpp"
#include "application/factories/parsers/StepParserProvider.hpp"
#include "application/jobs/AnalysisStep.hpp"
#include "application/jobs/StructuralAnalysis.hpp"
#include "application/locators/ClockworkFactoryLocator.hpp"
#include "application/locators/SolverFactoryLocator.hpp"
#include "application/output/ResultBucketConcrete.hpp"
#include "application/parsing/core/SymbolTable.hpp"
#include "application/parsing/core/ParseContext.hpp"
#include "application/parsing/parsers/EmptyBlockParser.hpp"
#include "application/parsing/error_messages.hpp"
#include "domain/algorithms/Solver.hpp"
#include "services/language/syntax/evaluation/ParameterList.hpp"
#include "services/messaging/ErrorMessage.hpp"
#include "foundation/NotSupportedException.hpp"
#include "foundation/definitions/AxisInputLanguage.hpp"
namespace aaj = axis::application::jobs;
namespace aal = axis::application::locators;
namespace aao = axis::application::output;
namespace aapps = axis::application::parsing::parsers;
namespace aafp = axis::application::factories::parsers;
namespace aapc = axis::application::parsing::core;
namespace adal = axis::domain::algorithms;
namespace asli = axis::services::language::iterators;
namespace aslse = axis::services::language::syntax::evaluation;
namespace aslp = axis::services::language::parsing;
namespace asmm = axis::services::messaging;
namespace afdf = axis::foundation::definitions;
// Enforce instantiation of this specialized template
template class aapps::StepParserTemplate<aal::SolverFactoryLocator,
aal::ClockworkFactoryLocator>;
template <class SolverFactoryLoc, class ClockworkFactoryLoc>
aapps::StepParserTemplate<SolverFactoryLoc, ClockworkFactoryLoc>::StepParserTemplate(
aafp::StepParserProvider& parentProvider,
const axis::String& stepName,
SolverFactoryLoc& solverLocator,
const axis::String& solverType,
real startTime, real endTime,
const aslse::ParameterList& solverParams,
aal::CollectorFactoryLocator& collectorLocator,
aal::WorkbookFactoryLocator& formatLocator) :
provider_(parentProvider), stepName_(stepName), solverLocator_(solverLocator),
collectorLocator_(collectorLocator), formatLocator_(formatLocator)
{
Init(solverType, startTime, endTime, solverParams);
}
template <class SolverFactoryLoc, class ClockworkFactoryLoc>
aapps::StepParserTemplate<SolverFactoryLoc, ClockworkFactoryLoc>::StepParserTemplate(
aafp::StepParserProvider& parentProvider,
const axis::String& stepName,
SolverFactoryLoc& solverLocator,
ClockworkFactoryLoc& clockworkLocator,
const axis::String& solverType,
real startTime, real endTime,
const aslse::ParameterList& solverParams,
const axis::String& clockworkType,
const aslse::ParameterList& clockworkParams,
aal::CollectorFactoryLocator& collectorLocator,
aal::WorkbookFactoryLocator& formatLocator) :
provider_(parentProvider), stepName_(stepName), solverLocator_(solverLocator),
collectorLocator_(collectorLocator), formatLocator_(formatLocator)
{
Init(solverType, startTime, endTime, solverParams);
isClockworkDeclared_ = true;
clockworkTypeName_ = clockworkType;
clockworkParams_ = &clockworkParams.Clone();
clockworkLocator_ = &clockworkLocator;
}
template <class SolverFactoryLoc, class ClockworkFactoryLoc>
void aapps::StepParserTemplate<SolverFactoryLoc, ClockworkFactoryLoc>::Init(
const axis::String& solverType, real startTime, real endTime,
const aslse::ParameterList& solverParams )
{
solverTypeName_ = solverType;
stepStartTime_ = startTime;
stepEndTime_ = endTime;
solverParams_ = &solverParams.Clone();
isNewReadRound_ = false;
dirtyStepBlock_ = false;
isClockworkDeclared_ = false;
clockworkParams_ = NULL;
clockworkLocator_ = NULL;
stepResultBucket_ = NULL;
nullParser_ = new axis::application::parsing::parsers::EmptyBlockParser(provider_);
}
template <class SolverFactoryLoc, class ClockworkFactoryLoc>
aapps::StepParserTemplate<SolverFactoryLoc, ClockworkFactoryLoc>::~StepParserTemplate( void )
{
delete nullParser_;
solverParams_->Destroy();
if (clockworkParams_ != NULL) clockworkParams_->Destroy();
clockworkParams_ = NULL;
solverParams_ = NULL;
}
template <class SolverFactoryLoc, class ClockworkFactoryLoc>
aapps::BlockParser& aapps::StepParserTemplate<SolverFactoryLoc, ClockworkFactoryLoc>::GetNestedContext(
const axis::String& contextName,
const aslse::ParameterList& paramList )
{
// if couldn't build a step block, we cannot provide nested
// contexts because it probably depends on the step begin
// defined
if (dirtyStepBlock_)
{ // throwing this exception shows that we don't know how to
// proceed with these blocks
throw axis::foundation::NotSupportedException();
}
// check if the requested context is the special context
// 'SNAPSHOT'
if (contextName == afdf::AxisInputLanguage::SnapshotsBlockName && paramList.IsEmpty())
{ // yes, it is; let's override the default behavior and trick
// the main parser giving him our own snapshot block parser
SnapshotParser& p = *new SnapshotParser(isNewReadRound_);
p.SetAnalysis(GetAnalysis());
return p;
}
else if (contextName == afdf::AxisInputLanguage::ResultCollectionSyntax.BlockName)
{ // no, this is the special context 'OUTPUT'
if (!ValidateCollectorBlockInformation(paramList))
{ // invalid, insufficient or unknown parameters
throw axis::foundation::NotSupportedException();
}
BlockParser& p = CreateResultCollectorParser(paramList);
p.SetAnalysis(GetAnalysis());
return p;
}
// any other non-special block registered
if (provider_.ContainsProvider(contextName, paramList))
{
aafp::BlockProvider& provider = provider_.GetProvider(contextName, paramList);
aapps::BlockParser& nestedContext = provider.BuildParser(contextName, paramList);
nestedContext.SetAnalysis(GetAnalysis());
return nestedContext;
}
// no provider found
throw axis::foundation::NotSupportedException();
}
template <class SolverFactoryLoc, class ClockworkFactoryLoc>
aslp::ParseResult aapps::StepParserTemplate<SolverFactoryLoc, ClockworkFactoryLoc>::Parse(
const asli::InputIterator& begin,
const asli::InputIterator& end )
{
return nullParser_->Parse(begin, end);
}
template <class SolverFactoryLoc, class ClockworkFactoryLoc>
void aapps::StepParserTemplate<SolverFactoryLoc, ClockworkFactoryLoc>::DoStartContext( void )
{
aapc::SymbolTable& st = GetParseContext().Symbols();
nullParser_->StartContext(GetParseContext());
// first, check if we are able to build the specified solver
bool canBuildSolver;
if (isClockworkDeclared_)
{
canBuildSolver = solverLocator_.CanBuild(solverTypeName_, *solverParams_,
stepStartTime_, stepEndTime_,
clockworkTypeName_, *clockworkParams_);
}
else
{
canBuildSolver = solverLocator_.CanBuild(solverTypeName_, *solverParams_,
stepStartTime_, stepEndTime_);
}
if (!canBuildSolver)
{ // huh?
GetParseContext().RegisterEvent(asmm::ErrorMessage(AXIS_ERROR_ID_UNKNOWN_SOLVER_TYPE,
AXIS_ERROR_MSG_UNKNOWN_SOLVER_TYPE));
dirtyStepBlock_ = true;
return;
}
// then, check if this is a new read round
axis::String symbolName = st.GenerateDecoratedName(aapc::SymbolTable::kAnalysisStep);
if (st.IsSymbolDefined(symbolName, aapc::SymbolTable::kAnalysisStep))
{ // yes, it is a new read round; we don't need to create a new solver and step objects
isNewReadRound_ = true;
}
st.DefineOrRefreshSymbol(symbolName, aapc::SymbolTable::kAnalysisStep);
// set analysis step to work on
aaj::StructuralAnalysis& analysis = GetAnalysis();
if (!isNewReadRound_)
{ // we need to create the new step
// build clockwork if we have to
adal::Solver *solver = NULL;
if (isClockworkDeclared_)
{
adal::Clockwork *clockwork = NULL;
if (clockworkLocator_->CanBuild(clockworkTypeName_, *clockworkParams_,
stepStartTime_, stepEndTime_))
{
clockwork = &clockworkLocator_->BuildClockwork(clockworkTypeName_,
*clockworkParams_,
stepStartTime_,
stepEndTime_);
}
else
{
// there is something wrong with supplied parameters
GetParseContext().RegisterEvent(
asmm::ErrorMessage(AXIS_ERROR_ID_UNKNOWN_TIME_CONTROL_ALGORITHM,
AXIS_ERROR_MSG_UNKNOWN_TIME_CONTROL_ALGORITHM));
dirtyStepBlock_ = true;
return;
}
solver = &solverLocator_.BuildSolver(solverTypeName_, *solverParams_,
stepStartTime_, stepEndTime_, *clockwork);
}
else
{
solver = &solverLocator_.BuildSolver(solverTypeName_, *solverParams_,
stepStartTime_, stepEndTime_);
}
stepResultBucket_ = new aao::ResultBucketConcrete();
aaj::AnalysisStep& step = aaj::AnalysisStep::Create(stepStartTime_, stepEndTime_,
*solver, *stepResultBucket_);
step.SetName(stepName_);
analysis.AddStep(step);
}
else
{ // since we are on a new parse round, retrieve result bucket that we created earlier
int stepIndex = GetParseContext().GetStepOnFocusIndex() + 1;
aaj::AnalysisStep *step = &GetAnalysis().GetStep(stepIndex);
stepResultBucket_ = static_cast<aao::ResultBucketConcrete *>(&step->GetResults());
GetParseContext().SetStepOnFocus(step);
GetParseContext().SetStepOnFocusIndex(stepIndex);
}
if (analysis.GetStepCount() == 1)
{ // we are parsing the first step
GetParseContext().SetStepOnFocus(&analysis.GetStep(0));
GetParseContext().SetStepOnFocusIndex(0);
}
else
{
int nextStepIndex = GetParseContext().GetStepOnFocusIndex() + 1;
GetParseContext().SetStepOnFocus(&analysis.GetStep(nextStepIndex));
GetParseContext().SetStepOnFocusIndex(nextStepIndex);
}
}
template <class SolverFactoryLoc, class ClockworkFactoryLoc>
bool aapps::StepParserTemplate<SolverFactoryLoc, ClockworkFactoryLoc>
::ValidateCollectorBlockInformation( const aslse::ParameterList& contextParams )
{
int paramsFound = 2;
if (!contextParams.IsDeclared(
afdf::AxisInputLanguage::ResultCollectionSyntax.FileNameParameterName)) return false;
if (!contextParams.IsDeclared(
afdf::AxisInputLanguage::ResultCollectionSyntax.FileFormatParameterName)) return false;
// check optional parameters
if (contextParams.IsDeclared(afdf::AxisInputLanguage::ResultCollectionSyntax.AppendParameterName))
{
String val = contextParams.GetParameterValue(
afdf::AxisInputLanguage::ResultCollectionSyntax.AppendParameterName).ToString();
val.to_lower_case().trim();
if (val != _T("yes") && val != _T("no") && val != _T("true") && val != _T("false"))
{
return false;
}
paramsFound++;
}
if (contextParams.IsDeclared(
afdf::AxisInputLanguage::ResultCollectionSyntax.FormatArgumentsParameterName))
{
aslse::ParameterValue& val = contextParams.GetParameterValue(
afdf::AxisInputLanguage::ResultCollectionSyntax.FormatArgumentsParameterName);
if (!val.IsArray()) return false;
// check if it is an array of parameters
try
{
aslse::ParameterList& test =
aslse::ParameterList::FromParameterArray(static_cast<aslse::ArrayValue&>(val));
test.Destroy();
}
catch (...)
{ // uh oh, it is not valid
return false;
}
paramsFound++;
}
return (contextParams.Count() == paramsFound);
}
template <class SolverFactoryLoc, class ClockworkFactoryLoc>
aapps::BlockParser& aapps::StepParserTemplate<SolverFactoryLoc, ClockworkFactoryLoc>
::CreateResultCollectorParser( const aslse::ParameterList& contextParams ) const
{
String fileName = contextParams.GetParameterValue(
afdf::AxisInputLanguage::ResultCollectionSyntax.FileNameParameterName).ToString();
String formatName = contextParams.GetParameterValue(
afdf::AxisInputLanguage::ResultCollectionSyntax.FileFormatParameterName).ToString();
const aslse::ParameterList *formatArgs = NULL;
bool append = false;
if (contextParams.IsDeclared(afdf::AxisInputLanguage::ResultCollectionSyntax.AppendParameterName))
{
String val = contextParams.GetParameterValue(
afdf::AxisInputLanguage::ResultCollectionSyntax.AppendParameterName).ToString();
val.to_lower_case().trim();
append = (val != _T("yes") && val != _T("true"));
}
if (contextParams.IsDeclared(
afdf::AxisInputLanguage::ResultCollectionSyntax.FormatArgumentsParameterName))
{
aslse::ParameterValue& val = contextParams.GetParameterValue(
afdf::AxisInputLanguage::ResultCollectionSyntax.FormatArgumentsParameterName);
formatArgs = &aslse::ParameterList::FromParameterArray(static_cast<aslse::ArrayValue&>(val));
}
else
{
formatArgs = &aslse::ParameterList::Empty.Clone();
}
aapps::BlockParser *parser = new aapps::ResultCollectorParser(formatLocator_, collectorLocator_,
*stepResultBucket_, fileName,
formatName, *formatArgs, append);
formatArgs->Destroy();
return *parser;
}
| 42.285714
| 104
| 0.678089
|
renato-yuzup
|
ade82238899ca28b846453ac02501936e158abb7
| 2,088
|
cpp
|
C++
|
ClubDetailsDlg.cpp
|
chrisoldwood/FCManager
|
f26aad68e572d21d3cb27d1fc285143b6c3ee848
|
[
"MIT"
] | 1
|
2017-08-17T15:33:33.000Z
|
2017-08-17T15:33:33.000Z
|
ClubDetailsDlg.cpp
|
chrisoldwood/FCManager
|
f26aad68e572d21d3cb27d1fc285143b6c3ee848
|
[
"MIT"
] | null | null | null |
ClubDetailsDlg.cpp
|
chrisoldwood/FCManager
|
f26aad68e572d21d3cb27d1fc285143b6c3ee848
|
[
"MIT"
] | null | null | null |
/******************************************************************************
** (C) Chris Oldwood
**
** MODULE: CLUBDETAILSDLG.CPP
** COMPONENT: The Application.
** DESCRIPTION: CClubDetailsDlg class definition.
**
*******************************************************************************
*/
#include "Common.hpp"
#include "ClubDetailsDlg.hpp"
#include "ClubDetails.hpp"
/******************************************************************************
** Method: Constructor.
**
** Description: .
**
** Parameters: None.
**
** Returns: Nothing.
**
*******************************************************************************
*/
CClubDetailsDlg::CClubDetailsDlg(CRow& oDetails) : CDialog(IDD_CLUB_DETAILS)
, m_oDetails(oDetails)
{
DEFINE_CTRL_TABLE
CTRL(IDC_CLUB_NAME, &m_ebName)
CTRL(IDC_SEASON, &m_ebSeason)
CTRL(IDC_LEAGUE_NAME, &m_ebLeague)
END_CTRL_TABLE
}
/******************************************************************************
** Method: OnInitDialog()
**
** Description: Initialise the dialog.
**
** Parameters: None.
**
** Returns: Nothing.
**
*******************************************************************************
*/
void CClubDetailsDlg::OnInitDialog()
{
// Initialise the controls.
m_ebName.Text(m_oDetails[CClubDetails::NAME]);
m_ebName.TextLimit(CClubDetails::NAME_LEN);
m_ebSeason.Text(m_oDetails[CClubDetails::SEASON]);
m_ebSeason.TextLimit(CClubDetails::SEASON_LEN);
m_ebLeague.Text(m_oDetails[CClubDetails::LEAGUE]);
m_ebLeague.TextLimit(CClubDetails::LEAGUE_LEN);
}
/******************************************************************************
** Method: OnOk()
**
** Description: Validate the data and close the dialog.
**
** Parameters: None.
**
** Returns: true or false.
**
*******************************************************************************
*/
bool CClubDetailsDlg::OnOk()
{
// Fetch data from the controls.
m_oDetails[CClubDetails::NAME] = m_ebName.Text();
m_oDetails[CClubDetails::SEASON] = m_ebSeason.Text();
m_oDetails[CClubDetails::LEAGUE] = m_ebLeague.Text();
return true;
}
| 25.156627
| 79
| 0.499042
|
chrisoldwood
|
ade991857f9ce165f7166cae00134638ce25675a
| 7,501
|
cpp
|
C++
|
openstudiocore/src/energyplus/Test/GeneratorMicroTurbine_GTest.cpp
|
hongyuanjia/OpenStudio
|
6cc52f1b66c069cf13f2b6ca2a0cc3c137c37cf0
|
[
"MIT"
] | 1
|
2019-04-21T15:38:54.000Z
|
2019-04-21T15:38:54.000Z
|
openstudiocore/src/energyplus/Test/GeneratorMicroTurbine_GTest.cpp
|
hongyuanjia/OpenStudio
|
6cc52f1b66c069cf13f2b6ca2a0cc3c137c37cf0
|
[
"MIT"
] | null | null | null |
openstudiocore/src/energyplus/Test/GeneratorMicroTurbine_GTest.cpp
|
hongyuanjia/OpenStudio
|
6cc52f1b66c069cf13f2b6ca2a0cc3c137c37cf0
|
[
"MIT"
] | 1
|
2019-07-18T06:52:29.000Z
|
2019-07-18T06:52:29.000Z
|
/**********************************************************************
* Copyright (c) 2008-2016, Alliance for Sustainable Energy.
* All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**********************************************************************/
#include <gtest/gtest.h>
#include "EnergyPlusFixture.hpp"
#include "../ErrorFile.hpp"
#include "../ForwardTranslator.hpp"
#include "../ReverseTranslator.hpp"
// Objects of interest
#include "../../model/GeneratorMicroTurbine.hpp"
#include "../../model/GeneratorMicroTurbine_Impl.hpp"
#include "../../model/GeneratorMicroTurbineHeatRecovery.hpp"
#include "../../model/GeneratorMicroTurbineHeatRecovery_Impl.hpp"
// Needed resources
#include "../../model/PlantLoop.hpp"
#include "../../model/PlantLoop_Impl.hpp"
#include "../../model/Node.hpp"
#include "../../model/Node_Impl.hpp"
#include "../../model/Curve.hpp"
#include "../../model/Curve_Impl.hpp"
#include "../../model/CurveBiquadratic.hpp"
#include "../../model/CurveBiquadratic_Impl.hpp"
#include "../../model/CurveCubic.hpp"
#include "../../model/CurveCubic_Impl.hpp"
#include "../../model/CurveQuadratic.hpp"
#include "../../model/CurveQuadratic_Impl.hpp"
#include "../../model/StraightComponent.hpp"
#include "../../model/StraightComponent_Impl.hpp"
#include "../../model/Schedule.hpp"
#include "../../model/Schedule_Impl.hpp"
// For testing PlantEquipOperation
#include "../../model/WaterHeaterMixed.hpp"
#include "../../model/WaterHeaterMixed_Impl.hpp"
#include "../../model/PlantEquipmentOperationHeatingLoad.hpp"
#include "../../model/PlantEquipmentOperationHeatingLoad_Impl.hpp"
#include "../../model/ElectricLoadCenterDistribution.hpp"
#include "../../model/ElectricLoadCenterDistribution_Impl.hpp"
// IDF FieldEnums
#include <utilities/idd/Generator_MicroTurbine_FieldEnums.hxx>
// #include <utilities/idd/OS_Generator_MicroTurbine_HeatRecovery_FieldEnums.hxx>
#include <utilities/idd/PlantEquipmentList_FieldEnums.hxx>
#include <utilities/idd/IddEnums.hxx>
#include <utilities/idd/IddFactory.hxx>
// Misc
#include "../../model/Version.hpp"
#include "../../model/Version_Impl.hpp"
#include "../../utilities/core/Optional.hpp"
#include "../../utilities/core/Checksum.hpp"
#include "../../utilities/core/UUID.hpp"
#include "../../utilities/sql/SqlFile.hpp"
#include "../../utilities/idf/IdfFile.hpp"
#include "../../utilities/idf/IdfObject.hpp"
#include "../../utilities/idf/IdfExtensibleGroup.hpp"
#include <boost/algorithm/string/predicate.hpp>
#include <QThread>
#include <resources.hxx>
#include <sstream>
#include <vector>
// Debug
#include "../../utilities/core/Logger.hpp"
using namespace openstudio::energyplus;
using namespace openstudio::model;
using namespace openstudio;
/**
* Tests whether the ForwarTranslator will handle the name of the GeneratorMicroTurbine correctly in the PlantEquipmentOperationHeatingLoad
**/
TEST_F(EnergyPlusFixture,ForwardTranslatorGeneratorMicroTurbine_ELCD_PlantLoop)
{
// TODO: Temporarily output the Log in the console with the Trace (-3) level
// for debug
// openstudio::Logger::instance().standardOutLogger().enable();
// openstudio::Logger::instance().standardOutLogger().setLogLevel(Trace);
// Create a model, a mchp, a mchpHR, a plantLoop and an electricalLoadCenter
Model model;
GeneratorMicroTurbine mchp = GeneratorMicroTurbine(model);
GeneratorMicroTurbineHeatRecovery mchpHR = GeneratorMicroTurbineHeatRecovery(model, mchp);
ASSERT_EQ(mchpHR, mchp.generatorMicroTurbineHeatRecovery().get());
PlantLoop plantLoop(model);
// Add a supply branch for the mchpHR
ASSERT_TRUE(plantLoop.addSupplyBranchForComponent(mchpHR));
// Create a WaterHeater:Mixed
WaterHeaterMixed waterHeater(model);
// Add it on the same branch as the chpHR, right after it
Node mchpHROutletNode = mchpHR.outletModelObject()->cast<Node>();
ASSERT_TRUE(waterHeater.addToNode(mchpHROutletNode));
// Create a plantEquipmentOperationHeatingLoad
PlantEquipmentOperationHeatingLoad operation(model);
operation.setName(plantLoop.name().get() + " PlantEquipmentOperationHeatingLoad");
ASSERT_TRUE(plantLoop.setPlantEquipmentOperationHeatingLoad(operation));
ASSERT_TRUE(operation.addEquipment(mchpHR));
ASSERT_TRUE(operation.addEquipment(waterHeater));
// Create an ELCD
ElectricLoadCenterDistribution elcd = ElectricLoadCenterDistribution(model);
elcd.setName("Capstone C65 ELCD");
elcd.setElectricalBussType("AlternatingCurrent");
elcd.addGenerator(mchp);
// Forward Translates
ForwardTranslator forwardTranslator;
Workspace workspace = forwardTranslator.translateModel(model);
EXPECT_EQ(0u, forwardTranslator.errors().size());
ASSERT_EQ(1u, workspace.getObjectsByType(IddObjectType::WaterHeater_Mixed).size());
ASSERT_EQ(1u, workspace.getObjectsByType(IddObjectType::ElectricLoadCenter_Distribution).size());
// The MicroTurbine should have been forward translated since there is an ELCD
WorkspaceObjectVector microTurbineObjects(workspace.getObjectsByType(IddObjectType::Generator_MicroTurbine));
EXPECT_EQ(1u, microTurbineObjects.size());
// Check that the HR nodes have been set
WorkspaceObject idf_mchp(microTurbineObjects[0]);
EXPECT_EQ(mchpHR.inletModelObject()->name().get(), idf_mchp.getString(Generator_MicroTurbineFields::HeatRecoveryWaterInletNodeName).get());
EXPECT_EQ(mchpHR.outletModelObject()->name().get(), idf_mchp.getString(Generator_MicroTurbineFields::HeatRecoveryWaterOutletNodeName).get());
OptionalWorkspaceObject idf_operation(workspace.getObjectByTypeAndName(IddObjectType::PlantEquipmentOperation_HeatingLoad,*(operation.name())));
ASSERT_TRUE(idf_operation);
// Get the extensible
ASSERT_EQ(1u, idf_operation->numExtensibleGroups());
// IdfExtensibleGroup eg = idf_operation.getExtensibleGroup(0);
// idf_operation.targets[0]
ASSERT_EQ(1u, idf_operation->targets().size());
WorkspaceObject plantEquipmentList(idf_operation->targets()[0]);
ASSERT_EQ(2u, plantEquipmentList.extensibleGroups().size());
IdfExtensibleGroup eg(plantEquipmentList.extensibleGroups()[0]);
ASSERT_EQ("Generator:MicroTurbine", eg.getString(PlantEquipmentListExtensibleFields::EquipmentObjectType).get());
// This fails
EXPECT_EQ(mchp.name().get(), eg.getString(PlantEquipmentListExtensibleFields::EquipmentName).get());
IdfExtensibleGroup eg2(plantEquipmentList.extensibleGroups()[1]);
ASSERT_EQ("WaterHeater:Mixed", eg2.getString(PlantEquipmentListExtensibleFields::EquipmentObjectType).get());
EXPECT_EQ(waterHeater.name().get(), eg2.getString(PlantEquipmentListExtensibleFields::EquipmentName).get());
model.save(toPath("./ForwardTranslatorGeneratorMicroTurbine_ELCD_PlantLoop.osm"), true);
workspace.save(toPath("./ForwardTranslatorGeneratorMicroTurbine_ELCD_PlantLoop.idf"), true);
}
| 41.441989
| 146
| 0.758299
|
hongyuanjia
|
aded0ee28d9c261cc7caadeac6e5b774acc35e07
| 4,393
|
cpp
|
C++
|
hardware/libraries/MD/MDRecorder.cpp
|
anupam19/mididuino
|
27c30f586a8d61381309434ed05b4958c7727402
|
[
"BSD-3-Clause"
] | null | null | null |
hardware/libraries/MD/MDRecorder.cpp
|
anupam19/mididuino
|
27c30f586a8d61381309434ed05b4958c7727402
|
[
"BSD-3-Clause"
] | null | null | null |
hardware/libraries/MD/MDRecorder.cpp
|
anupam19/mididuino
|
27c30f586a8d61381309434ed05b4958c7727402
|
[
"BSD-3-Clause"
] | null | null | null |
#include <inttypes.h>
#include "WProgram.h"
#include "helpers.h"
#include "MDRecorder.h"
MDRecorderClass::MDRecorderClass() {
recording = false;
playing = false;
recordLength = 0;
playPtr = NULL;
looping = true;
md_playback_phase = MD_PLAYBACK_NONE;
muted = false;
}
void MDRecorderClass::setup() {
MidiClock.addOn16Callback(this, (midi_clock_callback_ptr_t)&MDRecorderClass::on16Callback);
}
void MDRecorderClass::startRecord(uint8_t length, uint8_t boundary) {
if (playing) {
stopPlayback();
}
USE_LOCK();
SET_LOCK();
eventList.freeAll();
// start16th = MidiClock.div16th_counter;
rec16th_counter = 0;
if (boundary != 0) {
recordingBoundary = boundary;
recordingTriggered = true;
recording = false;
} else {
recording = true;
}
recordLength = length;
MidiUart.addOnNoteOnCallback(this, (midi_callback_ptr_t)&MDRecorderClass::onNoteOnCallback);
MidiUart.addOnControlChangeCallback(this, (midi_callback_ptr_t)&MDRecorderClass::onCCCallback);
CLEAR_LOCK();
}
void MDRecorderClass::stopRecord() {
USE_LOCK();
SET_LOCK();
recording = false;
MidiUart.removeOnNoteOnCallback(this);
MidiUart.removeOnControlChangeCallback(this);
CLEAR_LOCK();
eventList.reverse();
}
void MDRecorderClass::startMDPlayback(uint8_t boundary) {
md_playback_phase = MD_PLAYBACK_HITS;
startPlayback(boundary);
}
void MDRecorderClass::startPlayback(uint8_t boundary) {
if (recording) {
stopRecord();
}
USE_LOCK();
SET_LOCK();
play16th_counter = 0;
if (boundary != 0) {
playbackBoundary = boundary;
playbackTriggered = true;
playing = false;
} else {
playing = true;
}
playPtr = eventList.head;
CLEAR_LOCK();
}
void MDRecorderClass::stopPlayback() {
USE_LOCK();
SET_LOCK();
playing = false;
CLEAR_LOCK();
}
void MDRecorderClass::onNoteOnCallback(uint8_t *msg) {
USE_LOCK();
SET_LOCK();
uint8_t pos = rec16th_counter;
CLEAR_LOCK();
ListElt<md_recorder_event_t> *elt = eventList.pool.alloc();
if (elt != NULL) {
elt->obj.channel = msg[0] & 0xF;
elt->obj.pitch = msg[1];
elt->obj.value = msg[2];
elt->obj.step = pos;
eventList.push(elt);
// GUI.setLine(GUI.LINE2);
// GUI.put_value(1, pos);
}
}
void MDRecorderClass::onCCCallback(uint8_t *msg) {
USE_LOCK();
SET_LOCK();
uint8_t pos = rec16th_counter;
CLEAR_LOCK();
ListElt<md_recorder_event_t> *elt = eventList.pool.alloc();
if (elt != NULL) {
elt->obj.channel = (msg[0] & 0xF) | 0x80;
elt->obj.pitch = msg[1];
elt->obj.value = msg[2];
elt->obj.step = pos;
eventList.push(elt);
}
}
void MDRecorderClass::on16Callback() {
USE_LOCK();
SET_LOCK();
if (recording) {
if (++rec16th_counter >= recordLength) {
stopRecord();
}
}
if (recordingTriggered) {
if ((MidiClock.div16th_counter % recordingBoundary) == 0) {
recordingTriggered = false;
recording = true;
}
}
if (playbackTriggered) {
if ((MidiClock.div16th_counter % playbackBoundary) == 0) {
playbackTriggered = false;
playing = true;
}
}
if (playing) {
while ((playPtr != NULL) && (playPtr->obj.step <= play16th_counter)) {
if (!muted) {
if (playPtr->obj.channel & 0x80) {
if (md_playback_phase == MD_PLAYBACK_NONE) {
MidiUart.sendCC(playPtr->obj.channel & 0xF, playPtr->obj.pitch, playPtr->obj.value);
} else if (md_playback_phase == MD_PLAYBACK_CCS) {
MidiUart.sendCC(playPtr->obj.channel & 0xF, playPtr->obj.pitch, playPtr->obj.value - 5);
delayMicroseconds(100);
MidiUart.sendCC(playPtr->obj.channel & 0xF, playPtr->obj.pitch, playPtr->obj.value);
}
} else {
if (md_playback_phase != MD_PLAYBACK_CCS) {
MidiUart.sendNoteOn(playPtr->obj.channel, playPtr->obj.pitch, playPtr->obj.value);
}
}
}
playPtr = playPtr->next;
}
if (++play16th_counter >= recordLength) {
if (md_playback_phase == MD_PLAYBACK_HITS) {
md_playback_phase = MD_PLAYBACK_CCS;
play16th_counter = 0;
playing = true;
playPtr = eventList.head;
return;
} else if (md_playback_phase == MD_PLAYBACK_CCS) {
md_playback_phase = MD_PLAYBACK_NONE;
}
if (looping) {
play16th_counter = 0;
playing = true;
playPtr = eventList.head;
} else {
stopPlayback();
}
}
}
CLEAR_LOCK();
}
MDRecorderClass MDRecorder;
| 22.528205
| 97
| 0.660369
|
anupam19
|
adeffceeb96cee1cc8a934082009d3dcbcc471dc
| 2,709
|
cpp
|
C++
|
aws-cpp-sdk-opsworks/source/model/AppAttributesKeys.cpp
|
lintonv/aws-sdk-cpp
|
15e19c265ffce19d2046b18aa1b7307fc5377e58
|
[
"Apache-2.0"
] | 1
|
2022-02-10T08:06:54.000Z
|
2022-02-10T08:06:54.000Z
|
aws-cpp-sdk-opsworks/source/model/AppAttributesKeys.cpp
|
lintonv/aws-sdk-cpp
|
15e19c265ffce19d2046b18aa1b7307fc5377e58
|
[
"Apache-2.0"
] | 1
|
2022-01-03T23:59:37.000Z
|
2022-01-03T23:59:37.000Z
|
aws-cpp-sdk-opsworks/source/model/AppAttributesKeys.cpp
|
ravindra-wagh/aws-sdk-cpp
|
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
|
[
"Apache-2.0"
] | 1
|
2021-12-30T04:25:33.000Z
|
2021-12-30T04:25:33.000Z
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/opsworks/model/AppAttributesKeys.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>
using namespace Aws::Utils;
namespace Aws
{
namespace OpsWorks
{
namespace Model
{
namespace AppAttributesKeysMapper
{
static const int DocumentRoot_HASH = HashingUtils::HashString("DocumentRoot");
static const int RailsEnv_HASH = HashingUtils::HashString("RailsEnv");
static const int AutoBundleOnDeploy_HASH = HashingUtils::HashString("AutoBundleOnDeploy");
static const int AwsFlowRubySettings_HASH = HashingUtils::HashString("AwsFlowRubySettings");
AppAttributesKeys GetAppAttributesKeysForName(const Aws::String& name)
{
int hashCode = HashingUtils::HashString(name.c_str());
if (hashCode == DocumentRoot_HASH)
{
return AppAttributesKeys::DocumentRoot;
}
else if (hashCode == RailsEnv_HASH)
{
return AppAttributesKeys::RailsEnv;
}
else if (hashCode == AutoBundleOnDeploy_HASH)
{
return AppAttributesKeys::AutoBundleOnDeploy;
}
else if (hashCode == AwsFlowRubySettings_HASH)
{
return AppAttributesKeys::AwsFlowRubySettings;
}
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
overflowContainer->StoreOverflow(hashCode, name);
return static_cast<AppAttributesKeys>(hashCode);
}
return AppAttributesKeys::NOT_SET;
}
Aws::String GetNameForAppAttributesKeys(AppAttributesKeys enumValue)
{
switch(enumValue)
{
case AppAttributesKeys::DocumentRoot:
return "DocumentRoot";
case AppAttributesKeys::RailsEnv:
return "RailsEnv";
case AppAttributesKeys::AutoBundleOnDeploy:
return "AutoBundleOnDeploy";
case AppAttributesKeys::AwsFlowRubySettings:
return "AwsFlowRubySettings";
default:
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
}
return {};
}
}
} // namespace AppAttributesKeysMapper
} // namespace Model
} // namespace OpsWorks
} // namespace Aws
| 31.870588
| 100
| 0.63529
|
lintonv
|
adf0c68c4d4e4dff66ea7a9388d9a254bcb27d32
| 375
|
cpp
|
C++
|
src/libgraphic/src/message/entity/DestroyGraphicEntityMessage.cpp
|
SimonPiCarter/GameEngine
|
10d366bd37d202a5a22eb504b2a2dd9a49669dc8
|
[
"Apache-2.0"
] | null | null | null |
src/libgraphic/src/message/entity/DestroyGraphicEntityMessage.cpp
|
SimonPiCarter/GameEngine
|
10d366bd37d202a5a22eb504b2a2dd9a49669dc8
|
[
"Apache-2.0"
] | 15
|
2021-05-18T14:16:03.000Z
|
2021-06-17T19:36:32.000Z
|
src/libgraphic/src/message/entity/DestroyGraphicEntityMessage.cpp
|
SimonPiCarter/GameEngine
|
10d366bd37d202a5a22eb504b2a2dd9a49669dc8
|
[
"Apache-2.0"
] | null | null | null |
#include "DestroyGraphicEntityMessage.h"
#include "message/GraphicMessageHandler.h"
DestroyGraphicEntityMessage::DestroyGraphicEntityMessage(GraphicEntity * entity_p, bool delete_p)
: GraphicMessage("")
, _entity(entity_p)
, _delete(delete_p)
{}
void DestroyGraphicEntityMessage::visit(GraphicMessageHandler &handler_p)
{
handler_p.visitDestroyGraphicEntity(*this);
}
| 25
| 97
| 0.816
|
SimonPiCarter
|
adf2f68c4db3313d196b8d7dd7fd4b58bfd933e7
| 1,253
|
cpp
|
C++
|
src/option.cpp
|
jserot/rfsm-gui
|
4eee507ae6e06088fbc66fd2383d5533af49090b
|
[
"MIT"
] | null | null | null |
src/option.cpp
|
jserot/rfsm-gui
|
4eee507ae6e06088fbc66fd2383d5533af49090b
|
[
"MIT"
] | null | null | null |
src/option.cpp
|
jserot/rfsm-gui
|
4eee507ae6e06088fbc66fd2383d5533af49090b
|
[
"MIT"
] | null | null | null |
/**********************************************************************/
/* */
/* This file is part of the RFSM package */
/* */
/* Copyright (c) 2018-present, Jocelyn SEROT. All rights reserved. */
/* */
/* This source code is licensed under the license found in the */
/* LICENSE file in the root directory of this source tree. */
/* */
/**********************************************************************/
#include "option.h"
AppOption::AppOption(QString _category, QString _name, Opt_kind _kind, QString _desc) {
category = _category;
name = _name;
kind = _kind;
desc = _desc;
switch ( kind ) {
case UnitOpt:
checkbox = new QCheckBox();
val = NULL;
break;
case StringOpt:
checkbox = NULL;
val = new QLineEdit();
//val->setFixedSize(100,20);
case IntOpt:
checkbox = NULL;
val = new QLineEdit();
//val->setFixedSize(100,20);
break;
}
}
| 35.8
| 88
| 0.381484
|
jserot
|
adfa2a6509c6eb97a30e4c8cf91e4d188ed88b0c
| 952
|
cpp
|
C++
|
914C.cpp
|
basuki57/Codeforces
|
5227c3deecf13d90e5ea45dab0dfc16b44bd028c
|
[
"MIT"
] | null | null | null |
914C.cpp
|
basuki57/Codeforces
|
5227c3deecf13d90e5ea45dab0dfc16b44bd028c
|
[
"MIT"
] | null | null | null |
914C.cpp
|
basuki57/Codeforces
|
5227c3deecf13d90e5ea45dab0dfc16b44bd028c
|
[
"MIT"
] | 2
|
2020-10-03T04:52:14.000Z
|
2020-10-03T05:19:12.000Z
|
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
ll c[1010][1010], mod = 1e9 + 7;
void comb(){
c[0][0] = 1;
for(ll i = 1; i < 1010; ++i){
c[i][0] = 1;
for(ll j = 1; j < 1010; ++j) c[i][j] = (c[i-1][j-1] + c[i-1][j])%mod;
}
}
void solve(){
comb();
string s;
cin >> s;
ll k;
cin >> k;
if(!k){
cout << 1 << endl; return;
}
ll f[1010] = {0}, cnt = 0, ans = 0, n = s.size();
if(k == 1){
cout << n-1 << endl; return;
}
for(ll i = 2; i <= n; ++i) f[i] = f[__builtin_popcount(i)] + 1;
for(ll i = 0; i < n; i++) if(s[i] == '1'){
for(ll j = (i==0); j < n-i; ++j) ans = (ans + c[n-i-1][j]*(f[cnt + j] == k-1))%mod;
cnt++;
}
ans = (ans + (f[cnt] == k-1))%mod;
cout << ans << endl;
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0);
// int t;cin>>t;for(int i = 0 ;i<t;i++)
solve();
return 0;
}
| 21.636364
| 91
| 0.422269
|
basuki57
|
adfc689d5fd35369ad097c09dc98495f9ec30835
| 736
|
cpp
|
C++
|
faculdade2020Fatec/lista2/ex4.cpp
|
DouSam/AnyLiteryAnyThingIDo
|
48313b1dd0534df15c6b024f2f2118a76bd2ac0a
|
[
"MIT"
] | 1
|
2018-07-13T23:59:34.000Z
|
2018-07-13T23:59:34.000Z
|
faculdade2020Fatec/lista2/ex4.cpp
|
CoalaDrogado69/AnyLiteryAnyThingIDo
|
48313b1dd0534df15c6b024f2f2118a76bd2ac0a
|
[
"MIT"
] | null | null | null |
faculdade2020Fatec/lista2/ex4.cpp
|
CoalaDrogado69/AnyLiteryAnyThingIDo
|
48313b1dd0534df15c6b024f2f2118a76bd2ac0a
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
int main()
{
int vetor[10];
int pares = 0;
//Para cada posição eu irei pedir um valor para o usuário
for (int i = 0; i < 10; i++)
{
cout << "Digite um valor para posição " << i << endl;
cin >> vetor[i];
};
//Para cada posição irei analisar se essa é par e apenas exibir caso seja.
for (int i = 0; i < 10; i++)
{
if (vetor[i] % 2 == 0)
{
cout << "Elemento " << i << " é par" << endl;
cout << "Valor: " << vetor[i] << endl;
//Somando caso seja par.
pares++;
};
};
cout << "Total de elementos pares: " << pares;
return 0;
}
| 22.30303
| 79
| 0.45788
|
DouSam
|
adfc7e4e1421cd2e7252b8bd45f1a168a4d124e3
| 5,476
|
cpp
|
C++
|
Compiler/src/AST.cpp
|
BrandonKi/ARCANE
|
425d481610125ba89bbe36e4c16b680d6e2b7868
|
[
"MIT"
] | 7
|
2020-06-24T03:32:36.000Z
|
2022-01-15T03:59:56.000Z
|
Compiler/src/AST.cpp
|
BrandonKi/ARCANE
|
425d481610125ba89bbe36e4c16b680d6e2b7868
|
[
"MIT"
] | 2
|
2021-06-25T02:18:41.000Z
|
2021-06-25T18:59:05.000Z
|
Compiler/src/AST.cpp
|
BrandonKi/ARCANE
|
425d481610125ba89bbe36e4c16b680d6e2b7868
|
[
"MIT"
] | 1
|
2021-06-25T17:43:20.000Z
|
2021-06-25T17:43:20.000Z
|
#include "AST.h"
extern ErrorHandler error_log;
extern TypeManager type_manager;
AST::AST() {
PROFILE();
}
AST::~AST() {
PROFILE();
}
//FIXME fix all of this absolute trash
// at the moment we are making copies of the vectors and moving some and none of it is good
// FIXME use allocator
[[nodiscard]] Project* AST::new_project_node(const SourcePos pos, std::vector<File*>& files) {
PROFILE();
return new Project{{pos}, files};
}
[[nodiscard]] File* AST::new_file_node(
const SourcePos pos,
const std::string name,
std::vector<Import*>& imports,
std::vector<Decl*>& decls,
std::vector<Function*>& functions,
const bool is_main
) {
PROFILE();
return new File{{pos}, name, std::move(imports), std::move(decls), std::move(functions), is_main};
}
[[nodiscard]] Import* AST::new_import_node(const SourcePos pos, std::string& id, std::string& filename) {
PROFILE();
return new Import{{pos}, id, filename};
}
[[nodiscard]] Function* AST::new_function_node(const SourcePos pos, std::string& id, std::vector<Arg>& fn_args, type_handle type, Block* body, const bool is_main) {
PROFILE();
return new Function{{pos}, id, fn_args, type, body, is_main };
}
[[nodiscard]] Block* AST::new_block_node(const SourcePos pos, std::vector<Statement*>& statements) {
PROFILE();
return new Block{{pos}, statements};
}
[[nodiscard]] WhileStmnt* AST::new_while_node(const SourcePos pos, Expr* expr, Block* block) {
PROFILE();
return new WhileStmnt{{pos}, expr, block};
}
[[nodiscard]] ForStmnt* AST::new_for_node(const SourcePos pos, Decl* decl, Expr* expr1, Expr* expr2, Block* block) {
PROFILE();
return new ForStmnt{{pos}, decl, expr1, expr2, block};
}
[[nodiscard]] IfStmnt* AST::new_if_node(const SourcePos pos, Expr* expr, Block* block, Block* else_stmnt) {
PROFILE();
return new IfStmnt{{pos}, expr, block, else_stmnt};
}
[[nodiscard]] RetStmnt* AST::new_ret_node(const SourcePos pos, Expr* expr) {
PROFILE();
return new RetStmnt{{pos}, expr};
}
[[nodiscard]] Statement* AST::new_statement_node_while(const SourcePos pos, WhileStmnt* while_stmnt) {
PROFILE();
auto *ptr = new Statement{ {pos}, WHILE};
ptr->while_stmnt = while_stmnt;
return ptr;
}
[[nodiscard]] Statement* AST::new_statement_node_for(const SourcePos pos, ForStmnt* for_stmnt) {
PROFILE();
auto *ptr = new Statement{ {pos}, FOR};
ptr->for_stmnt = for_stmnt;
return ptr;
}
[[nodiscard]] Statement* AST::new_statement_node_if(const SourcePos pos, IfStmnt* if_stmnt) {
PROFILE();
auto *ptr = new Statement{ {pos}, IF};
ptr->if_stmnt = if_stmnt;
return ptr;
}
[[nodiscard]] Statement* AST::new_statement_node_ret(const SourcePos pos, RetStmnt* ret_stmnt) {
PROFILE();
auto *ptr = new Statement{ {pos}, RET};
ptr->ret_stmnt = ret_stmnt;
return ptr;
}
Statement* AST::new_statement_node_decl(const SourcePos pos, Decl* decl) {
PROFILE();
auto *ptr = new Statement{ {pos}, DECLARATION};
ptr->decl = decl;
return ptr;
}
[[nodiscard]] Statement* AST::new_statement_node_expr(const SourcePos pos, Expr* expr) {
PROFILE();
auto *ptr = new Statement { {pos}, EXPRESSION};
ptr->expr = expr;
return ptr;
}
[[nodiscard]] Expr* AST::new_expr_node_int_literal(const SourcePos pos, const i64 int_literal, type_handle type) {
PROFILE();
auto *ptr = new Expr{{pos}, EXPR_INT_LIT, type};
ptr->int_literal.val = int_literal;
return ptr;
}
[[nodiscard]] Expr* AST::new_expr_node_float_literal(const SourcePos pos, const f64 float_literal, type_handle type) {
PROFILE();
auto *ptr = new Expr{{pos}, EXPR_FLOAT_LIT, type};
ptr->float_literal.val = float_literal;
return ptr;
}
[[nodiscard]] Expr* AST::new_expr_node_string_literal(const SourcePos pos, std::string& string_literal, type_handle type) {
PROFILE();
auto *ptr = new Expr{{pos}, EXPR_STRING_LIT, type};
ptr->string_literal.val = new std::string(string_literal);
return ptr;
}
[[nodiscard]] Expr* AST::new_expr_node_variable(const SourcePos pos, std::string& id, type_handle type) {
PROFILE();
auto *ptr = new Expr{{pos}, EXPR_ID, type};
// FIXME allocator
ptr->id.val = new std::string(id);
return ptr;
}
[[nodiscard]] Expr* AST::new_expr_node_fn_call(const SourcePos pos, std::string& id, u32 argc, Expr** argv, type_handle type) {
PROFILE();
auto *ptr = new Expr{{pos}, EXPR_FN_CALL, type};
// FIXME allocator
ptr->fn_call.val = new std::string(id);
ptr->fn_call.argc = argc;
ptr->fn_call.args = argv;
return ptr;
}
[[nodiscard]] Expr* AST::new_expr_node_bin_expr(const SourcePos pos, const TokenKind op, Expr* left, Expr* right, type_handle type) {
PROFILE();
auto *ptr = new Expr{ {pos}, EXPR_BIN, type};
ptr->binary_expr.op = op;
ptr->binary_expr.left = left;
ptr->binary_expr.right = right;
return ptr;
}
[[nodiscard]] Expr* AST::new_expr_node_unary_expr(const SourcePos pos, const TokenKind op, Expr* expr, type_handle type) {
PROFILE();
auto* ptr = new Expr{ {pos}, EXPR_UNARY, type};
ptr->unary_expr.op = op;
ptr->unary_expr.expr = expr;
return ptr;
}
[[nodiscard]] Decl* AST::new_decl_node(const SourcePos pos, std::string& id, const type_handle type, Expr* val) {
PROFILE();
// FIXME allocator
auto* ptr = new Decl{ {pos}, new std::string(id), type, val };
return ptr;
}
| 31.471264
| 164
| 0.669467
|
BrandonKi
|
adfd0ca913de67a10322e8feb232510d30d79519
| 2,588
|
cpp
|
C++
|
Procedural Programming I/tema10.cpp
|
dindareanualin/School-Work
|
3ce04376e0a22d4c709303540a91ba17d0b63096
|
[
"MIT"
] | null | null | null |
Procedural Programming I/tema10.cpp
|
dindareanualin/School-Work
|
3ce04376e0a22d4c709303540a91ba17d0b63096
|
[
"MIT"
] | null | null | null |
Procedural Programming I/tema10.cpp
|
dindareanualin/School-Work
|
3ce04376e0a22d4c709303540a91ba17d0b63096
|
[
"MIT"
] | null | null | null |
//10. Given an n lines, m columns matrix, write an algorithm which will
// first display the matrix with each line sorted in ascending order,
//then display the matrix with each column sorted in ascending order.
#include <iostream>
using namespace std;
int main(){
int m, n;
int matrice[50][50], copie_matrice[50][50];
cout << "\nIntroduceti m,n positive integers, 1 > m,n <= 50 (size of the matrix):";
cout << "\nm = ";
cin >> m;
cout << "\nn = ";
cin >> n;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++){
cout << "\nelement [" << j << "][" << i << "] = ";
cin >> matrice[j][i];
copie_matrice[j][i] = matrice[j][i];
}
cout << "\nInitial matrix:";
cout << "\n";
for (int i = 1; i <= n; i++){
for (int j = 1; j <= m; j++){
cout << " " << matrice[j][i] << " ";
}
cout << "\n";
}
for (int i = 1; i <= n; i++){
bool sortat = false;
while (not sortat){
sortat = true;
for (int j = 1; j <= m - 1; j++){
if (matrice[j + 1][i] < matrice[j][i]){
int temp = matrice[j][i];
matrice[j][i] = matrice[j + 1][i];
matrice[j + 1][i] = temp;
sortat = false;
}
}
}
}
cout << "\nLines sorted in ascending order: ";
cout << "\n";
for (int i = 1; i <= n; i++){
for (int j = 1; j <= m; j++){
cout << " " << matrice[j][i] << " ";
}
cout << "\n";
}
//matrice = copie_matrice;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
matrice[j][i] = copie_matrice[j][i];
for (int i = 1; i <= n; i++){
bool sortat = false;
while (not sortat){
sortat = true;
for (int j = 1; j <= m - 1; j++){
if (matrice[i][j + 1] < matrice[i][j]){
int temp = matrice[j][i];
matrice[i][j] = matrice[i][j + 1];
matrice[i][j + 1] = temp;
sortat = false;
}
}
}
}
cout << "\nColumns sorted in ascending order: ";
cout << "\n";
for (int i = 1; i <= n; i++){
for (int j = 1; j <= m; j++){
cout << " " << matrice[j][i] << " ";
}
cout << "\n";
}
char ch;
cin >> ch;
return 0;
}
| 25.372549
| 88
| 0.376739
|
dindareanualin
|
adfe7009f0b19c0b0f04824e96a7395b56099222
| 1,323
|
cpp
|
C++
|
2018/AdventOfCode/Day2/Box.cpp
|
Ganon11/AdventCode
|
eebf3413c8e73c45d0e0a65a80e57eaf594baead
|
[
"MIT"
] | null | null | null |
2018/AdventOfCode/Day2/Box.cpp
|
Ganon11/AdventCode
|
eebf3413c8e73c45d0e0a65a80e57eaf594baead
|
[
"MIT"
] | null | null | null |
2018/AdventOfCode/Day2/Box.cpp
|
Ganon11/AdventCode
|
eebf3413c8e73c45d0e0a65a80e57eaf594baead
|
[
"MIT"
] | null | null | null |
#include "pch.h"
#include "Box.h"
#include <algorithm>
Box::Box(const std::wstring& name) : m_name{ name } {
CharacterMap charMap;
for (wchar_t ch : name) {
if (charMap.end() == charMap.find(ch)) {
charMap[ch] = 1u;
} else {
++charMap[ch];
}
}
auto two_count_comparator{ [](const CharacterMap::value_type& v) { return v.second == 2u; } };
CharacterMap::iterator two_char_iter{
find_if(charMap.begin(), charMap.end(), two_count_comparator) };
m_has_exactly_two = (charMap.end() != two_char_iter);
auto three_count_comparator{ [](const CharacterMap::value_type& v) { return v.second == 3u; } };
CharacterMap::iterator three_char_iter{
find_if(charMap.begin(), charMap.end(), three_count_comparator) };
m_has_exactly_three = (charMap.end() != three_char_iter);
}
bool Box::has_exactly_two_of_a_character() const {
return m_has_exactly_two;
}
bool Box::has_exactly_three_of_a_character() const {
return m_has_exactly_three;
}
unsigned int Box::edit_distance(const Box& other) const {
std::wstring otherName{ other.get_name() };
unsigned int diffCount{ 0u };
for (unsigned int i = 0; i < m_name.length(); ++i) {
if (m_name[i] != otherName[i]) {
++diffCount;
}
}
return diffCount;
}
std::wstring Box::get_name() const {
return m_name;
}
| 27
| 98
| 0.671958
|
Ganon11
|
bc0287b34fa8cbfa7b7c45fb81aa69b519d9f986
| 284
|
cpp
|
C++
|
src/hir/crate_ptr.cpp
|
spacekookie/mrustc
|
e49cd3b71a5b5458ecd3f3937c04d1a35871a190
|
[
"MIT"
] | null | null | null |
src/hir/crate_ptr.cpp
|
spacekookie/mrustc
|
e49cd3b71a5b5458ecd3f3937c04d1a35871a190
|
[
"MIT"
] | null | null | null |
src/hir/crate_ptr.cpp
|
spacekookie/mrustc
|
e49cd3b71a5b5458ecd3f3937c04d1a35871a190
|
[
"MIT"
] | null | null | null |
/*
*/
#include "crate_ptr.hpp"
#include "hir.hpp"
::HIR::CratePtr::CratePtr():
m_ptr(nullptr)
{
}
::HIR::CratePtr::CratePtr(HIR::Crate c):
m_ptr( new ::HIR::Crate(mv$(c)) )
{
}
::HIR::CratePtr::~CratePtr()
{
if( m_ptr ) {
delete m_ptr, m_ptr = nullptr;
}
}
| 13.52381
| 40
| 0.559859
|
spacekookie
|
bc02beb0ad485beedd30647a1b9ce0ce47eae7a1
| 348
|
cpp
|
C++
|
src/lexer/token.cpp
|
masyagin1998/CSC
|
d1e93697f80b071a69f776e70ea15b3280a53837
|
[
"MIT"
] | 12
|
2019-04-15T09:54:35.000Z
|
2022-03-27T10:37:21.000Z
|
src/lexer/token.cpp
|
masyagin1998/CSC
|
d1e93697f80b071a69f776e70ea15b3280a53837
|
[
"MIT"
] | null | null | null |
src/lexer/token.cpp
|
masyagin1998/CSC
|
d1e93697f80b071a69f776e70ea15b3280a53837
|
[
"MIT"
] | 2
|
2020-02-27T10:17:34.000Z
|
2020-07-29T22:01:15.000Z
|
#include "token.hpp"
TOKEN::TOKEN(DOMAIN_TAG tag, POSITION starting, POSITION following) : tag(tag), frag(FRAGMENT(starting, following)) {}
DOMAIN_TAG TOKEN::get_tag() const
{
return tag;
}
FRAGMENT TOKEN::get_frag() const
{
return frag;
}
std::ostream& operator<<(std::ostream &strm, const TOKEN &tok)
{
return strm << tok.frag;
}
| 18.315789
| 118
| 0.689655
|
masyagin1998
|
bc031b6cf323dfbee91a416d72e6c2f41d995fb2
| 475
|
cpp
|
C++
|
sample20.cpp
|
sunjinbo/wapiti
|
b7cb8b0007f9df708522da74a233541dd4e24afa
|
[
"MIT"
] | null | null | null |
sample20.cpp
|
sunjinbo/wapiti
|
b7cb8b0007f9df708522da74a233541dd4e24afa
|
[
"MIT"
] | null | null | null |
sample20.cpp
|
sunjinbo/wapiti
|
b7cb8b0007f9df708522da74a233541dd4e24afa
|
[
"MIT"
] | null | null | null |
// 函数指针
#include <iostream>
using namespace std;
int foo();
double goo();
int hoo(int x);
int main()
{
// 给函数指针赋值
int (*funcPtr1)() = foo; // 可以
//int (*funcPtr2)() = goo; // 错误!返回值不匹配!
double (*funcPtr4)() = goo; // 可以
//funcPtr1 = hoo; // 错误,因为参数不匹配,funcPtr1只能指向不含参数的函数,而hoo含有int型的参数
int (*funcPtr3)(int) = hoo; // 可以,所以应该这么写
return 0;
}
int foo()
{
return 1;
}
double goo()
{
return 3.14;
}
int hoo(int x)
{
return x * x;
}
| 12.837838
| 69
| 0.56
|
sunjinbo
|
bc0347e6aed7df394f7fcec0a06f4230c7da6001
| 721
|
cpp
|
C++
|
test/unit_tests/compiler/bytecode_gen/record_template_test.cpp
|
mbeckem/tiro
|
b3d729fce46243f25119767c412c6db234c2d938
|
[
"MIT"
] | 10
|
2020-01-23T20:41:19.000Z
|
2021-12-28T20:24:44.000Z
|
test/unit_tests/compiler/bytecode_gen/record_template_test.cpp
|
mbeckem/tiro
|
b3d729fce46243f25119767c412c6db234c2d938
|
[
"MIT"
] | 22
|
2021-03-25T16:22:08.000Z
|
2022-03-17T12:50:38.000Z
|
test/unit_tests/compiler/bytecode_gen/record_template_test.cpp
|
mbeckem/tiro
|
b3d729fce46243f25119767c412c6db234c2d938
|
[
"MIT"
] | null | null | null |
#include <catch2/catch.hpp>
#include "support/test_compiler.hpp"
namespace tiro::test {
TEST_CASE("Using the same record structure multiple times should only generate one record template",
"[bytecode_gen]") {
std::string_view source = R"(
export func a() {
return (foo: "1", bar: 2, baz: #x);
}
export func b() {
return (foo: 3, bar: 2, baz: 1);
}
export func c() {
return (bar: "x", foo: "y", baz: "z");
}
export func d() {
return (baz: "x", bar: "y", foo: "z");
}
)";
auto module = test_support::compile(source);
REQUIRE(module->record_count() == 1);
}
} // namespace tiro::test
| 22.53125
| 100
| 0.525659
|
mbeckem
|
bc06002ef7dfd4b4baffe42fa63ee98eb66c952d
| 3,190
|
cpp
|
C++
|
Code/exec/BCHLaiTest.cpp
|
amihashemi/cs294project
|
7d0f67a40f72cd58a86fb7d7fcb3ed40f5ddc1ec
|
[
"MIT"
] | null | null | null |
Code/exec/BCHLaiTest.cpp
|
amihashemi/cs294project
|
7d0f67a40f72cd58a86fb7d7fcb3ed40f5ddc1ec
|
[
"MIT"
] | null | null | null |
Code/exec/BCHLaiTest.cpp
|
amihashemi/cs294project
|
7d0f67a40f72cd58a86fb7d7fcb3ed40f5ddc1ec
|
[
"MIT"
] | null | null | null |
// Final project for CS 294-73 at Berkeley
// Amirreza Hashemi and Júlio Caineta
// 2017
#include "RectMDArray.H"
#include "FFT1DW.H"
#include "FieldData.H"
#include "RK4.H"
#include "WriteRectMDArray.H"
#include "RHSNavierStokes.H"
void computeVorticity(RectMDArray< double >& vorticity, const DBox box,
FieldData& velocities, double dx)
{
for (Point pt = box.getLowCorner(); box.notDone(pt); box.increment(pt))
{
Point lowShift;
Point highShift;
double dudy;
double dvdx;
lowShift[0] = pt[0];
lowShift[1] = pt[1] - 1;
highShift[0] = pt[0];
highShift[1] = pt[1] + 1;
dudy = (velocities.m_data(highShift, 0) -
velocities.m_data(lowShift, 0)) / (2 * dx);
lowShift[0] = pt[0] - 1;
lowShift[1] = pt[1];
highShift[0] = pt[0] + 1;
highShift[1] = pt[1];
dvdx = (velocities.m_data(highShift, 1) -
velocities.m_data(lowShift, 1)) / (2 * dx);
vorticity[pt] = dudy - dvdx;
}
};
double maxVelocity(RectMDArray< double, DIM > velocities)
{
// only working for 2D
double umax = 0.;
double vmax = 0.;
DBox box = velocities.getDBox();
for (Point pt = box.getLowCorner(); box.notDone(pt); box.increment(pt))
{
double velocity[2];
velocity[0] = velocities(pt, 0);
velocity[1] = velocities(pt, 1);
umax = max(velocity[0], umax);
vmax = max(velocity[1], vmax);
}
return max(umax, vmax);
};
int main(int argc, char* argv[])
{
int M;
// int M = 8;
cout << "input log_2(number of grid points) [e.g., 8]" << endl;
cin >> M;
int N = Power(2, M);
std::shared_ptr< FFT1D > fft1dPtr(new FFT1DW(M));
FieldData velocities(fft1dPtr, 1);
Point low = {{{0, 0}}};
Point high = {{{N - 1, N - 1}}};
DBox box(low, high);
double dx = 1.0 / ((double) N);
double timeEnd = 0.8;
char filename[10];
int nstop = 400;
double sigma = 0.04;
double x_0 = 0.4;
double y_0 = 0.5;
for (Point pt = box.getLowCorner(); box.notDone(pt); box.increment(pt))
{
velocities.m_data(pt, 0) = exp(-(pow((pt[0] * dx - x_0), 2) +
pow((pt[1] * dx - y_0), 2)) /
(2 * pow(sigma, 2.))) / pow(sigma, 2.);
velocities.m_data(pt, 1) = exp(-(pow((pt[0] * dx - x_0), 2) +
pow((pt[1] * dx - y_0), 2)) /
(2 * pow(sigma, 2.))) / pow(sigma, 2.);
}
RK4 <FieldData, RHSNavierStokes, DeltaVelocity> integrator;
double dt = 0.0001;
double time = 0.0;
RectMDArray< double > vorticity(box);
computeVorticity(vorticity, box, velocities, dx);
sprintf(filename, "Vorticity.%.4f.%.4f", timeEnd, time);
MDWrite(string(filename), vorticity);
int nstep = 0;
while (nstep < nstop)
{
velocities.setBoundaries();
integrator.advance(time, dt, velocities);
sprintf(filename, "velocity.%d", nstep);
MDWrite(string(filename), velocities.m_data);
velocities.setBoundaries();
time += dt;
nstep++;
computeVorticity(vorticity, box, velocities, dx);
sprintf(filename, "Vorticity.%d", nstep);
MDWrite(string(filename), vorticity);
cout << "iter = " << nstep << endl;
}
};
| 27.5
| 74
| 0.577429
|
amihashemi
|
bc0c4d6a5d840e43582c8b9398cfc22a90a2e49b
| 7,266
|
cpp
|
C++
|
lib/https/server/src/session.cpp
|
solosTec/node
|
e35e127867a4f66129477b780cbd09c5231fc7da
|
[
"MIT"
] | 2
|
2020-03-03T12:40:29.000Z
|
2021-05-06T06:20:19.000Z
|
lib/https/server/src/session.cpp
|
solosTec/node
|
e35e127867a4f66129477b780cbd09c5231fc7da
|
[
"MIT"
] | 7
|
2020-01-14T20:38:04.000Z
|
2021-05-17T09:52:07.000Z
|
lib/https/server/src/session.cpp
|
solosTec/node
|
e35e127867a4f66129477b780cbd09c5231fc7da
|
[
"MIT"
] | 2
|
2019-11-09T09:14:48.000Z
|
2020-03-03T12:40:30.000Z
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2018 Sylko Olzscher
*
*/
#include <smf/https/srv/session.h>
#include <smf/https/srv/connections.h>
#include <cyng/vm/controller.h>
#include <cyng/vm/generator.h>
#include <boost/uuid/uuid_io.hpp>
namespace node
{
namespace https
{
plain_session::plain_session(cyng::logging::log_ptr logger
, connections& cm
, boost::uuids::uuid tag
, boost::asio::ip::tcp::socket socket
, boost::beast::flat_buffer buffer
, std::string const& doc_root
, auth_dirs const& ad)
: session<plain_session>(logger, cm, tag, socket.get_executor().context(), std::move(buffer), doc_root, ad)
, socket_(std::move(socket))
, strand_(socket_.get_executor())
{}
plain_session::~plain_session()
{}
// Called by the base class
boost::asio::ip::tcp::socket& plain_session::stream()
{
return socket_;
}
// Called by the base class
boost::asio::ip::tcp::socket plain_session::release_stream()
{
return std::move(socket_);
}
// Start the asynchronous operation
void plain_session::run(cyng::object obj)
{
//
// substitute cb_
//
this->connection_manager_.vm().async_run(cyng::generate_invoke("http.session.launch", tag(), false, stream().lowest_layer().remote_endpoint()));
// Run the timer. The timer is operated
// continuously, this simplifies the code.
//on_timer({});
on_timer(obj, boost::system::error_code{});
do_read(obj);
}
void plain_session::do_eof(cyng::object obj)
{
// Send a TCP shutdown
boost::system::error_code ec;
socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_send, ec);
//
// substitute cb_
//
//this->connection_manager_.vm().async_run(cyng::generate_invoke("http.session.eof", tag(), false));
//cb_(cyng::generate_invoke("https.eof.session.plain", obj));
// At this point the connection is closed gracefully
}
void plain_session::do_timeout(cyng::object obj)
{
// Closing the socket cancels all outstanding operations. They
// will complete with boost::asio::error::operation_aborted
boost::system::error_code ec;
socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);
socket_.close(ec);
}
ssl_session::ssl_session(cyng::logging::log_ptr logger
, connections& cm
, boost::uuids::uuid tag
, boost::asio::ip::tcp::socket socket
, boost::asio::ssl::context& ctx
, boost::beast::flat_buffer buffer
, std::string const& doc_root
, auth_dirs const& ad)
: session<ssl_session>(logger, cm, tag, socket.get_executor().context(), std::move(buffer), doc_root, ad)
, stream_(std::move(socket), ctx)
, strand_(stream_.get_executor())
{}
ssl_session::~ssl_session()
{
//std::cerr << "ssl_session::~ssl_session()" << std::endl;
}
// Called by the base class
boost::beast::ssl_stream<boost::asio::ip::tcp::socket>& ssl_session::stream()
{
return stream_;
}
// Called by the base class
boost::beast::ssl_stream<boost::asio::ip::tcp::socket> ssl_session::release_stream()
{
return std::move(stream_);
}
// Start the asynchronous operation
void ssl_session::run(cyng::object obj)
{
//
// ToDo: substitute cb_
//
this->connection_manager_.vm().async_run(cyng::generate_invoke("http.session.launch", tag(), true, stream().lowest_layer().remote_endpoint()));
// Run the timer. The timer is operated
// continuously, this simplifies the code.
//on_timer({});
on_timer(obj, boost::system::error_code{});
// Set the timer
timer_.expires_after(std::chrono::seconds(15));
// Perform the SSL handshake
// Note, this is the buffered version of the handshake.
stream_.async_handshake(
boost::asio::ssl::stream_base::server,
buffer_.data(),
boost::asio::bind_executor(
strand_,
std::bind(
&ssl_session::on_handshake,
this,
obj, // hold reference
std::placeholders::_1,
std::placeholders::_2)));
}
void ssl_session::on_handshake(cyng::object obj
, boost::system::error_code ec
, std::size_t bytes_used)
{
// Happens when the handshake times out
if (ec == boost::asio::error::operation_aborted) {
CYNG_LOG_ERROR(logger_, "handshake timeout ");
return;
}
if (ec)
{
CYNG_LOG_FATAL(logger_, "handshake: " << ec.message());
return;
}
// Consume the portion of the buffer used by the handshake
buffer_.consume(bytes_used);
do_read(obj);
}
void ssl_session::do_eof(cyng::object obj)
{
eof_ = true;
// Set the timer
timer_.expires_after(std::chrono::seconds(15));
// Perform the SSL shutdown
stream_.async_shutdown(
boost::asio::bind_executor(
strand_,
std::bind(
&ssl_session::on_shutdown,
this,
obj,
std::placeholders::_1)));
//
// ToDo: substitute cb_
//
CYNG_LOG_WARNING(logger_, tag() << " - SSL shutdown");
//cb_(cyng::generate_invoke("https.eof.session.ssl", obj));
}
void ssl_session::on_shutdown(cyng::object obj, boost::system::error_code ec)
{
// Happens when the shutdown times out
if (ec == boost::asio::error::operation_aborted)
{
CYNG_LOG_WARNING(logger_, tag() << " - SSL shutdown timeout");
connection_manager_.stop_session(tag());
return;
}
if (ec)
{
//return fail(ec, "shutdown");
CYNG_LOG_WARNING(logger_, tag() << " - SSL shutdown failed");
connection_manager_.stop_session(tag());
return;
}
//
// ToDo: substitute cb_
//
//cb_(cyng::generate_invoke("https.on.shutdown.session.ssl", obj));
connection_manager_.stop_session(tag());
// At this point the connection is closed gracefully
}
void ssl_session::do_timeout(cyng::object obj)
{
// If this is true it means we timed out performing the shutdown
if (eof_)
{
return;
}
// Start the timer again
timer_.expires_at((std::chrono::steady_clock::time_point::max)());
//on_timer({});
on_timer(obj, boost::system::error_code());
do_eof(obj);
}
}
}
namespace cyng
{
namespace traits
{
#if defined(CYNG_LEGACY_MODE_ON)
const char type_tag<node::https::plain_session>::name[] = "plain-session";
const char type_tag<node::https::ssl_session>::name[] = "ssl-session";
#endif
} // traits
}
namespace std
{
size_t hash<node::https::plain_session>::operator()(node::https::plain_session const& s) const noexcept
{
return s.hash();
}
bool equal_to<node::https::plain_session>::operator()(node::https::plain_session const& s1, node::https::plain_session const& s2) const noexcept
{
return s1.hash() == s2.hash();
}
bool less<node::https::plain_session>::operator()(node::https::plain_session const& s1, node::https::plain_session const& s2) const noexcept
{
return s1.hash() < s2.hash();
}
size_t hash<node::https::ssl_session>::operator()(node::https::ssl_session const& s) const noexcept
{
return s.hash();
}
bool equal_to<node::https::ssl_session>::operator()(node::https::ssl_session const& s1, node::https::ssl_session const& s2) const noexcept
{
return s1.hash() == s2.hash();
}
bool less<node::https::ssl_session>::operator()(node::https::ssl_session const& s1, node::https::ssl_session const& s2) const noexcept
{
return s1.hash() < s2.hash();
}
}
| 25.674912
| 147
| 0.664052
|
solosTec
|
bc12089b2c6c25751953acfb23eec71c208d6e35
| 7,391
|
cpp
|
C++
|
moai/src/moaicore/MOAIFrameBufferTexture.cpp
|
jjimenezg93/ai-pathfinding
|
e32ae8be30d3df21c7e64be987134049b585f1e6
|
[
"MIT"
] | null | null | null |
moai/src/moaicore/MOAIFrameBufferTexture.cpp
|
jjimenezg93/ai-pathfinding
|
e32ae8be30d3df21c7e64be987134049b585f1e6
|
[
"MIT"
] | null | null | null |
moai/src/moaicore/MOAIFrameBufferTexture.cpp
|
jjimenezg93/ai-pathfinding
|
e32ae8be30d3df21c7e64be987134049b585f1e6
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2010-2011 Zipline Games, Inc. All Rights Reserved.
// http://getmoai.com
#include "pch.h"
#include <moaicore/MOAIGfxDevice.h>
#include <moaicore/MOAILogMessages.h>
#include <moaicore/MOAIFrameBufferTexture.h>
//================================================================//
// local
//================================================================//
//----------------------------------------------------------------//
/** @name init
@text Initializes frame buffer.
@in MOAIFrameBufferTexture self
@in number width
@in number height
@out nil
*/
int MOAIFrameBufferTexture::_init ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAIFrameBufferTexture, "UNN" )
u32 width = state.GetValue < u32 >( 2, 0 );
u32 height = state.GetValue < u32 >( 3, 0 );
// TODO: fix me
#ifdef MOAI_OS_ANDROID
GLenum colorFormat = state.GetValue < GLenum >( 4, GL_RGB565 );
#else
GLenum colorFormat = state.GetValue < GLenum >( 4, GL_RGBA8 );
#endif
GLenum depthFormat = state.GetValue < GLenum >( 5, 0 );
GLenum stencilFormat = state.GetValue < GLenum >( 6, 0 );
self->Init ( width, height, colorFormat, depthFormat, stencilFormat );
return 0;
}
//================================================================//
// MOAIFrameBufferTexture
//================================================================//
//----------------------------------------------------------------//
void MOAIFrameBufferTexture::Init ( u32 width, u32 height, GLenum colorFormat, GLenum depthFormat, GLenum stencilFormat ) {
this->Clear ();
if ( MOAIGfxDevice::Get ().IsFramebufferSupported ()) {
this->mWidth = width;
this->mHeight = height;
this->mColorFormat = colorFormat;
this->mDepthFormat = depthFormat;
this->mStencilFormat = stencilFormat;
this->Load ();
}
else {
MOAILog ( 0, MOAILogMessages::MOAITexture_NoFramebuffer );
}
}
//----------------------------------------------------------------//
bool MOAIFrameBufferTexture::IsRenewable () {
return true;
}
//----------------------------------------------------------------//
bool MOAIFrameBufferTexture::IsValid () {
return ( this->mGLFrameBufferID != 0 );
}
//----------------------------------------------------------------//
MOAIFrameBufferTexture::MOAIFrameBufferTexture () :
mGLColorBufferID ( 0 ),
mGLDepthBufferID ( 0 ),
mGLStencilBufferID ( 0 ),
mColorFormat ( 0 ),
mDepthFormat ( 0 ),
mStencilFormat ( 0 ) {
RTTI_BEGIN
RTTI_EXTEND ( MOAIFrameBuffer )
RTTI_EXTEND ( MOAITextureBase )
RTTI_END
}
//----------------------------------------------------------------//
MOAIFrameBufferTexture::~MOAIFrameBufferTexture () {
this->Clear ();
}
//----------------------------------------------------------------//
void MOAIFrameBufferTexture::OnCreate () {
if ( !( this->mWidth && this->mHeight && ( this->mColorFormat || this->mDepthFormat || this->mStencilFormat ))) {
return;
}
this->mBufferWidth = this->mWidth;
this->mBufferHeight = this->mHeight;
// bail and retry (no error) if GL cannot generate buffer ID
glGenFramebuffers ( 1, &this->mGLFrameBufferID );
if ( !this->mGLFrameBufferID ) return;
if ( this->mColorFormat ) {
glGenRenderbuffers( 1, &this->mGLColorBufferID );
glBindRenderbuffer ( GL_RENDERBUFFER, this->mGLColorBufferID );
glRenderbufferStorage ( GL_RENDERBUFFER, this->mColorFormat, this->mWidth, this->mHeight );
}
if ( this->mDepthFormat ) {
glGenRenderbuffers ( 1, &this->mGLDepthBufferID );
glBindRenderbuffer ( GL_RENDERBUFFER, this->mGLDepthBufferID );
glRenderbufferStorage ( GL_RENDERBUFFER, this->mDepthFormat, this->mWidth, this->mHeight );
}
if ( this->mStencilFormat ) {
glGenRenderbuffers ( 1, &this->mGLStencilBufferID );
glBindRenderbuffer ( GL_RENDERBUFFER, this->mGLStencilBufferID );
glRenderbufferStorage ( GL_RENDERBUFFER, this->mStencilFormat, this->mWidth, this->mHeight );
}
glBindFramebuffer ( GL_FRAMEBUFFER, this->mGLFrameBufferID );
if ( this->mGLColorBufferID ) {
glFramebufferRenderbuffer ( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, this->mGLColorBufferID );
}
if ( this->mGLDepthBufferID ) {
glFramebufferRenderbuffer ( GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, this->mGLDepthBufferID );
}
if ( this->mGLStencilBufferID ) {
glFramebufferRenderbuffer ( GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, this->mGLStencilBufferID );
}
// TODO: handle error; clear
GLenum status = glCheckFramebufferStatus ( GL_FRAMEBUFFER );
if ( status == GL_FRAMEBUFFER_COMPLETE ) {
glGenTextures ( 1, &this->mGLTexID );
glBindTexture ( GL_TEXTURE_2D, this->mGLTexID );
glTexImage2D ( GL_TEXTURE_2D, 0, GL_RGBA, this->mWidth, this->mHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0 );
glFramebufferTexture2D ( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, this->mGLTexID, 0 );
// refresh tex params on next bind
this->mIsDirty = true;
}
else {
this->Clear ();
}
}
//----------------------------------------------------------------//
void MOAIFrameBufferTexture::OnDestroy () {
if ( this->mGLFrameBufferID ) {
MOAIGfxDevice::Get ().PushDeleter ( MOAIGfxDeleter::DELETE_FRAMEBUFFER, this->mGLFrameBufferID );
this->mGLFrameBufferID = 0;
}
if ( this->mGLColorBufferID ) {
MOAIGfxDevice::Get ().PushDeleter ( MOAIGfxDeleter::DELETE_RENDERBUFFER, this->mGLColorBufferID );
this->mGLColorBufferID = 0;
}
if ( this->mGLDepthBufferID ) {
MOAIGfxDevice::Get ().PushDeleter ( MOAIGfxDeleter::DELETE_RENDERBUFFER, this->mGLDepthBufferID );
this->mGLDepthBufferID = 0;
}
if ( this->mGLStencilBufferID ) {
MOAIGfxDevice::Get ().PushDeleter ( MOAIGfxDeleter::DELETE_RENDERBUFFER, this->mGLStencilBufferID );
this->mGLStencilBufferID = 0;
}
this->MOAITextureBase::OnDestroy ();
}
//----------------------------------------------------------------//
void MOAIFrameBufferTexture::OnInvalidate () {
this->mGLFrameBufferID = 0;
this->mGLColorBufferID = 0;
this->mGLDepthBufferID = 0;
this->mGLStencilBufferID = 0;
this->MOAITextureBase::OnInvalidate ();
}
//----------------------------------------------------------------//
void MOAIFrameBufferTexture::OnLoad () {
}
//----------------------------------------------------------------//
void MOAIFrameBufferTexture::RegisterLuaClass ( MOAILuaState& state ) {
MOAIFrameBuffer::RegisterLuaClass ( state );
MOAITextureBase::RegisterLuaClass ( state );
}
//----------------------------------------------------------------//
void MOAIFrameBufferTexture::RegisterLuaFuncs ( MOAILuaState& state ) {
MOAIFrameBuffer::RegisterLuaFuncs ( state );
MOAITextureBase::RegisterLuaFuncs ( state );
luaL_Reg regTable [] = {
{ "init", _init },
{ NULL, NULL }
};
luaL_register ( state, 0, regTable );
}
//----------------------------------------------------------------//
void MOAIFrameBufferTexture::Render () {
if ( this->Affirm ()) {
MOAIFrameBuffer::Render ();
}
}
//----------------------------------------------------------------//
void MOAIFrameBufferTexture::SerializeIn ( MOAILuaState& state, MOAIDeserializer& serializer ) {
MOAITextureBase::SerializeIn ( state, serializer );
}
//----------------------------------------------------------------//
void MOAIFrameBufferTexture::SerializeOut ( MOAILuaState& state, MOAISerializer& serializer ) {
MOAITextureBase::SerializeOut ( state, serializer );
}
| 30.290984
| 123
| 0.593154
|
jjimenezg93
|
bc13edf112b8f9d50bc5a4620b431ef1d143ae80
| 498
|
cpp
|
C++
|
coding/if else condition.cpp
|
tusharkumar2005/developer
|
b371cedcd77b7926db7b6b7c7d6a144f48eed07b
|
[
"CC0-1.0"
] | 1
|
2021-09-21T11:49:50.000Z
|
2021-09-21T11:49:50.000Z
|
coding/if else condition.cpp
|
tusharkumar2005/developer
|
b371cedcd77b7926db7b6b7c7d6a144f48eed07b
|
[
"CC0-1.0"
] | null | null | null |
coding/if else condition.cpp
|
tusharkumar2005/developer
|
b371cedcd77b7926db7b6b7c7d6a144f48eed07b
|
[
"CC0-1.0"
] | null | null | null |
#include <iostream>
using namespace std;
int main(){
int age;
cout<<"enter your age"<<endl;
cin>>age;
/*
if (age>=150){
cout<<"invalid age";
}
else if (age >=18){
cout<<"you can vote";
}
else
{
cout<<"sorry,you can not vote";
}
*/
switch (age){
case 12:
cout<<"you are 10 year old";
break;
case 18:
cout<<"you are 18 year old";
break;
default :
cout<<"you are dis match";
break;
}
}
| 10.375
| 34
| 0.487952
|
tusharkumar2005
|
bc1fc1a8a367e5db98a479107f426247edc329ae
| 1,561
|
cpp
|
C++
|
scm_gl_core/src/scm/gl_classic/utilities/volume_generator_checkerboard.cpp
|
Nyran/schism
|
c2cdb8884e3e6714a3b291f0f754220b7f5cbc7b
|
[
"BSD-3-Clause"
] | 10
|
2015-09-17T06:01:03.000Z
|
2019-10-23T07:10:20.000Z
|
scm_gl_core/src/scm/gl_classic/utilities/volume_generator_checkerboard.cpp
|
Nyran/schism
|
c2cdb8884e3e6714a3b291f0f754220b7f5cbc7b
|
[
"BSD-3-Clause"
] | 5
|
2015-01-06T14:11:32.000Z
|
2016-12-12T10:26:53.000Z
|
scm_gl_core/src/scm/gl_classic/utilities/volume_generator_checkerboard.cpp
|
Nyran/schism
|
c2cdb8884e3e6714a3b291f0f754220b7f5cbc7b
|
[
"BSD-3-Clause"
] | 15
|
2015-01-29T20:56:13.000Z
|
2020-07-02T19:03:20.000Z
|
// Copyright (c) 2012 Christopher Lux <christopherlux@gmail.com>
// Distributed under the Modified BSD License, see license.txt.
#include "volume_generator_checkerboard.h"
#include <scm/core/math/math.h>
#include <exception>
#include <new>
namespace scm {
namespace gl_classic {
bool volume_generator_checkerboard::generate_float_volume(unsigned dim_x,
unsigned dim_y,
unsigned dim_z,
unsigned components,
boost::scoped_array<float>& buffer)
{
if (dim_x < 1 || dim_y < 1 || dim_z < 1 || components < 1) {
return (false);
}
try {
buffer.reset(new float[dim_x * dim_y * dim_z * components]);
}
catch (std::bad_alloc&) {
return (false);
}
float val;
unsigned offset_dst;
for (unsigned z = 0; z < dim_z; z++) {
for (unsigned y = 0; y < dim_y; y++) {
for (unsigned x = 0; x < dim_x; x++) {
val = float(scm::math::sign(-int((x+y+z) % 2)));
offset_dst = x * components
+ y * dim_x * components
+ z * dim_x * dim_y * components;
for (unsigned c = 0; c < components; c++) {
buffer[offset_dst + c] = val;
}
}
}
}
return (true);
}
} // namespace gl_classic
} // namespace scm
| 28.381818
| 93
| 0.467008
|
Nyran
|
bc22c3e20e78c425c89b39a2d6243c4cae9717a0
| 4,390
|
cpp
|
C++
|
Atom.AI_Contest/main/Distance.cpp
|
mocxi/Arduino
|
3133f7416238c448347ef39bb259ac7dcf016d19
|
[
"BSD-3-Clause"
] | null | null | null |
Atom.AI_Contest/main/Distance.cpp
|
mocxi/Arduino
|
3133f7416238c448347ef39bb259ac7dcf016d19
|
[
"BSD-3-Clause"
] | null | null | null |
Atom.AI_Contest/main/Distance.cpp
|
mocxi/Arduino
|
3133f7416238c448347ef39bb259ac7dcf016d19
|
[
"BSD-3-Clause"
] | null | null | null |
#include "Distance.h"
#include <DebugUtils.h>
#if USE_IR
#include "IR_Distance.h"
#endif
//Init
int avr_front , avr_right , avr_left, avr_TOTAL = 0;
//int angle, delta_angle;
NewPing sonar_front (PING_PIN_FRONT, PING_PIN_FRONT, MAX_DISTANCE);
NewPing sonar_right (PING_PIN_RIGHT, PING_PIN_RIGHT, MAX_DISTANCE);
NewPing sonar_left (PING_PIN_LEFT, PING_PIN_LEFT, MAX_DISTANCE);
distance* distance::GetInstance()
{
static distance* _distance = NULL;
if(!_distance)
{
_distance = new distance();
}
return _distance;
}
distance::distance():
isFollowLeft(false),
isWallOnLeft(false),
isWallOnRight(false),
isWallInFront(false),
isSlowSpeed(false),
m_isMinFront(false)
{
Last_active_sensor = millis();
Last_distance_check = millis();
}
const int& distance::getAvrTotal()
{
return avr_TOTAL;
}
void distance::init()
{
d_front = get_distance(sonar_front, MIN_DISTANCE, MAX_DISTANCE);
DEBUG_PRINTLN("Setup d_front!");
d_right = get_distance(sonar_right, MIN_DISTANCE, MAX_DISTANCE);
DEBUG_PRINTLN("Setup d_right!");
d_left = get_distance(sonar_left, MIN_DISTANCE, MAX_DISTANCE);
DEBUG_PRINTLN("Setup d_left!");
for (uint8_t i = 0; i < DISTANCE_STACK_MAX; i++)
{
arr_front_stack[i] = d_front + 10 ;
arr_right_stack[i] = d_right + 10;
arr_left_stack[i] = d_left + 10;
}
#if USE_IR
IR_DISTANCE->init();
#endif
isFollowLeft = (d_right > d_left);
}
uint8_t distance::getAvrDistance(uint8_t stack[], uint8_t max_count)
{
int sum = 0;
for(uint8_t i = 0; i < max_count; i++)
{
sum += stack[i];
}
return sum/max_count;
}
void distance::updateDistanceStack()
{
arr_front_stack[g_DistanceStackIndex] = d_front;
arr_right_stack[g_DistanceStackIndex] = d_right;
arr_left_stack[g_DistanceStackIndex] = d_left;
g_DistanceStackIndex++;
if (g_DistanceStackIndex >= DISTANCE_STACK_MAX) g_DistanceStackIndex = 0;
avr_front = getAvrDistance(arr_front_stack,DISTANCE_STACK_MAX);
avr_right = getAvrDistance(arr_right_stack,DISTANCE_STACK_MAX);
avr_left = getAvrDistance(arr_left_stack,DISTANCE_STACK_MAX);
avr_TOTAL = avr_front + avr_right + avr_left ;
// Debug Log +
DEBUG_PRINT(">>>>>>>> g_DistanceStackIndex ");
DEBUG_PRINTLN(g_DistanceStackIndex);
DEBUG_PRINTLN("updateDistanceStack ______________ BEGIN");
DEBUG_PRINT("avr_front ");
DEBUG_PRINT(avr_front);
DEBUG_PRINT(" avr_right ");
DEBUG_PRINT(avr_right);
DEBUG_PRINT(" avr_left ");
DEBUG_PRINT(avr_left);
DEBUG_PRINT(" [[avr_TOTAL]] ");
DEBUG_PRINTLN(avr_TOTAL);
DEBUG_PRINT("d_front ");
DEBUG_PRINT(d_front);
DEBUG_PRINT(" d_right ");
DEBUG_PRINT(d_right);
DEBUG_PRINT(" d_left ");
DEBUG_PRINT(d_left);
DEBUG_PRINT(" <<d_TOTAL>> ");
DEBUG_PRINTLN(d_front + d_right + d_left);
DEBUG_PRINTLN(" ______________ END ");
// Debug Log -
}
int distance::ping_mean_cm(NewPing& sonar, int N, int max_cm_distance)
{
int sum_dist = 0;
int temp_dist = 0;
int i = 0;
unsigned long t;
while(i<=N)
{
t = micros();
temp_dist = sonar.ping_cm(max_cm_distance);
if(temp_dist > 0 && temp_dist <= max_cm_distance)
{
sum_dist += temp_dist;
i++;
}
else
{
if(N==1)
{
return 0; //error result every ping
}
N--;
}
//add delay between ping (hardware limitation)
if(i<=N && (micros() - t) < PING_MEAN_DELAY)
{
delay((PING_MEAN_DELAY + t - micros())/1000);
}
}
return (sum_dist/N);
}
int distance::get_distance(NewPing sonar , int min , int max , int last_distance)
{
int d = ping_mean_cm(sonar, GET_DISTANCE_COUNTS, MAX_DISTANCE);
if (last_distance > 0 && (d < min || d > max))
{
d = last_distance;
}
else
{
if (d < min) d = min;
if (d > max) d = max;
}
return d;
}
void distance::updateDistance()
{
#if USE_IR
IR_DISTANCE->updateIR_distance();
#endif
if(Last_distance_check < (millis()-CHECK_DISTANCE_DELAY))
{
updateDistanceStack();
d_front = get_distance(sonar_front, MIN_DISTANCE, MAX_DISTANCE, MAX_DISTANCE );// phphat the 4th param should be previous value , not MAX_DISTANCE !!!
d_right = get_distance(sonar_right, MIN_DISTANCE, MAX_DISTANCE, MAX_DISTANCE);
d_left = get_distance(sonar_left, MIN_DISTANCE, MAX_DISTANCE, MAX_DISTANCE);
Last_distance_check = millis();
}
}
| 23.475936
| 153
| 0.680182
|
mocxi
|
bc22f869e4814f5a688468eedfd57b6363e4b108
| 596
|
cpp
|
C++
|
example/BasicExample.cpp
|
marty1885/NeuralInterface
|
1da613e7af5fa93bc05c607f3acbda6ae04443e6
|
[
"MIT"
] | null | null | null |
example/BasicExample.cpp
|
marty1885/NeuralInterface
|
1da613e7af5fa93bc05c607f3acbda6ae04443e6
|
[
"MIT"
] | null | null | null |
example/BasicExample.cpp
|
marty1885/NeuralInterface
|
1da613e7af5fa93bc05c607f3acbda6ae04443e6
|
[
"MIT"
] | null | null | null |
#include "NeuralInterface.h"
int main()
{
//Define how much dimension we want and how large it is0
int dimensionSize[] = {2,50,70};
int size = 3;
//Create a manager. This is the core component.
NeuralInterface::InterfaceManager interfaceManager;
//Add a Interface named "Test1" with the parameter we defined.
interfaceManager.add("Test1",dimensionSize,size);
//set every element in our interface to 0.2;
interfaceManager.find("Test1").clear(0.2);
//pick a random one and print it out
std::cout << interfaceManager.find("Test1")[0][0].interface->data[0] << std::endl;
return 0;
}
| 27.090909
| 83
| 0.719799
|
marty1885
|
bc22fe2cac68d6912490bbd1c953818a646c3f94
| 2,110
|
cpp
|
C++
|
nau/src/nau/material/materialGroup.cpp
|
Khirion/nau
|
47a2ad8e0355a264cd507da5e7bba1bf7abbff95
|
[
"MIT"
] | 29
|
2015-09-16T22:28:30.000Z
|
2022-03-11T02:57:36.000Z
|
nau/src/nau/material/materialGroup.cpp
|
Khirion/nau
|
47a2ad8e0355a264cd507da5e7bba1bf7abbff95
|
[
"MIT"
] | 1
|
2017-03-29T13:32:58.000Z
|
2017-03-31T13:56:03.000Z
|
nau/src/nau/material/materialGroup.cpp
|
Khirion/nau
|
47a2ad8e0355a264cd507da5e7bba1bf7abbff95
|
[
"MIT"
] | 10
|
2015-10-15T14:20:15.000Z
|
2022-02-17T10:37:29.000Z
|
#include "nau/material/materialGroup.h"
#include "nau.h"
#include "nau/geometry/vertexData.h"
#include "nau/render/opengl/glMaterialGroup.h"
#include "nau/math/vec3.h"
#include "nau/clogger.h"
using namespace nau::material;
using namespace nau::render;
using namespace nau::render::opengl;
using namespace nau::math;
std::shared_ptr<MaterialGroup>
MaterialGroup::Create(IRenderable *parent, std::string materialName) {
#ifdef NAU_OPENGL
return std::shared_ptr<MaterialGroup>(new GLMaterialGroup(parent, materialName));
#endif
}
MaterialGroup::MaterialGroup() :
m_Parent (0),
m_MaterialName ("default") {
//ctor
}
MaterialGroup::MaterialGroup(IRenderable *parent, std::string materialName) :
m_Parent(parent),
m_MaterialName(materialName) {
//ctor
}
MaterialGroup::~MaterialGroup() {
}
void
MaterialGroup::setParent(std::shared_ptr<nau::render::IRenderable> &parent) {
this->m_Parent = parent.get();
}
void
MaterialGroup::setMaterialName (std::string name) {
this->m_MaterialName = name;
m_IndexData->setName(getName());
}
std::string &
MaterialGroup::getName() {
m_Name = m_Parent->getName() + ":" + m_MaterialName;
return m_Name;
}
const std::string&
MaterialGroup::getMaterialName () {
return m_MaterialName;
}
std::shared_ptr<nau::geometry::IndexData>&
MaterialGroup::getIndexData (void) {
if (!m_IndexData) {
m_IndexData = IndexData::Create(getName());
}
return (m_IndexData);
}
size_t
MaterialGroup::getIndexOffset(void) {
return 0;
}
size_t
MaterialGroup::getIndexSize(void) {
if (!m_IndexData) {
return 0;
}
return m_IndexData->getIndexSize();
}
void
MaterialGroup::setIndexList (std::shared_ptr<std::vector<unsigned int>> &indices) {
if (!m_IndexData) {
m_IndexData.reset();
m_IndexData = IndexData::Create(getName());
}
m_IndexData->setIndexData (indices);
}
unsigned int
MaterialGroup::getNumberOfPrimitives(void) {
return RENDERER->getNumberOfPrimitives(this);
}
IRenderable&
MaterialGroup::getParent () {
return *(this->m_Parent);
}
void
MaterialGroup::updateIndexDataName() {
m_IndexData->setName(getName());
}
| 16.10687
| 83
| 0.729858
|
Khirion
|
bc2e1cac9ed2df3f1065af958a3136f3415fa07e
| 1,866
|
hpp
|
C++
|
src/cc/Books/ElementsOfProgrammingInterviews/ch8.hpp
|
nuggetwheat/study
|
1e438a995c3c6ce783af9ae6a537c349afeedbb8
|
[
"MIT"
] | null | null | null |
src/cc/Books/ElementsOfProgrammingInterviews/ch8.hpp
|
nuggetwheat/study
|
1e438a995c3c6ce783af9ae6a537c349afeedbb8
|
[
"MIT"
] | null | null | null |
src/cc/Books/ElementsOfProgrammingInterviews/ch8.hpp
|
nuggetwheat/study
|
1e438a995c3c6ce783af9ae6a537c349afeedbb8
|
[
"MIT"
] | null | null | null |
#ifndef Books_ElementsOfProgrammingInterviews_ch8_hpp
#define Books_ElementsOfProgrammingInterviews_ch8_hpp
#include "reference/ch8.hpp"
#include <cstdlib>
#include <memory>
#include <string>
#include <vector>
namespace study {
extern std::shared_ptr<reference::ListNode<int>> MergeTwoSortedLists(std::shared_ptr<reference::ListNode<int>> l1,
std::shared_ptr<reference::ListNode<int>> l2);
extern std::shared_ptr<reference::ListNode<int>> ReverseLinkedList(const std::shared_ptr<reference::ListNode<int>> &list);
extern std::shared_ptr<reference::ListNode<int>> HasCycle(const std::shared_ptr<reference::ListNode<int>> &list);
extern std::shared_ptr<reference::ListNode<int>> OverlappingNoCycleLists(const std::shared_ptr<reference::ListNode<int>> &l1,
const std::shared_ptr<reference::ListNode<int>> &l2);
extern void DeleteFromList(const std::shared_ptr<reference::ListNode<int>> &list);
extern std::shared_ptr<reference::ListNode<int>> RemoveKthLast(std::shared_ptr<reference::ListNode<int>> &list, int k);
extern void RemoveDuplicates(const std::shared_ptr<reference::ListNode<int>> &list);
extern void CyclicallyRightShiftList(std::shared_ptr<reference::ListNode<int>> &list, int k);
extern void EvenOddMerge(std::shared_ptr<reference::ListNode<int>> &list);
extern bool IsPalindrome(std::shared_ptr<reference::ListNode<int>> &list);
extern void PivotList(std::shared_ptr<reference::ListNode<int>> &list, int k);
extern std::shared_ptr<reference::ListNode<int>> AddNumbers(const std::shared_ptr<reference::ListNode<int>> &l1,
const std::shared_ptr<reference::ListNode<int>> &l2);
}
#endif // Books_ElementsOfProgrammingInterviews_ch8_hpp
| 40.565217
| 127
| 0.700429
|
nuggetwheat
|
bc2f0548b0855345014ca64feeb3ad37eadb0d7f
| 10,012
|
cc
|
C++
|
build/X86_MESI_Two_Level/python/m5/internal/param_X86ACPIRSDP.py.cc
|
hoho20000000/gem5-fy
|
b59f6feed22896d6752331652c4d8a41a4ca4435
|
[
"BSD-3-Clause"
] | null | null | null |
build/X86_MESI_Two_Level/python/m5/internal/param_X86ACPIRSDP.py.cc
|
hoho20000000/gem5-fy
|
b59f6feed22896d6752331652c4d8a41a4ca4435
|
[
"BSD-3-Clause"
] | 1
|
2020-08-20T05:53:30.000Z
|
2020-08-20T05:53:30.000Z
|
build/X86_MESI_Two_Level/python/m5/internal/param_X86ACPIRSDP.py.cc
|
hoho20000000/gem5-fy
|
b59f6feed22896d6752331652c4d8a41a4ca4435
|
[
"BSD-3-Clause"
] | null | null | null |
#include "sim/init.hh"
namespace {
const uint8_t data_m5_internal_param_X86ACPIRSDP[] = {
120,156,197,88,109,115,220,72,17,238,209,190,121,109,175,189,
142,223,242,226,196,162,136,47,11,199,217,192,85,224,224,66,
138,92,46,64,170,14,39,37,135,74,98,168,82,201,171,177,
45,103,87,218,90,141,237,236,149,205,7,28,94,254,6,31,
169,226,27,63,16,250,233,145,20,197,113,114,87,5,89,214,
222,217,209,168,103,166,123,158,167,123,122,166,75,217,103,158,
191,191,116,137,210,127,40,162,144,255,21,189,32,234,41,218,
118,72,105,135,194,121,58,168,81,114,133,84,88,163,87,68,
219,21,210,21,58,227,74,149,126,95,161,248,83,43,181,80,
72,53,46,146,106,241,11,30,123,130,94,84,165,201,161,209,
36,233,26,109,215,233,105,60,79,85,221,160,131,73,74,26,
164,248,19,243,204,207,70,109,202,122,76,208,118,147,165,86,
89,106,82,164,230,69,42,123,219,196,91,233,17,54,41,156,
164,87,172,249,20,133,83,162,197,52,133,211,82,105,81,216,
146,202,12,133,51,82,153,205,135,111,211,246,92,94,191,84,
170,207,151,234,11,165,250,98,169,190,84,170,47,75,125,150,
244,28,69,151,41,186,66,209,85,218,85,20,182,49,29,175,
196,243,237,107,164,171,20,173,208,246,10,105,254,191,70,103,
138,151,101,174,212,227,186,244,184,84,244,184,33,61,86,105,
123,149,52,255,223,176,61,38,104,171,179,200,176,69,255,230,
79,135,97,35,51,205,197,145,30,166,81,18,251,81,188,155,
68,14,222,55,80,0,228,46,138,10,127,235,252,189,15,180,
135,36,80,179,238,140,246,41,143,160,136,251,132,14,102,8,
43,116,229,84,225,33,170,208,9,87,170,180,43,47,162,106,
38,113,202,248,205,209,9,143,94,163,19,105,217,122,26,95,
167,170,169,11,64,115,2,144,125,205,157,241,154,225,33,86,
187,198,211,110,138,222,6,122,175,139,118,230,18,23,254,32,
24,6,125,255,217,103,63,185,119,255,241,67,111,235,203,199,
29,168,111,154,176,161,63,72,134,166,23,237,152,9,72,250,
113,208,215,190,111,38,249,97,200,221,76,100,216,110,83,229,
199,131,36,138,13,140,236,165,102,24,13,76,171,232,237,247,
147,240,176,167,205,20,183,60,148,150,7,195,97,50,236,96,
85,60,20,6,197,224,197,158,129,142,125,76,209,129,114,82,
164,191,227,98,99,63,233,107,46,226,189,209,225,198,158,238,
223,254,100,119,180,177,115,24,245,194,13,214,218,255,237,131,
173,135,254,147,227,196,255,74,31,233,222,198,96,100,88,116,
163,127,123,131,53,210,195,56,224,166,243,22,174,179,16,108,
79,143,163,61,63,83,115,95,247,6,122,8,171,211,25,76,
173,166,213,188,186,161,42,106,78,205,168,168,158,131,137,181,
105,229,96,254,51,3,211,201,92,151,241,84,25,184,14,157,
74,5,136,117,0,38,48,172,0,58,182,147,129,217,83,116,
230,208,31,42,16,56,229,178,202,158,230,22,64,46,88,79,
179,67,53,232,148,209,174,1,203,175,87,100,168,9,25,202,
161,19,46,25,230,42,157,178,59,179,40,55,113,121,208,164,
100,134,20,63,68,77,208,89,197,76,222,103,39,117,166,65,
181,160,129,165,47,172,9,163,33,22,221,3,115,59,147,121,
107,146,174,15,2,179,239,181,114,132,120,153,4,233,205,36,
182,96,238,70,113,152,131,107,233,177,27,245,152,30,30,214,
80,70,19,177,94,18,20,98,64,184,219,75,82,45,20,147,
177,189,89,8,66,122,119,32,195,96,86,232,35,157,67,157,
118,65,39,166,153,29,17,26,96,180,113,80,196,131,115,47,
96,138,171,66,136,54,83,162,206,132,232,48,33,108,109,197,
105,169,89,181,25,97,45,187,181,204,205,171,57,59,254,69,
22,17,69,7,142,248,230,137,68,5,150,102,220,196,55,79,
196,243,241,246,7,164,140,147,181,179,243,51,188,104,189,196,
125,132,51,76,30,150,189,3,87,22,52,65,130,26,49,43,
45,226,204,36,75,17,193,189,134,30,24,202,193,20,85,26,
44,243,224,19,32,195,9,101,172,57,171,48,43,88,35,118,
101,142,19,220,188,196,243,254,73,232,150,197,10,33,129,217,
143,210,228,216,122,56,234,18,238,182,216,105,30,143,30,237,
28,232,174,73,87,185,225,121,114,232,118,131,56,78,140,27,
132,161,27,24,142,0,59,135,70,167,174,73,220,181,180,3,
32,189,171,57,143,138,241,70,3,237,73,197,146,39,140,186,
134,99,203,188,60,136,99,166,218,48,13,246,147,48,229,118,
116,221,211,198,107,163,7,150,57,17,5,132,37,62,68,49,
45,203,193,119,239,229,26,216,72,83,207,137,147,234,222,174,
4,175,110,47,72,83,31,26,72,187,208,13,86,31,5,189,
67,45,163,167,60,30,43,132,170,213,97,44,49,233,50,140,
201,109,23,131,226,36,14,71,172,95,212,253,20,83,95,22,
34,182,56,38,181,212,18,127,155,106,81,53,152,142,13,181,
236,116,171,25,249,138,189,102,9,134,147,160,174,50,224,153,
140,103,28,73,58,142,4,2,177,9,228,245,190,143,26,58,
123,55,81,172,161,248,8,197,173,220,236,15,109,123,235,188,
237,247,49,159,35,6,119,43,153,105,133,111,249,111,248,214,
76,201,183,206,224,35,39,178,171,70,149,146,127,84,96,126,
50,149,123,148,248,31,131,206,254,7,97,241,36,222,108,203,
126,128,73,55,189,43,80,227,59,92,220,90,75,111,185,150,
117,238,126,144,186,113,242,154,234,46,94,218,160,6,162,123,
43,88,249,18,149,247,74,84,246,92,72,128,199,222,119,81,
84,223,181,244,223,27,255,210,239,217,165,255,53,230,155,206,
184,54,35,28,155,82,93,16,5,120,52,114,16,182,184,50,
90,6,8,229,213,95,230,141,239,105,188,194,123,153,32,128,
237,172,101,183,51,217,19,109,202,152,71,181,168,150,87,234,
192,97,183,66,75,217,46,149,98,27,25,12,147,151,35,55,
217,117,13,229,42,221,89,75,215,215,210,207,57,176,184,119,
95,175,120,22,68,134,122,128,32,96,131,2,214,197,68,49,
63,99,168,7,47,187,90,54,18,121,242,125,27,3,108,50,
227,103,27,20,131,35,104,56,57,26,18,5,57,163,65,240,
27,11,20,147,5,20,48,229,49,38,155,20,28,42,106,153,
189,190,132,2,190,21,160,0,154,253,149,36,129,85,244,23,
194,26,243,74,102,46,46,158,147,123,207,60,196,145,197,156,
168,11,119,37,39,243,10,39,11,25,236,54,131,150,108,54,
217,46,197,105,201,223,74,241,164,216,69,42,89,106,83,246,
158,106,225,61,2,208,183,218,41,170,111,58,16,22,159,61,
13,98,226,42,54,103,188,249,102,108,146,60,166,34,209,221,
124,104,116,38,236,52,62,52,122,254,26,27,196,227,235,106,
193,177,12,17,242,252,20,197,103,133,3,171,188,237,3,42,
183,122,62,128,150,54,15,223,70,159,103,208,160,42,58,207,
54,204,13,254,229,49,30,110,221,243,239,63,250,234,209,230,
150,143,225,242,58,134,149,140,23,31,108,142,95,128,61,63,
230,138,230,83,156,34,45,145,245,149,36,192,40,29,112,224,
204,81,124,2,229,148,226,149,156,64,237,65,211,179,41,133,
48,55,255,74,252,64,220,121,35,110,151,22,176,96,129,5,
24,197,203,177,120,32,48,190,211,11,250,59,97,112,247,5,
166,194,124,221,220,227,156,92,247,118,89,119,248,138,122,135,
250,242,248,121,110,195,209,88,18,215,59,36,199,75,171,187,
56,71,152,116,37,80,60,217,215,110,95,247,119,248,200,186,
31,13,220,221,94,176,39,184,84,50,219,30,229,182,25,1,
182,228,207,18,78,82,228,9,155,137,219,77,98,142,138,135,
93,147,12,221,80,243,73,64,135,238,39,174,132,84,55,74,
221,96,135,223,6,93,99,121,255,166,235,74,198,21,12,247,
82,73,174,94,28,163,58,54,96,125,62,164,71,156,102,246,
169,200,45,236,30,34,145,7,41,150,36,144,214,141,120,243,
225,19,161,25,217,32,118,15,197,109,20,27,84,222,151,63,
52,150,63,231,145,15,48,5,150,171,174,174,57,77,199,204,
89,207,205,197,30,163,95,250,182,179,254,253,219,56,171,174,
210,118,45,119,217,58,36,117,3,39,76,148,77,108,1,219,
147,121,227,148,148,211,210,216,202,27,103,164,156,149,198,118,
222,56,39,229,37,105,156,167,236,2,107,65,26,23,105,123,
137,194,186,180,44,35,54,52,254,203,216,32,206,53,54,183,
50,255,203,144,224,253,226,255,162,186,119,151,178,188,225,93,
225,64,149,237,106,217,190,145,202,243,102,89,246,77,107,134,
156,202,47,95,196,71,191,59,212,129,209,22,163,155,99,50,
84,130,138,157,248,248,181,143,23,73,83,45,183,233,87,133,
77,103,146,49,141,22,4,186,252,230,13,215,125,114,243,105,
36,69,69,14,219,182,119,107,178,8,190,147,165,177,84,44,
70,189,88,12,220,16,198,250,216,127,107,65,108,162,10,193,
96,48,208,113,232,253,16,125,126,68,229,132,83,100,198,194,
8,196,179,63,82,145,195,76,115,134,185,192,121,204,219,158,
136,208,88,50,84,224,108,23,206,55,46,96,133,193,127,206,
25,220,1,227,94,7,109,239,11,20,18,166,139,8,237,61,
40,16,89,185,144,158,137,238,251,81,136,35,207,251,5,56,
155,178,23,14,242,152,103,77,231,100,135,250,40,146,75,96,
12,247,13,34,24,16,155,81,222,96,174,94,44,159,134,70,
134,123,207,107,12,133,85,192,195,59,228,94,190,127,152,151,
229,97,240,32,196,16,143,14,117,79,27,253,54,143,13,208,
207,14,182,161,230,157,62,25,241,57,170,33,141,220,199,247,
199,183,57,222,207,8,145,226,154,142,55,71,85,231,237,113,
81,201,159,211,172,55,149,228,29,231,46,229,75,109,245,162,
205,165,252,24,49,74,61,180,24,208,41,75,4,68,27,191,
124,207,47,119,131,150,93,114,105,153,167,10,32,162,28,48,
55,131,190,189,126,146,247,217,81,52,181,46,47,23,164,200,
164,188,143,81,124,82,240,246,103,232,125,157,139,254,237,245,
220,240,245,243,134,63,145,219,210,254,109,243,209,57,193,76,
100,107,148,126,169,211,238,147,96,135,15,180,71,26,57,154,
89,123,223,152,229,14,230,218,133,146,91,81,223,94,248,73,
234,81,126,31,14,3,174,47,158,107,77,245,48,10,122,209,
215,250,253,214,60,131,53,88,159,252,181,193,109,240,249,41,
177,92,197,147,228,67,230,99,250,166,163,139,32,55,212,123,
81,202,35,203,176,197,16,89,52,6,119,222,225,170,229,190,
99,35,179,61,121,216,139,136,187,114,239,240,27,46,218,184,
229,155,104,170,6,126,103,249,215,225,72,237,84,212,164,154,
81,53,254,109,243,239,156,51,221,110,86,155,77,150,155,154,
86,229,191,85,118,129,73,103,117,190,169,254,3,9,41,59,
195,
};
EmbeddedPython embedded_m5_internal_param_X86ACPIRSDP(
"m5/internal/param_X86ACPIRSDP.py",
"/home/hongyu/gem5-fy/build/X86_MESI_Two_Level/python/m5/internal/param_X86ACPIRSDP.py",
"m5.internal.param_X86ACPIRSDP",
data_m5_internal_param_X86ACPIRSDP,
2465,
7288);
} // anonymous namespace
| 58.209302
| 92
| 0.6669
|
hoho20000000
|
bc30785f43a2059b7a6e9c87e32c84d9a2157470
| 1,228
|
cpp
|
C++
|
aws-cpp-sdk-shield/source/model/ProtectionGroupArbitraryPatternLimits.cpp
|
perfectrecall/aws-sdk-cpp
|
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
|
[
"Apache-2.0"
] | 1
|
2022-01-05T18:20:03.000Z
|
2022-01-05T18:20:03.000Z
|
aws-cpp-sdk-shield/source/model/ProtectionGroupArbitraryPatternLimits.cpp
|
perfectrecall/aws-sdk-cpp
|
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
|
[
"Apache-2.0"
] | 1
|
2022-01-03T23:59:37.000Z
|
2022-01-03T23:59:37.000Z
|
aws-cpp-sdk-shield/source/model/ProtectionGroupArbitraryPatternLimits.cpp
|
ravindra-wagh/aws-sdk-cpp
|
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
|
[
"Apache-2.0"
] | 1
|
2021-12-30T04:25:33.000Z
|
2021-12-30T04:25:33.000Z
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/shield/model/ProtectionGroupArbitraryPatternLimits.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace Shield
{
namespace Model
{
ProtectionGroupArbitraryPatternLimits::ProtectionGroupArbitraryPatternLimits() :
m_maxMembers(0),
m_maxMembersHasBeenSet(false)
{
}
ProtectionGroupArbitraryPatternLimits::ProtectionGroupArbitraryPatternLimits(JsonView jsonValue) :
m_maxMembers(0),
m_maxMembersHasBeenSet(false)
{
*this = jsonValue;
}
ProtectionGroupArbitraryPatternLimits& ProtectionGroupArbitraryPatternLimits::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("MaxMembers"))
{
m_maxMembers = jsonValue.GetInt64("MaxMembers");
m_maxMembersHasBeenSet = true;
}
return *this;
}
JsonValue ProtectionGroupArbitraryPatternLimits::Jsonize() const
{
JsonValue payload;
if(m_maxMembersHasBeenSet)
{
payload.WithInt64("MaxMembers", m_maxMembers);
}
return payload;
}
} // namespace Model
} // namespace Shield
} // namespace Aws
| 19.806452
| 108
| 0.762215
|
perfectrecall
|
bc308fc74a58e7d9e4929425df42b0800ce878d4
| 2,010
|
cpp
|
C++
|
aoapcbac2nd/example9-4_unidirectionaltsp.cpp
|
aoibird/pc
|
b72c0b10117f95d45e2e7423614343b5936b260a
|
[
"MIT"
] | null | null | null |
aoapcbac2nd/example9-4_unidirectionaltsp.cpp
|
aoibird/pc
|
b72c0b10117f95d45e2e7423614343b5936b260a
|
[
"MIT"
] | null | null | null |
aoapcbac2nd/example9-4_unidirectionaltsp.cpp
|
aoibird/pc
|
b72c0b10117f95d45e2e7423614343b5936b260a
|
[
"MIT"
] | null | null | null |
// UVa 116
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int MAXR = 10+10;
const int MAXC = 100+10;
const int INF = 1 << 30;
int F[MAXR][MAXC];
int dp[MAXR][MAXC];
int nxt[MAXR][MAXC];
int R, C;
void print_table()
{
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) printf("%d(%d) ", dp[i][j], nxt[i][j]);
printf("\n");
}
printf("\n");
}
void solve()
{
for (int r = 0; r < R; r++) for (int c = 0; c < C; c++) dp[r][c] = INF;
for (int r = 0; r < R; r++) dp[r][C-1] = F[r][C-1];
for (int c = C-2; c >= 0; c--) {
for (int r = 0; r < R; r++) {
int up = (r-1+R)%R;
int down = (r+1)%R;
if (dp[r][c] > dp[up][c+1] + F[r][c]
|| (dp[r][c] == dp[up][c+1] + F[r][c] && nxt[r][c] > up)) {
dp[r][c] = dp[up][c+1] + F[r][c];
nxt[r][c] = up;
}
if (dp[r][c] > dp[r][c+1] + F[r][c]
|| (dp[r][c] == dp[r][c+1] + F[r][c] && nxt[r][c] > r)) {
dp[r][c] = dp[r][c+1] + F[r][c];
nxt[r][c] = r;
}
if (dp[r][c] > dp[down][c+1] + F[r][c]
|| (dp[r][c] == dp[down][c+1] + F[r][c] && nxt[r][c] > down)) {
dp[r][c] = dp[down][c+1] + F[r][c];
nxt[r][c] = down;
}
}
}
// print_table();
int row, ans = INF;
for (int r = 0; r < R; r++)
if (dp[r][0] < ans) { ans = dp[r][0]; row = r; }
printf("%d", row+1);
for (int i = 0; i < C-1; i++) {
printf(" %d", nxt[row][i]+1);
row = nxt[row][i];
}
printf("\n%d\n", ans);
}
int main()
{
while (scanf("%d%d", &R, &C) == 2) {
memset(dp, 0, sizeof(dp));
for (int i = 0; i < R; i++)
for (int j = 0; j < C; j++) scanf("%d", &F[i][j]);
// printf("INF = %d\n", INF);
solve();
}
}
| 26.103896
| 79
| 0.374129
|
aoibird
|
bc343ef1acf95d594fd021c9dc93956ae9b51c7d
| 2,807
|
cpp
|
C++
|
[Lib]__RanClientUI/Sources/InnerUI/ItemBankWindow.cpp
|
yexiuph/RanOnline
|
7f7be07ef740c8e4cc9c7bef1790b8d099034114
|
[
"Apache-2.0"
] | null | null | null |
[Lib]__RanClientUI/Sources/InnerUI/ItemBankWindow.cpp
|
yexiuph/RanOnline
|
7f7be07ef740c8e4cc9c7bef1790b8d099034114
|
[
"Apache-2.0"
] | null | null | null |
[Lib]__RanClientUI/Sources/InnerUI/ItemBankWindow.cpp
|
yexiuph/RanOnline
|
7f7be07ef740c8e4cc9c7bef1790b8d099034114
|
[
"Apache-2.0"
] | null | null | null |
#include "pch.h"
#include "ItemBankWindow.h"
#include "ItemBankPage.h"
#include "../[Lib]__EngineUI/Sources/BasicButton.h"
#include "GLGaeaClient.h"
#include "../[Lib]__EngineUI/Sources/BasicTextBox.h"
#include "InnerInterface.h"
#include "ModalCallerID.h"
#include "../[Lib]__Engine/Sources/DxTools/DxFontMan.h"
#include "ModalWindow.h"
#include "UITextControl.h"
#include "GameTextControl.h"
#include "BasicTextButton.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
CItemBankWindow::CItemBankWindow () :
m_pPage ( NULL )
{
}
CItemBankWindow::~CItemBankWindow ()
{
}
void CItemBankWindow::CreateSubControl ()
{
// CreateTextButton ( "ITEMBANK_REFRESH_BUTTON", ITEMBANK_REFRESH_BUTTON, const_cast<char*>(ID2GAMEWORD("ITEMBANK_REFRESH_BUTTON")) );
CItemBankPage* pItemBankPage = new CItemBankPage;
pItemBankPage->CreateSub ( this, "ITEMBANK_PAGE", UI_FLAG_DEFAULT, ITEMBANK_PAGE );
pItemBankPage->CreateSubControl ();
RegisterControl ( pItemBankPage );
m_pPage = pItemBankPage;
}
CBasicTextButton* CItemBankWindow::CreateTextButton ( char* szButton, UIGUID ControlID, char* szText )
{
const int nBUTTONSIZE = CBasicTextButton::SIZE14;
CBasicTextButton* pTextButton = new CBasicTextButton;
pTextButton->CreateSub ( this, "BASIC_TEXT_BUTTON14", UI_FLAG_XSIZE, ControlID );
pTextButton->CreateBaseButton ( szButton, nBUTTONSIZE, CBasicButton::CLICK_FLIP, szText );
RegisterControl ( pTextButton );
return pTextButton;
}
void CItemBankWindow::InitItemBank ()
{
m_pPage->UnLoadItemPage ();
GLCharacter* pCharacter = GLGaeaClient::GetInstance().GetCharacter();
m_pPage->LoadItemPage ( pCharacter->m_cInvenCharged );
}
void CItemBankWindow::ClearItemBank()
{
m_pPage->UnLoadItemPage ();
}
void CItemBankWindow::TranslateUIMessage ( UIGUID ControlID, DWORD dwMsg )
{
CUIWindowEx::TranslateUIMessage ( ControlID, dwMsg );
if ( ET_CONTROL_TITLE == ControlID || ET_CONTROL_TITLE_F == ControlID )
{
if ( (dwMsg & UIMSG_LB_DUP) && CHECK_MOUSE_IN ( dwMsg ) )
{
CInnerInterface::GetInstance().SetDefaultPosInterface( ITEMBANK_WINDOW );
return;
}
}
else if ( ITEMBANK_PAGE == ControlID )
{
if ( CHECK_MOUSE_IN ( dwMsg ) )
{
int nPosX, nPosY;
m_pPage->GetItemIndex ( &nPosX, &nPosY );
//CDebugSet::ToView ( 1, 3, "[itembank] Page:%d %d / %d", nPosX, nPosY );
if ( nPosX < 0 || nPosY < 0 ) return ;
SINVENITEM sInvenItem = m_pPage->GetItem ( nPosX, nPosY );
if ( sInvenItem.sItemCustom.sNativeID != NATIVEID_NULL () )
{
CInnerInterface::GetInstance().SHOW_ITEM_INFO ( sInvenItem.sItemCustom, FALSE, FALSE, FALSE, sInvenItem.wPosX, sInvenItem.wPosY );
}
if ( dwMsg & UIMSG_LB_UP )
{
GLGaeaClient::GetInstance().GetCharacter()->ReqChargedItemTo ( static_cast<WORD>(nPosX), static_cast<WORD>(nPosY) );
return ;
}
}
}
}
| 27.519608
| 134
| 0.728892
|
yexiuph
|
bc39a9484ab2f2df4c4ffbfdfd93fdb3d40b66b1
| 225
|
cpp
|
C++
|
src_server/Player.cpp
|
Naftoreiclag/VS7C
|
5b736a0550969752514433fb0fd9d9680fa46bdd
|
[
"Apache-2.0"
] | null | null | null |
src_server/Player.cpp
|
Naftoreiclag/VS7C
|
5b736a0550969752514433fb0fd9d9680fa46bdd
|
[
"Apache-2.0"
] | null | null | null |
src_server/Player.cpp
|
Naftoreiclag/VS7C
|
5b736a0550969752514433fb0fd9d9680fa46bdd
|
[
"Apache-2.0"
] | null | null | null |
#include "Player.h"
Player::Player(std::string username, sf::Uint64 id, sf::IpAddress address, unsigned short port)
: username(username),
id(id),
address(address),
port(port)
{
//ctor
}
Player::~Player()
{
//dtor
}
| 14.0625
| 95
| 0.666667
|
Naftoreiclag
|
bc3bf4d210522a103d2ad6ddc8d8c6f117082c03
| 1,805
|
hpp
|
C++
|
include/string_algorithm_impl.hpp
|
Shtan7/KTL
|
9c0adf8fac2f0bb481060b7bbb15b1356089af3c
|
[
"MIT"
] | 38
|
2020-12-16T22:12:50.000Z
|
2022-03-24T04:07:14.000Z
|
include/string_algorithm_impl.hpp
|
Shtan7/KTL
|
9c0adf8fac2f0bb481060b7bbb15b1356089af3c
|
[
"MIT"
] | 165
|
2020-11-11T21:22:23.000Z
|
2022-03-26T14:30:40.000Z
|
include/string_algorithm_impl.hpp
|
Shtan7/KTL
|
9c0adf8fac2f0bb481060b7bbb15b1356089af3c
|
[
"MIT"
] | 5
|
2021-07-16T19:05:28.000Z
|
2021-12-22T11:46:42.000Z
|
#pragma once
#include <algorithm.hpp>
namespace ktl {
namespace str::details {
template <class Traits, class CharT, class SizeType>
constexpr SizeType find_ch(const CharT* str,
CharT ch,
SizeType length,
SizeType start_pos,
SizeType npos) {
if (start_pos >= length) {
return npos;
}
const CharT* found_ptr{Traits::find(str + start_pos, length - start_pos, ch)};
return found_ptr ? static_cast<SizeType>(found_ptr - str) : npos;
}
template <class Traits, class CharT, class SizeType>
constexpr SizeType rfind_ch(const CharT* str,
CharT ch,
SizeType length,
SizeType start_pos,
SizeType npos) {
if (start_pos >= length) {
return npos;
}
for (SizeType idx = length; idx > 0; --idx) {
const SizeType pos{idx - 1};
if (Traits::eq(str[pos], ch)) {
return pos;
}
}
return npos;
}
template <class Traits, class CharT, class SizeType>
constexpr SizeType find_substr(const CharT* str,
SizeType str_start_pos,
SizeType str_length,
const CharT* substr,
SizeType substr_length,
SizeType npos) {
if (substr_length > str_length) {
return npos;
}
const CharT* str_end{str + str_length};
const auto found_ptr{find_subrange(
str + str_start_pos, str_end, substr, substr + substr_length,
[](CharT lhs, CharT rhs) { return Traits::eq(lhs, rhs); })};
return found_ptr != str_end ? static_cast<SizeType>(found_ptr - str) : npos;
}
} // namespace str::details
} // namespace ktl
| 33.425926
| 80
| 0.556233
|
Shtan7
|
bc3e67071673456f2ff996ca5248a914ba86b0a6
| 983
|
hpp
|
C++
|
include/tools/StringTools.hpp
|
CapRat/APAL
|
a08f4bc6ee6299e8e370ef99750262ad23c87d58
|
[
"MIT"
] | 2
|
2020-09-21T12:30:05.000Z
|
2020-10-14T19:43:51.000Z
|
include/tools/StringTools.hpp
|
CapRat/APAL
|
a08f4bc6ee6299e8e370ef99750262ad23c87d58
|
[
"MIT"
] | null | null | null |
include/tools/StringTools.hpp
|
CapRat/APAL
|
a08f4bc6ee6299e8e370ef99750262ad23c87d58
|
[
"MIT"
] | null | null | null |
#ifndef STRING_TOOLS_HPP
#define STRING_TOOLS_HPP
#include <string>
namespace APAL {
/**
* @brief Replaces all occurences of an itemToReplace in the given strToChange
* @param strToChange string to replaces stuff in.
* @param itemToReplace String value, which should be replaces
* @param substitute Text to replace itemToReplace with
*/
std::string
replaceInString(std::string strToChange,
const std::string itemToReplace,
const std::string substitute);
/**
* @brief Gets the filename from a path with or without extension
* When no seperator is found, the whole filePath is returned.
* @param filePath filepath, to retreive filename from
* @param withExtension return the fileextension with the filename.
* @param seperator Seperator for the given fielpath. Defaults to /.
* @return
*/
std::string
getFileName(std::string filePath,
bool withExtension = true,
char seperator = '/');
}
#endif //! STRING_TOOLS_HPP
| 33.896552
| 78
| 0.722279
|
CapRat
|
bc3ec80aab2aafa2db45125a14f98e557efaa48a
| 4,217
|
hpp
|
C++
|
data_structure/set_managed_by_interval.hpp
|
emthrm/library
|
0876ba7ec64e23b5ec476a7a0b4880d497a36be1
|
[
"Unlicense"
] | 1
|
2021-12-26T14:17:29.000Z
|
2021-12-26T14:17:29.000Z
|
data_structure/set_managed_by_interval.hpp
|
emthrm/library
|
0876ba7ec64e23b5ec476a7a0b4880d497a36be1
|
[
"Unlicense"
] | 3
|
2020-07-13T06:23:02.000Z
|
2022-02-16T08:54:26.000Z
|
data_structure/set_managed_by_interval.hpp
|
emthrm/library
|
0876ba7ec64e23b5ec476a7a0b4880d497a36be1
|
[
"Unlicense"
] | null | null | null |
#pragma once
#include <cassert>
#include <iostream>
#include <iterator>
#include <limits>
#include <set>
#include <tuple>
#include <utility>
template <typename T>
struct SetManagedByInterval {
using IntervalType = std::set<std::pair<T, T>>;
IntervalType interval{
{std::numeric_limits<T>::lowest(), std::numeric_limits<T>::lowest()},
{std::numeric_limits<T>::max(), std::numeric_limits<T>::max()},
};
bool contains(T x) const { return contains(x, x); }
bool contains(T left, T right) const {
typename IntervalType::const_iterator it = interval.lower_bound({left, left});
if (left < it->first) it = std::prev(it);
return it->first <= left && right <= it->second;
}
std::pair<typename IntervalType::const_iterator, bool> erase(T x) {
typename IntervalType::const_iterator it = interval.lower_bound({x, x});
if (it->first == x) {
T right = it->second;
it = interval.erase(it);
if (x + 1 <= right) it = interval.emplace(x + 1, right).first;
return {it, true};
}
it = std::prev(it);
T left, right; std::tie(left, right) = *it;
if (right < x) return {std::next(it), false};
interval.erase(it);
it = std::next(interval.emplace(left, x - 1).first);
if (x + 1 <= right) it = interval.emplace(x + 1, right).first;
return {it, true};
}
std::pair<typename IntervalType::const_iterator, T> erase(T left, T right) {
assert(left <= right);
typename IntervalType::const_iterator it = interval.lower_bound({left, left});
T res = 0;
for (; it->second <= right; it = interval.erase(it)) res += it->second - it->first + 1;
if (it->first <= right) {
res += right - it->first + 1;
T r = it->second;
interval.erase(it);
it = interval.emplace(right + 1, r).first;
}
if (left < std::prev(it)->second) {
it = std::prev(it);
res += it->second - left + 1;
T l = it->first;
interval.erase(it);
it = std::next(interval.emplace(l, left - 1).first);
}
return {it, res};
}
std::pair<typename IntervalType::const_iterator, bool> insert(T x) {
typename IntervalType::const_iterator it = interval.lower_bound({x, x});
if (it->first == x) return {it, false};
if (x <= std::prev(it)->second) return {std::prev(it), false};
T left = x, right = x;
if (x + 1 == it->first) {
right = it->second;
it = interval.erase(it);
}
if (std::prev(it)->second == x - 1) {
it = std::prev(it);
left = it->first;
interval.erase(it);
}
return {interval.emplace(left, right).first, true};
}
std::pair<typename IntervalType::const_iterator, T> insert(T left, T right) {
assert(left <= right);
typename IntervalType::const_iterator it = interval.lower_bound({left, left});
if (left <= std::prev(it)->second) {
it = std::prev(it);
left = it->first;
}
T res = 0;
if (left == it->first && right <= it->second) return {it, res};
for (; it->second <= right; it = interval.erase(it)) res -= it->second - it->first + 1;
if (it->first <= right) {
res -= it->second - it->first + 1;
right = it->second;
it = interval.erase(it);
}
res += right - left + 1;
if (right + 1 == it->first) {
right = it->second;
it = interval.erase(it);
}
if (std::prev(it)->second == left - 1) {
it = std::prev(it);
left = it->first;
interval.erase(it);
}
return {interval.emplace(left, right).first, res};
}
T mex(T x = 0) const {
auto it = interval.lower_bound({x, x});
if (x <= std::prev(it)->second) it = std::prev(it);
return x < it->first ? x : it->second + 1;
}
friend std::ostream &operator<<(std::ostream &os, const SetManagedByInterval &st) {
if (st.interval.size() == 2) return os;
auto it = next(st.interval.begin());
while (true) {
os << '[' << it->first << ", " << it->second << ']';
it = next(it);
if (next(it) == st.interval.end()) {
break;
} else {
os << ' ';
}
}
return os;
}
};
| 32.438462
| 92
| 0.549917
|
emthrm
|
bc432cc1d963bf3c64b4b54ba0a67bf1b82144d7
| 18,897
|
cpp
|
C++
|
src/simulation/dynamics/dualHingedRigidBodies/dualHingedRigidBodyStateEffector.cpp
|
ian-cooke/basilisk_mag
|
a8b1e37c31c1287549d6fd4d71fcaa35b6fc3f14
|
[
"0BSD"
] | null | null | null |
src/simulation/dynamics/dualHingedRigidBodies/dualHingedRigidBodyStateEffector.cpp
|
ian-cooke/basilisk_mag
|
a8b1e37c31c1287549d6fd4d71fcaa35b6fc3f14
|
[
"0BSD"
] | 1
|
2019-03-13T20:52:22.000Z
|
2019-03-13T20:52:22.000Z
|
src/simulation/dynamics/dualHingedRigidBodies/dualHingedRigidBodyStateEffector.cpp
|
ian-cooke/basilisk_mag
|
a8b1e37c31c1287549d6fd4d71fcaa35b6fc3f14
|
[
"0BSD"
] | null | null | null |
/*
ISC License
Copyright (c) 2016, Autonomous Vehicle Systems Lab, University of Colorado at Boulder
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, 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.
*/
#include "dualHingedRigidBodyStateEffector.h"
DualHingedRigidBodyStateEffector::DualHingedRigidBodyStateEffector()
{
// - zero the mass props and mass prop rates contributions
this->effProps.mEff = 0.0;
this->effProps.mEffDot = 0.0;
this->effProps.rEff_CB_B.setZero();
this->effProps.IEffPntB_B.setZero();
this->effProps.rEffPrime_CB_B.setZero();
this->effProps.IEffPrimePntB_B.setZero();
this->matrixFDHRB.resize(2, 3);
this->matrixGDHRB.resize(2, 3);
// - Initialize the variables to working values
this->mass1 = 0.0;
this->d1 = 1.0;
this->k1 = 1.0;
this->c1 = 0.0;
this->mass2 = 0.0;
this->d2 = 1.0;
this->k2 = 1.0;
this->c2 = 0.0;
this->theta1Init = 0.0;
this->theta1DotInit = 0.0;
this->theta2Init = 0.0;
this->theta2DotInit = 0.0;
this->IPntS1_S1.setIdentity();
this->IPntS2_S2.setIdentity();
this->rH1B_B.setZero();
this->dcmH1B.setIdentity();
this->thetaH2S1 = 0.0;
this->nameOfTheta1State = "hingedRigidBodyTheta1";
this->nameOfTheta1DotState = "hingedRigidBodyTheta1Dot";
this->nameOfTheta2State = "hingedRigidBodyTheta2";
this->nameOfTheta2DotState = "hingedRigidBodyTheta2Dot";
return;
}
DualHingedRigidBodyStateEffector::~DualHingedRigidBodyStateEffector()
{
return;
}
void DualHingedRigidBodyStateEffector::linkInStates(DynParamManager& statesIn)
{
// - Get access to the hubs sigma, omegaBN_B and velocity needed for dynamic coupling
this->hubVelocity = statesIn.getStateObject("hubVelocity");
this->hubSigma = statesIn.getStateObject("hubSigma");
this->hubOmega = statesIn.getStateObject("hubOmega");
this->g_N = statesIn.getPropertyReference("g_N");
return;
}
void DualHingedRigidBodyStateEffector::registerStates(DynParamManager& states)
{
// - Register the states associated with hinged rigid bodies - theta and thetaDot
this->theta1State = states.registerState(1, 1, this->nameOfTheta1State);
this->theta1DotState = states.registerState(1, 1, this->nameOfTheta1DotState);
this->theta2State = states.registerState(1, 1, this->nameOfTheta2State);
this->theta2DotState = states.registerState(1, 1, this->nameOfTheta2DotState);
// - Add this code to allow for non-zero initial conditions, as well hingedRigidBody
Eigen::MatrixXd theta1InitMatrix(1,1);
theta1InitMatrix(0,0) = this->theta1Init;
this->theta1State->setState(theta1InitMatrix);
Eigen::MatrixXd theta1DotInitMatrix(1,1);
theta1DotInitMatrix(0,0) = this->theta1DotInit;
this->theta1DotState->setState(theta1DotInitMatrix);
Eigen::MatrixXd theta2InitMatrix(1,1);
theta2InitMatrix(0,0) = this->theta2Init;
this->theta2State->setState(theta2InitMatrix);
Eigen::MatrixXd theta2DotInitMatrix(1,1);
theta2DotInitMatrix(0,0) = this->theta2DotInit;
this->theta2DotState->setState(theta2DotInitMatrix);
return;
}
void DualHingedRigidBodyStateEffector::updateEffectorMassProps(double integTime)
{
// - Give the mass of the hinged rigid body to the effProps mass
this->effProps.mEff = this->mass1 + this->mass2;
// - find hinged rigid bodies' position with respect to point B
// - First need to grab current states
this->theta1 = this->theta1State->getState()(0, 0);
this->theta1Dot = this->theta1DotState->getState()(0, 0);
this->theta2 = this->theta2State->getState()(0, 0);
this->theta2Dot = this->theta2DotState->getState()(0, 0);
// - Next find the sHat unit vectors
Eigen::Matrix3d dcmS1H1;
dcmS1H1 = eigenM2(this->theta1);
this->dcmS1B = dcmS1H1*this->dcmH1B;
Eigen::Matrix3d dcmH2S1;
dcmH2S1 = eigenM2(this->thetaH2S1);
Eigen::Matrix3d dcmH2B;
dcmH2B = dcmH2S1*this->dcmS1B;
Eigen::Matrix3d dcmS2H2;
dcmS2H2 = eigenM2(this->theta2);
this->dcmS2B = dcmS2H2 * dcmH2B;
this->sHat11_B = this->dcmS1B.row(0);
this->sHat12_B = this->dcmS1B.row(1);
this->sHat13_B = this->dcmS1B.row(2);
this->sHat21_B = this->dcmS2B.row(0);
this->sHat22_B = this->dcmS2B.row(1);
this->sHat23_B = this->dcmS2B.row(2);
this->rS1B_B = this->rH1B_B - this->d1*this->sHat11_B;
this->rS2B_B = this->rH1B_B - this->l1*this->sHat11_B - this->d2*this->sHat21_B;
this->effProps.rEff_CB_B = 1.0/this->effProps.mEff*(this->mass1*this->rS1B_B + this->mass2*this->rS2B_B);
// - Find the inertia of the hinged rigid body about point B
// - Define rTildeSB_B
this->rTildeS1B_B = eigenTilde(this->rS1B_B);
this->rTildeS2B_B = eigenTilde(this->rS2B_B);
this->effProps.IEffPntB_B = this->dcmS1B.transpose()*this->IPntS1_S1*this->dcmS1B + this->mass1*this->rTildeS1B_B*this->rTildeS1B_B.transpose() + this->dcmS2B.transpose()*this->IPntS2_S2*this->dcmS2B + this->mass2*this->rTildeS2B_B*this->rTildeS2B_B.transpose();
// First, find the rPrimeSB_B
this->rPrimeS1B_B = this->d1*this->theta1Dot*this->sHat13_B;
this->rPrimeS2B_B = this->l1*this->theta1Dot*this->sHat13_B + this->d2*(this->theta1Dot + this->theta2Dot)*this->sHat23_B;
this->effProps.rEffPrime_CB_B = 1.0/this->effProps.mEff*(this->mass1*this->rPrimeS1B_B + this->mass2*this->rPrimeS2B_B);
// - Next find the body time derivative of the inertia about point B
// - Define tilde matrix of rPrimeSB_B
this->rPrimeTildeS1B_B = eigenTilde(this->rPrimeS1B_B);
this->rPrimeTildeS2B_B = eigenTilde(this->rPrimeS2B_B);
// - Find body time derivative of IPntS_B
this->IS1PrimePntS1_B = this->theta1Dot*(this->IPntS1_S1(2,2) - this->IPntS1_S1(0,0))*(this->sHat11_B*this->sHat13_B.transpose() + this->sHat13_B*this->sHat11_B.transpose());
this->IS2PrimePntS2_B = (this->theta1Dot+this->theta2Dot)*(this->IPntS2_S2(2,2) - this->IPntS2_S2(0,0))*(this->sHat21_B*this->sHat23_B.transpose() + this->sHat23_B*this->sHat21_B.transpose());
// - Find body time derivative of IPntB_B
this->effProps.IEffPrimePntB_B = this->IS1PrimePntS1_B - this->mass1*(this->rPrimeTildeS1B_B*this->rTildeS1B_B + this->rTildeS1B_B*this->rPrimeTildeS1B_B) + this->IS2PrimePntS2_B - this->mass2*(this->rPrimeTildeS2B_B*this->rTildeS2B_B + this->rTildeS2B_B*this->rPrimeTildeS2B_B);
return;
}
void DualHingedRigidBodyStateEffector::updateContributions(double integTime, BackSubMatrices & backSubContr, Eigen::Vector3d sigma_BN, Eigen::Vector3d omega_BN_B, Eigen::Vector3d g_N)
{
Eigen::MRPd sigmaBNLocal;
Eigen::Matrix3d dcmBN; /* direction cosine matrix from N to B */
Eigen::Matrix3d dcmNB; /* direction cosine matrix from B to N */
Eigen::Vector3d gravityTorquePntH1_B; /* torque of gravity on HRB about Pnt H */
Eigen::Vector3d gravityTorquePntH2_B; /* torque of gravity on HRB about Pnt H */
Eigen::Vector3d gLocal_N; /* gravitational acceleration in N frame */
Eigen::Vector3d g_B; /* gravitational acceleration in B frame */
gLocal_N = *this->g_N;
// - Find dcmBN
sigmaBNLocal = (Eigen::Vector3d )this->hubSigma->getState();
dcmNB = sigmaBNLocal.toRotationMatrix();
dcmBN = dcmNB.transpose();
// - Map gravity to body frame
g_B = dcmBN*gLocal_N;
// - Define gravity terms
Eigen::Vector3d gravTorquePan1PntH1 = -this->d1*this->sHat11_B.cross(this->mass1*g_B);
Eigen::Vector3d gravForcePan2 = this->mass2*g_B;
Eigen::Vector3d gravTorquePan2PntH2 = -this->d2*this->sHat21_B.cross(this->mass2*g_B);
// - Define omegaBN_S
this->omegaBNLoc_B = this->hubOmega->getState();
this->omegaBN_S1 = this->dcmS1B*this->omegaBNLoc_B;
this->omegaBN_S2 = this->dcmS2B*this->omegaBNLoc_B;
// - Define omegaTildeBNLoc_B
this->omegaTildeBNLoc_B = eigenTilde(this->omegaBNLoc_B);
// - Define matrices needed for back substitution
//gravityTorquePntH1_B = -this->d1*this->sHat11_B.cross(this->mass1*g_B); //Need to review these equations and implement them - SJKC
//gravityTorquePntH2_B = -this->d2*this->sHat21_B.cross(this->mass2*g_B); //Need to review these equations and implement them - SJKC
this->matrixADHRB(0,0) = this->IPntS1_S1(1,1) + this->mass1*this->d1*this->d1 + this->mass2*this->l1*this->l1 + this->mass2*this->l1*this->d2*this->sHat13_B.transpose()*(this->sHat23_B);
this->matrixADHRB(0,1) = this->mass2*this->l1*this->d2*this->sHat13_B.transpose()*(this->sHat23_B);
this->matrixADHRB(1,0) = IPntS2_S2(1,1) + this->mass2*this->d2*this->d2 + this->mass2*this->l1*this->d2*this->sHat23_B.transpose()*this->sHat13_B;
this->matrixADHRB(1,1) = this->IPntS2_S2(1,1) + this->mass2*this->d2*this->d2;
this->matrixEDHRB = this->matrixADHRB.inverse();
this->matrixFDHRB.row(0) = -(this->mass2*this->l1 + this->mass1*this->d1)*this->sHat13_B.transpose();
this->matrixFDHRB.row(1) = -this->mass2*this->d2*this->sHat23_B.transpose();
this->matrixGDHRB.row(0) = -(this->IPntS1_S1(1,1)*this->sHat12_B.transpose() - this->mass1*this->d1*this->sHat13_B.transpose()*this->rTildeS1B_B - this->mass2*this->l1*this->sHat13_B.transpose()*this->rTildeS2B_B);
this->matrixGDHRB.row(1) = -(this->IPntS2_S2(1,1)*this->sHat22_B.transpose() - this->mass2*this->d2*this->sHat23_B.transpose()*this->rTildeS2B_B);
this->vectorVDHRB(0) = -(this->IPntS1_S1(0,0) - this->IPntS1_S1(2,2))*this->omegaBN_S1(2)*this->omegaBN_S1(0) - this->k1*this->theta1 - this->c1*this->theta1Dot + this->k2*this->theta2 + this->c2*this->theta2Dot + this->sHat12_B.dot(gravTorquePan1PntH1) + this->l1*this->sHat13_B.dot(gravForcePan2)
- this->mass1*this->d1*this->sHat13_B.transpose()*(2*this->omegaTildeBNLoc_B*this->rPrimeS1B_B + this->omegaTildeBNLoc_B*this->omegaTildeBNLoc_B*this->rS1B_B)
- this->mass2*this->l1*this->sHat13_B.transpose()*(2*this->omegaTildeBNLoc_B*this->rPrimeS2B_B + this->omegaTildeBNLoc_B*this->omegaTildeBNLoc_B*this->rS2B_B + this->l1*this->theta1Dot*this->theta1Dot*this->sHat11_B + this->d2*(this->theta1Dot + this->theta2Dot)*(this->theta1Dot + this->theta2Dot)*this->sHat21_B); //still missing torque and force terms - SJKC
this->vectorVDHRB(1) = -(this->IPntS2_S2(0,0) - this->IPntS2_S2(2,2))*this->omegaBN_S2(2)*this->omegaBN_S2(0)
- this->k2*this->theta2 - this->c2*this->theta2Dot + this->sHat22_B.dot(gravTorquePan2PntH2) - this->mass2*this->d2*this->sHat23_B.transpose()*(2*this->omegaTildeBNLoc_B*this->rPrimeS2B_B + this->omegaTildeBNLoc_B*this->omegaTildeBNLoc_B*this->rS2B_B + this->l1*this->theta1Dot*this->theta1Dot*this->sHat11_B); // still missing torque term. - SJKC
// - Start defining them good old contributions - start with translation
// - For documentation on contributions see Allard, Diaz, Schaub flex/slosh paper
backSubContr.matrixA = (this->mass1*this->d1*this->sHat13_B + this->mass2*this->l1*this->sHat13_B + this->mass2*this->d2*this->sHat23_B)*matrixEDHRB.row(0)*this->matrixFDHRB + this->mass2*this->d2*this->sHat23_B*this->matrixEDHRB.row(1)*this->matrixFDHRB;
backSubContr.matrixB = (this->mass1*this->d1*this->sHat13_B + this->mass2*this->l1*this->sHat13_B + this->mass2*this->d2*this->sHat23_B)*this->matrixEDHRB.row(0)*(matrixGDHRB) + this->mass2*this->d2*this->sHat23_B*this->matrixEDHRB.row(1)*(matrixGDHRB);
backSubContr.vecTrans = -(this->mass1*this->d1*this->theta1Dot*this->theta1Dot*this->sHat11_B + this->mass2*(this->l1*this->theta1Dot*this->theta1Dot*this->sHat11_B + this->d2*(this->theta1Dot+this->theta2Dot)*(this->theta1Dot+this->theta2Dot)*this->sHat21_B)
+ (this->mass1*this->d1*this->sHat13_B + this->mass2*this->l1*this->sHat13_B + this->mass2*this->d2*this->sHat23_B)*this->matrixEDHRB.row(0)*this->vectorVDHRB + this->mass2*this->d2*this->sHat23_B*this->matrixEDHRB.row(1)*this->vectorVDHRB);
// - Define rotational matrice contributions (Eq 96 in paper)
backSubContr.matrixC = (this->IPntS1_S1(1,1)*this->sHat12_B + this->mass1*this->d1*this->rTildeS1B_B*this->sHat13_B + this->IPntS2_S2(1,1)*this->sHat22_B + this->mass2*this->l1*this->rTildeS2B_B*this->sHat13_B + this->mass2*this->d2*this->rTildeS2B_B*this->sHat23_B)*this->matrixEDHRB.row(0)*this->matrixFDHRB
+ (this->IPntS2_S2(1,1)*this->sHat22_B + this->mass2*this->d2*this->rTildeS2B_B*this->sHat23_B)*this->matrixEDHRB.row(1)*this->matrixFDHRB;
backSubContr.matrixD = (this->IPntS1_S1(1,1)*this->sHat12_B + this->mass1*this->d1*this->rTildeS1B_B*this->sHat13_B + this->IPntS2_S2(1,1)*this->sHat22_B + this->mass2*this->l1*this->rTildeS2B_B*this->sHat13_B + this->mass2*this->d2*this->rTildeS2B_B*this->sHat23_B)*this->matrixEDHRB.row(0)*this->matrixGDHRB
+(this->IPntS2_S2(1,1)*this->sHat22_B + this->mass2*this->d2*this->rTildeS2B_B*this->sHat23_B)*this->matrixEDHRB.row(1)*this->matrixGDHRB;
backSubContr.vecRot = -(this->theta1Dot*this->IPntS1_S1(1,1)*this->omegaTildeBNLoc_B*this->sHat12_B
+ this->mass1*this->omegaTildeBNLoc_B*this->rTildeS1B_B*this->rPrimeS1B_B + this->mass1*this->d1*this->theta1Dot*this->theta1Dot*this->rTildeS1B_B*this->sHat11_B + (this->theta1Dot+this->theta2Dot)*this->IPntS2_S2(1,1)*this->omegaTildeBNLoc_B*this->sHat22_B + this->mass2*this->omegaTildeBNLoc_B*this->rTildeS2B_B*this->rPrimeS2B_B
+ this->mass2*this->rTildeS2B_B*(this->l1*this->theta1Dot*this->theta1Dot*this->sHat11_B + this->d2*(this->theta1Dot+this->theta2Dot)*(this->theta1Dot+this->theta2Dot)*this->sHat21_B) + (this->IPntS1_S1(1,1)*this->sHat12_B + this->mass1*this->d1*this->rTildeS1B_B*this->sHat13_B + this->IPntS2_S2(1,1)*this->sHat22_B
+ this->mass2*this->l1*this->rTildeS2B_B*this->sHat13_B + this->mass2*this->d2*this->rTildeS2B_B*this->sHat23_B)*this->matrixEDHRB.row(0)*this->vectorVDHRB + (this->IPntS2_S2(1,1)*this->sHat22_B + this->mass2*this->d2*this->rTildeS2B_B*this->sHat23_B)*this->matrixEDHRB.row(1)*this->vectorVDHRB);
return;
}
void DualHingedRigidBodyStateEffector::computeDerivatives(double integTime, Eigen::Vector3d rDDot_BN_N, Eigen::Vector3d omegaDot_BN_B, Eigen::Vector3d sigma_BN)
{
// - Define necessarry variables
Eigen::MRPd sigmaBNLocal;
Eigen::Matrix3d dcmBN; /* direction cosine matrix from N to B */
Eigen::Matrix3d dcmNB; /* direction cosine matrix from B to N */
Eigen::MatrixXd theta1DDot(1,1); /* thetaDDot variable to send to state manager */
Eigen::MatrixXd theta2DDot(1,1); /* thetaDDot variable to send to state manager */
Eigen::Vector3d rDDotBNLoc_N; /* second time derivative of rBN in N frame */
Eigen::Vector3d rDDotBNLoc_B; /* second time derivative of rBN in B frame */
Eigen::Vector3d omegaDotBNLoc_B; /* time derivative of omegaBN in B frame */
// Grab necessarry values from manager (these have been previously computed in hubEffector)
rDDotBNLoc_N = this->hubVelocity->getStateDeriv();
sigmaBNLocal = (Eigen::Vector3d )this->hubSigma->getState();
omegaDotBNLoc_B = this->hubOmega->getStateDeriv();
dcmNB = sigmaBNLocal.toRotationMatrix();
dcmBN = dcmNB.transpose();
rDDotBNLoc_B = dcmBN*rDDotBNLoc_N;
// - Compute Derivatives
// - First is trivial
this->theta1State->setDerivative(theta1DotState->getState());
// - Second, a little more involved - see Allard, Diaz, Schaub flex/slosh paper
theta1DDot(0,0) = this->matrixEDHRB.row(0).dot(this->matrixFDHRB*rDDotBNLoc_B) + this->matrixEDHRB.row(0)*this->matrixGDHRB*omegaDotBNLoc_B + this->matrixEDHRB.row(0)*this->vectorVDHRB;
this->theta1DotState->setDerivative(theta1DDot);
this->theta2State->setDerivative(theta2DotState->getState());
theta2DDot(0,0) = this->matrixEDHRB.row(1)*(this->matrixFDHRB*rDDotBNLoc_B) + this->matrixEDHRB.row(1).dot(this->matrixGDHRB*omegaDotBNLoc_B) + this->matrixEDHRB.row(1)*this->vectorVDHRB;
this->theta2DotState->setDerivative(theta2DDot);
return;
}
/*! This method is for calculating the contributions of the DHRB state effector to the energy and momentum of the s/c */
void DualHingedRigidBodyStateEffector::updateEnergyMomContributions(double integTime, Eigen::Vector3d & rotAngMomPntCContr_B, double & rotEnergyContr, Eigen::Vector3d omega_BN_B)
{
// - Get the current omega state
Eigen::Vector3d omegaLocal_BN_B;
omegaLocal_BN_B = hubOmega->getState();
// - Find rotational angular momentum contribution from hub
Eigen::Vector3d omega_S1B_B;
Eigen::Vector3d omega_S2B_B;
Eigen::Vector3d omega_S1N_B;
Eigen::Vector3d omega_S2N_B;
Eigen::Matrix3d IPntS1_B;
Eigen::Matrix3d IPntS2_B;
Eigen::Vector3d rDot_S1B_B;
Eigen::Vector3d rDot_S2B_B;
omega_S1B_B = this->theta1Dot*this->sHat12_B;
omega_S2B_B = (this->theta1Dot + this->theta2Dot)*this->sHat22_B;
omega_S1N_B = omega_S1B_B + omegaLocal_BN_B;
omega_S2N_B = omega_S2B_B + omegaLocal_BN_B;
IPntS1_B = this->dcmS1B.transpose()*this->IPntS1_S1*this->dcmS1B;
IPntS2_B = this->dcmS2B.transpose()*this->IPntS2_S2*this->dcmS2B;
rDot_S1B_B = this->rPrimeS1B_B + omegaLocal_BN_B.cross(this->rS1B_B);
rDot_S2B_B = this->rPrimeS2B_B + omegaLocal_BN_B.cross(this->rS2B_B);
rotAngMomPntCContr_B = IPntS1_B*omega_S1N_B + this->mass1*this->rS1B_B.cross(rDot_S1B_B)
+ IPntS2_B*omega_S2N_B + this->mass2*this->rS2B_B.cross(rDot_S2B_B);
// - Find rotational energy contribution from the hub
double rotEnergyContrS1;
double rotEnergyContrS2;
rotEnergyContrS1 = 0.5*omega_S1N_B.dot(IPntS1_B*omega_S1N_B)
+ 0.5*this->mass1*rDot_S1B_B.dot(rDot_S1B_B)
+ 0.5*this->k1*this->theta1*this->theta1;
rotEnergyContrS2 = 0.5*omega_S2N_B.dot(IPntS2_B*omega_S2N_B)
+ 0.5*this->mass2*rDot_S2B_B.dot(rDot_S2B_B)
+ 0.5*this->k2*this->theta2*this->theta2;
rotEnergyContr = rotEnergyContrS1 + rotEnergyContrS2;
return;
}
| 62.161184
| 389
| 0.702598
|
ian-cooke
|
bc43ddd9bd88a47b21799d3839ef60f62e13b2b3
| 4,262
|
cpp
|
C++
|
src/Lexer/LexerGenerator.cpp
|
AlexRoar/SxTree
|
7d37ed0ff5c5bdd3c497c070825ca4ebe10eab0e
|
[
"MIT"
] | null | null | null |
src/Lexer/LexerGenerator.cpp
|
AlexRoar/SxTree
|
7d37ed0ff5c5bdd3c497c070825ca4ebe10eab0e
|
[
"MIT"
] | null | null | null |
src/Lexer/LexerGenerator.cpp
|
AlexRoar/SxTree
|
7d37ed0ff5c5bdd3c497c070825ca4ebe10eab0e
|
[
"MIT"
] | null | null | null |
/*
* =================================================
* Copyright © 2021
* Aleksandr Dremov
*
* This code has been written by Aleksandr Dremov
* Check license agreement of this project to evade
* possible illegal use.
* =================================================
*/
#include "Lexer/LexerGenerator.h"
#include "Lexer/StructureUnits.h"
#include <string>
#include <regex>
#include <vector>
namespace SxTree::Lexer::Generator {
using std::string;
using std::vector;
using LexerStruct::Expression;
using LexerStruct::Value;
static const string contents =
#include "templates/lexerStructTemplate.h.template"
static const string contentsHeader =
#include "templates/lexerStructTemplateHeader.h.template"
static string valTypeString(Value::ValueType type) {
switch (type) {
case Value::VAL_EXPRESSION:
return "Value::VAL_EXPRESSION";
case Value::VAL_REGEXP:
return "Value::VAL_REGEXP";
case Value::VAL_SKIP:
return "Value::VAL_SKIP";
}
}
static string exprTypeString(Expression::ExprType type) {
switch (type) {
case Expression::EXP_ONE:
return "Expression::EXP_ONE";
case Expression::EXP_ANY:
return "Expression::EXP_ANY";
case Expression::EXP_OPTIONAL:
return "Expression::EXP_OPTIONAL";
}
}
static string generateExpression(const Expression &exp) {
string output = "{{";
for (const auto &val: exp.possible) {
output += "{ R\"(" + val.regexString + ")\", " + valTypeString(val.type) + "," +
generateExpression(val.expr) + "},";
}
output += "}, " + exprTypeString(exp.type) + "}";
return output;
}
static string generateLexemesToStringBody(const SxTree::LexerStruct::LexerStruct &structure) {
string output;
for (auto &lex: structure.getLexemesMap())
output += "\t\tcase SxTree::Lexer::LexemeType::lex_" + lex.first + ": return \"" + lex.first + "\";\n";
return output;
}
static string generateLexerStruct(const SxTree::LexerStruct::LexerStruct &structure) {
string output = "{\n";
for (const auto &rule: structure.getRules())
output += "\t{" + std::to_string(rule.id + 1) + ", " + generateExpression(rule.expression) + "},\n";
output += "}";
return output;
}
static string generateIdsEnum(const SxTree::LexerStruct::LexerStruct &structure) {
string output = "{\n";
const auto &ruleIdsNo = structure.getLexemesMap();
vector<const string *> orderedIds(ruleIdsNo.size() + 1, nullptr);
string none = "NONE";
orderedIds[0] = &none;
for (const auto &id: ruleIdsNo)
orderedIds[id.second + 1] = &id.first;
for (unsigned i = 0; i < orderedIds.size(); i++)
output += "\tlex_" + *(orderedIds[i]) + " = " + std::to_string(i) + ",\n";
output += "}";
return output;
}
string getCompleteLexerStruct(const SxTree::LexerStruct::LexerStruct &structure, const string& headerName) {
string newContent = contents;
newContent = replaceFirstOccurrence(newContent, "HEADERNAME", headerName);
newContent = replaceFirstOccurrence(newContent, "INSERT", generateLexerStruct(structure));
newContent = replaceFirstOccurrence(newContent, "SWITCHBODY", generateLexemesToStringBody(structure));
newContent = replaceFirstOccurrence(newContent, "LEXNUM", std::to_string(structure.getLexemesMap().size()));
return newContent;
}
string getHeader(const SxTree::LexerStruct::LexerStruct &structure) {
string newContent = contentsHeader;
newContent = replaceFirstOccurrence(newContent, "ENUM", generateIdsEnum(structure));
return newContent;
}
std::string replaceFirstOccurrence(
std::string &s,
const std::string &toReplace,
const std::string &replaceWith) {
std::size_t pos = s.find(toReplace);
if (pos == std::string::npos) return s;
return s.replace(pos, toReplace.length(), replaceWith);
}
}
| 34.934426
| 116
| 0.601361
|
AlexRoar
|
a4bae2b46f729cf5e390dec87ea27ca6e79be0d4
| 462
|
cc
|
C++
|
src/base/Exception.cc
|
plantree/Slack
|
469fff18792a6d4d20c409f0331e3c93117c5ddf
|
[
"MIT"
] | 2
|
2019-07-15T08:34:38.000Z
|
2019-08-07T12:27:23.000Z
|
src/base/Exception.cc
|
plantree/Slack
|
469fff18792a6d4d20c409f0331e3c93117c5ddf
|
[
"MIT"
] | null | null | null |
src/base/Exception.cc
|
plantree/Slack
|
469fff18792a6d4d20c409f0331e3c93117c5ddf
|
[
"MIT"
] | null | null | null |
/*
* @Author: py.wang
* @Date: 2019-05-04 09:08:42
* @Last Modified by: py.wang
* @Last Modified time: 2019-06-06 18:26:02
*/
#include "src/base/Exception.h"
#include "src/base/CurrentThread.h"
#include <iostream>
#include <cxxabi.h>
#include <execinfo.h>
#include <stdlib.h>
#include <stdio.h>
namespace slack
{
Exception::Exception(string msg)
: message_(std::move(msg)),
stack_(CurrentThread::stackTrace(false))
{
}
} // namespace slack
| 17.111111
| 44
| 0.67316
|
plantree
|
a4bb20896fd90541883eaa179780cb85402ae1ed
| 2,078
|
cpp
|
C++
|
dali/public-api/signals/signal-slot-connections.cpp
|
vcebollada/dali-core
|
1f880695d4f6cb871db7f946538721e882ba1633
|
[
"Apache-2.0",
"BSD-3-Clause"
] | 1
|
2016-08-05T09:58:38.000Z
|
2016-08-05T09:58:38.000Z
|
dali/public-api/signals/signal-slot-connections.cpp
|
tizenorg/platform.core.uifw.dali-core
|
dd89513b4bb1fdde74a83996c726e10adaf58349
|
[
"Apache-2.0"
] | 1
|
2020-03-22T10:19:17.000Z
|
2020-03-22T10:19:17.000Z
|
dali/public-api/signals/signal-slot-connections.cpp
|
tizenorg/platform.core.uifw.dali-core
|
dd89513b4bb1fdde74a83996c726e10adaf58349
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright (c) 2015 Samsung Electronics Co., Ltd.
*
* 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.
*
*/
// CLASS HEADER
#include <dali/public-api/signals/signal-slot-connections.h>
// EXTERNAL INCLUDES
#include <cstddef>
// INTERNAL INCLUDES
#include <dali/public-api/signals/callback.h>
namespace Dali
{
SlotConnection::SlotConnection( SlotObserver* slotObserver, CallbackBase* callback )
: mSlotObserver( slotObserver ),
mCallback( callback )
{
}
SlotConnection::~SlotConnection()
{
}
CallbackBase* SlotConnection::GetCallback()
{
return mCallback;
}
SlotObserver* SlotConnection::GetSlotObserver()
{
return mSlotObserver;
}
SignalConnection::SignalConnection( CallbackBase* callback )
: mSignalObserver( NULL ),
mCallback( callback )
{
}
SignalConnection::SignalConnection( SignalObserver* signalObserver, CallbackBase* callback )
: mSignalObserver( signalObserver ),
mCallback( callback )
{
}
SignalConnection::~SignalConnection()
{
// signal connections have ownership of the callback.
delete mCallback;
}
void SignalConnection::Disconnect( SlotObserver* slotObserver )
{
if( mSignalObserver )
{
// tell the slot the signal wants to disconnect
mSignalObserver->SignalDisconnected( slotObserver, mCallback );
mSignalObserver = NULL;
}
// we own the callback, SignalObserver is expected to delete the SlotConnection on Disconnected so its pointer to our mCallback is no longer used
delete mCallback;
mCallback = NULL;
}
CallbackBase* SignalConnection::GetCallback()
{
return mCallback;
}
} // namespace Dali
| 23.613636
| 147
| 0.751203
|
vcebollada
|
a4be20b3add2814e1866e728892150ded1e63d33
| 1,406
|
cpp
|
C++
|
BOJ_solve/8143.cpp
|
python-programmer1512/Code_of_gunwookim
|
e72e6724fb9ee6ccf2e1064583956fa954ba0282
|
[
"MIT"
] | 4
|
2021-01-27T11:51:30.000Z
|
2021-01-30T17:02:55.000Z
|
BOJ_solve/8143.cpp
|
python-programmer1512/Code_of_gunwookim
|
e72e6724fb9ee6ccf2e1064583956fa954ba0282
|
[
"MIT"
] | null | null | null |
BOJ_solve/8143.cpp
|
python-programmer1512/Code_of_gunwookim
|
e72e6724fb9ee6ccf2e1064583956fa954ba0282
|
[
"MIT"
] | 5
|
2021-01-27T11:46:12.000Z
|
2021-05-06T05:37:47.000Z
|
#include <bits/stdc++.h>
#define x first
#define y second
#define pb push_back
#define all(v) v.begin(),v.end()
#pragma gcc optimize("O3")
#pragma gcc optimize("Ofast")
#pragma gcc optimize("unroll-loops")
using namespace std;
const int INF = 1e9;
const int TMX = 1 << 18;
const long long llINF = 2e18;
const long long mod = 1e18;
const long long hashmod = 100003;
typedef long long ll;
typedef long double ld;
typedef pair <int,int> pi;
typedef pair <ll,ll> pl;
typedef vector <int> vec;
typedef vector <pi> vecpi;
typedef long long ll;
int n,m,p[1000005],hole[1000005];
int ans,a[1005][1005];
vec q[1005];
vecpi op[1005];
int f(int x,int y) {return (x-1)*m+y;}
int Find(int x) {return (x^p[x] ? p[x] = Find(p[x]) : x);}
int main() {
ios_base::sync_with_stdio(false); cin.tie(0);
cin >> n >> m;
for(int i = 1;i <= n;i++) {
for(int j = 1;j <= m;j++) {
cin >> a[i][j];
p[f(i,j)] = f(i,j);
if(a[i][j] > 0) q[a[i][j]].pb(f(i,j));
}
}
for(int i = 1;i <= n;i++) {
for(int j = 1;j <= m;j++) {
if(i < n) op[max(abs(a[i][j]),abs(a[i+1][j]))].pb({f(i,j),f(i+1,j)});
if(j < m) op[max(abs(a[i][j]),abs(a[i][j+1]))].pb({f(i,j),f(i,j+1)});
}
}
for(int i = 1;i <= 1000;i++) {
for(pi j : op[i]) {
if(Find(j.x) == Find(j.y)) continue;
hole[p[j.x]] |= hole[p[j.y]];
p[p[j.y]] = p[j.x];
}
for(int j : q[i]) {
if(!hole[Find(j)]) ans++, hole[p[j]] = 1;
}
}
cout << ans;
}
| 24.666667
| 72
| 0.555477
|
python-programmer1512
|
a4c0b3a4a0bd799c0bf2bcb12e8d575c70435f37
| 3,177
|
hpp
|
C++
|
compile_time_sha1.hpp
|
bb1950328/Compile-time-hash-functions
|
f0da28457eec122901c90849e544d488009de36a
|
[
"MIT"
] | 26
|
2021-07-21T18:25:38.000Z
|
2021-07-29T18:25:06.000Z
|
compile_time_sha1.hpp
|
bb1950328/Compile-time-hash-functions
|
f0da28457eec122901c90849e544d488009de36a
|
[
"MIT"
] | 2
|
2021-07-22T13:52:51.000Z
|
2021-07-28T08:21:47.000Z
|
compile_time_sha1.hpp
|
bb1950328/Compile-time-hash-functions
|
f0da28457eec122901c90849e544d488009de36a
|
[
"MIT"
] | 1
|
2021-07-27T15:28:32.000Z
|
2021-07-27T15:28:32.000Z
|
#ifndef COMPILE_TIME_SHA1_H
#define COMPILE_TIME_SHA1_H
#include "crypto_hash.hpp"
#define MASK 0xffffffff
#define SHA1_HASH_SIZE 5
template<typename H=const char *>
class SHA1 : public CryptoHash<SHA1_HASH_SIZE> {
private:
constexpr static uint32_t scheduled(CircularQueue<uint32_t,16> queue) {
return leftrotate(queue[13]^queue[8]^queue[2]^queue[0],1);
}
constexpr static uint32_t k[4] = { 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6 };
struct hash_parameters {
const Array<uint32_t,SHA1_HASH_SIZE> arr;
const uint32_t f_array[4][5];
template <typename ... Args>
constexpr hash_parameters(Args ... args):
arr{args...},
f_array{ {arr[2],arr[3],arr[1],arr[3],MASK},
{arr[2],arr[1],MASK,arr[3],MASK},
{arr[2],arr[1],arr[3],arr[1],arr[2]},
{arr[2],arr[1],MASK,arr[3],MASK} } {}
constexpr hash_parameters() :
hash_parameters((uint32_t) 0x67452301, (uint32_t) 0xefcdab89,
(uint32_t) 0x98badcfe, (uint32_t) 0x10325476,
(uint32_t) 0xC3D2E1F0) {}
constexpr uint32_t operator [](int index) { return arr[index]; }
};
using Hash_T = SHA1<H>;
using PaddedValue_T = PaddedValue<H>;
using Section_T = Section<H>;
constexpr Array<uint32_t,SHA1_HASH_SIZE> create_hash(PaddedValue_T value, hash_parameters h, int block_index=0) {
return block_index*64 == value.total_size ? h.arr
: create_hash(
value,
hash_block(Section_T(value,block_index*16,scheduled),h,h,block_index*16),
block_index+1);
}
// (a ^ b) & c ^ (d & e)
constexpr uint32_t f(int i, struct hash_parameters h) const {
return (h.f_array[i][0] ^ h.f_array[i][1]) & h.f_array[i][2] ^ (h.f_array[i][3] & h.f_array[i][4]);
}
constexpr uint32_t get_updated_h0(Section_T section, int i, struct hash_parameters h) const {
return leftrotate(h[0],5) + f(i/20,h) + h[4] + k[i/20] + section[i % 16];
}
constexpr hash_parameters hash_section(Section_T section, hash_parameters h, int start, int i=0) const {
return i == 16 ? h :
hash_section( section, {
get_updated_h0(section,start+i,h),
h[0],
leftrotate(h[1],30),
h[2],
h[3]
}, start, i+1);
}
constexpr hash_parameters hash_block(Section_T section, hash_parameters h , hash_parameters prev_h,
int start_index, int i=0) const {
return i == 80 ?
(hash_parameters) {
prev_h[0]+h[0],
prev_h[1]+h[1],
prev_h[2]+h[2],
prev_h[3]+h[3],
prev_h[4]+h[4]
} : hash_block(
Section_T(section,start_index+i+16,scheduled),
hash_section(section,h,i),
prev_h, start_index, i+16);
}
public:
constexpr SHA1(H input) :
CryptoHash<SHA1_HASH_SIZE>(create_hash(PaddedValue_T(input,true),{})) {}
};
typedef SHA1<> SHA1String;
template<typename T> constexpr uint32_t SHA1<T>::k[4];
#endif
| 30.257143
| 117
| 0.585143
|
bb1950328
|
a4c81611a034d29574d4a0c23b6a8d8a3cc54020
| 80
|
cpp
|
C++
|
test/com/facebook/buck/cxx/testdata/prebuilt_cxx_from_genrule/core/binary.cpp
|
Unknoob/buck
|
2dfc734354b326f2f66896dde7746a11965d5a13
|
[
"Apache-2.0"
] | 8,027
|
2015-01-02T05:31:44.000Z
|
2022-03-31T07:08:09.000Z
|
test/com/facebook/buck/cxx/testdata/prebuilt_cxx_from_genrule/core/binary.cpp
|
Unknoob/buck
|
2dfc734354b326f2f66896dde7746a11965d5a13
|
[
"Apache-2.0"
] | 2,355
|
2015-01-01T15:30:53.000Z
|
2022-03-30T20:21:16.000Z
|
test/com/facebook/buck/cxx/testdata/prebuilt_cxx_from_genrule/core/binary.cpp
|
Unknoob/buck
|
2dfc734354b326f2f66896dde7746a11965d5a13
|
[
"Apache-2.0"
] | 1,280
|
2015-01-09T03:29:04.000Z
|
2022-03-30T15:14:14.000Z
|
#include <stdio.h>
extern int bar();
int main() {
printf("%d\n", bar());
}
| 11.428571
| 26
| 0.5375
|
Unknoob
|
a4c94d3d806817f4a090267b313f86629a684465
| 685
|
cpp
|
C++
|
M1ProgramDesign-PYQ/2013/FormulaOne/Car.cpp
|
chowder/Imperial-PYQs
|
76edf454c5cd96a70a78698d61f3f3cf742d83ea
|
[
"MIT"
] | 2
|
2020-03-06T20:16:52.000Z
|
2020-05-03T19:56:47.000Z
|
M1ProgramDesign-PYQ/2013/FormulaOne/Car.cpp
|
chowder/Imperial-PYQs
|
76edf454c5cd96a70a78698d61f3f3cf742d83ea
|
[
"MIT"
] | null | null | null |
M1ProgramDesign-PYQ/2013/FormulaOne/Car.cpp
|
chowder/Imperial-PYQs
|
76edf454c5cd96a70a78698d61f3f3cf742d83ea
|
[
"MIT"
] | 1
|
2020-01-29T09:57:16.000Z
|
2020-01-29T09:57:16.000Z
|
#include <iostream>
#include "Car.h"
#include "Engine.h"
#include "Driver.h"
using namespace std;
Car::Car(string name, float chassisMass, Engine* engine, float* min_mass):
name(name), chassisMass(chassisMass), engine(engine),
min_mass(min_mass) {}
float Car::getRacingMass() {
if (!driver) {
cout << name << " does not have a driver!" << endl;
return -1;
}
float racing_mass = chassisMass + engine->mass + driver->mass;
return racing_mass > *min_mass ? racing_mass : *min_mass;
}
float Car::benchmark(float distance) {
return engine->benchmark(distance, getRacingMass());
}
void Car::setDriver(Driver* d) {
driver = d;
}
| 24.464286
| 74
| 0.649635
|
chowder
|
a4ca45395f05e3ef2572bee0e71b5c1fae4f3446
| 21,929
|
cpp
|
C++
|
hplip-3.20.3/prnt/hpijs/ljzjs.cpp
|
Deril-Pana/wikiBlackcoinNL
|
9633307f0b485c27feae5da242944adf450e8963
|
[
"MIT"
] | null | null | null |
hplip-3.20.3/prnt/hpijs/ljzjs.cpp
|
Deril-Pana/wikiBlackcoinNL
|
9633307f0b485c27feae5da242944adf450e8963
|
[
"MIT"
] | 1
|
2021-11-20T16:33:39.000Z
|
2021-11-20T16:33:39.000Z
|
hplip-3.20.3/prnt/hpijs/ljzjs.cpp
|
Deril-Pana/wikiBlackcoinNL
|
9633307f0b485c27feae5da242944adf450e8963
|
[
"MIT"
] | null | null | null |
/*****************************************************************************\
ljzjs.cpp : Implementation for the LJZjs class
Copyright (c) 1996 - 2007, HP Co.
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 HP 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 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, PATENT INFRINGEMENT; 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.
\*****************************************************************************/
#if defined (APDK_LJZJS_MONO) || defined (APDK_LJZJS_COLOR) || defined (APDK_LJM1005)
#include "header.h"
#include "io_defs.h"
#include "printerproxy.h"
#include "resources.h"
#include "ljzjs.h"
#ifdef HAVE_LIBDL
#include <dlfcn.h>
#endif
extern "C"
{
int (*HPLJJBGCompress) (int iWidth, int iHeight, unsigned char **pBuff,
HPLJZjcBuff *pOutBuff, HPLJZjsJbgEncSt *pJbgEncSt);
int (*HPLJSoInit) (int iFlag);
}
APDK_BEGIN_NAMESPACE
#ifdef HAVE_LIBDL
extern void *LoadPlugin (const char *szPluginName);
#endif
const unsigned char LJZjs::szByte1[256] =
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 32, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 34, 34, 34, 34,
34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34,
40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40,
40, 40, 40, 40, 42, 42, 42, 42, 42, 42, 42, 42,
42, 42, 42, 42, 42, 42, 42, 42, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130,
130, 130, 130, 130, 136, 136, 136, 136, 136, 136, 136, 136,
136, 136, 136, 136, 136, 136, 136, 136, 138, 138, 138, 138,
138, 138, 138, 138, 138, 138, 138, 138, 138, 138, 138, 138,
160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160,
160, 160, 160, 160, 162, 162, 162, 162, 162, 162, 162, 162,
162, 162, 162, 162, 162, 162, 162, 162, 168, 168, 168, 168,
168, 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, 168,
170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170,
170, 170, 170, 170,
};
const unsigned char LJZjs::szByte2[256] =
{
0, 2, 8, 10, 32, 34, 40, 42, 128, 130, 136, 138,
160, 162, 168, 170, 0, 2, 8, 10, 32, 34, 40, 42,
128, 130, 136, 138, 160, 162, 168, 170, 0, 2, 8, 10,
32, 34, 40, 42, 128, 130, 136, 138, 160, 162, 168, 170,
0, 2, 8, 10, 32, 34, 40, 42, 128, 130, 136, 138,
160, 162, 168, 170, 0, 2, 8, 10, 32, 34, 40, 42,
128, 130, 136, 138, 160, 162, 168, 170, 0, 2, 8, 10,
32, 34, 40, 42, 128, 130, 136, 138, 160, 162, 168, 170,
0, 2, 8, 10, 32, 34, 40, 42, 128, 130, 136, 138,
160, 162, 168, 170, 0, 2, 8, 10, 32, 34, 40, 42,
128, 130, 136, 138, 160, 162, 168, 170, 0, 2, 8, 10,
32, 34, 40, 42, 128, 130, 136, 138, 160, 162, 168, 170,
0, 2, 8, 10, 32, 34, 40, 42, 128, 130, 136, 138,
160, 162, 168, 170, 0, 2, 8, 10, 32, 34, 40, 42,
128, 130, 136, 138, 160, 162, 168, 170, 0, 2, 8, 10,
32, 34, 40, 42, 128, 130, 136, 138, 160, 162, 168, 170,
0, 2, 8, 10, 32, 34, 40, 42, 128, 130, 136, 138,
160, 162, 168, 170, 0, 2, 8, 10, 32, 34, 40, 42,
128, 130, 136, 138, 160, 162, 168, 170, 0, 2, 8, 10,
32, 34, 40, 42, 128, 130, 136, 138, 160, 162, 168, 170,
0, 2, 8, 10, 32, 34, 40, 42, 128, 130, 136, 138,
160, 162, 168, 170,
};
LJZjs::LJZjs (SystemServices* pSS, int numfonts, BOOL proto)
: Printer(pSS, numfonts, proto)
{
CMYMap = NULL;
#ifdef APDK_AUTODUPLEX
m_bRotateBackPage = FALSE; // Lasers don't require back side image to be rotated
#endif
m_pszInputRasterData = NULL;
m_dwCurrentRaster = 0;
m_bStartPageSent = FALSE;
HPLJJBGCompress = NULL;
m_hHPLibHandle = NULL;
m_iPrinterType = UNSUPPORTED;
#ifdef HAVE_LIBDL
m_hHPLibHandle = LoadPlugin ("lj.so");
if (m_hHPLibHandle)
{
dlerror ();
*(void **) (&HPLJJBGCompress) = dlsym (m_hHPLibHandle, "hp_encode_bits_to_jbig");
*(void **) (&HPLJSoInit) = dlsym (m_hHPLibHandle, "hp_init_lib");
if (!HPLJSoInit || (HPLJSoInit && !HPLJSoInit (1)))
{
constructor_error = PLUGIN_LIBRARY_MISSING;
}
}
#endif
if (HPLJJBGCompress == NULL)
{
constructor_error = PLUGIN_LIBRARY_MISSING;
}
//Issue: LJZJSMono class printers not printing in RHEL
//Cause: Since start page is common for LJZJSMono and LJZJSColor class, the items of
//LJZJSColor-2 format was used for LJZJSMono due to below variable not initialised
//Fix: Added initialisation so that correct LJZJSMono items are used.
//Variable is updated in LJZJSColor.
m_bLJZjsColor2Printer = FALSE;
}
LJZjs::~LJZjs ()
{
#ifdef HAVE_LIBDL
if (m_hHPLibHandle)
{
dlclose (m_hHPLibHandle);
}
#endif
if (m_pszInputRasterData)
{
delete [] m_pszInputRasterData;
}
}
HeaderLJZjs::HeaderLJZjs (Printer* p,PrintContext* pc)
: Header(p,pc)
{
}
DRIVER_ERROR HeaderLJZjs::Send ()
{
DRIVER_ERROR err = NO_ERROR;
char szStr[256];
WORD wItems[3] = {ZJI_DMCOLLATE, ZJI_PAGECOUNT, ZJI_DMDUPLEX};
int i = 4;
QUALITY_MODE eQuality;
MEDIATYPE cmt;
BOOL cdt;
COLORMODE ccm;
thePrintContext->GetPrintModeSettings (eQuality, cmt, ccm, cdt);
if (((LJZjs *) thePrinter)->m_iPrinterType == eLJM1005)
{
strcpy (szStr, "\x1B\x25-12345X@PJL JOB\x0D\x0A");
strcpy (szStr+strlen (szStr), "@PJL SET JAMRECOVERY=OFF\x0D\x0A");
strcpy (szStr+strlen (szStr), "@PJL SET DENSITY=3\x0D\x0A");
strcpy (szStr+strlen (szStr), "@PJL SET RET=MEDIUM\x0D\x0A");
strcpy (szStr+strlen (szStr), "@PJL SET ECONOMODE=");
if (eQuality == QUALITY_DRAFT)
{
strcpy (szStr+strlen (szStr), "ON\x0D\x0A");
}
else
{
strcpy (szStr+strlen (szStr), "OFF\x0D\x0A");
}
err = thePrinter->Send ((const BYTE *) szStr, strlen (szStr));
ERRCHECK;
strcpy (szStr, "\x1B\x25-12345X,XQX");
err = thePrinter->Send ((const BYTE *) szStr, strlen (szStr));
memset (szStr, 0x0, 92);
szStr[3] = 0x01;
szStr[7] = 0x07;
i = 8;
i += ((LJZjs *) thePrinter)->SendIntItem ((BYTE *) szStr+i, 0x80000000, 0x04, 0x54);
i += ((LJZjs *) thePrinter)->SendIntItem ((BYTE *) szStr+i, 0x10000005, 0x04, 0x01);
i += ((LJZjs *) thePrinter)->SendIntItem ((BYTE *) szStr+i, 0x10000001, 0x04, 0x00);
i += ((LJZjs *) thePrinter)->SendIntItem ((BYTE *) szStr+i, 0x10000002, 0x04, 0x00);
i += ((LJZjs *) thePrinter)->SendIntItem ((BYTE *) szStr+i, 0x10000000, 0x04, 0x00);
i += ((LJZjs *) thePrinter)->SendIntItem ((BYTE *) szStr+i, 0x10000003, 0x04, 0x01);
i += ((LJZjs *) thePrinter)->SendIntItem ((BYTE *) szStr+i, 0x80000001, 0x04, 0xDEADBEEF);
err = thePrinter->Send ((const BYTE *) szStr, i);
return err;
}
strcpy (szStr, "\x1B\x25-12345X@PJL ENTER LANGUAGE=ZJS\x0A");
err = thePrinter->Send ((const BYTE *) szStr, strlen (szStr));
ERRCHECK;
memset (szStr, 0, 256);
strcpy (szStr, "JZJZ");
i = 0;
szStr[i+7] = 52;
szStr[i+11] = ZJT_START_DOC;
szStr[i+15] = 3;
szStr[i+17] = 36;
szStr[i+18] = 'Z';
szStr[i+19] = 'Z';
i += 20;
for (int j = 0; j < 3; j++)
{
szStr[i+3] = 12;
szStr[i+5] = (char) wItems[j];
szStr[i+6] = ZJIT_UINT32;
szStr[i+11] = j / 2;
i += 12;
}
err = thePrinter->Send ((const BYTE *) szStr, i);
return err;
}
int LJZjs::MapPaperSize ()
{
switch (thePrintContext->GetPaperSize ())
{
case LETTER: return 1;
case LEGAL: return 5;
case A4: return 9;
case B4: return 12;
case B5: return 357;
case OUFUKU: return 43;
case HAGAKI: return 43;
#ifdef APDK_EXTENDED_MEDIASIZE
case A3: return 8;
case A5: return 11;
// case LEDGER: return 4;
case EXECUTIVE: return 7;
// case CUSTOM_SIZE: return 96;
case ENVELOPE_NO_10: return 20;
case ENVELOPE_DL: return 27;
case FLSA: return 258;
#endif
default: return 1;
}
}
DRIVER_ERROR LJZjs::StartPage (DWORD dwWidth, DWORD dwHeight)
{
DRIVER_ERROR err = NO_ERROR;
QUALITY_MODE cqm;
MEDIATYPE cmt;
BOOL cdt;
DWORD dwNumItems = (m_bIamColor) ? 15 : 14;
BYTE szStr[16 + 15 * 12];
int iPlanes = 1;
int i;
int iMediaType = 1; // Plain paper
if (m_bStartPageSent)
{
return NO_ERROR;
}
m_bStartPageSent = TRUE;
err = thePrintContext->GetPrintModeSettings (cqm, cmt, m_cmColorMode, cdt);
if (cmt == MEDIA_TRANSPARENCY)
{
iMediaType = 2;
}
else if (cmt == MEDIA_PHOTO)
{
iMediaType = 3;
}
if (m_iPrinterType == eLJM1005)
{
int iOutputResolution = GetOutputResolutionY ();
if (cqm == QUALITY_BEST)
iOutputResolution = (int) thePrintContext->EffectiveResolutionY ();
memset (szStr, 0x0, sizeof (szStr));
szStr[3] = 0x03;
szStr[7] = 0x0F;
err = Send ((const BYTE *) szStr, 8);
i = 0;
i += SendIntItem (szStr+i, 0x80000000, 0x04, 0xB4);
i += SendIntItem (szStr+i, 0x20000005, 0x04, 0x01);
i += SendIntItem (szStr+i, 0x20000006, 0x04, 0x07);
i += SendIntItem (szStr+i, 0x20000000, 0x04, 0x01);
i += SendIntItem (szStr+i, 0x20000007, 0x04, 0x01);
i += SendIntItem (szStr+i, 0x20000008, 0x04, (int) thePrintContext->EffectiveResolutionX ());
i += SendIntItem (szStr+i, 0x20000009, 0x04, iOutputResolution);
i += SendIntItem (szStr+i, 0x2000000D, 0x04, (int) dwWidth);
i += SendIntItem (szStr+i, 0x2000000E, 0x04, (int) m_dwLastRaster);
i += SendIntItem (szStr+i, 0x2000000A, 0x04, m_iBPP);
i += SendIntItem (szStr+i, 0x2000000F, 0x04, (int) dwWidth/m_iBPP);
i += SendIntItem (szStr+i, 0x20000010, 0x04, (int) m_dwLastRaster);
i += SendIntItem (szStr+i, 0x20000011, 0x04, 0x01);
i += SendIntItem (szStr+i, 0x20000001, 0x04, MapPaperSize ());
i += SendIntItem (szStr+i, 0x80000001, 0x04, 0xDEADBEEF);
err = Send ((const BYTE *) szStr, i);
return err;
}
if(m_bLJZjsColor2Printer)
{
dwNumItems = 13;
}
if (m_cmColorMode == COLOR && m_bIamColor)
{
iPlanes = 4;
}
i = 0;
i += SendChunkHeader (szStr, 16 + dwNumItems * 12, ZJT_START_PAGE, dwNumItems);
if (m_bIamColor)
{
i += SendItem (szStr+i, ZJIT_UINT32, ZJI_PLANE, iPlanes);
}
i += SendItem (szStr+i, ZJIT_UINT32, ZJI_DMPAPER, MapPaperSize ());
i += SendItem (szStr+i, ZJIT_UINT32, ZJI_DMCOPIES, thePrintContext->GetCopyCount ());
i += SendItem (szStr+i, ZJIT_UINT32, ZJI_DMDEFAULTSOURCE, thePrintContext->GetMediaSource ());
i += SendItem (szStr+i, ZJIT_UINT32, ZJI_DMMEDIATYPE, iMediaType);
i += SendItem (szStr+i, ZJIT_UINT32, ZJI_NBIE, iPlanes);
i += SendItem (szStr+i, ZJIT_UINT32, ZJI_RESOLUTION_X, thePrintContext->EffectiveResolutionX ());
i += SendItem (szStr+i, ZJIT_UINT32, ZJI_RESOLUTION_Y, thePrintContext->EffectiveResolutionY ());
i += SendItem (szStr+i, ZJIT_UINT32, ZJI_RASTER_X, dwWidth);
i += SendItem (szStr+i, ZJIT_UINT32, ZJI_RASTER_Y, m_dwLastRaster);
i += SendItem (szStr+i, ZJIT_UINT32, ZJI_VIDEO_BPP, m_iBPP);
i += SendItem (szStr+i, ZJIT_UINT32, ZJI_VIDEO_X, dwWidth/m_iBPP);
i += SendItem (szStr+i, ZJIT_UINT32, ZJI_VIDEO_Y, m_dwLastRaster);
if(!m_bLJZjsColor2Printer)
{
i += SendItem (szStr+i, ZJIT_UINT32, ZJI_RET, RET_ON);
i += SendItem (szStr+i, ZJIT_UINT32, ZJI_TONER_SAVE, (cqm == QUALITY_DRAFT) ? 1 : 0);
}
err = Send ((const BYTE *) szStr, i);
return err;
}
int LJZjs::SendChunkHeader (BYTE *szStr, DWORD dwSize, DWORD dwChunkType, DWORD dwNumItems)
{
for (int j = 3, i = 0; j >= 0; j--)
{
szStr[i] = (BYTE) ((dwSize >> (8 * (j))) & 0xFF);
szStr[4+i] = (BYTE) ((dwChunkType >> (8 * (j))) & 0xFF);
szStr[8+i] = (BYTE) ((dwNumItems >> (8 * (j))) & 0xFF);
i++;
}
szStr[12] = (BYTE) (((dwNumItems * 12) & 0xFF00) >> 8);
szStr[13] = (BYTE) (((dwNumItems * 12) & 0x00FF));
szStr[14] = 'Z';
szStr[15] = 'Z';
return 16;
}
int LJZjs::SendItem (BYTE *szStr, BYTE cType, WORD wItem, DWORD dwValue, DWORD dwExtra)
{
int i, j;
dwExtra += 12;
for (j = 3, i = 0; j >= 0; j--)
{
szStr[i++] = (BYTE) ((dwExtra >> (8 * (j))) & 0xFF);
}
szStr[i++] = (BYTE) ((wItem & 0xFF00) >> 8);
szStr[i++] = (BYTE) ((wItem & 0x00FF));
szStr[i++] = (BYTE) cType;
szStr[i++] = 0;
for (j = 3; j >= 0; j--)
{
szStr[i++] = (BYTE) ((dwValue >> (8 * (j))) & 0xFF);
}
return i;
}
int LJZjs::SendIntItem (BYTE *szStr, int iItem, int iItemType, int iItemValue)
{
int i = 0;
int j;
for (j = 3; j >= 0; j--)
{
szStr[i++] = (BYTE) ((iItem >> (8 * (j))) & 0xFF);
}
for (j = 3; j >= 0; j--)
{
szStr[i++] = (BYTE) ((iItemType >> (8 * (j))) & 0xFF);
}
for (j = 3; j >= 0; j--)
{
szStr[i++] = (BYTE) ((iItemValue >> (8 * (j))) & 0xFF);
}
return i;
}
DRIVER_ERROR LJZjs::SkipRasters (int iBlankRasters)
{
DRIVER_ERROR err = NO_ERROR;
BOOL bLastPlane;
int iPlanes = (m_cmColorMode == COLOR) ? 4 : 1;
for (int i = 1; i <= iPlanes; i++)
{
bLastPlane = (i == iPlanes) ? TRUE : FALSE;
for (int j = 0; j < iBlankRasters; j++)
{
err = this->Encapsulate (NULL, bLastPlane);
}
}
return err;
}
DRIVER_ERROR HeaderLJZjs::FormFeed ()
{
DRIVER_ERROR err = NO_ERROR;
err = thePrinter->Flush (0);
return err;
}
DRIVER_ERROR HeaderLJZjs::SendCAPy (unsigned int iAbsY)
{
return NO_ERROR;
}
DRIVER_ERROR LJZjs::Flush (int FlushSize)
{
DRIVER_ERROR err = NO_ERROR;
if (m_dwCurrentRaster == 0)
{
return NO_ERROR;
}
err = SkipRasters ((m_dwLastRaster - m_dwCurrentRaster));
return err;
}
DRIVER_ERROR LJZjs::JbigCompress ()
{
DRIVER_ERROR err = NO_ERROR;
HPLJZjcBuff myBuffer;
int iPlanes = (m_cmColorMode == COLOR) ? 4 : 1;
int iIncr = (m_bIamColor) ? 100 : m_dwLastRaster;
HPLJZjsJbgEncSt se;
BYTE *bitmaps[4] =
{
m_pszInputRasterData,
m_pszInputRasterData + (m_dwWidth * m_iBPP * m_dwLastRaster),
m_pszInputRasterData + (m_dwWidth * m_iBPP * m_dwLastRaster * 2),
m_pszInputRasterData + (m_dwWidth * m_iBPP * m_dwLastRaster * 3)
};
myBuffer.pszCompressedData = new BYTE[m_dwWidth * m_dwLastRaster * m_iBPP];
myBuffer.dwTotalSize = 0;
BYTE *p;
int iHeight;
for (DWORD y = 0; y < m_dwLastRaster; y += iIncr)
{
for (int i = 0; i < iPlanes; i++)
{
memset (myBuffer.pszCompressedData, 0, m_dwWidth * m_dwLastRaster * m_iBPP);
myBuffer.dwTotalSize = 0;
p = bitmaps[i] + (y * m_dwWidth * m_iBPP);
iHeight = iIncr;
if (y + iIncr > m_dwLastRaster)
{
iHeight = m_dwLastRaster - y;
}
HPLJJBGCompress (m_dwWidth * 8 * m_iBPP, iHeight, &p, &myBuffer, &se);
if (i == 0)
{
StartPage (se.xd, se.yd);
}
err = this->SendPlaneData (i + 1, &se, &myBuffer, (y + iIncr) >= m_dwLastRaster);
}
}
delete [] myBuffer.pszCompressedData;
m_dwCurrentRaster = 0;
m_pszCurPtr = m_pszInputRasterData;
memset (m_pszCurPtr, 0, (m_dwWidth * m_dwLastRaster * iPlanes * m_iBPP));
err = EndPage ();
return err;
}
/*JBig Compress for LJZjsColor-2 Printers
Separate function written for LJZjsColor-2 Printers, since for them, compression is done for whole plane data at a time
whereas for other deiveces, compression is done for 100 lines of each plane*/
DRIVER_ERROR LJZjs::JbigCompress_LJZjsColor2 ()
{
DRIVER_ERROR err = NO_ERROR;
HPLJZjcBuff myBuffer;
int iPlanes = (m_cmColorMode == COLOR) ? 4 : 1;
int arrPlanesOrder[] = {3,2,1,4};
int nByteCount = 0;
int iHeight = 0;
HPLJZjsJbgEncSt se;
BYTE *pbUnCompressedData = NULL;
BYTE *bitmaps[4] =
{
m_pszInputRasterData,
m_pszInputRasterData + (m_dwWidth * m_iBPP * m_dwLastRaster),
m_pszInputRasterData + (m_dwWidth * m_iBPP * m_dwLastRaster * 2),
m_pszInputRasterData + (m_dwWidth * m_iBPP * m_dwLastRaster * 3)
};
myBuffer.pszCompressedData = new BYTE[m_dwWidth * m_dwLastRaster * m_iBPP];
if(NULL == myBuffer.pszCompressedData)
{
return ALLOCMEM_ERROR;
}
myBuffer.dwTotalSize = 0;
for (int nPlaneCount = 0; nPlaneCount < iPlanes; nPlaneCount++)
{
memset (myBuffer.pszCompressedData, 0, m_dwWidth * m_dwLastRaster * m_iBPP);
myBuffer.dwTotalSize = 0;
if(4 == iPlanes)/*If there are 4 planes follow LJZjsColor-2 order of 3 2 1 4*/
{
pbUnCompressedData = bitmaps[arrPlanesOrder[nPlaneCount]-1] ;
}
else /* Should not happen */
{
return SYSTEM_ERROR;
}
iHeight = m_dwLastRaster; /*Send all scan lines at one go*/
HPLJJBGCompress (m_dwWidth * 8 * m_iBPP, iHeight, &pbUnCompressedData, &myBuffer, &se);
if(0 == nPlaneCount)
{
StartPage (se.xd, se.yd);
}
err = this->SendPlaneData (arrPlanesOrder[nPlaneCount], &se, &myBuffer, FALSE);
}
delete [] myBuffer.pszCompressedData;
m_dwCurrentRaster = 0;
m_pszCurPtr = m_pszInputRasterData;
memset (m_pszCurPtr, 0, (m_dwWidth * m_dwLastRaster * iPlanes * m_iBPP));
err = EndPage ();
return err;
}
DRIVER_ERROR HeaderLJZjs::EndJob ()
{
DRIVER_ERROR err = NO_ERROR;
char szStr[64];
if (((LJZjs *) thePrinter)->m_iPrinterType == eLJM1005)
{
memset (szStr, 0, 8);
szStr[3] = 2;
strcpy ((char *) szStr+8, "\x1B\x25-12345X@PJL EOJ\x0D\x0A\x1B\x25-12345X");
err = thePrinter->Send ((const BYTE *) szStr, 8 + strlen ((char *) (szStr+8)));
return err;
}
memset (szStr, 0, 64);
szStr[3] = 16;
szStr[7] = ZJT_END_DOC;
szStr[14] = 'Z';
szStr[15] = 'Z';
err = thePrinter->Send ((const BYTE *) szStr, 16);
return err;
}
Header *LJZjs::SelectHeader (PrintContext* pc)
{
DRIVER_ERROR err = NO_ERROR;
DWORD dwSize;
int iPlanes = 1;
QUALITY_MODE cqm;
MEDIATYPE cmt;
BOOL cdt;
err = pc->GetPrintModeSettings (cqm, cmt, m_cmColorMode, cdt);
if (m_cmColorMode == COLOR && m_bIamColor)
{
iPlanes = 4;
m_iP[0] = 3;
}
m_dwWidth = pc->OutputPixelsPerRow () / 8;
if (m_dwWidth % 8)
{
m_dwWidth = (m_dwWidth / 8 + 1) * 8;
}
m_dwLastRaster = (int) (pc->PrintableHeight () * pc->EffectiveResolutionY () + 0.5);
dwSize = m_dwWidth * m_dwLastRaster * iPlanes * m_iBPP;
m_pszInputRasterData = new BYTE[dwSize];
if (m_pszInputRasterData == NULL)
{
return NULL;
}
m_pszCurPtr = m_pszInputRasterData;
memset (m_pszCurPtr, 0, dwSize);
thePrintContext = pc;
return new HeaderLJZjs (this,pc);
}
DRIVER_ERROR LJZjs::VerifyPenInfo()
{
ePen = BOTH_PENS;
return NO_ERROR;
}
DRIVER_ERROR LJZjs::ParsePenInfo (PEN_TYPE& ePen, BOOL QueryPrinter)
{
ePen = BOTH_PENS;
return NO_ERROR;
}
APDK_END_NAMESPACE
#endif // defined APDK_LJZJS_MONO || defined APDK_LJZJS_COLOR || defined APDK_LJM1005
| 33.326748
| 119
| 0.568197
|
Deril-Pana
|
a4cb1a5d435016656fc91cf343305e09509455d6
| 178
|
cpp
|
C++
|
src/imgui_runner_demos/imgui_runner_demo_glfw.cpp
|
sacceus/BabylonCpp
|
94669cf7cbe3214ec6e905cbf249fa0c9daf6222
|
[
"Apache-2.0"
] | 277
|
2017-05-18T08:27:10.000Z
|
2022-03-26T01:31:37.000Z
|
src/imgui_runner_demos/imgui_runner_demo_glfw.cpp
|
sacceus/BabylonCpp
|
94669cf7cbe3214ec6e905cbf249fa0c9daf6222
|
[
"Apache-2.0"
] | 77
|
2017-09-03T15:35:02.000Z
|
2022-03-28T18:47:20.000Z
|
src/imgui_runner_demos/imgui_runner_demo_glfw.cpp
|
sacceus/BabylonCpp
|
94669cf7cbe3214ec6e905cbf249fa0c9daf6222
|
[
"Apache-2.0"
] | 37
|
2017-03-30T03:36:24.000Z
|
2022-01-28T08:28:36.000Z
|
#include "imgui_utils/imgui_runner/runner_glfw.h"
#include "example_gui.h"
int main()
{
ImGui::ImGuiRunner::RunnerGlfw runner;
runner.ShowGui = ExampleGui;
runner.Run();
}
| 19.777778
| 49
| 0.741573
|
sacceus
|
a4d27e88f279061cc7a40d1d6ebd9b9c5eaf786f
| 1,352
|
cpp
|
C++
|
c++/solution393.cpp
|
imafish/leetcodetests
|
abee2c2d6c0b25a21ef4294bceb7e069b6547b85
|
[
"MIT"
] | null | null | null |
c++/solution393.cpp
|
imafish/leetcodetests
|
abee2c2d6c0b25a21ef4294bceb7e069b6547b85
|
[
"MIT"
] | null | null | null |
c++/solution393.cpp
|
imafish/leetcodetests
|
abee2c2d6c0b25a21ef4294bceb7e069b6547b85
|
[
"MIT"
] | null | null | null |
#include "afx.h"
using namespace std;
class Solution
{
public:
bool validUtf8(vector<int> &data)
{
/*
state:
0: end of byte sequence;
>0: in byte sequence, state = bytes remaining
*/
int state = 0;
int result = true;
for (auto &i : data)
{
if (state == 0)
{
if ((i & 0xF8) == 0xF0)
{
state = 3;
}
else if ((i & 0xF0) == 0xE0)
{
state = 2;
}
else if ((i & 0xE0) == 0xC0)
{
state = 1;
}
else if ((i & 0x80) == 0)
{
state = 0;
}
else
{
result = false;
break;
}
}
else if ((i & 0xC0) == 0x80)
{
state--;
}
else
{
result = false;
break;
}
}
if (state > 0)
{
result = false;
}
return result;
}
};
int main()
{
Solution s;
vector<int> data = {197, 130, 1};
s.validUtf8(data);
return 0;
}
| 19.882353
| 53
| 0.293639
|
imafish
|
a4d62c89fa73afb1f5bf984935a6c1d5b4af7106
| 216
|
cpp
|
C++
|
PhoneCall/Source.cpp
|
TanyaZheleva/OOP
|
f44c67e5df69a91a77d35668f0709954546f210d
|
[
"MIT"
] | null | null | null |
PhoneCall/Source.cpp
|
TanyaZheleva/OOP
|
f44c67e5df69a91a77d35668f0709954546f210d
|
[
"MIT"
] | null | null | null |
PhoneCall/Source.cpp
|
TanyaZheleva/OOP
|
f44c67e5df69a91a77d35668f0709954546f210d
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include "PhoneCall.h"
int main()
{
PhoneCall p;
p.setLength(50);
p.getPrice();
p.setNumber(9002121004);
std::cout << p.getPrice() << "\n";
std::cout << p.getNumber() << "\n";
return 0;
}
| 15.428571
| 36
| 0.611111
|
TanyaZheleva
|
a4d6b2036dc04896d24c0fc37c83ed1b3050c521
| 886
|
hpp
|
C++
|
kfr/include/kfr/dsp/state_holder.hpp
|
yekm/gate_recorder
|
e76fda4a6d67672c0c2d7802417116ac3c1a1896
|
[
"MIT"
] | null | null | null |
kfr/include/kfr/dsp/state_holder.hpp
|
yekm/gate_recorder
|
e76fda4a6d67672c0c2d7802417116ac3c1a1896
|
[
"MIT"
] | 1
|
2021-02-25T14:20:19.000Z
|
2021-02-25T14:24:03.000Z
|
kfr/include/kfr/dsp/state_holder.hpp
|
For-The-Birds/gate_recorder
|
e76fda4a6d67672c0c2d7802417116ac3c1a1896
|
[
"MIT"
] | null | null | null |
/** @addtogroup fir
* @{
*/
/**
* KFR (http://kfrlib.com)
* Copyright (C) 2016 D Levin
* See LICENSE.txt for details
*/
#pragma once
#include "../cident.h"
namespace kfr
{
inline namespace CMT_ARCH_NAME
{
namespace internal
{
template <typename T, bool stateless>
struct state_holder
{
state_holder() = delete;
state_holder(const state_holder&) = default;
state_holder(state_holder&&) = default;
constexpr state_holder(const T& state) CMT_NOEXCEPT : s(state) {}
T s;
};
template <typename T>
struct state_holder<T, true>
{
state_holder() = delete;
state_holder(const state_holder&) = default;
state_holder(state_holder&&) = default;
constexpr state_holder(const T& state) CMT_NOEXCEPT : s(state) {}
const T& s;
};
} // namespace internal
} // namespace CMT_ARCH_NAME
} // namespace kfr
| 21.095238
| 69
| 0.64447
|
yekm
|
a4d78e42defc0e2e6777080f89c9d2bd19032f53
| 17,080
|
cpp
|
C++
|
Sources/Elastos/LibCore/src/elastos/io/CRandomAccessFile.cpp
|
jingcao80/Elastos
|
d0f39852356bdaf3a1234743b86364493a0441bc
|
[
"Apache-2.0"
] | 7
|
2017-07-13T10:34:54.000Z
|
2021-04-16T05:40:35.000Z
|
Sources/Elastos/LibCore/src/elastos/io/CRandomAccessFile.cpp
|
jingcao80/Elastos
|
d0f39852356bdaf3a1234743b86364493a0441bc
|
[
"Apache-2.0"
] | null | null | null |
Sources/Elastos/LibCore/src/elastos/io/CRandomAccessFile.cpp
|
jingcao80/Elastos
|
d0f39852356bdaf3a1234743b86364493a0441bc
|
[
"Apache-2.0"
] | 9
|
2017-07-13T12:33:20.000Z
|
2021-06-19T02:46:48.000Z
|
//=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================
#include "CRandomAccessFile.h"
#include "CFile.h"
#include "IoUtils.h"
#include "NioUtils.h"
#include "Math.h"
#include "Character.h"
#include "StringBuilder.h"
#include "OsConstants.h"
#include "IoBridge.h"
#include "CLibcore.h"
#include "CFileDescriptor.h"
#include "CModifiedUtf8.h"
#include "AutoLock.h"
#include "Memory.h"
#include "CCloseGuard.h"
using Elastos::Droid::System::OsConstants;
using Elastos::Droid::System::IStructStat;
using Elastos::Core::CCloseGuard;
using Elastos::Core::Character;
using Elastos::Core::StringBuilder;
using Elastos::IO::Channels::IChannel;
using Elastos::IO::Charset::IModifiedUtf8;
using Elastos::IO::Charset::CModifiedUtf8;
using Libcore::IO::IoBridge;
using Libcore::IO::ILibcore;
using Libcore::IO::CLibcore;
using Libcore::IO::IOs;
using Libcore::IO::IoUtils;
using Libcore::IO::Memory;
namespace Elastos {
namespace IO {
CAR_OBJECT_IMPL(CRandomAccessFile)
CAR_INTERFACE_IMPL_4(CRandomAccessFile, Object, IRandomAccessFile, IDataInput, IDataOutput, ICloseable)
CRandomAccessFile::CRandomAccessFile()
: mSyncMetadata(FALSE)
, mMode(0)
{
mScratch = ArrayOf<Byte>::Alloc(8);
}
CRandomAccessFile::~CRandomAccessFile()
{
mScratch = NULL;
if (mGuard != NULL) {
mGuard->WarnIfOpen();
mGuard->Close();
}
// can not call virtual method Close() on destructor.
//
AutoLock lock(this);
Boolean isflag(FALSE);
if (mChannel != NULL && (IChannel::Probe(mChannel)->IsOpen(&isflag) , isflag)) {
ICloseable::Probe(mChannel)->Close();
mChannel = NULL;
}
IoBridge::CloseAndSignalBlockedThreads(mFd);
}
ECode CRandomAccessFile::constructor(
/* [in] */ IFile* file,
/* [in] */ const String& mode)
{
CCloseGuard::New((ICloseGuard**)&mGuard);
Int32 flags;
if (mode.Equals("r")) {
flags = OsConstants::_O_RDONLY;
}
else if (mode.Equals("rw") || mode.Equals("rws") || mode.Equals("rwd")) {
flags = OsConstants::_O_RDWR | OsConstants::_O_CREAT;
if (mode.Equals("rws")) {
// Sync file and metadata with every write
mSyncMetadata = true;
} else if (mode.Equals("rwd")) {
// Sync file, but not necessarily metadata
flags |= OsConstants::_O_SYNC;
}
}
else {
// throw new IllegalArgumentException("Invalid mode: " + mode);
return E_ILLEGAL_ARGUMENT_EXCEPTION;
}
mMode = flags;
String path;
file->GetPath(&path);
AutoPtr<IFileDescriptor> fd;
FAIL_RETURN(IoBridge::Open(path, flags, (IFileDescriptor**)&fd));
Int32 ifd;
fd->GetDescriptor(&ifd);
CFileDescriptor::New((IFileDescriptor**)&mFd);
mFd->SetDescriptor(ifd);
// if we are in "rws" mode, attempt to sync file+metadata
if (mSyncMetadata) {
mFd->Sync();
}
return mGuard->Open(String("CRandomAccessFile::Close"));
}
ECode CRandomAccessFile::constructor(
/* [in] */ const String& fileName,
/* [in] */ const String& mode)
{
AutoPtr<CFile> obj;
FAIL_RETURN(CFile::NewByFriend(fileName, (CFile**)&obj));
AutoPtr<IFile> file = (IFile*)obj;
return constructor(file, mode);
}
ECode CRandomAccessFile::Close()
{
mGuard->Close();
AutoLock lock(this);
Boolean isflag(FALSE);
if (mChannel != NULL && (IChannel::Probe(mChannel)->IsOpen(&isflag) , isflag)) {
ICloseable::Probe(mChannel)->Close();
mChannel = NULL;
}
return IoBridge::CloseAndSignalBlockedThreads(mFd);
}
ECode CRandomAccessFile::GetChannel(
/* [out] */ IFileChannel **channel)
{
VALIDATE_NOT_NULL(channel)
AutoLock lock(this);
if (mChannel == NULL) {
mChannel = NioUtils::NewFileChannel(this, mFd, mMode);
}
*channel = mChannel;
REFCOUNT_ADD(*channel)
return NOERROR;
}
ECode CRandomAccessFile::GetFD(
/* [out] */ IFileDescriptor ** fd)
{
VALIDATE_NOT_NULL(fd);
*fd = mFd;
REFCOUNT_ADD(*fd);
return NOERROR;
}
ECode CRandomAccessFile::GetFilePointer(
/* [out] */ Int64* offset)
{
VALIDATE_NOT_NULL(offset);
*offset = -1;
AutoPtr<ILibcore> libcore;
CLibcore::AcquireSingleton((ILibcore**)&libcore);
AutoPtr<IOs> os;
libcore->GetOs((IOs**)&os);
ECode ec = os->Lseek(mFd, 0ll, OsConstants::_SEEK_CUR, offset);
if (FAILED(ec)) return E_IO_EXCEPTION;
return NOERROR;
}
ECode CRandomAccessFile::GetLength(
/* [out] */ Int64* len)
{
VALIDATE_NOT_NULL(len);
*len = 0;
AutoPtr<ILibcore> libcore;
CLibcore::AcquireSingleton((ILibcore**)&libcore);
AutoPtr<IOs> os;
libcore->GetOs((IOs**)&os);
AutoPtr<IStructStat> stat;
ECode ec = os->Fstat(mFd, (IStructStat**)&stat);
if (FAILED(ec)) return E_IO_EXCEPTION;
return stat->GetSize(len);
}
ECode CRandomAccessFile::Read(
/* [out] */ Int32* value)
{
VALIDATE_NOT_NULL(value);
*value = -1;
Int32 byteCount;
FAIL_RETURN(Read(mScratch, 0, 1, &byteCount))
*value = byteCount != -1 ? (*mScratch)[0] & 0xff : -1;
return NOERROR;
}
ECode CRandomAccessFile::Read(
/* [out] */ ArrayOf<Byte>* buffer,
/* [out] */ Int32* number)
{
VALIDATE_NOT_NULL(number);
*number = -1;
VALIDATE_NOT_NULL(buffer);
return Read(buffer, 0, buffer->GetLength(), number);
}
ECode CRandomAccessFile::Read(
/* [out] */ ArrayOf<Byte>* buffer,
/* [in] */ Int32 offset,
/* [in] */ Int32 length,
/* [out] */ Int32* number)
{
VALIDATE_NOT_NULL(number);
return IoBridge::Read(mFd, buffer, offset, length, number);
}
ECode CRandomAccessFile::ReadBoolean(
/* [out] */ Boolean* value)
{
VALIDATE_NOT_NULL(value);
Int32 temp;
FAIL_RETURN(Read(&temp));
if (temp < 0) {
// throw new EOFException();
return E_EOF_EXCEPTION;
}
*value = temp != 0;
return NOERROR;
}
ECode CRandomAccessFile::ReadByte(
/* [out] */ Byte* value)
{
VALIDATE_NOT_NULL(value);
Int32 temp;
FAIL_RETURN(Read(&temp));
if (temp < 0) {
// throw new EOFException();
return E_EOF_EXCEPTION;
}
*value = (Byte)temp;
return NOERROR;
}
ECode CRandomAccessFile::ReadChar(
/* [out] */ Char32* value)
{
VALIDATE_NOT_NULL(value);
Byte firstChar;
FAIL_RETURN(ReadByte(&firstChar));
if ((firstChar & 0x80) == 0) { // ASCII
*value = (Char32)firstChar;
return NOERROR;
}
Char32 mask, toIgnoreMask;
Int32 numToRead = 1;
Char32 utf32 = firstChar;
for (mask = 0x40, toIgnoreMask = 0xFFFFFF80;
(firstChar & mask);
numToRead++, toIgnoreMask |= mask, mask >>= 1) {
// 0x3F == 00111111
Byte ch;
FAIL_RETURN(ReadByte(&ch));
utf32 = (utf32 << 6) + (ch & 0x3F);
}
toIgnoreMask |= mask;
utf32 &= ~(toIgnoreMask << (6 * (numToRead - 1)));
*value = utf32;
return NOERROR;
}
ECode CRandomAccessFile::ReadDouble(
/* [out] */ Double* value)
{
VALIDATE_NOT_NULL(value);
*value = 0;
Int64 i64Value;
FAIL_RETURN(ReadInt64(&i64Value));
*value = Elastos::Core::Math::Int64BitsToDouble(i64Value);
return NOERROR;
}
ECode CRandomAccessFile::ReadFloat(
/* [out] */ Float* value)
{
VALIDATE_NOT_NULL(value);
*value = 0;
Int32 i32Value;
FAIL_RETURN(ReadInt32(&i32Value));
*value = Elastos::Core::Math::Int32BitsToFloat(i32Value);
return NOERROR;
}
ECode CRandomAccessFile::ReadFully(
/* [out] */ ArrayOf<Byte>* buffer)
{
return ReadFully(buffer, 0, buffer->GetLength());
}
ECode CRandomAccessFile::ReadFully(
/* [out] */ ArrayOf<byte>* buffer,
/* [in] */ Int32 offset,
/* [in] */ Int32 length)
{
if (buffer == NULL) {
// throw new NullPointerException("buffer == null");
return E_NULL_POINTER_EXCEPTION;
}
// avoid int overflow
// BEGIN android-changed
// Exception priorities (in case of multiple errors) differ from
// RI, but are spec-compliant.
// used (offset | length) < 0 instead of separate (offset < 0) and
// (length < 0) check to safe one operation
if ((offset | length) < 0 || offset > buffer->GetLength() - length) {
// throw new IndexOutOfBoundsException();
return E_ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION;
}
// END android-changed
Int32 number;
while (length > 0) {
FAIL_RETURN(Read(buffer, offset, length, &number));
if (number < 0) {
// throw new EOFException();
return E_EOF_EXCEPTION;
}
offset += number;
length -= number;
}
return NOERROR;
}
ECode CRandomAccessFile::ReadInt32(
/* [out] */ Int32* value)
{
VALIDATE_NOT_NULL(value);
FAIL_RETURN(ReadFully(mScratch, 0, sizeof(Int32)));
*value = Memory::PeekInt32(mScratch, 0, ByteOrder_BIG_ENDIAN);
return NOERROR;
}
ECode CRandomAccessFile::ReadLine(
/* [out] */ String* str)
{
VALIDATE_NOT_NULL(str);
AutoPtr<StringBuilder> line = new StringBuilder(80);
Boolean foundTerminator = FALSE;
Int64 unreadPosition = 0;
while (TRUE) {
Int32 nextByte;
FAIL_RETURN(Read(&nextByte));
switch (nextByte) {
case -1:
if (line->GetLength() != 0) {
*str = line->ToString();
}
else {
*str = NULL;
}
return NOERROR;
case (Byte)'\r':
if (foundTerminator) {
Seek(unreadPosition);
*str = line->ToString();
return NOERROR;
}
foundTerminator = TRUE;
/* Have to be able to peek ahead one byte */
GetFilePointer(&unreadPosition);
break;
case (Byte)'\n':
*str = line->ToString();
return NOERROR;
default:
if (foundTerminator) {
Seek(unreadPosition);
*str = line->ToString();
return NOERROR;
}
line->AppendChar((Char32)nextByte);
}
}
return NOERROR;
}
ECode CRandomAccessFile::ReadInt64(
/* [out] */ Int64* value)
{
VALIDATE_NOT_NULL(value);
FAIL_RETURN(ReadFully(mScratch, 0, sizeof(Int64)));
*value = Memory::PeekInt64(mScratch, 0, ByteOrder_BIG_ENDIAN);
return NOERROR;
}
ECode CRandomAccessFile::ReadInt16(
/* [out] */ Int16* value)
{
VALIDATE_NOT_NULL(value);
FAIL_RETURN(ReadFully(mScratch, 0, sizeof(Int16)));
*value = Memory::PeekInt16(mScratch, 0, ByteOrder_BIG_ENDIAN);
return NOERROR;
}
ECode CRandomAccessFile::ReadUnsignedByte(
/* [out] */ Int32* value)
{
VALIDATE_NOT_NULL(value);
FAIL_RETURN(Read(value));
return *value < 0 ? E_EOF_EXCEPTION : NOERROR;
}
ECode CRandomAccessFile::ReadUnsignedInt16(
/* [out] */ Int32* value)
{
VALIDATE_NOT_NULL(value);
Int16 temp;
FAIL_RETURN(ReadInt16(&temp));
*value = ((Int32)temp) & 0xFFFF;
return NOERROR;
}
ECode CRandomAccessFile::ReadUTF(
/* [out] */ String* str)
{
VALIDATE_NOT_NULL(str)
Int32 utfSize = 0;
FAIL_RETURN(ReadUnsignedInt16(&utfSize));
if (utfSize == 0) {
*str = "";
return NOERROR;
}
AutoPtr< ArrayOf<Byte> > buf = ArrayOf<Byte>::Alloc(utfSize);
Int32 readsize = 0;
Read(buf, 0, buf->GetLength(), &readsize);
if (readsize != buf->GetLength()) {
// throw new EOFException();
return E_EOF_EXCEPTION;
}
AutoPtr<IModifiedUtf8> mutf8help;
CModifiedUtf8::AcquireSingleton((IModifiedUtf8**)&mutf8help);
AutoPtr< ArrayOf<Char32> > charbuf = ArrayOf<Char32>::Alloc(utfSize);
return mutf8help->Decode(buf, charbuf, 0, utfSize, str);
}
ECode CRandomAccessFile::Seek(
/* [in] */ Int64 offset)
{
if (offset < 0) {
// seek position is negative
// throw new IOException("offset < 0");
return E_IO_EXCEPTION;
}
AutoPtr<CLibcore> ioObj;
CLibcore::AcquireSingletonByFriend((CLibcore**)&ioObj);
AutoPtr<ILibcore> libcore = (ILibcore*)ioObj.Get();
AutoPtr<IOs> os;
libcore->GetOs((IOs**)&os);
Int64 res;
ECode ec = os->Lseek(mFd, offset, OsConstants::_SEEK_SET, &res);
if (FAILED(ec)) return E_IO_EXCEPTION;
return NOERROR;
}
ECode CRandomAccessFile::SetLength(
/* [in] */ Int64 newLength)
{
if (newLength < 0) {
// throw new IllegalArgumentException();
return E_ILLEGAL_ARGUMENT_EXCEPTION;
}
AutoPtr<CLibcore> ioObj;
CLibcore::AcquireSingletonByFriend((CLibcore**)&ioObj);
AutoPtr<ILibcore> libcore = (ILibcore*)ioObj.Get();
AutoPtr<IOs> os;
libcore->GetOs((IOs**)&os);
ECode ec = os->Ftruncate(mFd, newLength);
if (FAILED(ec)) return E_IO_EXCEPTION;
Int64 filePointer;
FAIL_RETURN(GetFilePointer(&filePointer));
if (filePointer > newLength) {
FAIL_RETURN(Seek(newLength));
}
// if we are in "rws" mode, attempt to sync file+metadata
if (mSyncMetadata) {
mFd->Sync();
}
return NOERROR;
}
ECode CRandomAccessFile::SkipBytes(
/* [in] */ Int32 count,
/* [out] */ Int32* number)
{
VALIDATE_NOT_NULL(number);
*number = 0;
if (count > 0) {
Int64 currentPos, eof;
GetFilePointer(¤tPos);
GetLength(&eof);
Int32 newCount = (Int32)((currentPos + count > eof) ? eof - currentPos
: count);
FAIL_RETURN(Seek(currentPos + newCount));
*number = newCount;
return NOERROR;
}
*number = 0;
return NOERROR;
}
ECode CRandomAccessFile::Write(
/* [in] */ ArrayOf<Byte>* buffer)
{
return Write(buffer, 0, buffer->GetLength());
}
ECode CRandomAccessFile::Write(
/* [in] */ ArrayOf<Byte>* buffer,
/* [in] */ Int32 offset,
/* [in] */ Int32 count)
{
FAIL_RETURN(IoBridge::Write(mFd, buffer, offset, count));
// if we are in "rws" mode, attempt to sync file+metadata
if (mSyncMetadata) {
mFd->Sync();
}
return NOERROR;
}
ECode CRandomAccessFile::Write(
/* [in] */ Int32 oneByte)
{
(*mScratch)[0] = (Byte)(oneByte & 0xFF);
return Write(mScratch, 0, 1);
}
ECode CRandomAccessFile::WriteBoolean(
/* [in] */ Boolean value)
{
return Write(value? 1 : 0);
}
ECode CRandomAccessFile::WriteByte(
/* [in] */ Int32 value)
{
return Write(value & 0xff);
}
ECode CRandomAccessFile::WriteChar(
/* [in] */ Int32 value)
{
AutoPtr< ArrayOf<Byte> > buffer = ArrayOf<Byte>::Alloc(4);
Int32 len;
Character::ToChars((Char32)value, *buffer, 0, &len);
return Write(buffer, 0, len);
}
ECode CRandomAccessFile::WriteBytes(
/* [in] */ const String& str)
{
if (str.IsNullOrEmpty())
return NOERROR;
AutoPtr<ArrayOf<Byte> > bytes = ArrayOf<Byte>::Alloc(str.GetLength());
for (Int32 index = 0; index < str.GetLength(); index++) {
bytes->Set(index, (Byte)(str.GetChar(index) & 0xFF));
}
return Write(bytes);
}
ECode CRandomAccessFile::WriteChars(
/* [in] */ const String& str)
{
if (str.IsNullOrEmpty())
return NOERROR;
// write(str.getBytes("UTF-16BE"));
AutoPtr<ArrayOf<Byte> > chs = str.GetBytes();
return Write(chs);
}
ECode CRandomAccessFile::WriteDouble(
/* [in] */ Double value)
{
return WriteInt64(Elastos::Core::Math::DoubleToInt64Bits(value));
}
ECode CRandomAccessFile::WriteFloat(
/* [in] */ Float value)
{
return WriteInt32(Elastos::Core::Math::FloatToInt32Bits(value));
}
ECode CRandomAccessFile::WriteInt32(
/* [in] */ Int32 value)
{
Memory::PokeInt32(mScratch, 0, value, ByteOrder_BIG_ENDIAN);
return Write(mScratch, 0, sizeof(Int32));
}
ECode CRandomAccessFile::WriteInt64(
/* [in] */ Int64 value)
{
Memory::PokeInt64(mScratch, 0, value, ByteOrder_BIG_ENDIAN);
return Write(mScratch, 0, sizeof(Int64));
}
ECode CRandomAccessFile::WriteInt16(
/* [in] */ Int32 value)
{
Memory::PokeInt16(mScratch, 0, value, ByteOrder_BIG_ENDIAN);
return Write(mScratch, 0, sizeof(Int32));
}
ECode CRandomAccessFile::WriteUTF(
/* [in] */ const String& str)
{
AutoPtr<IModifiedUtf8> utf8help;
CModifiedUtf8::AcquireSingleton((IModifiedUtf8**)&utf8help);
AutoPtr<ArrayOf<Byte> > bytes;
utf8help->Encode(str, (ArrayOf<Byte>**)&bytes);
return Write(bytes);
}
} // namespace IO
} // namespace Elastos
| 25.228951
| 103
| 0.617213
|
jingcao80
|
a4de8c9b2755d2990eb30107d52f4125dabf7653
| 876
|
cc
|
C++
|
sdk/lib/fit/test/thread_checker_tests.cc
|
allansrc/fuchsia
|
a2c235b33fc4305044d496354a08775f30cdcf37
|
[
"BSD-2-Clause"
] | 210
|
2019-02-05T12:45:09.000Z
|
2022-03-28T07:59:06.000Z
|
sdk/lib/fit/test/thread_checker_tests.cc
|
allansrc/fuchsia
|
a2c235b33fc4305044d496354a08775f30cdcf37
|
[
"BSD-2-Clause"
] | 56
|
2021-06-03T03:16:25.000Z
|
2022-03-20T01:07:44.000Z
|
sdk/lib/fit/test/thread_checker_tests.cc
|
allansrc/fuchsia
|
a2c235b33fc4305044d496354a08775f30cdcf37
|
[
"BSD-2-Clause"
] | 73
|
2019-03-06T18:55:23.000Z
|
2022-03-26T12:04:51.000Z
|
// Copyright 2016 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <lib/fit/thread_checker.h>
#include <thread>
#include <zxtest/zxtest.h>
namespace {
TEST(ThreadCheckerTest, SameThread) {
fit::thread_checker checker;
EXPECT_TRUE(checker.is_thread_valid());
}
TEST(ThreadCheckerTest, DifferentThreads) {
fit::thread_checker checker1;
EXPECT_TRUE(checker1.is_thread_valid());
checker1.lock();
checker1.unlock();
std::thread thread([&checker1]() {
fit::thread_checker checker2;
EXPECT_TRUE(checker2.is_thread_valid());
EXPECT_FALSE(checker1.is_thread_valid());
checker2.lock();
checker2.unlock();
});
thread.join();
// Note: Without synchronization, we can't look at |checker2| from the main
// thread.
}
} // namespace
| 23.052632
| 77
| 0.718037
|
allansrc
|
a4e4907df8f1e31eadadea20bc86b9db5e0c481d
| 2,880
|
cpp
|
C++
|
test/qupzilla-master/src/lib/webengine/webscrollbar.cpp
|
JamesMBallard/qmake-unity
|
cf5006a83e7fb1bbd173a9506771693a673d387f
|
[
"MIT"
] | 16
|
2019-05-23T08:10:39.000Z
|
2021-12-21T11:20:37.000Z
|
test/qupzilla-master/src/lib/webengine/webscrollbar.cpp
|
JamesMBallard/qmake-unity
|
cf5006a83e7fb1bbd173a9506771693a673d387f
|
[
"MIT"
] | null | null | null |
test/qupzilla-master/src/lib/webengine/webscrollbar.cpp
|
JamesMBallard/qmake-unity
|
cf5006a83e7fb1bbd173a9506771693a673d387f
|
[
"MIT"
] | 2
|
2019-05-23T18:37:43.000Z
|
2021-08-24T21:29:40.000Z
|
/* ============================================================
* QupZilla - Qt web browser
* Copyright (C) 2016-2017 David Rosca <nowrep@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* ============================================================ */
#include "webscrollbar.h"
#include "webview.h"
#include "webpage.h"
#include <QPaintEvent>
WebScrollBar::WebScrollBar(Qt::Orientation orientation, WebView *view)
: QScrollBar(orientation)
, m_view(view)
{
setFocusProxy(m_view);
resize(sizeHint());
connect(this, &QScrollBar::valueChanged, this, &WebScrollBar::performScroll);
connect(view, &WebView::focusChanged, this, [this]() { update(); });
}
int WebScrollBar::thickness() const
{
return orientation() == Qt::Vertical ? width() : height();
}
void WebScrollBar::updateValues(const QSize &viewport)
{
setMinimum(0);
setParent(m_view->overlayWidget());
int newValue;
m_blockScrolling = true;
if (orientation() == Qt::Vertical) {
setFixedHeight(m_view->height() - (m_view->height() - viewport.height()) * devicePixelRatioF());
move(m_view->width() - width(), 0);
setPageStep(viewport.height());
setMaximum(qMax(0, m_view->page()->contentsSize().toSize().height() - viewport.height()));
newValue = m_view->page()->scrollPosition().toPoint().y();
} else {
setFixedWidth(m_view->width() - (m_view->width() - viewport.width()) * devicePixelRatioF());
move(0, m_view->height() - height());
setPageStep(viewport.width());
setMaximum(qMax(0, m_view->page()->contentsSize().toSize().width() - viewport.width()));
newValue = m_view->page()->scrollPosition().toPoint().x();
}
if (!isSliderDown()) {
setValue(newValue);
}
m_blockScrolling = false;
}
void WebScrollBar::performScroll()
{
if (m_blockScrolling) {
return;
}
QPointF pos = m_view->page()->scrollPosition();
if (orientation() == Qt::Vertical) {
pos.setY(value());
} else {
pos.setX(value());
}
m_view->page()->setScrollPosition(pos);
}
void WebScrollBar::paintEvent(QPaintEvent *ev)
{
QPainter painter(this);
painter.fillRect(ev->rect(), palette().background());
QScrollBar::paintEvent(ev);
}
| 30.638298
| 104
| 0.632986
|
JamesMBallard
|
a4e5652802e3e3b819aee3fee6a1d00aed609bb8
| 77,150
|
cpp
|
C++
|
mozilla/gfx/layers/Layers.cpp
|
naver/webgraphics
|
4f9b9aa6a13428b5872dd020eaf34ec77b33f240
|
[
"MS-PL"
] | 5
|
2016-12-20T15:48:05.000Z
|
2020-05-01T20:12:09.000Z
|
mozilla/gfx/layers/Layers.cpp
|
naver/webgraphics
|
4f9b9aa6a13428b5872dd020eaf34ec77b33f240
|
[
"MS-PL"
] | null | null | null |
mozilla/gfx/layers/Layers.cpp
|
naver/webgraphics
|
4f9b9aa6a13428b5872dd020eaf34ec77b33f240
|
[
"MS-PL"
] | 2
|
2016-12-20T15:48:13.000Z
|
2019-12-10T15:15:05.000Z
|
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* vim: sw=2 ts=8 et :
*/
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "Layers.h"
#include <algorithm> // for max, min
#include "apz/src/AsyncPanZoomController.h"
#include "CompositableHost.h" // for CompositableHost
#include "ImageContainer.h" // for ImageContainer, etc
#include "ImageLayers.h" // for ImageLayer
#include "LayerSorter.h" // for SortLayersBy3DZOrder
#include "LayersLogging.h" // for AppendToString
#include "ReadbackLayer.h" // for ReadbackLayer
#include "UnitTransforms.h" // for ViewAs
#include "gfxEnv.h"
#include "gfxPlatform.h" // for gfxPlatform
#include "gfxPrefs.h"
#include "gfxUtils.h" // for gfxUtils, etc
#include "gfx2DGlue.h"
#include "mozilla/DebugOnly.h" // for DebugOnly
#include "mozilla/Telemetry.h" // for Accumulate
#include "mozilla/dom/Animation.h" // for ComputedTimingFunction
#include "mozilla/gfx/2D.h" // for DrawTarget
#include "mozilla/gfx/BaseSize.h" // for BaseSize
#include "mozilla/gfx/Matrix.h" // for Matrix4x4
#include "mozilla/layers/AsyncCanvasRenderer.h"
#include "mozilla/layers/CompositableClient.h" // for CompositableClient
#include "mozilla/layers/Compositor.h" // for Compositor
#include "mozilla/layers/CompositorTypes.h"
#include "mozilla/layers/LayerManagerComposite.h" // for LayerComposite
#include "mozilla/layers/LayerMetricsWrapper.h" // for LayerMetricsWrapper
#include "mozilla/layers/LayersMessages.h" // for TransformFunction, etc
#include "mozilla/layers/LayersTypes.h" // for TextureDumpMode
#include "mozilla/layers/PersistentBufferProvider.h"
#include "mozilla/layers/ShadowLayers.h" // for ShadowableLayer
#include "nsAString.h"
#include "nsCSSValue.h" // for nsCSSValue::Array, etc
#include "nsPrintfCString.h" // for nsPrintfCString
#include "nsStyleStruct.h" // for nsTimingFunction, etc
#include "protobuf/LayerScopePacket.pb.h"
#include "mozilla/Compression.h"
uint8_t gLayerManagerLayerBuilder;
namespace mozilla {
namespace layers {
FILE*
FILEOrDefault(FILE* aFile)
{
return aFile ? aFile : stderr;
}
typedef FrameMetrics::ViewID ViewID;
using namespace mozilla::gfx;
using namespace mozilla::Compression;
//--------------------------------------------------
// LayerManager
/* static */ mozilla::LogModule*
LayerManager::GetLog()
{
static LazyLogModule sLog("Layers");
return sLog;
}
FrameMetrics::ViewID
LayerManager::GetRootScrollableLayerId()
{
if (!mRoot) {
return FrameMetrics::NULL_SCROLL_ID;
}
nsTArray<LayerMetricsWrapper> queue = { LayerMetricsWrapper(mRoot) };
while (queue.Length()) {
LayerMetricsWrapper layer = queue[0];
queue.RemoveElementAt(0);
const FrameMetrics& frameMetrics = layer.Metrics();
if (frameMetrics.IsScrollable()) {
return frameMetrics.GetScrollId();
}
LayerMetricsWrapper child = layer.GetFirstChild();
while (child) {
queue.AppendElement(child);
child = child.GetNextSibling();
}
}
return FrameMetrics::NULL_SCROLL_ID;
}
void
LayerManager::GetRootScrollableLayers(nsTArray<Layer*>& aArray)
{
if (!mRoot) {
return;
}
FrameMetrics::ViewID rootScrollableId = GetRootScrollableLayerId();
if (rootScrollableId == FrameMetrics::NULL_SCROLL_ID) {
aArray.AppendElement(mRoot);
return;
}
nsTArray<Layer*> queue = { mRoot };
while (queue.Length()) {
Layer* layer = queue[0];
queue.RemoveElementAt(0);
if (LayerMetricsWrapper::TopmostScrollableMetrics(layer).GetScrollId() == rootScrollableId) {
aArray.AppendElement(layer);
continue;
}
for (Layer* child = layer->GetFirstChild(); child; child = child->GetNextSibling()) {
queue.AppendElement(child);
}
}
}
void
LayerManager::GetScrollableLayers(nsTArray<Layer*>& aArray)
{
if (!mRoot) {
return;
}
nsTArray<Layer*> queue = { mRoot };
while (!queue.IsEmpty()) {
Layer* layer = queue.LastElement();
queue.RemoveElementAt(queue.Length() - 1);
if (layer->HasScrollableFrameMetrics()) {
aArray.AppendElement(layer);
continue;
}
for (Layer* child = layer->GetFirstChild(); child; child = child->GetNextSibling()) {
queue.AppendElement(child);
}
}
}
already_AddRefed<DrawTarget>
LayerManager::CreateOptimalDrawTarget(const gfx::IntSize &aSize,
SurfaceFormat aFormat)
{
return gfxPlatform::GetPlatform()->CreateOffscreenContentDrawTarget(aSize,
aFormat);
}
already_AddRefed<DrawTarget>
LayerManager::CreateOptimalMaskDrawTarget(const gfx::IntSize &aSize)
{
return CreateOptimalDrawTarget(aSize, SurfaceFormat::A8);
}
already_AddRefed<DrawTarget>
LayerManager::CreateDrawTarget(const IntSize &aSize,
SurfaceFormat aFormat)
{
return gfxPlatform::GetPlatform()->
CreateOffscreenCanvasDrawTarget(aSize, aFormat);
}
already_AddRefed<PersistentBufferProvider>
LayerManager::CreatePersistentBufferProvider(const mozilla::gfx::IntSize &aSize,
mozilla::gfx::SurfaceFormat aFormat)
{
RefPtr<PersistentBufferProviderBasic> bufferProvider =
new PersistentBufferProviderBasic(aSize, aFormat,
gfxPlatform::GetPlatform()->GetPreferredCanvasBackend());
if (!bufferProvider->IsValid()) {
bufferProvider =
new PersistentBufferProviderBasic(aSize, aFormat,
gfxPlatform::GetPlatform()->GetFallbackCanvasBackend());
}
if (!bufferProvider->IsValid()) {
return nullptr;
}
return bufferProvider.forget();
}
#ifdef DEBUG
void
LayerManager::Mutated(Layer* aLayer)
{
}
#endif // DEBUG
already_AddRefed<ImageContainer>
LayerManager::CreateImageContainer(ImageContainer::Mode flag)
{
RefPtr<ImageContainer> container = new ImageContainer(flag);
return container.forget();
}
bool
LayerManager::AreComponentAlphaLayersEnabled()
{
return gfxPrefs::ComponentAlphaEnabled();
}
/*static*/ void
LayerManager::LayerUserDataDestroy(void* data)
{
delete static_cast<LayerUserData*>(data);
}
nsAutoPtr<LayerUserData>
LayerManager::RemoveUserData(void* aKey)
{
nsAutoPtr<LayerUserData> d(static_cast<LayerUserData*>(mUserData.Remove(static_cast<gfx::UserDataKey*>(aKey))));
return d;
}
//--------------------------------------------------
// Layer
Layer::Layer(LayerManager* aManager, void* aImplData) :
mManager(aManager),
mParent(nullptr),
mNextSibling(nullptr),
mPrevSibling(nullptr),
mImplData(aImplData),
mMaskLayer(nullptr),
mPostXScale(1.0f),
mPostYScale(1.0f),
mOpacity(1.0),
mMixBlendMode(CompositionOp::OP_OVER),
mForceIsolatedGroup(false),
mContentFlags(0),
mUseTileSourceRect(false),
mIsFixedPosition(false),
mTransformIsPerspective(false),
mFixedPositionData(nullptr),
mStickyPositionData(nullptr),
mScrollbarTargetId(FrameMetrics::NULL_SCROLL_ID),
mScrollbarDirection(ScrollDirection::NONE),
mScrollbarThumbRatio(0.0f),
mIsScrollbarContainer(false),
mDebugColorIndex(0),
mAnimationGeneration(0)
{
MOZ_COUNT_CTOR(Layer);
}
Layer::~Layer()
{
MOZ_COUNT_DTOR(Layer);
}
Animation*
Layer::AddAnimation()
{
MOZ_LAYERS_LOG_IF_SHADOWABLE(this, ("Layer::Mutated(%p) AddAnimation", this));
MOZ_ASSERT(!mPendingAnimations, "should have called ClearAnimations first");
Animation* anim = mAnimations.AppendElement();
Mutated();
return anim;
}
void
Layer::ClearAnimations()
{
mPendingAnimations = nullptr;
if (mAnimations.IsEmpty() && mAnimationData.IsEmpty()) {
return;
}
MOZ_LAYERS_LOG_IF_SHADOWABLE(this, ("Layer::Mutated(%p) ClearAnimations", this));
mAnimations.Clear();
mAnimationData.Clear();
Mutated();
}
Animation*
Layer::AddAnimationForNextTransaction()
{
MOZ_ASSERT(mPendingAnimations,
"should have called ClearAnimationsForNextTransaction first");
Animation* anim = mPendingAnimations->AppendElement();
return anim;
}
void
Layer::ClearAnimationsForNextTransaction()
{
// Ensure we have a non-null mPendingAnimations to mark a future clear.
if (!mPendingAnimations) {
mPendingAnimations = new AnimationArray;
}
mPendingAnimations->Clear();
}
static inline void
SetCSSAngle(const CSSAngle& aAngle, nsCSSValue& aValue)
{
aValue.SetFloatValue(aAngle.value(), nsCSSUnit(aAngle.unit()));
}
static nsCSSValueSharedList*
CreateCSSValueList(const InfallibleTArray<TransformFunction>& aFunctions)
{
nsAutoPtr<nsCSSValueList> result;
nsCSSValueList** resultTail = getter_Transfers(result);
for (uint32_t i = 0; i < aFunctions.Length(); i++) {
RefPtr<nsCSSValue::Array> arr;
switch (aFunctions[i].type()) {
case TransformFunction::TRotationX:
{
const CSSAngle& angle = aFunctions[i].get_RotationX().angle();
arr = StyleAnimationValue::AppendTransformFunction(eCSSKeyword_rotatex,
resultTail);
SetCSSAngle(angle, arr->Item(1));
break;
}
case TransformFunction::TRotationY:
{
const CSSAngle& angle = aFunctions[i].get_RotationY().angle();
arr = StyleAnimationValue::AppendTransformFunction(eCSSKeyword_rotatey,
resultTail);
SetCSSAngle(angle, arr->Item(1));
break;
}
case TransformFunction::TRotationZ:
{
const CSSAngle& angle = aFunctions[i].get_RotationZ().angle();
arr = StyleAnimationValue::AppendTransformFunction(eCSSKeyword_rotatez,
resultTail);
SetCSSAngle(angle, arr->Item(1));
break;
}
case TransformFunction::TRotation:
{
const CSSAngle& angle = aFunctions[i].get_Rotation().angle();
arr = StyleAnimationValue::AppendTransformFunction(eCSSKeyword_rotate,
resultTail);
SetCSSAngle(angle, arr->Item(1));
break;
}
case TransformFunction::TRotation3D:
{
float x = aFunctions[i].get_Rotation3D().x();
float y = aFunctions[i].get_Rotation3D().y();
float z = aFunctions[i].get_Rotation3D().z();
const CSSAngle& angle = aFunctions[i].get_Rotation3D().angle();
arr =
StyleAnimationValue::AppendTransformFunction(eCSSKeyword_rotate3d,
resultTail);
arr->Item(1).SetFloatValue(x, eCSSUnit_Number);
arr->Item(2).SetFloatValue(y, eCSSUnit_Number);
arr->Item(3).SetFloatValue(z, eCSSUnit_Number);
SetCSSAngle(angle, arr->Item(4));
break;
}
case TransformFunction::TScale:
{
arr =
StyleAnimationValue::AppendTransformFunction(eCSSKeyword_scale3d,
resultTail);
arr->Item(1).SetFloatValue(aFunctions[i].get_Scale().x(), eCSSUnit_Number);
arr->Item(2).SetFloatValue(aFunctions[i].get_Scale().y(), eCSSUnit_Number);
arr->Item(3).SetFloatValue(aFunctions[i].get_Scale().z(), eCSSUnit_Number);
break;
}
case TransformFunction::TTranslation:
{
arr =
StyleAnimationValue::AppendTransformFunction(eCSSKeyword_translate3d,
resultTail);
arr->Item(1).SetFloatValue(aFunctions[i].get_Translation().x(), eCSSUnit_Pixel);
arr->Item(2).SetFloatValue(aFunctions[i].get_Translation().y(), eCSSUnit_Pixel);
arr->Item(3).SetFloatValue(aFunctions[i].get_Translation().z(), eCSSUnit_Pixel);
break;
}
case TransformFunction::TSkewX:
{
const CSSAngle& x = aFunctions[i].get_SkewX().x();
arr = StyleAnimationValue::AppendTransformFunction(eCSSKeyword_skewx,
resultTail);
SetCSSAngle(x, arr->Item(1));
break;
}
case TransformFunction::TSkewY:
{
const CSSAngle& y = aFunctions[i].get_SkewY().y();
arr = StyleAnimationValue::AppendTransformFunction(eCSSKeyword_skewy,
resultTail);
SetCSSAngle(y, arr->Item(1));
break;
}
case TransformFunction::TSkew:
{
const CSSAngle& x = aFunctions[i].get_Skew().x();
const CSSAngle& y = aFunctions[i].get_Skew().y();
arr = StyleAnimationValue::AppendTransformFunction(eCSSKeyword_skew,
resultTail);
SetCSSAngle(x, arr->Item(1));
SetCSSAngle(y, arr->Item(2));
break;
}
case TransformFunction::TTransformMatrix:
{
arr =
StyleAnimationValue::AppendTransformFunction(eCSSKeyword_matrix3d,
resultTail);
const gfx::Matrix4x4& matrix = aFunctions[i].get_TransformMatrix().value();
arr->Item(1).SetFloatValue(matrix._11, eCSSUnit_Number);
arr->Item(2).SetFloatValue(matrix._12, eCSSUnit_Number);
arr->Item(3).SetFloatValue(matrix._13, eCSSUnit_Number);
arr->Item(4).SetFloatValue(matrix._14, eCSSUnit_Number);
arr->Item(5).SetFloatValue(matrix._21, eCSSUnit_Number);
arr->Item(6).SetFloatValue(matrix._22, eCSSUnit_Number);
arr->Item(7).SetFloatValue(matrix._23, eCSSUnit_Number);
arr->Item(8).SetFloatValue(matrix._24, eCSSUnit_Number);
arr->Item(9).SetFloatValue(matrix._31, eCSSUnit_Number);
arr->Item(10).SetFloatValue(matrix._32, eCSSUnit_Number);
arr->Item(11).SetFloatValue(matrix._33, eCSSUnit_Number);
arr->Item(12).SetFloatValue(matrix._34, eCSSUnit_Number);
arr->Item(13).SetFloatValue(matrix._41, eCSSUnit_Number);
arr->Item(14).SetFloatValue(matrix._42, eCSSUnit_Number);
arr->Item(15).SetFloatValue(matrix._43, eCSSUnit_Number);
arr->Item(16).SetFloatValue(matrix._44, eCSSUnit_Number);
break;
}
case TransformFunction::TPerspective:
{
float perspective = aFunctions[i].get_Perspective().value();
arr =
StyleAnimationValue::AppendTransformFunction(eCSSKeyword_perspective,
resultTail);
arr->Item(1).SetFloatValue(perspective, eCSSUnit_Pixel);
break;
}
default:
NS_ASSERTION(false, "All functions should be implemented?");
}
}
if (aFunctions.Length() == 0) {
result = new nsCSSValueList();
result->mValue.SetNoneValue();
}
return new nsCSSValueSharedList(result.forget());
}
void
Layer::SetAnimations(const AnimationArray& aAnimations)
{
MOZ_LAYERS_LOG_IF_SHADOWABLE(this, ("Layer::Mutated(%p) SetAnimations", this));
mAnimations = aAnimations;
mAnimationData.Clear();
for (uint32_t i = 0; i < mAnimations.Length(); i++) {
AnimData* data = mAnimationData.AppendElement();
InfallibleTArray<nsAutoPtr<ComputedTimingFunction> >& functions =
data->mFunctions;
const InfallibleTArray<AnimationSegment>& segments =
mAnimations.ElementAt(i).segments();
for (uint32_t j = 0; j < segments.Length(); j++) {
TimingFunction tf = segments.ElementAt(j).sampleFn();
ComputedTimingFunction* ctf = new ComputedTimingFunction();
switch (tf.type()) {
case TimingFunction::TCubicBezierFunction: {
CubicBezierFunction cbf = tf.get_CubicBezierFunction();
ctf->Init(nsTimingFunction(cbf.x1(), cbf.y1(), cbf.x2(), cbf.y2()));
break;
}
default: {
NS_ASSERTION(tf.type() == TimingFunction::TStepFunction,
"Function must be bezier or step");
StepFunction sf = tf.get_StepFunction();
nsTimingFunction::Type type = sf.type() == 1 ?
nsTimingFunction::Type::StepStart :
nsTimingFunction::Type::StepEnd;
ctf->Init(nsTimingFunction(type, sf.steps(),
nsTimingFunction::Keyword::Explicit));
break;
}
}
functions.AppendElement(ctf);
}
// Precompute the StyleAnimationValues that we need if this is a transform
// animation.
InfallibleTArray<StyleAnimationValue>& startValues = data->mStartValues;
InfallibleTArray<StyleAnimationValue>& endValues = data->mEndValues;
for (uint32_t j = 0; j < mAnimations[i].segments().Length(); j++) {
const AnimationSegment& segment = mAnimations[i].segments()[j];
StyleAnimationValue* startValue = startValues.AppendElement();
StyleAnimationValue* endValue = endValues.AppendElement();
if (segment.endState().type() == Animatable::TArrayOfTransformFunction) {
const InfallibleTArray<TransformFunction>& startFunctions =
segment.startState().get_ArrayOfTransformFunction();
startValue->SetTransformValue(CreateCSSValueList(startFunctions));
const InfallibleTArray<TransformFunction>& endFunctions =
segment.endState().get_ArrayOfTransformFunction();
endValue->SetTransformValue(CreateCSSValueList(endFunctions));
} else {
NS_ASSERTION(segment.endState().type() == Animatable::Tfloat,
"Unknown Animatable type");
startValue->SetFloatValue(segment.startState().get_float());
endValue->SetFloatValue(segment.endState().get_float());
}
}
}
Mutated();
}
void
Layer::StartPendingAnimations(const TimeStamp& aReadyTime)
{
bool updated = false;
for (size_t animIdx = 0, animEnd = mAnimations.Length();
animIdx < animEnd; animIdx++) {
Animation& anim = mAnimations[animIdx];
if (anim.startTime().IsNull()) {
anim.startTime() = aReadyTime - anim.initialCurrentTime();
updated = true;
}
}
if (updated) {
Mutated();
}
for (Layer* child = GetFirstChild(); child; child = child->GetNextSibling()) {
child->StartPendingAnimations(aReadyTime);
}
}
void
Layer::SetAsyncPanZoomController(uint32_t aIndex, AsyncPanZoomController *controller)
{
MOZ_ASSERT(aIndex < GetFrameMetricsCount());
mApzcs[aIndex] = controller;
}
AsyncPanZoomController*
Layer::GetAsyncPanZoomController(uint32_t aIndex) const
{
MOZ_ASSERT(aIndex < GetFrameMetricsCount());
#ifdef DEBUG
if (mApzcs[aIndex]) {
MOZ_ASSERT(GetFrameMetrics(aIndex).IsScrollable());
}
#endif
return mApzcs[aIndex];
}
void
Layer::FrameMetricsChanged()
{
mApzcs.SetLength(GetFrameMetricsCount());
}
void
Layer::ApplyPendingUpdatesToSubtree()
{
ApplyPendingUpdatesForThisTransaction();
for (Layer* child = GetFirstChild(); child; child = child->GetNextSibling()) {
child->ApplyPendingUpdatesToSubtree();
}
}
bool
Layer::IsOpaqueForVisibility()
{
return GetLocalOpacity() == 1.0f &&
GetEffectiveMixBlendMode() == CompositionOp::OP_OVER;
}
bool
Layer::CanUseOpaqueSurface()
{
// If the visible content in the layer is opaque, there is no need
// for an alpha channel.
if (GetContentFlags() & CONTENT_OPAQUE)
return true;
// Also, if this layer is the bottommost layer in a container which
// doesn't need an alpha channel, we can use an opaque surface for this
// layer too. Any transparent areas must be covered by something else
// in the container.
ContainerLayer* parent = GetParent();
return parent && parent->GetFirstChild() == this &&
parent->CanUseOpaqueSurface();
}
// NB: eventually these methods will be defined unconditionally, and
// can be moved into Layers.h
const Maybe<ParentLayerIntRect>&
Layer::GetEffectiveClipRect()
{
if (LayerComposite* shadow = AsLayerComposite()) {
return shadow->GetShadowClipRect();
}
return GetClipRect();
}
const LayerIntRegion&
Layer::GetEffectiveVisibleRegion()
{
if (LayerComposite* shadow = AsLayerComposite()) {
return shadow->GetShadowVisibleRegion();
}
return GetVisibleRegion();
}
Matrix4x4
Layer::SnapTransformTranslation(const Matrix4x4& aTransform,
Matrix* aResidualTransform)
{
if (aResidualTransform) {
*aResidualTransform = Matrix();
}
if (!mManager->IsSnappingEffectiveTransforms()) {
return aTransform;
}
Matrix matrix2D;
Matrix4x4 result;
if (aTransform.Is2D(&matrix2D) &&
!matrix2D.HasNonTranslation() &&
matrix2D.HasNonIntegerTranslation()) {
IntPoint snappedTranslation = RoundedToInt(matrix2D.GetTranslation());
Matrix snappedMatrix = Matrix::Translation(snappedTranslation.x,
snappedTranslation.y);
result = Matrix4x4::From2D(snappedMatrix);
if (aResidualTransform) {
// set aResidualTransform so that aResidual * snappedMatrix == matrix2D.
// (I.e., appying snappedMatrix after aResidualTransform gives the
// ideal transform.)
*aResidualTransform =
Matrix::Translation(matrix2D._31 - snappedTranslation.x,
matrix2D._32 - snappedTranslation.y);
}
return result;
}
if(aTransform.IsSingular() ||
aTransform.HasPerspectiveComponent() ||
aTransform.HasNonTranslation() ||
!aTransform.HasNonIntegerTranslation()) {
// For a singular transform, there is no reversed matrix, so we
// don't snap it.
// For a perspective transform, the content is transformed in
// non-linear, so we don't snap it too.
return aTransform;
}
// Snap for 3D Transforms
Point3D transformedOrigin = aTransform * Point3D();
// Compute the transformed snap by rounding the values of
// transformed origin.
IntPoint transformedSnapXY =
RoundedToInt(Point(transformedOrigin.x, transformedOrigin.y));
Matrix4x4 inverse = aTransform;
inverse.Invert();
// see Matrix4x4::ProjectPoint()
Float transformedSnapZ =
inverse._33 == 0 ? 0 : (-(transformedSnapXY.x * inverse._13 +
transformedSnapXY.y * inverse._23 +
inverse._43) / inverse._33);
Point3D transformedSnap =
Point3D(transformedSnapXY.x, transformedSnapXY.y, transformedSnapZ);
if (transformedOrigin == transformedSnap) {
return aTransform;
}
// Compute the snap from the transformed snap.
Point3D snap = inverse * transformedSnap;
if (snap.z > 0.001 || snap.z < -0.001) {
// Allow some level of accumulated computation error.
MOZ_ASSERT(inverse._33 == 0.0);
return aTransform;
}
// The difference between the origin and snap is the residual transform.
if (aResidualTransform) {
// The residual transform is to translate the snap to the origin
// of the content buffer.
*aResidualTransform = Matrix::Translation(-snap.x, -snap.y);
}
// Translate transformed origin to transformed snap since the
// residual transform would trnslate the snap to the origin.
Point3D transformedShift = transformedSnap - transformedOrigin;
result = aTransform;
result.PostTranslate(transformedShift.x,
transformedShift.y,
transformedShift.z);
// For non-2d transform, residual translation could be more than
// 0.5 pixels for every axis.
return result;
}
Matrix4x4
Layer::SnapTransform(const Matrix4x4& aTransform,
const gfxRect& aSnapRect,
Matrix* aResidualTransform)
{
if (aResidualTransform) {
*aResidualTransform = Matrix();
}
Matrix matrix2D;
Matrix4x4 result;
if (mManager->IsSnappingEffectiveTransforms() &&
aTransform.Is2D(&matrix2D) &&
gfxSize(1.0, 1.0) <= aSnapRect.Size() &&
matrix2D.PreservesAxisAlignedRectangles()) {
IntPoint transformedTopLeft = RoundedToInt(matrix2D * ToPoint(aSnapRect.TopLeft()));
IntPoint transformedTopRight = RoundedToInt(matrix2D * ToPoint(aSnapRect.TopRight()));
IntPoint transformedBottomRight = RoundedToInt(matrix2D * ToPoint(aSnapRect.BottomRight()));
Matrix snappedMatrix = gfxUtils::TransformRectToRect(aSnapRect,
transformedTopLeft, transformedTopRight, transformedBottomRight);
result = Matrix4x4::From2D(snappedMatrix);
if (aResidualTransform && !snappedMatrix.IsSingular()) {
// set aResidualTransform so that aResidual * snappedMatrix == matrix2D.
// (i.e., appying snappedMatrix after aResidualTransform gives the
// ideal transform.
Matrix snappedMatrixInverse = snappedMatrix;
snappedMatrixInverse.Invert();
*aResidualTransform = matrix2D * snappedMatrixInverse;
}
} else {
result = aTransform;
}
return result;
}
static bool
AncestorLayerMayChangeTransform(Layer* aLayer)
{
for (Layer* l = aLayer; l; l = l->GetParent()) {
if (l->GetContentFlags() & Layer::CONTENT_MAY_CHANGE_TRANSFORM) {
return true;
}
}
return false;
}
bool
Layer::MayResample()
{
Matrix transform2d;
return !GetEffectiveTransform().Is2D(&transform2d) ||
ThebesMatrix(transform2d).HasNonIntegerTranslation() ||
AncestorLayerMayChangeTransform(this);
}
RenderTargetIntRect
Layer::CalculateScissorRect(const RenderTargetIntRect& aCurrentScissorRect)
{
ContainerLayer* container = GetParent();
ContainerLayer* containerChild = nullptr;
NS_ASSERTION(GetParent(), "This can't be called on the root!");
// Find the layer creating the 3D context.
while (container->Extend3DContext() &&
!container->UseIntermediateSurface()) {
containerChild = container;
container = container->GetParent();
MOZ_ASSERT(container);
}
// Find the nearest layer with a clip, or this layer.
// ContainerState::SetupScrollingMetadata() may install a clip on
// the layer.
Layer *clipLayer =
containerChild && containerChild->GetEffectiveClipRect() ?
containerChild : this;
// Establish initial clip rect: it's either the one passed in, or
// if the parent has an intermediate surface, it's the extents of that surface.
RenderTargetIntRect currentClip;
if (container->UseIntermediateSurface()) {
currentClip.SizeTo(container->GetIntermediateSurfaceRect().Size());
} else {
currentClip = aCurrentScissorRect;
}
if (!clipLayer->GetEffectiveClipRect()) {
return currentClip;
}
if (GetVisibleRegion().IsEmpty()) {
// When our visible region is empty, our parent may not have created the
// intermediate surface that we would require for correct clipping; however,
// this does not matter since we are invisible.
return RenderTargetIntRect(currentClip.TopLeft(), RenderTargetIntSize(0, 0));
}
const RenderTargetIntRect clipRect =
ViewAs<RenderTargetPixel>(*clipLayer->GetEffectiveClipRect(),
PixelCastJustification::RenderTargetIsParentLayerForRoot);
if (clipRect.IsEmpty()) {
// We might have a non-translation transform in the container so we can't
// use the code path below.
return RenderTargetIntRect(currentClip.TopLeft(), RenderTargetIntSize(0, 0));
}
RenderTargetIntRect scissor = clipRect;
if (!container->UseIntermediateSurface()) {
gfx::Matrix matrix;
DebugOnly<bool> is2D = container->GetEffectiveTransform().Is2D(&matrix);
// See DefaultComputeEffectiveTransforms below
NS_ASSERTION(is2D && matrix.PreservesAxisAlignedRectangles(),
"Non preserves axis aligned transform with clipped child should have forced intermediate surface");
gfx::Rect r(scissor.x, scissor.y, scissor.width, scissor.height);
gfxRect trScissor = gfx::ThebesRect(matrix.TransformBounds(r));
trScissor.Round();
IntRect tmp;
if (!gfxUtils::GfxRectToIntRect(trScissor, &tmp)) {
return RenderTargetIntRect(currentClip.TopLeft(), RenderTargetIntSize(0, 0));
}
scissor = ViewAs<RenderTargetPixel>(tmp);
// Find the nearest ancestor with an intermediate surface
do {
container = container->GetParent();
} while (container && !container->UseIntermediateSurface());
}
if (container) {
scissor.MoveBy(-container->GetIntermediateSurfaceRect().TopLeft());
}
return currentClip.Intersect(scissor);
}
const FrameMetrics&
Layer::GetFrameMetrics(uint32_t aIndex) const
{
MOZ_ASSERT(aIndex < GetFrameMetricsCount());
return mFrameMetrics[aIndex];
}
bool
Layer::HasScrollableFrameMetrics() const
{
for (uint32_t i = 0; i < GetFrameMetricsCount(); i++) {
if (GetFrameMetrics(i).IsScrollable()) {
return true;
}
}
return false;
}
bool
Layer::IsScrollInfoLayer() const
{
// A scrollable container layer with no children
return AsContainerLayer()
&& HasScrollableFrameMetrics()
&& !GetFirstChild();
}
const Matrix4x4
Layer::GetTransform() const
{
Matrix4x4 transform = mTransform;
transform.PostScale(GetPostXScale(), GetPostYScale(), 1.0f);
if (const ContainerLayer* c = AsContainerLayer()) {
transform.PreScale(c->GetPreXScale(), c->GetPreYScale(), 1.0f);
}
return transform;
}
const CSSTransformMatrix
Layer::GetTransformTyped() const
{
return ViewAs<CSSTransformMatrix>(GetTransform());
}
const Matrix4x4
Layer::GetLocalTransform()
{
Matrix4x4 transform;
if (LayerComposite* shadow = AsLayerComposite())
transform = shadow->GetShadowTransform();
else
transform = mTransform;
transform.PostScale(GetPostXScale(), GetPostYScale(), 1.0f);
if (ContainerLayer* c = AsContainerLayer()) {
transform.PreScale(c->GetPreXScale(), c->GetPreYScale(), 1.0f);
}
return transform;
}
const LayerToParentLayerMatrix4x4
Layer::GetLocalTransformTyped()
{
return ViewAs<LayerToParentLayerMatrix4x4>(GetLocalTransform());
}
bool
Layer::HasTransformAnimation() const
{
for (uint32_t i = 0; i < mAnimations.Length(); i++) {
if (mAnimations[i].property() == eCSSProperty_transform) {
return true;
}
}
return false;
}
void
Layer::ApplyPendingUpdatesForThisTransaction()
{
if (mPendingTransform && *mPendingTransform != mTransform) {
MOZ_LAYERS_LOG_IF_SHADOWABLE(this, ("Layer::Mutated(%p) PendingUpdatesForThisTransaction", this));
mTransform = *mPendingTransform;
Mutated();
}
mPendingTransform = nullptr;
if (mPendingAnimations) {
MOZ_LAYERS_LOG_IF_SHADOWABLE(this, ("Layer::Mutated(%p) PendingUpdatesForThisTransaction", this));
mPendingAnimations->SwapElements(mAnimations);
mPendingAnimations = nullptr;
Mutated();
}
}
float
Layer::GetLocalOpacity()
{
float opacity = mOpacity;
if (LayerComposite* shadow = AsLayerComposite())
opacity = shadow->GetShadowOpacity();
return std::min(std::max(opacity, 0.0f), 1.0f);
}
float
Layer::GetEffectiveOpacity()
{
float opacity = GetLocalOpacity();
for (ContainerLayer* c = GetParent(); c && !c->UseIntermediateSurface();
c = c->GetParent()) {
opacity *= c->GetLocalOpacity();
}
return opacity;
}
CompositionOp
Layer::GetEffectiveMixBlendMode()
{
if(mMixBlendMode != CompositionOp::OP_OVER)
return mMixBlendMode;
for (ContainerLayer* c = GetParent(); c && !c->UseIntermediateSurface();
c = c->GetParent()) {
if(c->mMixBlendMode != CompositionOp::OP_OVER)
return c->mMixBlendMode;
}
return mMixBlendMode;
}
void
Layer::ComputeEffectiveTransformForMaskLayers(const gfx::Matrix4x4& aTransformToSurface)
{
if (GetMaskLayer()) {
ComputeEffectiveTransformForMaskLayer(GetMaskLayer(), aTransformToSurface);
}
for (size_t i = 0; i < GetAncestorMaskLayerCount(); i++) {
Layer* maskLayer = GetAncestorMaskLayerAt(i);
ComputeEffectiveTransformForMaskLayer(maskLayer, aTransformToSurface);
}
}
/* static */ void
Layer::ComputeEffectiveTransformForMaskLayer(Layer* aMaskLayer, const gfx::Matrix4x4& aTransformToSurface)
{
aMaskLayer->mEffectiveTransform = aTransformToSurface;
#ifdef DEBUG
bool maskIs2D = aMaskLayer->GetTransform().CanDraw2D();
NS_ASSERTION(maskIs2D, "How did we end up with a 3D transform here?!");
#endif
// The mask layer can have an async transform applied to it in some
// situations, so be sure to use its GetLocalTransform() rather than
// its GetTransform().
aMaskLayer->mEffectiveTransform = aMaskLayer->GetLocalTransform() *
aMaskLayer->mEffectiveTransform;
}
RenderTargetRect
Layer::TransformRectToRenderTarget(const LayerIntRect& aRect)
{
LayerRect rect(aRect);
RenderTargetRect quad = RenderTargetRect::FromUnknownRect(
GetEffectiveTransform().TransformBounds(rect.ToUnknownRect()));
return quad;
}
bool
Layer::GetVisibleRegionRelativeToRootLayer(nsIntRegion& aResult,
nsIntPoint* aLayerOffset)
{
MOZ_ASSERT(aLayerOffset, "invalid offset pointer");
if (!GetParent()) {
return false;
}
IntPoint offset;
aResult = GetEffectiveVisibleRegion().ToUnknownRegion();
for (Layer* layer = this; layer; layer = layer->GetParent()) {
gfx::Matrix matrix;
if (!layer->GetLocalTransform().Is2D(&matrix) ||
!matrix.IsTranslation()) {
return false;
}
// The offset of |layer| to its parent.
IntPoint currentLayerOffset = RoundedToInt(matrix.GetTranslation());
// Translate the accumulated visible region of |this| by the offset of
// |layer|.
aResult.MoveBy(currentLayerOffset.x, currentLayerOffset.y);
// If the parent layer clips its lower layers, clip the visible region
// we're accumulating.
if (layer->GetEffectiveClipRect()) {
aResult.AndWith(layer->GetEffectiveClipRect()->ToUnknownRect());
}
// Now we need to walk across the list of siblings for this parent layer,
// checking to see if any of these layer trees obscure |this|. If so,
// remove these areas from the visible region as well. This will pick up
// chrome overlays like a tab modal prompt.
Layer* sibling;
for (sibling = layer->GetNextSibling(); sibling;
sibling = sibling->GetNextSibling()) {
gfx::Matrix siblingMatrix;
if (!sibling->GetLocalTransform().Is2D(&siblingMatrix) ||
!siblingMatrix.IsTranslation()) {
return false;
}
// Retreive the translation from sibling to |layer|. The accumulated
// visible region is currently oriented with |layer|.
IntPoint siblingOffset = RoundedToInt(siblingMatrix.GetTranslation());
nsIntRegion siblingVisibleRegion(sibling->GetEffectiveVisibleRegion().ToUnknownRegion());
// Translate the siblings region to |layer|'s origin.
siblingVisibleRegion.MoveBy(-siblingOffset.x, -siblingOffset.y);
// Apply the sibling's clip.
// Layer clip rects are not affected by the layer's transform.
Maybe<ParentLayerIntRect> clipRect = sibling->GetEffectiveClipRect();
if (clipRect) {
siblingVisibleRegion.AndWith(clipRect->ToUnknownRect());
}
// Subtract the sibling visible region from the visible region of |this|.
aResult.SubOut(siblingVisibleRegion);
}
// Keep track of the total offset for aLayerOffset. We use this in plugin
// positioning code.
offset += currentLayerOffset;
}
*aLayerOffset = nsIntPoint(offset.x, offset.y);
return true;
}
Maybe<ParentLayerIntRect>
Layer::GetCombinedClipRect() const
{
Maybe<ParentLayerIntRect> clip = GetClipRect();
for (size_t i = 0; i < mFrameMetrics.Length(); i++) {
if (!mFrameMetrics[i].HasClipRect()) {
continue;
}
const ParentLayerIntRect& other = mFrameMetrics[i].ClipRect();
if (clip) {
clip = Some(clip.value().Intersect(other));
} else {
clip = Some(other);
}
}
return clip;
}
ContainerLayer::ContainerLayer(LayerManager* aManager, void* aImplData)
: Layer(aManager, aImplData),
mFirstChild(nullptr),
mLastChild(nullptr),
mPreXScale(1.0f),
mPreYScale(1.0f),
mInheritedXScale(1.0f),
mInheritedYScale(1.0f),
mPresShellResolution(1.0f),
mScaleToResolution(false),
mUseIntermediateSurface(false),
mSupportsComponentAlphaChildren(false),
mMayHaveReadbackChild(false),
mChildrenChanged(false),
mEventRegionsOverride(EventRegionsOverride::NoOverride),
mVRDeviceID(0)
{
MOZ_COUNT_CTOR(ContainerLayer);
mContentFlags = 0; // Clear NO_TEXT, NO_TEXT_OVER_TRANSPARENT
}
ContainerLayer::~ContainerLayer()
{
MOZ_COUNT_DTOR(ContainerLayer);
}
bool
ContainerLayer::InsertAfter(Layer* aChild, Layer* aAfter)
{
if(aChild->Manager() != Manager()) {
NS_ERROR("Child has wrong manager");
return false;
}
if(aChild->GetParent()) {
NS_ERROR("aChild already in the tree");
return false;
}
if (aChild->GetNextSibling() || aChild->GetPrevSibling()) {
NS_ERROR("aChild already has siblings?");
return false;
}
if (aAfter && (aAfter->Manager() != Manager() ||
aAfter->GetParent() != this))
{
NS_ERROR("aAfter is not our child");
return false;
}
aChild->SetParent(this);
if (aAfter == mLastChild) {
mLastChild = aChild;
}
if (!aAfter) {
aChild->SetNextSibling(mFirstChild);
if (mFirstChild) {
mFirstChild->SetPrevSibling(aChild);
}
mFirstChild = aChild;
NS_ADDREF(aChild);
DidInsertChild(aChild);
return true;
}
Layer* next = aAfter->GetNextSibling();
aChild->SetNextSibling(next);
aChild->SetPrevSibling(aAfter);
if (next) {
next->SetPrevSibling(aChild);
}
aAfter->SetNextSibling(aChild);
NS_ADDREF(aChild);
DidInsertChild(aChild);
return true;
}
bool
ContainerLayer::RemoveChild(Layer *aChild)
{
if (aChild->Manager() != Manager()) {
NS_ERROR("Child has wrong manager");
return false;
}
if (aChild->GetParent() != this) {
NS_ERROR("aChild not our child");
return false;
}
Layer* prev = aChild->GetPrevSibling();
Layer* next = aChild->GetNextSibling();
if (prev) {
prev->SetNextSibling(next);
} else {
this->mFirstChild = next;
}
if (next) {
next->SetPrevSibling(prev);
} else {
this->mLastChild = prev;
}
aChild->SetNextSibling(nullptr);
aChild->SetPrevSibling(nullptr);
aChild->SetParent(nullptr);
this->DidRemoveChild(aChild);
NS_RELEASE(aChild);
return true;
}
bool
ContainerLayer::RepositionChild(Layer* aChild, Layer* aAfter)
{
if (aChild->Manager() != Manager()) {
NS_ERROR("Child has wrong manager");
return false;
}
if (aChild->GetParent() != this) {
NS_ERROR("aChild not our child");
return false;
}
if (aAfter && (aAfter->Manager() != Manager() ||
aAfter->GetParent() != this))
{
NS_ERROR("aAfter is not our child");
return false;
}
if (aChild == aAfter) {
NS_ERROR("aChild cannot be the same as aAfter");
return false;
}
Layer* prev = aChild->GetPrevSibling();
Layer* next = aChild->GetNextSibling();
if (prev == aAfter) {
// aChild is already in the correct position, nothing to do.
return true;
}
if (prev) {
prev->SetNextSibling(next);
} else {
mFirstChild = next;
}
if (next) {
next->SetPrevSibling(prev);
} else {
mLastChild = prev;
}
if (!aAfter) {
aChild->SetPrevSibling(nullptr);
aChild->SetNextSibling(mFirstChild);
if (mFirstChild) {
mFirstChild->SetPrevSibling(aChild);
}
mFirstChild = aChild;
return true;
}
Layer* afterNext = aAfter->GetNextSibling();
if (afterNext) {
afterNext->SetPrevSibling(aChild);
} else {
mLastChild = aChild;
}
aAfter->SetNextSibling(aChild);
aChild->SetPrevSibling(aAfter);
aChild->SetNextSibling(afterNext);
return true;
}
void
ContainerLayer::FillSpecificAttributes(SpecificLayerAttributes& aAttrs)
{
aAttrs = ContainerLayerAttributes(mPreXScale, mPreYScale,
mInheritedXScale, mInheritedYScale,
mPresShellResolution, mScaleToResolution,
mEventRegionsOverride,
mVRDeviceID);
}
bool
ContainerLayer::Creates3DContextWithExtendingChildren()
{
if (Extend3DContext()) {
return false;
}
for (Layer* child = GetFirstChild();
child;
child = child->GetNextSibling()) {
if (child->Extend3DContext()) {
return true;
}
}
return false;
}
bool
ContainerLayer::HasMultipleChildren()
{
uint32_t count = 0;
for (Layer* child = GetFirstChild(); child; child = child->GetNextSibling()) {
const Maybe<ParentLayerIntRect>& clipRect = child->GetEffectiveClipRect();
if (clipRect && clipRect->IsEmpty())
continue;
if (child->GetVisibleRegion().IsEmpty())
continue;
++count;
if (count > 1)
return true;
}
return false;
}
/**
* Collect all leaf descendants of the current 3D context.
*/
void
ContainerLayer::Collect3DContextLeaves(nsTArray<Layer*>& aToSort)
{
for (Layer* l = GetFirstChild(); l; l = l->GetNextSibling()) {
ContainerLayer* container = l->AsContainerLayer();
if (container && container->Extend3DContext() &&
!container->UseIntermediateSurface()) {
container->Collect3DContextLeaves(aToSort);
} else {
aToSort.AppendElement(l);
}
}
}
void
ContainerLayer::SortChildrenBy3DZOrder(nsTArray<Layer*>& aArray)
{
nsAutoTArray<Layer*, 10> toSort;
for (Layer* l = GetFirstChild(); l; l = l->GetNextSibling()) {
ContainerLayer* container = l->AsContainerLayer();
if (container && container->Extend3DContext() &&
!container->UseIntermediateSurface()) {
container->Collect3DContextLeaves(toSort);
} else {
if (toSort.Length() > 0) {
SortLayersBy3DZOrder(toSort);
aArray.AppendElements(Move(toSort));
// XXX The move analysis gets confused here, because toSort gets moved
// here, and then gets used again outside of the loop. To clarify that
// we realize that the array is going to be empty to the move checker,
// we clear it again here. (This method renews toSort for the move
// analysis)
toSort.ClearAndRetainStorage();
}
aArray.AppendElement(l);
}
}
if (toSort.Length() > 0) {
SortLayersBy3DZOrder(toSort);
aArray.AppendElements(Move(toSort));
}
}
void
ContainerLayer::DefaultComputeEffectiveTransforms(const Matrix4x4& aTransformToSurface)
{
Matrix residual;
Matrix4x4 idealTransform = GetLocalTransform() * aTransformToSurface;
// Keep 3D transforms for leaves to keep z-order sorting correct.
if (!Extend3DContext() && !Is3DContextLeaf()) {
idealTransform.ProjectTo2D();
}
bool useIntermediateSurface;
if (HasMaskLayers() ||
GetForceIsolatedGroup()) {
useIntermediateSurface = true;
#ifdef MOZ_DUMP_PAINTING
} else if (gfxEnv::DumpPaintIntermediate() && !Extend3DContext()) {
useIntermediateSurface = true;
#endif
} else {
float opacity = GetEffectiveOpacity();
CompositionOp blendMode = GetEffectiveMixBlendMode();
if (((opacity != 1.0f || blendMode != CompositionOp::OP_OVER) && (HasMultipleChildren() || Creates3DContextWithExtendingChildren())) ||
(!idealTransform.Is2D() && Creates3DContextWithExtendingChildren())) {
useIntermediateSurface = true;
} else {
useIntermediateSurface = false;
gfx::Matrix contTransform;
bool checkClipRect = false;
bool checkMaskLayers = false;
if (!idealTransform.Is2D(&contTransform)) {
// In 3D case, always check if we should use IntermediateSurface.
checkClipRect = true;
checkMaskLayers = true;
} else {
#ifdef MOZ_GFX_OPTIMIZE_MOBILE
if (!contTransform.PreservesAxisAlignedRectangles()) {
#else
if (gfx::ThebesMatrix(contTransform).HasNonIntegerTranslation()) {
#endif
checkClipRect = true;
}
/* In 2D case, only translation and/or positive scaling can be done w/o using IntermediateSurface.
* Otherwise, when rotation or flip happen, we should check whether to use IntermediateSurface.
*/
if (contTransform.HasNonAxisAlignedTransform() || contTransform.HasNegativeScaling()) {
checkMaskLayers = true;
}
}
if (checkClipRect || checkMaskLayers) {
for (Layer* child = GetFirstChild(); child; child = child->GetNextSibling()) {
const Maybe<ParentLayerIntRect>& clipRect = child->GetEffectiveClipRect();
/* We can't (easily) forward our transform to children with a non-empty clip
* rect since it would need to be adjusted for the transform. See
* the calculations performed by CalculateScissorRect above.
* Nor for a child with a mask layer.
*/
if (checkClipRect && (clipRect && !clipRect->IsEmpty() && !child->GetVisibleRegion().IsEmpty())) {
useIntermediateSurface = true;
break;
}
if (checkMaskLayers && child->HasMaskLayers()) {
useIntermediateSurface = true;
break;
}
}
}
}
}
if (useIntermediateSurface) {
mEffectiveTransform = SnapTransformTranslation(idealTransform, &residual);
} else {
mEffectiveTransform = idealTransform;
}
// For layers extending 3d context, its ideal transform should be
// applied on children.
if (!Extend3DContext()) {
// Without this projection, non-container children would get a 3D
// transform while 2D is expected.
idealTransform.ProjectTo2D();
}
mUseIntermediateSurface = useIntermediateSurface && !GetEffectiveVisibleRegion().IsEmpty();
if (useIntermediateSurface) {
ComputeEffectiveTransformsForChildren(Matrix4x4::From2D(residual));
} else {
ComputeEffectiveTransformsForChildren(idealTransform);
}
if (idealTransform.CanDraw2D()) {
ComputeEffectiveTransformForMaskLayers(aTransformToSurface);
} else {
ComputeEffectiveTransformForMaskLayers(Matrix4x4());
}
}
void
ContainerLayer::DefaultComputeSupportsComponentAlphaChildren(bool* aNeedsSurfaceCopy)
{
if (!(GetContentFlags() & Layer::CONTENT_COMPONENT_ALPHA_DESCENDANT) ||
!Manager()->AreComponentAlphaLayersEnabled()) {
mSupportsComponentAlphaChildren = false;
if (aNeedsSurfaceCopy) {
*aNeedsSurfaceCopy = false;
}
return;
}
mSupportsComponentAlphaChildren = false;
bool needsSurfaceCopy = false;
CompositionOp blendMode = GetEffectiveMixBlendMode();
if (UseIntermediateSurface()) {
if (GetEffectiveVisibleRegion().GetNumRects() == 1 &&
(GetContentFlags() & Layer::CONTENT_OPAQUE))
{
mSupportsComponentAlphaChildren = true;
} else {
gfx::Matrix transform;
if (HasOpaqueAncestorLayer(this) &&
GetEffectiveTransform().Is2D(&transform) &&
!gfx::ThebesMatrix(transform).HasNonIntegerTranslation() &&
blendMode == gfx::CompositionOp::OP_OVER) {
mSupportsComponentAlphaChildren = true;
needsSurfaceCopy = true;
}
}
} else if (blendMode == gfx::CompositionOp::OP_OVER) {
mSupportsComponentAlphaChildren =
(GetContentFlags() & Layer::CONTENT_OPAQUE) ||
(GetParent() && GetParent()->SupportsComponentAlphaChildren());
}
if (aNeedsSurfaceCopy) {
*aNeedsSurfaceCopy = mSupportsComponentAlphaChildren && needsSurfaceCopy;
}
}
void
ContainerLayer::ComputeEffectiveTransformsForChildren(const Matrix4x4& aTransformToSurface)
{
for (Layer* l = mFirstChild; l; l = l->GetNextSibling()) {
l->ComputeEffectiveTransforms(aTransformToSurface);
}
}
/* static */ bool
ContainerLayer::HasOpaqueAncestorLayer(Layer* aLayer)
{
for (Layer* l = aLayer->GetParent(); l; l = l->GetParent()) {
if (l->GetContentFlags() & Layer::CONTENT_OPAQUE)
return true;
}
return false;
}
void
ContainerLayer::DidRemoveChild(Layer* aLayer)
{
PaintedLayer* tl = aLayer->AsPaintedLayer();
if (tl && tl->UsedForReadback()) {
for (Layer* l = mFirstChild; l; l = l->GetNextSibling()) {
if (l->GetType() == TYPE_READBACK) {
static_cast<ReadbackLayer*>(l)->NotifyPaintedLayerRemoved(tl);
}
}
}
if (aLayer->GetType() == TYPE_READBACK) {
static_cast<ReadbackLayer*>(aLayer)->NotifyRemoved();
}
}
void
ContainerLayer::DidInsertChild(Layer* aLayer)
{
if (aLayer->GetType() == TYPE_READBACK) {
mMayHaveReadbackChild = true;
}
}
void
RefLayer::FillSpecificAttributes(SpecificLayerAttributes& aAttrs)
{
aAttrs = RefLayerAttributes(GetReferentId(), mEventRegionsOverride);
}
/**
* StartFrameTimeRecording, together with StopFrameTimeRecording
* enable recording of frame intervals.
*
* To allow concurrent consumers, a cyclic array is used which serves all
* consumers, practically stateless with regard to consumers.
*
* To save resources, the buffer is allocated on first call to StartFrameTimeRecording
* and recording is paused if no consumer which called StartFrameTimeRecording is able
* to get valid results (because the cyclic buffer was overwritten since that call).
*
* To determine availability of the data upon StopFrameTimeRecording:
* - mRecording.mNextIndex increases on each PostPresent, and never resets.
* - Cyclic buffer position is realized as mNextIndex % bufferSize.
* - StartFrameTimeRecording returns mNextIndex. When StopFrameTimeRecording is called,
* the required start index is passed as an arg, and we're able to calculate the required
* length. If this length is bigger than bufferSize, it means data was overwritten.
* otherwise, we can return the entire sequence.
* - To determine if we need to pause, mLatestStartIndex is updated to mNextIndex
* on each call to StartFrameTimeRecording. If this index gets overwritten,
* it means that all earlier start indices obtained via StartFrameTimeRecording
* were also overwritten, hence, no point in recording, so pause.
* - mCurrentRunStartIndex indicates the oldest index of the recording after which
* the recording was not paused. If StopFrameTimeRecording is invoked with a start index
* older than this, it means that some frames were not recorded, so data is invalid.
*/
uint32_t
LayerManager::StartFrameTimeRecording(int32_t aBufferSize)
{
if (mRecording.mIsPaused) {
mRecording.mIsPaused = false;
if (!mRecording.mIntervals.Length()) { // Initialize recording buffers
mRecording.mIntervals.SetLength(aBufferSize);
}
// After being paused, recent values got invalid. Update them to now.
mRecording.mLastFrameTime = TimeStamp::Now();
// Any recording which started before this is invalid, since we were paused.
mRecording.mCurrentRunStartIndex = mRecording.mNextIndex;
}
// If we'll overwrite this index, there are no more consumers with aStartIndex
// for which we're able to provide the full recording, so no point in keep recording.
mRecording.mLatestStartIndex = mRecording.mNextIndex;
return mRecording.mNextIndex;
}
void
LayerManager::RecordFrame()
{
if (!mRecording.mIsPaused) {
TimeStamp now = TimeStamp::Now();
uint32_t i = mRecording.mNextIndex % mRecording.mIntervals.Length();
mRecording.mIntervals[i] = static_cast<float>((now - mRecording.mLastFrameTime)
.ToMilliseconds());
mRecording.mNextIndex++;
mRecording.mLastFrameTime = now;
if (mRecording.mNextIndex > (mRecording.mLatestStartIndex + mRecording.mIntervals.Length())) {
// We've just overwritten the most recent recording start -> pause.
mRecording.mIsPaused = true;
}
}
}
void
LayerManager::PostPresent()
{
if (!mTabSwitchStart.IsNull()) {
Telemetry::Accumulate(Telemetry::FX_TAB_SWITCH_TOTAL_MS,
uint32_t((TimeStamp::Now() - mTabSwitchStart).ToMilliseconds()));
mTabSwitchStart = TimeStamp();
}
}
void
LayerManager::StopFrameTimeRecording(uint32_t aStartIndex,
nsTArray<float>& aFrameIntervals)
{
uint32_t bufferSize = mRecording.mIntervals.Length();
uint32_t length = mRecording.mNextIndex - aStartIndex;
if (mRecording.mIsPaused || length > bufferSize || aStartIndex < mRecording.mCurrentRunStartIndex) {
// aStartIndex is too old. Also if aStartIndex was issued before mRecordingNextIndex overflowed (uint32_t)
// and stopped after the overflow (would happen once every 828 days of constant 60fps).
length = 0;
}
if (!length) {
aFrameIntervals.Clear();
return; // empty recording, return empty arrays.
}
// Set length in advance to avoid possibly repeated reallocations
aFrameIntervals.SetLength(length);
uint32_t cyclicPos = aStartIndex % bufferSize;
for (uint32_t i = 0; i < length; i++, cyclicPos++) {
if (cyclicPos == bufferSize) {
cyclicPos = 0;
}
aFrameIntervals[i] = mRecording.mIntervals[cyclicPos];
}
}
void
LayerManager::BeginTabSwitch()
{
mTabSwitchStart = TimeStamp::Now();
}
static void PrintInfo(std::stringstream& aStream, LayerComposite* aLayerComposite);
#ifdef MOZ_DUMP_PAINTING
template <typename T>
void WriteSnapshotToDumpFile_internal(T* aObj, DataSourceSurface* aSurf)
{
nsCString string(aObj->Name());
string.Append('-');
string.AppendInt((uint64_t)aObj);
if (gfxUtils::sDumpPaintFile != stderr) {
fprintf_stderr(gfxUtils::sDumpPaintFile, "array[\"%s\"]=\"", string.BeginReading());
}
gfxUtils::DumpAsDataURI(aSurf, gfxUtils::sDumpPaintFile);
if (gfxUtils::sDumpPaintFile != stderr) {
fprintf_stderr(gfxUtils::sDumpPaintFile, "\";");
}
}
void WriteSnapshotToDumpFile(Layer* aLayer, DataSourceSurface* aSurf)
{
WriteSnapshotToDumpFile_internal(aLayer, aSurf);
}
void WriteSnapshotToDumpFile(LayerManager* aManager, DataSourceSurface* aSurf)
{
WriteSnapshotToDumpFile_internal(aManager, aSurf);
}
void WriteSnapshotToDumpFile(Compositor* aCompositor, DrawTarget* aTarget)
{
RefPtr<SourceSurface> surf = aTarget->Snapshot();
RefPtr<DataSourceSurface> dSurf = surf->GetDataSurface();
WriteSnapshotToDumpFile_internal(aCompositor, dSurf);
}
#endif
void
Layer::Dump(std::stringstream& aStream, const char* aPrefix, bool aDumpHtml)
{
#ifdef MOZ_DUMP_PAINTING
bool dumpCompositorTexture = gfxEnv::DumpCompositorTextures() && AsLayerComposite() &&
AsLayerComposite()->GetCompositableHost();
bool dumpClientTexture = gfxEnv::DumpPaint() && AsShadowableLayer() &&
AsShadowableLayer()->GetCompositableClient();
nsCString layerId(Name());
layerId.Append('-');
layerId.AppendInt((uint64_t)this);
#endif
if (aDumpHtml) {
aStream << nsPrintfCString("<li><a id=\"%p\" ", this).get();
#ifdef MOZ_DUMP_PAINTING
if (dumpCompositorTexture || dumpClientTexture) {
aStream << nsPrintfCString("href=\"javascript:ViewImage('%s')\"", layerId.BeginReading()).get();
}
#endif
aStream << ">";
}
DumpSelf(aStream, aPrefix);
#ifdef MOZ_DUMP_PAINTING
if (dumpCompositorTexture) {
AsLayerComposite()->GetCompositableHost()->Dump(aStream, aPrefix, aDumpHtml);
} else if (dumpClientTexture) {
if (aDumpHtml) {
aStream << nsPrintfCString("<script>array[\"%s\"]=\"", layerId.BeginReading()).get();
}
AsShadowableLayer()->GetCompositableClient()->Dump(aStream, aPrefix,
aDumpHtml, TextureDumpMode::DoNotCompress);
if (aDumpHtml) {
aStream << "\";</script>";
}
}
#endif
if (aDumpHtml) {
aStream << "</a>";
#ifdef MOZ_DUMP_PAINTING
if (dumpClientTexture) {
aStream << nsPrintfCString("<br><img id=\"%s\">\n", layerId.BeginReading()).get();
}
#endif
}
if (Layer* mask = GetMaskLayer()) {
aStream << nsPrintfCString("%s Mask layer:\n", aPrefix).get();
nsAutoCString pfx(aPrefix);
pfx += " ";
mask->Dump(aStream, pfx.get(), aDumpHtml);
}
for (size_t i = 0; i < GetAncestorMaskLayerCount(); i++) {
aStream << nsPrintfCString("%s Ancestor mask layer %d:\n", aPrefix, uint32_t(i)).get();
nsAutoCString pfx(aPrefix);
pfx += " ";
GetAncestorMaskLayerAt(i)->Dump(aStream, pfx.get(), aDumpHtml);
}
#ifdef MOZ_DUMP_PAINTING
for (size_t i = 0; i < mExtraDumpInfo.Length(); i++) {
const nsCString& str = mExtraDumpInfo[i];
aStream << aPrefix << " Info:\n" << str.get();
}
#endif
if (Layer* kid = GetFirstChild()) {
nsAutoCString pfx(aPrefix);
pfx += " ";
if (aDumpHtml) {
aStream << "<ul>";
}
kid->Dump(aStream, pfx.get(), aDumpHtml);
if (aDumpHtml) {
aStream << "</ul>";
}
}
if (aDumpHtml) {
aStream << "</li>";
}
if (Layer* next = GetNextSibling())
next->Dump(aStream, aPrefix, aDumpHtml);
}
void
Layer::DumpSelf(std::stringstream& aStream, const char* aPrefix)
{
PrintInfo(aStream, aPrefix);
aStream << "\n";
}
void
Layer::Dump(layerscope::LayersPacket* aPacket, const void* aParent)
{
DumpPacket(aPacket, aParent);
if (Layer* kid = GetFirstChild()) {
kid->Dump(aPacket, this);
}
if (Layer* next = GetNextSibling()) {
next->Dump(aPacket, aParent);
}
}
void
Layer::SetDisplayListLog(const char* log)
{
if (gfxUtils::DumpDisplayList()) {
mDisplayListLog = log;
}
}
void
Layer::GetDisplayListLog(nsCString& log)
{
log.SetLength(0);
if (gfxUtils::DumpDisplayList()) {
// This function returns a plain text string which consists of two things
// 1. DisplayList log.
// 2. Memory address of this layer.
// We know the target layer of each display item by information in #1.
// Here is an example of a Text display item line log in #1
// Text p=0xa9850c00 f=0x0xaa405b00(.....
// f keeps the address of the target client layer of a display item.
// For LayerScope, display-item-to-client-layer mapping is not enough since
// LayerScope, which lives in the chrome process, knows only composite layers.
// As so, we need display-item-to-client-layer-to-layer-composite
// mapping. That's the reason we insert #2 into the log
log.AppendPrintf("0x%p\n%s",(void*) this, mDisplayListLog.get());
}
}
void
Layer::Log(const char* aPrefix)
{
if (!IsLogEnabled())
return;
LogSelf(aPrefix);
if (Layer* kid = GetFirstChild()) {
nsAutoCString pfx(aPrefix);
pfx += " ";
kid->Log(pfx.get());
}
if (Layer* next = GetNextSibling())
next->Log(aPrefix);
}
void
Layer::LogSelf(const char* aPrefix)
{
if (!IsLogEnabled())
return;
std::stringstream ss;
PrintInfo(ss, aPrefix);
MOZ_LAYERS_LOG(("%s", ss.str().c_str()));
if (mMaskLayer) {
nsAutoCString pfx(aPrefix);
pfx += " \\ MaskLayer ";
mMaskLayer->LogSelf(pfx.get());
}
}
void
Layer::PrintInfo(std::stringstream& aStream, const char* aPrefix)
{
aStream << aPrefix;
aStream << nsPrintfCString("%s%s (0x%p)", mManager->Name(), Name(), this).get();
layers::PrintInfo(aStream, AsLayerComposite());
if (mClipRect) {
AppendToString(aStream, *mClipRect, " [clip=", "]");
}
if (1.0 != mPostXScale || 1.0 != mPostYScale) {
aStream << nsPrintfCString(" [postScale=%g, %g]", mPostXScale, mPostYScale).get();
}
if (!mTransform.IsIdentity()) {
AppendToString(aStream, mTransform, " [transform=", "]");
}
if (!GetEffectiveTransform().IsIdentity()) {
AppendToString(aStream, GetEffectiveTransform(), " [effective-transform=", "]");
}
if (mTransformIsPerspective) {
aStream << " [perspective]";
}
if (!mLayerBounds.IsEmpty()) {
AppendToString(aStream, mLayerBounds, " [bounds=", "]");
}
if (!mVisibleRegion.IsEmpty()) {
AppendToString(aStream, mVisibleRegion.ToUnknownRegion(), " [visible=", "]");
} else {
aStream << " [not visible]";
}
if (!mEventRegions.IsEmpty()) {
AppendToString(aStream, mEventRegions, " ", "");
}
if (1.0 != mOpacity) {
aStream << nsPrintfCString(" [opacity=%g]", mOpacity).get();
}
if (GetContentFlags() & CONTENT_OPAQUE) {
aStream << " [opaqueContent]";
}
if (GetContentFlags() & CONTENT_COMPONENT_ALPHA) {
aStream << " [componentAlpha]";
}
if (GetContentFlags() & CONTENT_BACKFACE_HIDDEN) {
aStream << " [backfaceHidden]";
}
if (GetScrollbarDirection() == VERTICAL) {
aStream << nsPrintfCString(" [vscrollbar=%lld]", GetScrollbarTargetContainerId()).get();
}
if (GetScrollbarDirection() == HORIZONTAL) {
aStream << nsPrintfCString(" [hscrollbar=%lld]", GetScrollbarTargetContainerId()).get();
}
if (GetIsFixedPosition()) {
LayerPoint anchor = GetFixedPositionAnchor();
aStream << nsPrintfCString(" [isFixedPosition scrollId=%lld sides=0x%x anchor=%s%s]",
GetFixedPositionScrollContainerId(),
GetFixedPositionSides(),
ToString(anchor).c_str(),
IsClipFixed() ? "" : " scrollingClip").get();
}
if (GetIsStickyPosition()) {
aStream << nsPrintfCString(" [isStickyPosition scrollId=%d outer=%f,%f %fx%f "
"inner=%f,%f %fx%f]", mStickyPositionData->mScrollId,
mStickyPositionData->mOuter.x, mStickyPositionData->mOuter.y,
mStickyPositionData->mOuter.width, mStickyPositionData->mOuter.height,
mStickyPositionData->mInner.x, mStickyPositionData->mInner.y,
mStickyPositionData->mInner.width, mStickyPositionData->mInner.height).get();
}
if (mMaskLayer) {
aStream << nsPrintfCString(" [mMaskLayer=%p]", mMaskLayer.get()).get();
}
for (uint32_t i = 0; i < mFrameMetrics.Length(); i++) {
if (!mFrameMetrics[i].IsDefault()) {
aStream << nsPrintfCString(" [metrics%d=", i).get();
AppendToString(aStream, mFrameMetrics[i], "", "]");
}
}
}
// The static helper function sets the transform matrix into the packet
static void
DumpTransform(layerscope::LayersPacket::Layer::Matrix* aLayerMatrix, const Matrix4x4& aMatrix)
{
aLayerMatrix->set_is2d(aMatrix.Is2D());
if (aMatrix.Is2D()) {
Matrix m = aMatrix.As2D();
aLayerMatrix->set_isid(m.IsIdentity());
if (!m.IsIdentity()) {
aLayerMatrix->add_m(m._11), aLayerMatrix->add_m(m._12);
aLayerMatrix->add_m(m._21), aLayerMatrix->add_m(m._22);
aLayerMatrix->add_m(m._31), aLayerMatrix->add_m(m._32);
}
} else {
aLayerMatrix->add_m(aMatrix._11), aLayerMatrix->add_m(aMatrix._12);
aLayerMatrix->add_m(aMatrix._13), aLayerMatrix->add_m(aMatrix._14);
aLayerMatrix->add_m(aMatrix._21), aLayerMatrix->add_m(aMatrix._22);
aLayerMatrix->add_m(aMatrix._23), aLayerMatrix->add_m(aMatrix._24);
aLayerMatrix->add_m(aMatrix._31), aLayerMatrix->add_m(aMatrix._32);
aLayerMatrix->add_m(aMatrix._33), aLayerMatrix->add_m(aMatrix._34);
aLayerMatrix->add_m(aMatrix._41), aLayerMatrix->add_m(aMatrix._42);
aLayerMatrix->add_m(aMatrix._43), aLayerMatrix->add_m(aMatrix._44);
}
}
// The static helper function sets the IntRect into the packet
template <typename T, typename Sub, typename Point, typename SizeT, typename MarginT>
static void
DumpRect(layerscope::LayersPacket::Layer::Rect* aLayerRect,
const BaseRect<T, Sub, Point, SizeT, MarginT>& aRect)
{
aLayerRect->set_x(aRect.x);
aLayerRect->set_y(aRect.y);
aLayerRect->set_w(aRect.width);
aLayerRect->set_h(aRect.height);
}
// The static helper function sets the nsIntRegion into the packet
static void
DumpRegion(layerscope::LayersPacket::Layer::Region* aLayerRegion, const nsIntRegion& aRegion)
{
nsIntRegionRectIterator it(aRegion);
while (const IntRect* sr = it.Next()) {
DumpRect(aLayerRegion->add_r(), *sr);
}
}
void
Layer::DumpPacket(layerscope::LayersPacket* aPacket, const void* aParent)
{
// Add a new layer (UnknownLayer)
using namespace layerscope;
LayersPacket::Layer* layer = aPacket->add_layer();
// Basic information
layer->set_type(LayersPacket::Layer::UnknownLayer);
layer->set_ptr(reinterpret_cast<uint64_t>(this));
layer->set_parentptr(reinterpret_cast<uint64_t>(aParent));
// Shadow
if (LayerComposite* lc = AsLayerComposite()) {
LayersPacket::Layer::Shadow* s = layer->mutable_shadow();
if (const Maybe<ParentLayerIntRect>& clipRect = lc->GetShadowClipRect()) {
DumpRect(s->mutable_clip(), *clipRect);
}
if (!lc->GetShadowTransform().IsIdentity()) {
DumpTransform(s->mutable_transform(), lc->GetShadowTransform());
}
if (!lc->GetShadowVisibleRegion().IsEmpty()) {
DumpRegion(s->mutable_vregion(), lc->GetShadowVisibleRegion().ToUnknownRegion());
}
}
// Clip
if (mClipRect) {
DumpRect(layer->mutable_clip(), *mClipRect);
}
// Transform
if (!mTransform.IsIdentity()) {
DumpTransform(layer->mutable_transform(), mTransform);
}
// Visible region
if (!mVisibleRegion.ToUnknownRegion().IsEmpty()) {
DumpRegion(layer->mutable_vregion(), mVisibleRegion.ToUnknownRegion());
}
// EventRegions
if (!mEventRegions.IsEmpty()) {
const EventRegions &e = mEventRegions;
if (!e.mHitRegion.IsEmpty()) {
DumpRegion(layer->mutable_hitregion(), e.mHitRegion);
}
if (!e.mDispatchToContentHitRegion.IsEmpty()) {
DumpRegion(layer->mutable_dispatchregion(), e.mDispatchToContentHitRegion);
}
if (!e.mNoActionRegion.IsEmpty()) {
DumpRegion(layer->mutable_noactionregion(), e.mNoActionRegion);
}
if (!e.mHorizontalPanRegion.IsEmpty()) {
DumpRegion(layer->mutable_hpanregion(), e.mHorizontalPanRegion);
}
if (!e.mVerticalPanRegion.IsEmpty()) {
DumpRegion(layer->mutable_vpanregion(), e.mVerticalPanRegion);
}
}
// Opacity
layer->set_opacity(mOpacity);
// Content opaque
layer->set_copaque(static_cast<bool>(GetContentFlags() & CONTENT_OPAQUE));
// Component alpha
layer->set_calpha(static_cast<bool>(GetContentFlags() & CONTENT_COMPONENT_ALPHA));
// Vertical or horizontal bar
if (GetScrollbarDirection() != NONE) {
layer->set_direct(GetScrollbarDirection() == VERTICAL ?
LayersPacket::Layer::VERTICAL :
LayersPacket::Layer::HORIZONTAL);
layer->set_barid(GetScrollbarTargetContainerId());
}
// Mask layer
if (mMaskLayer) {
layer->set_mask(reinterpret_cast<uint64_t>(mMaskLayer.get()));
}
// DisplayList log.
if (mDisplayListLog.Length() > 0) {
layer->set_displaylistloglength(mDisplayListLog.Length());
auto compressedData =
MakeUnique<char[]>(LZ4::maxCompressedSize(mDisplayListLog.Length()));
int compressedSize = LZ4::compress((char*)mDisplayListLog.get(),
mDisplayListLog.Length(),
compressedData.get());
layer->set_displaylistlog(compressedData.get(), compressedSize);
}
}
bool
Layer::IsBackfaceHidden()
{
if (GetContentFlags() & CONTENT_BACKFACE_HIDDEN) {
Layer* container = AsContainerLayer() ? this : GetParent();
if (container) {
// The effective transform can include non-preserve-3d parent
// transforms, since we don't always require an intermediate.
if (container->Extend3DContext() || container->Is3DContextLeaf()) {
return container->GetEffectiveTransform().IsBackfaceVisible();
}
return container->GetBaseTransform().IsBackfaceVisible();
}
}
return false;
}
nsAutoPtr<LayerUserData>
Layer::RemoveUserData(void* aKey)
{
nsAutoPtr<LayerUserData> d(static_cast<LayerUserData*>(mUserData.Remove(static_cast<gfx::UserDataKey*>(aKey))));
return d;
}
void
PaintedLayer::PrintInfo(std::stringstream& aStream, const char* aPrefix)
{
Layer::PrintInfo(aStream, aPrefix);
if (!mValidRegion.IsEmpty()) {
AppendToString(aStream, mValidRegion, " [valid=", "]");
}
}
void
PaintedLayer::DumpPacket(layerscope::LayersPacket* aPacket, const void* aParent)
{
Layer::DumpPacket(aPacket, aParent);
// get this layer data
using namespace layerscope;
LayersPacket::Layer* layer = aPacket->mutable_layer(aPacket->layer_size()-1);
layer->set_type(LayersPacket::Layer::PaintedLayer);
if (!mValidRegion.IsEmpty()) {
DumpRegion(layer->mutable_valid(), mValidRegion);
}
}
void
ContainerLayer::PrintInfo(std::stringstream& aStream, const char* aPrefix)
{
Layer::PrintInfo(aStream, aPrefix);
if (UseIntermediateSurface()) {
aStream << " [usesTmpSurf]";
}
if (1.0 != mPreXScale || 1.0 != mPreYScale) {
aStream << nsPrintfCString(" [preScale=%g, %g]", mPreXScale, mPreYScale).get();
}
if (mScaleToResolution) {
aStream << nsPrintfCString(" [presShellResolution=%g]", mPresShellResolution).get();
}
if (mEventRegionsOverride & EventRegionsOverride::ForceDispatchToContent) {
aStream << " [force-dtc]";
}
if (mEventRegionsOverride & EventRegionsOverride::ForceEmptyHitRegion) {
aStream << " [force-ehr]";
}
if (mVRDeviceID) {
aStream << nsPrintfCString(" [hmd=%lu]", mVRDeviceID).get();
}
}
void
ContainerLayer::DumpPacket(layerscope::LayersPacket* aPacket, const void* aParent)
{
Layer::DumpPacket(aPacket, aParent);
// Get this layer data
using namespace layerscope;
LayersPacket::Layer* layer = aPacket->mutable_layer(aPacket->layer_size()-1);
layer->set_type(LayersPacket::Layer::ContainerLayer);
}
void
ColorLayer::PrintInfo(std::stringstream& aStream, const char* aPrefix)
{
Layer::PrintInfo(aStream, aPrefix);
AppendToString(aStream, mColor, " [color=", "]");
AppendToString(aStream, mBounds, " [bounds=", "]");
}
void
ColorLayer::DumpPacket(layerscope::LayersPacket* aPacket, const void* aParent)
{
Layer::DumpPacket(aPacket, aParent);
// Get this layer data
using namespace layerscope;
LayersPacket::Layer* layer = aPacket->mutable_layer(aPacket->layer_size()-1);
layer->set_type(LayersPacket::Layer::ColorLayer);
layer->set_color(mColor.ToABGR());
}
CanvasLayer::CanvasLayer(LayerManager* aManager, void* aImplData)
: Layer(aManager, aImplData)
, mPreTransCallback(nullptr)
, mPreTransCallbackData(nullptr)
, mPostTransCallback(nullptr)
, mPostTransCallbackData(nullptr)
, mFilter(gfx::Filter::GOOD)
, mDirty(false)
{}
CanvasLayer::~CanvasLayer()
{}
void
CanvasLayer::PrintInfo(std::stringstream& aStream, const char* aPrefix)
{
Layer::PrintInfo(aStream, aPrefix);
if (mFilter != Filter::GOOD) {
AppendToString(aStream, mFilter, " [filter=", "]");
}
}
// This help function is used to assign the correct enum value
// to the packet
static void
DumpFilter(layerscope::LayersPacket::Layer* aLayer, const Filter& aFilter)
{
using namespace layerscope;
switch (aFilter) {
case Filter::GOOD:
aLayer->set_filter(LayersPacket::Layer::FILTER_GOOD);
break;
case Filter::LINEAR:
aLayer->set_filter(LayersPacket::Layer::FILTER_LINEAR);
break;
case Filter::POINT:
aLayer->set_filter(LayersPacket::Layer::FILTER_POINT);
break;
default:
// ignore it
break;
}
}
void
CanvasLayer::DumpPacket(layerscope::LayersPacket* aPacket, const void* aParent)
{
Layer::DumpPacket(aPacket, aParent);
// Get this layer data
using namespace layerscope;
LayersPacket::Layer* layer = aPacket->mutable_layer(aPacket->layer_size()-1);
layer->set_type(LayersPacket::Layer::CanvasLayer);
DumpFilter(layer, mFilter);
}
void
ImageLayer::PrintInfo(std::stringstream& aStream, const char* aPrefix)
{
Layer::PrintInfo(aStream, aPrefix);
if (mFilter != Filter::GOOD) {
AppendToString(aStream, mFilter, " [filter=", "]");
}
}
void
ImageLayer::DumpPacket(layerscope::LayersPacket* aPacket, const void* aParent)
{
Layer::DumpPacket(aPacket, aParent);
// Get this layer data
using namespace layerscope;
LayersPacket::Layer* layer = aPacket->mutable_layer(aPacket->layer_size()-1);
layer->set_type(LayersPacket::Layer::ImageLayer);
DumpFilter(layer, mFilter);
}
void
RefLayer::PrintInfo(std::stringstream& aStream, const char* aPrefix)
{
ContainerLayer::PrintInfo(aStream, aPrefix);
if (0 != mId) {
AppendToString(aStream, mId, " [id=", "]");
}
}
void
RefLayer::DumpPacket(layerscope::LayersPacket* aPacket, const void* aParent)
{
Layer::DumpPacket(aPacket, aParent);
// Get this layer data
using namespace layerscope;
LayersPacket::Layer* layer = aPacket->mutable_layer(aPacket->layer_size()-1);
layer->set_type(LayersPacket::Layer::RefLayer);
layer->set_refid(mId);
}
void
ReadbackLayer::PrintInfo(std::stringstream& aStream, const char* aPrefix)
{
Layer::PrintInfo(aStream, aPrefix);
AppendToString(aStream, mSize, " [size=", "]");
if (mBackgroundLayer) {
AppendToString(aStream, mBackgroundLayer, " [backgroundLayer=", "]");
AppendToString(aStream, mBackgroundLayerOffset, " [backgroundOffset=", "]");
} else if (mBackgroundColor.a == 1.f) {
AppendToString(aStream, mBackgroundColor, " [backgroundColor=", "]");
} else {
aStream << " [nobackground]";
}
}
void
ReadbackLayer::DumpPacket(layerscope::LayersPacket* aPacket, const void* aParent)
{
Layer::DumpPacket(aPacket, aParent);
// Get this layer data
using namespace layerscope;
LayersPacket::Layer* layer = aPacket->mutable_layer(aPacket->layer_size()-1);
layer->set_type(LayersPacket::Layer::ReadbackLayer);
LayersPacket::Layer::Size* size = layer->mutable_size();
size->set_w(mSize.width);
size->set_h(mSize.height);
}
//--------------------------------------------------
// LayerManager
void
LayerManager::Dump(std::stringstream& aStream, const char* aPrefix, bool aDumpHtml)
{
#ifdef MOZ_DUMP_PAINTING
if (aDumpHtml) {
aStream << "<ul><li>";
}
#endif
DumpSelf(aStream, aPrefix);
nsAutoCString pfx(aPrefix);
pfx += " ";
if (!GetRoot()) {
aStream << nsPrintfCString("%s(null)", pfx.get()).get();
if (aDumpHtml) {
aStream << "</li></ul>";
}
return;
}
if (aDumpHtml) {
aStream << "<ul>";
}
GetRoot()->Dump(aStream, pfx.get(), aDumpHtml);
if (aDumpHtml) {
aStream << "</ul></li></ul>";
}
aStream << "\n";
}
void
LayerManager::DumpSelf(std::stringstream& aStream, const char* aPrefix)
{
PrintInfo(aStream, aPrefix);
aStream << "\n";
}
void
LayerManager::Dump()
{
std::stringstream ss;
Dump(ss);
print_stderr(ss);
}
void
LayerManager::Dump(layerscope::LayersPacket* aPacket)
{
DumpPacket(aPacket);
if (GetRoot()) {
GetRoot()->Dump(aPacket, this);
}
}
void
LayerManager::Log(const char* aPrefix)
{
if (!IsLogEnabled())
return;
LogSelf(aPrefix);
nsAutoCString pfx(aPrefix);
pfx += " ";
if (!GetRoot()) {
MOZ_LAYERS_LOG(("%s(null)", pfx.get()));
return;
}
GetRoot()->Log(pfx.get());
}
void
LayerManager::LogSelf(const char* aPrefix)
{
nsAutoCString str;
std::stringstream ss;
PrintInfo(ss, aPrefix);
MOZ_LAYERS_LOG(("%s", ss.str().c_str()));
}
void
LayerManager::PrintInfo(std::stringstream& aStream, const char* aPrefix)
{
aStream << aPrefix << nsPrintfCString("%sLayerManager (0x%p)", Name(), this).get();
}
void
LayerManager::DumpPacket(layerscope::LayersPacket* aPacket)
{
using namespace layerscope;
// Add a new layer data (LayerManager)
LayersPacket::Layer* layer = aPacket->add_layer();
layer->set_type(LayersPacket::Layer::LayerManager);
layer->set_ptr(reinterpret_cast<uint64_t>(this));
// Layer Tree Root
layer->set_parentptr(0);
}
/*static*/ bool
LayerManager::IsLogEnabled()
{
return MOZ_LOG_TEST(GetLog(), LogLevel::Debug);
}
void
PrintInfo(std::stringstream& aStream, LayerComposite* aLayerComposite)
{
if (!aLayerComposite) {
return;
}
if (const Maybe<ParentLayerIntRect>& clipRect = aLayerComposite->GetShadowClipRect()) {
AppendToString(aStream, *clipRect, " [shadow-clip=", "]");
}
if (!aLayerComposite->GetShadowTransform().IsIdentity()) {
AppendToString(aStream, aLayerComposite->GetShadowTransform(), " [shadow-transform=", "]");
}
if (!aLayerComposite->GetShadowVisibleRegion().IsEmpty()) {
AppendToString(aStream, aLayerComposite->GetShadowVisibleRegion().ToUnknownRegion(), " [shadow-visible=", "]");
}
}
void
SetAntialiasingFlags(Layer* aLayer, DrawTarget* aTarget)
{
bool permitSubpixelAA = !(aLayer->GetContentFlags() & Layer::CONTENT_DISABLE_SUBPIXEL_AA);
if (aTarget->IsCurrentGroupOpaque()) {
aTarget->SetPermitSubpixelAA(permitSubpixelAA);
return;
}
const IntRect& bounds = aLayer->GetVisibleRegion().ToUnknownRegion().GetBounds();
gfx::Rect transformedBounds = aTarget->GetTransform().TransformBounds(gfx::Rect(Float(bounds.x), Float(bounds.y),
Float(bounds.width), Float(bounds.height)));
transformedBounds.RoundOut();
IntRect intTransformedBounds;
transformedBounds.ToIntRect(&intTransformedBounds);
permitSubpixelAA &= !(aLayer->GetContentFlags() & Layer::CONTENT_COMPONENT_ALPHA) ||
aTarget->GetOpaqueRect().Contains(intTransformedBounds);
aTarget->SetPermitSubpixelAA(permitSubpixelAA);
}
IntRect
ToOutsideIntRect(const gfxRect &aRect)
{
gfxRect r = aRect;
r.RoundOut();
return IntRect(r.X(), r.Y(), r.Width(), r.Height());
}
} // namespace layers
} // namespace mozilla
| 31.209547
| 139
| 0.675515
|
naver
|
a4e65fccd156afa3f1979ebcfb7e5032c5337d12
| 1,755
|
cc
|
C++
|
cmd/cmd_wall.cc
|
jdb19937/makemore
|
61297dd322b3a9bb6cdfdd15e8886383cb490534
|
[
"MIT"
] | null | null | null |
cmd/cmd_wall.cc
|
jdb19937/makemore
|
61297dd322b3a9bb6cdfdd15e8886383cb490534
|
[
"MIT"
] | null | null | null |
cmd/cmd_wall.cc
|
jdb19937/makemore
|
61297dd322b3a9bb6cdfdd15e8886383cb490534
|
[
"MIT"
] | null | null | null |
#include <system.hh>
#include <process.hh>
#include <server.hh>
#include <agent.hh>
#include <wall.hh>
namespace makemore {
using namespace makemore;
using namespace std;
extern "C" void mainmore(Process *);
void mainmore(
Process *process
) {
Session *session = process->session;
Server *server = process->system->server;
Urb *urb = server->urb;
if (process->args.size() != 1) {
strvec outvec;
outvec.resize(1);
outvec[0] = "nope1";
process->write(outvec);
return;
}
if (!session->who) {
strvec outvec;
outvec.resize(1);
outvec[0] = "nope2";
process->write(outvec);
return;
}
Urbite &ufrom = *session->who;
Parson *from = ufrom.parson();
if (!from) {
strvec outvec;
outvec.resize(1);
outvec[0] = "nope3";
process->write(outvec);
return;
}
std::string fromnom = from->nom;
from->acted = time(NULL);
string txt = process->args[0];
txt += "\n";
if (txt.length() > 16384) {
strvec outvec;
outvec.resize(1);
outvec[0] = "nope4";
process->write(outvec);
return;
}
ufrom.make_home_dir();
string wallfn = urb->dir + "/home/" + ufrom.nom + "/wall.txt";
FILE *fp = fopen(wallfn.c_str(), "a");
if (!fp) {
strvec outvec;
outvec.resize(1);
outvec[0] = "nope7";
process->write(outvec);
return;
}
size_t ret = fwrite(txt.data(), 1, txt.length(), fp);
if (ret != txt.length()) {
strvec outvec;
outvec.resize(1);
outvec[0] = "nope8";
process->write(outvec);
return;
}
fclose(fp);
Wall wall;
wall.load(wallfn);
if (wall.posts.size() > 8) {
wall.truncate(8);
wall.save(wallfn);
}
strvec outvec;
outvec.resize(1);
outvec[0] = "ok";
process->write(outvec);
}
}
| 18.092784
| 64
| 0.589744
|
jdb19937
|
a4eecc261bca4120181f3044c4e7d60bf9a737cd
| 5,104
|
cpp
|
C++
|
src/main.cpp
|
tue-robotics/human_intention_prediction
|
e04f530f87cd06033d11f58f844cb7000a2a5bf5
|
[
"BSD-2-Clause"
] | null | null | null |
src/main.cpp
|
tue-robotics/human_intention_prediction
|
e04f530f87cd06033d11f58f844cb7000a2a5bf5
|
[
"BSD-2-Clause"
] | null | null | null |
src/main.cpp
|
tue-robotics/human_intention_prediction
|
e04f530f87cd06033d11f58f844cb7000a2a5bf5
|
[
"BSD-2-Clause"
] | null | null | null |
#include <ros/ros.h>
#include <ros/callback_queue.h>
#include "geometry_msgs/TransformStamped.h"
#include "geometry_msgs/Pose.h"
#include <visualization_msgs/MarkerArray.h>
#include "tf/transform_listener.h"
#include <tf2/LinearMath/Quaternion.h>
#include <hip_msgs/walls.h>
#include <hip_msgs/wall.h>
#include <hip_msgs/Pose.h>
#include <hip_msgs/hypothesis.h>
#include <hip_msgs/hypotheses.h>
#include <ed_gui_server/objsPosVel.h>
#include <functions.h>
#include <rosnode.h>
#include <functionsDiscretizedMap.h>
using namespace std;
/// [main]
int main(int argc, char** argv)
{
ros::init(argc, argv, "HIP");
rosNode rosNode;
vectorFieldMap map;
visualization_msgs::MarkerArray staticMarkers;
visualization_msgs::MarkerArray dynamicMarkers;
rosNode.initialize();
map.initializeMap();
map.readMap(staticMarkers,dynamicMarkers);
rosNode.setStaticMap(staticMarkers);
/// [loop start]
int i=0;
double likelihood;
double v_x = 1.0;
double v_y = 0.3;
// matrix A,H,P,Q,R,I; // Kalman filter matrices
// initializeKalman(A,H,P,Q,R,I,1/rate);
// double tPrev = ros::Time::now().toSec();
// double dt;
double rate = 15.0;
ros::Rate r(rate); // loop at 15 hz
double u,v,dist1,dist2,totP;
ros::spinOnce();
while(ros::ok())
{
i++;
rosNode.publishTube(map.globalTube,map.globalTubesH);
// Get yaw robot
tf2::Quaternion q ( rosNode.robotPose.pose.pose.orientation.x, rosNode.robotPose.pose.pose.orientation.y,
rosNode.robotPose.pose.pose.orientation.z, rosNode.robotPose.pose.pose.orientation.w );
tf2::Matrix3x3 matrix ( q );
double rollRobot, pitchRobot, yawRobot;
matrix.getRPY ( rollRobot, pitchRobot, yawRobot );
bool poseValid = rosNode.robotPose.pose.pose.position.x == rosNode.robotPose.pose.pose.position.x;
poseValid = (poseValid && rosNode.robotPose.pose.pose.position.y == rosNode.robotPose.pose.pose.position.y);
poseValid = (poseValid && yawRobot == yawRobot);
if(poseValid)
{
for(unsigned int iHumans = 0; iHumans < rosNode.humanFilters.size(); iHumans++)
{
hip_msgs::PoseVel humanPosVel = rosNode.humanFilters[iHumans].predictPos(rosNode.humanFilters[iHumans].getLatestUpdateTime() );
// std::cout << "\n\n\n main, iHumans = " << iHumans << "/" << rosNode.humanFilters.size() << " humanPosVel.x = " << humanPosVel.x << " humanPosVel.y = " << humanPosVel.y << std::endl;
ros::Duration dtProcessing = map.updateHypotheses(//humanPosVel.x, humanPosVel.y, humanPosVel.vx, humanPosVel.vy,
rosNode.humanFilters, iHumans,
rosNode.robotPose.pose.pose.position.x, rosNode.robotPose.pose.pose.position.y, yawRobot, rosNode.semanticMapFrame,
rosNode.semanticMapFrame, MARKER_LIFETIME);
std::string ns = "Hypotheses_Human" + std::to_string(iHumans);
rosNode.publishHypotheses(map.hypotheses, ns, rosNode.humanFilters[iHumans]);
map.readMap(staticMarkers,dynamicMarkers);
if( iHumans == 0)
{
rosNode.publishProcessingTime(dtProcessing);
}
for(unsigned int iMarker = 0; iMarker < dynamicMarkers.markers.size(); iMarker++)
{
visualization_msgs::Marker marker = dynamicMarkers.markers[iMarker];
// TODO check object ID if string is empty
//
marker.ns = marker.ns + "object" + std::to_string(iHumans);
dynamicMarkers.markers[iMarker] = marker;
}
// if (i%3==0)
// {
// rosNode.removeDynamicMap();
// }
rosNode.setDynamicMap(dynamicMarkers);
rosNode.publishMap();
}
// }
rosNode.visualizeHumans();
rosNode.visualizeMeasuredHumans();
rosNode.visualizeRobot();
// std::cout << "updateHypotheses, visualizations finished" << std::endl;
// WH: why wait?!
ros::getGlobalCallbackQueue()->callAvailable(ros::WallDuration(1000.0)); // Call ROS stream and wait 1000 sec if no new measurement
// ros::getGlobalCallbackQueue()->callAvailable(ros::WallDuration(1.0)); // Call ROS stream and wait 1 sec if no new measurement
// double dt = ros::Time::now().toSec() - tPrev; //TODO use measurement time!
// updateKalman(A,H,P,Q,R,I,rosNode.humanPosVel,rosNode.measurement,dt); // TODO -> for all humans
// cout<<"dt = "<<dt<<endl;
// tPrev = ros::Time::now().toSec();
rosNode.publishHumanPV();
} else {
ros::spinOnce();
}
r.sleep();
}
return 0; /// [loop end]
}
| 36.457143
| 199
| 0.586403
|
tue-robotics
|
a4f19349fe7dc82703e99a7e577de29c5ccc593e
| 352
|
hpp
|
C++
|
src/stan/math/rev/mat/fun/stan_print.hpp
|
alashworth/stan-monorepo
|
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
|
[
"BSD-3-Clause"
] | 1
|
2019-09-06T15:53:17.000Z
|
2019-09-06T15:53:17.000Z
|
src/stan/math/rev/mat/fun/stan_print.hpp
|
alashworth/stan-monorepo
|
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
|
[
"BSD-3-Clause"
] | 8
|
2019-01-17T18:51:16.000Z
|
2019-01-17T18:51:39.000Z
|
src/stan/math/rev/mat/fun/stan_print.hpp
|
alashworth/stan-monorepo
|
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
|
[
"BSD-3-Clause"
] | null | null | null |
#ifndef STAN_MATH_REV_MAT_FUN_STAN_PRINT_HPP
#define STAN_MATH_REV_MAT_FUN_STAN_PRINT_HPP
#include <stan/math/rev/meta.hpp>
#include <stan/math/rev/core.hpp>
#include <ostream>
namespace stan {
namespace math {
inline void stan_print(std::ostream* o, const var& x) { *o << x.val(); }
} // namespace math
} // namespace stan
#endif
| 22
| 73
| 0.710227
|
alashworth
|
a4f2c13fecd26e86d0e6b784ff7717469f188faa
| 195
|
cpp
|
C++
|
src/common/platform/string_windows.cpp
|
mpbarnwell/lightstep-tracer-cpp
|
4f8f110e7b69d1b8d24c9ea130cd560295e479b6
|
[
"MIT"
] | 47
|
2016-05-23T10:39:50.000Z
|
2022-03-08T08:46:25.000Z
|
src/common/platform/string_windows.cpp
|
mpbarnwell/lightstep-tracer-cpp
|
4f8f110e7b69d1b8d24c9ea130cd560295e479b6
|
[
"MIT"
] | 63
|
2016-07-26T00:02:09.000Z
|
2022-03-11T07:20:44.000Z
|
src/common/platform/string_windows.cpp
|
mpbarnwell/lightstep-tracer-cpp
|
4f8f110e7b69d1b8d24c9ea130cd560295e479b6
|
[
"MIT"
] | 19
|
2016-09-21T17:59:03.000Z
|
2021-09-16T06:42:40.000Z
|
#include "common/platform/string.h"
#include <string.h>
namespace lightstep {
int StrCaseCmp(const char* s1, const char* s2) noexcept {
return ::_stricmp(s1, s2);
}
} // namespace lightstep
| 19.5
| 57
| 0.712821
|
mpbarnwell
|
a4f492123ab4389cb45af95571e0c276e03b262d
| 3,579
|
hh
|
C++
|
core/test/UtGunnsBasicNode.hh
|
nasa/gunns
|
248323939a476abe5178538cd7a3512b5f42675c
|
[
"NASA-1.3"
] | 18
|
2020-01-23T12:14:09.000Z
|
2022-02-27T22:11:35.000Z
|
core/test/UtGunnsBasicNode.hh
|
nasa/gunns
|
248323939a476abe5178538cd7a3512b5f42675c
|
[
"NASA-1.3"
] | 39
|
2020-11-20T12:19:35.000Z
|
2022-02-22T18:45:55.000Z
|
core/test/UtGunnsBasicNode.hh
|
nasa/gunns
|
248323939a476abe5178538cd7a3512b5f42675c
|
[
"NASA-1.3"
] | 7
|
2020-02-10T19:25:43.000Z
|
2022-03-16T01:10:00.000Z
|
#ifndef UtGunnsBasicNode_EXISTS
#define UtGunnsBasicNode_EXISTS
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @defgroup UT_GUNNS_BASIC_NODE Gunns Basic Node Unit Test
/// @ingroup UT_GUNNS
///
/// @copyright Copyright 2019 United States Government as represented by the Administrator of the
/// National Aeronautics and Space Administration. All Rights Reserved.
///
/// @details Unit Tests for the Gunns Basic Node class
/// @{
////////////////////////////////////////////////////////////////////////////////////////////////////
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestFixture.h>
////////////////////////////////////////////////////////////////////////////////////////////////////
// Must list of all required C Code Model includes.
////////////////////////////////////////////////////////////////////////////////////////////////////
#include "core/GunnsBasicNode.hh"
#include "aspects/fluid/fluid/PolyFluid.hh"
class UtGunnsBasicNode;
class GunnsBasicNodeUnitTest : public GunnsBasicNode
{
public:
friend class UtGunnsBasicNode;
};
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details
/// Class containing model tests.
////////////////////////////////////////////////////////////////////////////////////////////////////
class UtGunnsBasicNode : public CppUnit::TestFixture
{
private:
/// @brief Copy constructor unavailable since declared private and not implemented.
UtGunnsBasicNode(const UtGunnsBasicNode& that);
/// @brief Assignment operator unavailable since declared private and not implemented.
UtGunnsBasicNode& operator =(const UtGunnsBasicNode& that);
////////////////////////////////////////////////////////////////////////////////////////////
/// Test Suite Name.
////////////////////////////////////////////////////////////////////////////////////////////
CPPUNIT_TEST_SUITE(UtGunnsBasicNode);
////////////////////////////////////////////////////////////////////////////////////////////
/// List all unit test methods here.
////////////////////////////////////////////////////////////////////////////////////////////
CPPUNIT_TEST(testDefaultConstruction);
CPPUNIT_TEST(testInitialize);
CPPUNIT_TEST(testValidate);
CPPUNIT_TEST(testAccessMethods);
CPPUNIT_TEST(testResetFlows);
CPPUNIT_TEST(testIntegrateFlows);
CPPUNIT_TEST(testPlaceholderMethods);
CPPUNIT_TEST(testRestart);
CPPUNIT_TEST_SUITE_END();
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
/// Define any data structures required in setUp.
////////////////////////////////////////////////////////////////////////////////////////////
GunnsBasicNodeUnitTest tNode;
GunnsNodeList tNodeList;
public:
UtGunnsBasicNode();
virtual ~UtGunnsBasicNode();
void tearDown();
void setUp();
void testDefaultConstruction();
void testInitialize();
void testValidate();
void testAccessMethods();
void testResetFlows();
void testIntegrateFlows();
void testPlaceholderMethods();
void testRestart();
};
///@}
#endif
| 39.766667
| 100
| 0.425258
|
nasa
|
a4ffbecd8a6b47e6681d075332d09fc43f2204b2
| 1,016
|
cpp
|
C++
|
001-050/027/c++/code.cpp
|
Shivam010/daily-coding-problem
|
679376a7b0f5f9bccdd261a1a660e951a1142174
|
[
"MIT"
] | 9
|
2020-09-13T12:48:35.000Z
|
2022-03-02T06:25:06.000Z
|
001-050/027/c++/code.cpp
|
Shivam010/daily-coding-problem
|
679376a7b0f5f9bccdd261a1a660e951a1142174
|
[
"MIT"
] | 9
|
2020-09-11T21:19:27.000Z
|
2020-09-14T20:18:02.000Z
|
001-050/027/c++/code.cpp
|
Shivam010/daily-coding-problem
|
679376a7b0f5f9bccdd261a1a660e951a1142174
|
[
"MIT"
] | 1
|
2020-09-11T22:03:29.000Z
|
2020-09-11T22:03:29.000Z
|
// Copyright (c) 2020 Shivam Rathore. All rights reserved.
// Use of this source code is governed by MIT License that
// can be found in the LICENSE file.
// This file contains Solution to Challenge #027, run using
// g++ 001-050/027/c++/code.cpp -o bin/out
// ./bin/out < 001-050/027/c++/in.txt > 001-050/027/c++/out.txt
#include <bits/stdc++.h>
using namespace std;
#define ll long long
void solve() {
string brk;
cin >> brk;
int n = brk.size(), top = 0;
string stk(n + 1, 0);
for (int i = 0; i < n; i++) {
if (stk[top] == brk[i])
top--;
else if (brk[i] == '(')
stk[++top] = ')';
else if (brk[i] == '[')
stk[++top] = ']';
else if (brk[i] == '{')
stk[++top] = '}';
else {
top = -1;
break;
}
}
if (top == 0)
cout << "true\n";
else
cout << "false\n";
return;
}
int main() {
int t;
cin >> t;
while (t--) {
solve();
}
}
| 22.577778
| 63
| 0.463583
|
Shivam010
|
35004e8b0f304cb3be7537d86b554dd6674a220e
| 6,436
|
cpp
|
C++
|
source/gcore/gtime.cpp
|
birderyu/CSystem
|
c7c9034b7eb660c0dcd17d51002f4d83080b88b4
|
[
"Apache-2.0"
] | 2
|
2016-07-30T04:55:39.000Z
|
2016-08-02T08:18:46.000Z
|
source/gcore/gtime.cpp
|
birderyu/gsystem
|
c7c9034b7eb660c0dcd17d51002f4d83080b88b4
|
[
"Apache-2.0"
] | null | null | null |
source/gcore/gtime.cpp
|
birderyu/gsystem
|
c7c9034b7eb660c0dcd17d51002f4d83080b88b4
|
[
"Apache-2.0"
] | null | null | null |
#include "gtime.h"
#include "gutility.h"
#include "gdatetime.h"
#include "gbytes.h"
#include "gstring.h"
#ifdef G_SYSTEM_WINDOWS
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif
#include <windows.h>
#include <time.h>
#else // !G_SYSTEM_WINDOWS
#endif // G_SYSTEM_WINDOWS
#define G_TIME_OFFSET_HOUR 0
#define G_TIME_OFFSET_MINUTE 1
#define G_TIME_OFFSET_SECOND 2
#define G_TIME_OFFSET_MILLISECOND 4
#define G_TIME_SIZE_HOUR 1
#define G_TIME_SIZE_MINUTE 1
#define G_TIME_SIZE_SECOND 1
#define G_TIME_SIZE_MILLISECOND 2
namespace gsystem { // gsystem
GTime GTime::Now()
{
GTime t;
#ifdef G_SYSTEM_WINDOWS
SYSTEMTIME st = { 0 };
GetLocalTime(&st);
t.SetHour(st.wHour);
t.SetMinute(st.wMinute);
t.SetSecond(st.wSecond);
t.SetMillisecond(st.wMilliseconds);
#else // !G_SYSTEM_WINDOWS
#endif // G_SYSTEM_WINDOWS
return t;
}
GTime GTime::Parse(const GString &time)
{
// TODO
return GTime();
}
GTime::GTime()
{
GMemSet(m_tTime, 0, G_TIME_SIZE);
}
GTime::GTime(gtime timestamp)
{
GMemSet(m_tTime, 0, G_TIME_SIZE);
SetTime(timestamp);
}
GTime::GTime(guint hour, guint minute, guint second, guint millisecond)
{
SetTime(hour, minute, second, millisecond);
}
GTime::GTime(const GTime &time)
{
SetTime(time);
}
GTime::GTime(GTime &&time)
{
SetTime(GForward<GTime>(time));
}
GTime::GTime(const gbyte *val)
{
GMemCopy(m_tTime, val, G_TIME_SIZE);
}
guint GTime::Hour() const
{
GIntegerForSize<G_TIME_SIZE_HOUR>::Unsigned val = 0;
GBytes::BytesToArithmetic(m_tTime + G_TIME_OFFSET_HOUR, &val);
return val;
}
guint GTime::Minute() const
{
GIntegerForSize<G_TIME_SIZE_MINUTE>::Unsigned val = 0;
GBytes::BytesToArithmetic(m_tTime + G_TIME_OFFSET_MINUTE, &val);
return val;
}
guint GTime::Second() const
{
GIntegerForSize<G_TIME_SIZE_SECOND>::Unsigned val = 0;
GBytes::BytesToArithmetic(m_tTime + G_TIME_OFFSET_SECOND, &val);
return val;
}
guint GTime::Millisecond() const
{
GIntegerForSize<G_TIME_SIZE_MILLISECOND>::Unsigned val = 0;
GBytes::BytesToArithmetic(m_tTime + G_TIME_OFFSET_MILLISECOND, &val);
return val;
}
gbool GTime::SetTime(gtime timestamp)
{
struct tm t = { 0 };
if (0 != localtime_s(&t, ×tamp))
{
return false;
}
SetHour(t.tm_hour);
SetMinute(t.tm_min);
SetSecond(t.tm_sec);
SetMillisecond(0);
return true;
}
gvoid GTime::SetTime(const GTime &time)
{
GMemCopy(m_tTime, time.m_tTime, G_TIME_SIZE);
}
gvoid GTime::SetTime(GTime &&time)
{
GMemCopy(m_tTime, time.m_tTime, G_TIME_SIZE);
}
gvoid GTime::SetTime(guint hour, guint minute, guint second, guint millisecond)
{
SetHour(hour);
SetMinute(minute);
SetSecond(second);
SetMillisecond(millisecond);
}
gvoid GTime::SetHour(guint h)
{
using Type = GIntegerForSize<G_TIME_SIZE_HOUR>::Unsigned;
Type val = h;
GBytes::ArithmeticToBytes<Type>(&val, m_tTime + G_TIME_OFFSET_HOUR);
}
gvoid GTime::SetMinute(guint mm)
{
using Type = GIntegerForSize<G_TIME_SIZE_MINUTE>::Unsigned;
Type val = mm;
GBytes::ArithmeticToBytes<Type>(&val, m_tTime + G_TIME_OFFSET_MINUTE);
}
gvoid GTime::SetSecond(guint s)
{
using Type = GIntegerForSize<G_TIME_SIZE_SECOND>::Unsigned;
Type val = s;
GBytes::ArithmeticToBytes<Type>(&val, m_tTime + G_TIME_OFFSET_SECOND);
}
gvoid GTime::SetMillisecond(guint ms)
{
using Type = GIntegerForSize<G_TIME_SIZE_MILLISECOND>::Unsigned;
Type val = ms;
GBytes::ArithmeticToBytes<Type>(&val, m_tTime + G_TIME_OFFSET_MILLISECOND);
}
gint GTime::HoursTo(const GTime &time) const
{
gint that_hour = time.Hour();
gint this_hour = Hour();
return that_hour - this_hour;
}
gint GTime::MinutesTo(const GTime &time) const
{
gint minutes_to = HoursTo(time) * 60;
minutes_to -= Minute();
minutes_to += time.Minute();
return minutes_to;
}
gint GTime::SecondsTo(const GTime &time) const
{
gint seconds_to = MinutesTo(time) * 60;
seconds_to -= Second();
seconds_to += time.Second();
return seconds_to;
}
gint GTime::MillisecondsTo(const GTime &time) const
{
gint milliseconds_to = SecondsTo(time) * 1000;
milliseconds_to -= Millisecond();
milliseconds_to += time.Millisecond();
return milliseconds_to;
}
GTime >ime::AddHours(gint h)
{
if (h == 0)
{
return *this;
}
gint new_hour = Hour() + h;
guint hours_in_a_day = 24;
while (new_hour / hours_in_a_day)
{
if (new_hour > 0)
{
new_hour = new_hour - hours_in_a_day;
}
else
{
new_hour = new_hour + hours_in_a_day;
}
}
SetHour(new_hour);
return *this;
}
GTime >ime::AddMinutes(gint mm)
{
if (mm == 0)
{
return *this;
}
gint new_minute = Minute() + mm;
gint add_hours = 0;
guint minutes_in_an_hour = 60;
while (new_minute / minutes_in_an_hour)
{
if (new_minute > 0)
{
new_minute = new_minute - minutes_in_an_hour;
++add_hours;
}
else
{
new_minute = new_minute + minutes_in_an_hour;
--add_hours;
}
}
AddHours(add_hours).SetMinute(new_minute);
return *this;
}
GTime >ime::AddSeconds(gint s)
{
if (s == 0)
{
return *this;
}
gint new_second = Second() + s;
gint add_minutes = 0;
guint seconds_in_a_minute = 60;
while (new_second / seconds_in_a_minute)
{
if (new_second > 0)
{
new_second = new_second - seconds_in_a_minute;
++add_minutes;
}
else
{
new_second = new_second + seconds_in_a_minute;
--add_minutes;
}
}
AddMinutes(add_minutes).SetSecond(new_second);
return *this;
}
GTime >ime::AddMilliseconds(gint ms)
{
if (ms == 0)
{
return *this;
}
gint new_millisecond = Millisecond() + ms;
gint add_seconds = 0;
guint milliseconds_in_a_second = 1000;
while (new_millisecond / milliseconds_in_a_second)
{
if (new_millisecond > 0)
{
new_millisecond = new_millisecond - milliseconds_in_a_second;
++add_seconds;
}
else
{
new_millisecond = new_millisecond + milliseconds_in_a_second;
--add_seconds;
}
}
AddSeconds(add_seconds).SetMillisecond(new_millisecond);
return *this;
}
/*
GString GTime::ToString() const
{
// 20:40 00:000
GString str;
str.Reserve(12);
str.Append(GString::Number(Hour()));
str.Append(":");
str.Append(GString::Number(Minute()));
str.Append(" ");
str.Append(GString::Number(Second()));
str.Append(":");
str.Append(GString::Number(Millisecond()));
return str;
}
*/
} // namespace gsystem
#undef G_TIME_SIZE_MILLISECOND
#undef G_TIME_SIZE_SECOND
#undef G_TIME_SIZE_MINUTE
#undef G_TIME_SIZE_HOUR
#undef G_TIME_OFFSET_MILLISECOND
#undef G_TIME_OFFSET_SECOND
#undef G_TIME_OFFSET_MINUTE
#undef G_TIME_OFFSET_HOUR
| 18.8739
| 79
| 0.71675
|
birderyu
|
3502aa9f31e55bbf70d08439c09590dd8a56d7e9
| 588
|
cpp
|
C++
|
Codeforces/Contests/Wunder_Fund_Round_2016(Div.1+Div.2combined)/PA.cpp
|
calee0219/CP
|
911ac3671881f6b80ca5a06b7d4f97a3ccc96e50
|
[
"MIT"
] | null | null | null |
Codeforces/Contests/Wunder_Fund_Round_2016(Div.1+Div.2combined)/PA.cpp
|
calee0219/CP
|
911ac3671881f6b80ca5a06b7d4f97a3ccc96e50
|
[
"MIT"
] | null | null | null |
Codeforces/Contests/Wunder_Fund_Round_2016(Div.1+Div.2combined)/PA.cpp
|
calee0219/CP
|
911ac3671881f6b80ca5a06b7d4f97a3ccc96e50
|
[
"MIT"
] | null | null | null |
/*************************************************************************
> File Name: PA.cpp
> Author: Gavin Lee
> Mail: sz110010@gmail.com
> Created Time: 西元2016年01月30日 (週六) 00時45分08秒
************************************************************************/
#include <bits/stdc++.h>
using namespace std;
int sv[10000];
int main()
{
int n;
cin >> n;
int cnt = 0;
while(n)
{
if(n & 1)
sv[cnt] = 1;
n >>= 1;
cnt++;
}
for(int i = cnt-1; i >= 0; --i)
if(sv[i])
cout << i+1 << ' ';
return 0;
}
| 18.967742
| 74
| 0.340136
|
calee0219
|
3503ad6ded863d307e6a0c7b412333db0a909996
| 26,120
|
cc
|
C++
|
src/object/datatype/bytes.cc
|
ArgonLang/Argon
|
462d3d8721acd5131894bcbfa0214b0cbcffdf66
|
[
"Apache-2.0"
] | 13
|
2021-06-24T17:50:20.000Z
|
2022-03-13T23:00:16.000Z
|
src/object/datatype/bytes.cc
|
ArgonLang/Argon
|
462d3d8721acd5131894bcbfa0214b0cbcffdf66
|
[
"Apache-2.0"
] | null | null | null |
src/object/datatype/bytes.cc
|
ArgonLang/Argon
|
462d3d8721acd5131894bcbfa0214b0cbcffdf66
|
[
"Apache-2.0"
] | 1
|
2022-03-31T22:58:42.000Z
|
2022-03-31T22:58:42.000Z
|
// This source file is part of the Argon project.
//
// Licensed under the Apache License v2.0
#include <memory/memory.h>
#include <vm/runtime.h>
#include "bool.h"
#include "bounds.h"
#include "error.h"
#include "integer.h"
#include "iterator.h"
#include "hash_magic.h"
#include "bytes.h"
#define BUFFER_GET(bs) (bs->view.buffer)
#define BUFFER_LEN(bs) (bs->view.len)
#define BUFFER_MAXLEN(left, right) (BUFFER_LEN(left) > BUFFER_LEN(right) ? BUFFER_LEN(right) : BUFFER_LEN(self))
using namespace argon::memory;
using namespace argon::object;
bool bytes_get_buffer(Bytes *self, ArBuffer *buffer, ArBufferFlags flags) {
return BufferSimpleFill(self, buffer, flags, BUFFER_GET(self), BUFFER_LEN(self), !self->frozen);
}
const BufferSlots bytes_buffer = {
(BufferGetFn) bytes_get_buffer,
nullptr
};
ArSize bytes_len(Bytes *self) {
return BUFFER_LEN(self);
}
ArObject *bytes_get_item(Bytes *self, ArSSize index) {
if (index < 0)
index = BUFFER_LEN(self) + index;
if (index < BUFFER_LEN(self))
return IntegerNew(BUFFER_GET(self)[index]);
return ErrorFormat(type_overflow_error_, "bytes index out of range (len: %d, idx: %d)",
BUFFER_LEN(self), index);
}
bool bytes_set_item(Bytes *self, ArObject *obj, ArSSize index) {
Bytes *other;
ArSize value;
if (self->frozen) {
ErrorFormat(type_type_error_, "unable to set item to frozen bytes object");
return false;
}
if (AR_TYPEOF(obj, type_bytes_)) {
other = (Bytes *) obj;
if (BUFFER_LEN(other) > 1) {
ErrorFormat(type_value_error_, "expected bytes of length 1 not %d", BUFFER_LEN(other));
return false;
}
value = BUFFER_GET(other)[0];
} else if (AR_TYPEOF(obj, type_integer_))
value = ((Integer *) obj)->integer;
else {
ErrorFormat(type_type_error_, "expected integer or bytes, found '%s'", AR_TYPE_NAME(obj));
return false;
}
if (value < 0 || value > 255) {
ErrorFormat(type_value_error_, "byte must be in range(0, 255)");
return false;
}
if (index < 0)
index = BUFFER_LEN(self) + index;
if (index < BUFFER_LEN(self)) {
BUFFER_GET(self)[index] = value;
return true;
}
ErrorFormat(type_overflow_error_, "bytes index out of range (len: %d, idx: %d)", BUFFER_LEN(self), index);
return false;
}
ArObject *bytes_get_slice(Bytes *self, Bounds *bounds) {
Bytes *ret;
ArSSize slice_len;
ArSSize start;
ArSSize stop;
ArSSize step;
slice_len = BoundsIndex(bounds, BUFFER_LEN(self), &start, &stop, &step);
if (step >= 0) {
ret = BytesNew(self, start, slice_len);
} else {
if ((ret = BytesNew(slice_len, true, false, self->frozen)) == nullptr)
return nullptr;
for (ArSize i = 0; stop < start; start += step)
BUFFER_GET(ret)[i++] = BUFFER_GET(self)[start];
}
return ret;
}
const SequenceSlots bytes_sequence = {
(SizeTUnaryOp) bytes_len,
(BinaryOpArSize) bytes_get_item,
(BoolTernOpArSize) bytes_set_item,
(BinaryOp) bytes_get_slice,
nullptr
};
ARGON_FUNCTION5(bytes_, new, "Creates bytes object."
""
"The src parameter is optional, in case of call without src parameter an empty zero-length"
"bytes object will be constructed."
""
"- Parameter [src]: integer or bytes-like object."
"- Returns: construct a new bytes object.", 0, true) {
IntegerUnderlying size = 0;
if (!VariadicCheckPositional("bytes::new", count, 0, 1))
return nullptr;
if (count == 1) {
if (!AR_TYPEOF(*argv, type_integer_))
return BytesNew(*argv);
size = ((Integer *) *argv)->integer;
}
return BytesNew(size, true, true, false);
}
ARGON_METHOD5(bytes_, count,
"Returns the number of times a specified value occurs in bytes."
""
"- Parameter sub: subsequence to search."
"- Returns: number of times a specified value appears in bytes.", 1, false) {
ArBuffer buffer{};
Bytes *bytes;
ArSSize n;
bytes = (Bytes *) self;
if (!BufferGet(argv[0], &buffer, ArBufferFlags::READ))
return nullptr;
n = support::Count(BUFFER_GET(bytes), BUFFER_LEN(bytes), buffer.buffer, buffer.len, -1);
BufferRelease(&buffer);
return IntegerNew(n);
}
ARGON_METHOD5(bytes_, clone,
"Returns the number of times a specified value occurs in bytes."
""
"- Parameter sub: subsequence to search."
"- Returns: number of times a specified value appears in the string.", 0, false) {
return BytesNew(self);
}
ARGON_METHOD5(bytes_, endswith,
"Returns true if bytes ends with the specified value."
""
"- Parameter suffix: the value to check if the bytes ends with."
"- Returns: true if bytes ends with the specified value, false otherwise."
""
"# SEE"
"- startswith: Returns true if bytes starts with the specified value.", 1, false) {
ArBuffer buffer{};
Bytes *bytes;
int res;
bytes = (Bytes *) self;
if (!BufferGet(argv[0], &buffer, ArBufferFlags::READ))
return nullptr;
res = BUFFER_LEN(bytes) > buffer.len ? buffer.len : BUFFER_LEN(bytes);
res = MemoryCompare(BUFFER_GET(bytes) + (BUFFER_LEN(bytes) - res), buffer.buffer, res);
BufferRelease(&buffer);
return BoolToArBool(res == 0);
}
ARGON_METHOD5(bytes_, find,
"Searches bytes for a specified value and returns the position of where it was found."
""
"- Parameter sub: the value to search for."
"- Returns: index of the first position, -1 otherwise."
""
"# SEE"
"- rfind: Same as find, but returns the index of the last position.", 1, false) {
ArBuffer buffer{};
Bytes *bytes;
ArSSize pos;
bytes = (Bytes *) self;
if (!BufferGet(argv[0], &buffer, ArBufferFlags::READ))
return nullptr;
pos = support::Find(BUFFER_GET(bytes), BUFFER_LEN(bytes), buffer.buffer, buffer.len, false);
return IntegerNew(pos);
}
ARGON_METHOD5(bytes_, freeze,
"Freeze bytes object."
""
"If bytes is already frozen, the same object will be returned, otherwise a new frozen bytes(view) will be returned."
"- Returns: frozen bytes object.", 0, false) {
auto *bytes = (Bytes *) self;
return BytesFreeze(bytes);
}
ARGON_METHOD5(bytes_, hex, "Convert bytes to str of hexadecimal numbers."
""
"- Returns: new str object.", 0, false) {
StringBuilder builder{};
Bytes *bytes;
bytes = (Bytes *) self;
if (StringBuilderWriteHex(&builder, BUFFER_GET(bytes), BUFFER_LEN(bytes)) < 0) {
StringBuilderClean(&builder);
return nullptr;
}
return StringBuilderFinish(&builder);
}
ARGON_METHOD5(bytes_, isalnum,
"Check if all characters in the bytes are alphanumeric (either alphabets or numbers)."
""
"- Returns: true if all characters are alphanumeric, false otherwise."
""
"# SEE"
"- isalpha: Check if all characters in the bytes are alphabets."
"- isascii: Check if all characters in the bytes are ascii."
"- isdigit: Check if all characters in the bytes are digits.", 0, false) {
auto *bytes = (Bytes *) self;
int chr;
for (ArSize i = 0; i < BUFFER_LEN(bytes); i++) {
chr = BUFFER_GET(bytes)[i];
if ((chr < 'A' || chr > 'Z') && (chr < 'a' || chr > 'z') && (chr < '0' || chr > '9'))
return BoolToArBool(false);
}
return BoolToArBool(true);
}
ARGON_METHOD5(bytes_, isalpha,
"Check if all characters in the bytes are alphabets."
""
"- Returns: true if all characters are alphabets, false otherwise."
""
"# SEE"
"- isalnum: Check if all characters in the bytes are alphanumeric (either alphabets or numbers)."
"- isascii: Check if all characters in the bytes are ascii."
"- isdigit: Check if all characters in the bytes are digits.", 0, false) {
auto *bytes = (Bytes *) self;
int chr;
for (ArSize i = 0; i < BUFFER_LEN(bytes); i++) {
chr = BUFFER_GET(bytes)[i];
if ((chr < 'A' || chr > 'Z') && (chr < 'a' || chr > 'z'))
return BoolToArBool(false);
}
return BoolToArBool(true);
}
ARGON_METHOD5(bytes_, isascii,
"Check if all characters in the bytes are ascii."
""
"- Returns: true if all characters are ascii, false otherwise."
""
"# SEE"
"- isalnum: Check if all characters in the bytes are alphanumeric (either alphabets or numbers)."
"- isalpha: Check if all characters in the bytes are alphabets."
"- isdigit: Check if all characters in the bytes are digits.", 0, false) {
auto *bytes = (Bytes *) self;
int chr;
for (ArSize i = 0; i < BUFFER_LEN(bytes); i++) {
chr = BUFFER_GET(bytes)[i];
if (chr > 0x7F)
return BoolToArBool(false);
}
return BoolToArBool(true);
}
ARGON_METHOD5(bytes_, isdigit,
"Check if all characters in the bytes are digits."
""
"- Returns: true if all characters are digits, false otherwise."
""
"# SEE"
"- isalnum: Check if all characters in the bytes are alphanumeric (either alphabets or numbers)."
"- isalpha: Check if all characters in the bytes are alphabets."
"- isascii: Check if all characters in the bytes are ascii.", 0, false) {
auto *bytes = (Bytes *) self;
int chr;
for (ArSize i = 0; i < BUFFER_LEN(bytes); i++) {
chr = BUFFER_GET(bytes)[i];
if (chr < '0' || chr > '9')
return BoolToArBool(false);
}
return BoolToArBool(true);
}
ARGON_METHOD5(bytes_, isfrozen,
"Check if this bytes object is frozen."
""
"- Returns: true if it is frozen, false otherwise.", 0, false) {
return BoolToArBool(((Bytes *) self)->frozen);
}
ARGON_METHOD5(bytes_, join,
"Joins the elements of an iterable to the end of the bytes."
""
"- Parameter iterable: any iterable object where all the returned values are bytes-like object."
"- Returns: new bytes where all items in an iterable are joined into one bytes.", 1, false) {
ArBuffer buffer{};
ArObject *item = nullptr;
ArObject *iter;
Bytes *bytes;
Bytes *ret;
ArSize idx = 0;
ArSize len;
bytes = (Bytes *) self;
if ((iter = IteratorGet(argv[0])) == nullptr)
return nullptr;
if ((ret = BytesNew()) == nullptr)
goto error;
while ((item = IteratorNext(iter)) != nullptr) {
if (!BufferGet(item, &buffer, ArBufferFlags::READ))
goto error;
len = buffer.len;
if (idx > 0)
len += bytes->view.len;
if (!BufferViewEnlarge(&ret->view, len)) {
BufferRelease(&buffer);
goto error;
}
if (idx > 0) {
MemoryCopy(BUFFER_GET(ret) + BUFFER_LEN(ret), BUFFER_GET(bytes), BUFFER_LEN(bytes));
ret->view.len += BUFFER_LEN(bytes);
}
MemoryCopy(BUFFER_GET(ret) + BUFFER_LEN(ret), buffer.buffer, buffer.len);
ret->view.len += buffer.len;
BufferRelease(&buffer);
Release(item);
idx++;
}
Release(iter);
return ret;
error:
Release(item);
Release(iter);
Release(ret);
return nullptr;
}
ARGON_METHOD5(bytes_, rfind,
"Searches bytes for a specified value and returns the position of where it was found."
""
"- Parameter sub: the value to search for."
"- Returns: index of the first position, -1 otherwise."
""
"# SEE"
"- find: Same as find, but returns the index of the last position.", 1, false) {
ArBuffer buffer{};
Bytes *bytes;
ArSSize pos;
bytes = (Bytes *) self;
if (!BufferGet(argv[0], &buffer, ArBufferFlags::READ))
return nullptr;
pos = support::Find(BUFFER_GET(bytes), BUFFER_LEN(bytes), buffer.buffer, buffer.len, true);
return IntegerNew(pos);
}
ARGON_METHOD5(bytes_, rmpostfix,
"Returns new bytes without postfix(if present), otherwise return this object."
""
"- Parameter postfix: postfix to looking for."
"- Returns: new bytes without indicated postfix."
""
"# SEE"
"- rmprefix: Returns new bytes without prefix(if present), otherwise return this object.",
1, false) {
ArBuffer buffer{};
auto *bytes = (Bytes *) self;
int len;
int compare;
if (!BufferGet(argv[0], &buffer, ArBufferFlags::READ))
return nullptr;
len = BUFFER_LEN(bytes) > buffer.len ? buffer.len : BUFFER_LEN(bytes);
compare = MemoryCompare(BUFFER_GET(bytes) + (BUFFER_LEN(bytes) - len), buffer.buffer, len);
BufferRelease(&buffer);
if (compare == 0)
return BytesNew(bytes, 0, BUFFER_LEN(bytes) - len);
return IncRef(bytes);
}
ARGON_METHOD5(bytes_, rmprefix,
"Returns new bytes without prefix(if present), otherwise return this object."
""
"- Parameter prefix: prefix to looking for."
"- Returns: new bytes without indicated prefix."
""
"# SEE"
"- rmpostfix: Returns new bytes without postfix(if present), otherwise return this object.", 1,
false) {
ArBuffer buffer{};
auto *bytes = (Bytes *) self;
int len;
int compare;
if (!BufferGet(argv[0], &buffer, ArBufferFlags::READ))
return nullptr;
len = BUFFER_LEN(bytes) > buffer.len ? buffer.len : BUFFER_LEN(bytes);
compare = MemoryCompare(BUFFER_GET(bytes), buffer.buffer, len);
BufferRelease(&buffer);
if (compare == 0)
return BytesNew(bytes, len, BUFFER_LEN(bytes) - len);
return IncRef(bytes);
}
ARGON_METHOD5(bytes_, split,
"Splits bytes at the specified separator, and returns a list."
""
"- Parameters:"
" - separator: specifies the separator to use when splitting bytes."
" - maxsplit: specifies how many splits to do."
"- Returns: new list of bytes.", 2, false) {
ArBuffer buffer{};
Bytes *bytes;
ArObject *ret;
bytes = (Bytes *) self;
if (!AR_TYPEOF(argv[1], type_integer_))
return ErrorFormat(type_type_error_, "bytes::split() expected integer not '%s'", AR_TYPE_NAME(argv[1]));
if (!BufferGet(argv[0], &buffer, ArBufferFlags::READ))
return nullptr;
ret = BytesSplit(bytes, buffer.buffer, buffer.len, ((Integer *) argv[1])->integer);
BufferRelease(&buffer);
return ret;
}
ARGON_METHOD5(bytes_, startswith,
"Returns true if bytes starts with the specified value."
""
"- Parameter prefix: the value to check if the bytes starts with."
"- Returns: true if bytes starts with the specified value, false otherwise."
""
"# SEE"
"- endswith: Returns true if bytes ends with the specified value.", 1, false) {
ArBuffer buffer{};
Bytes *bytes;
int res;
bytes = (Bytes *) self;
if (!BufferGet(argv[0], &buffer, ArBufferFlags::READ))
return nullptr;
res = BUFFER_LEN(bytes) > buffer.len ? buffer.len : BUFFER_LEN(bytes);
res = MemoryCompare(BUFFER_GET(bytes), buffer.buffer, res);
BufferRelease(&buffer);
return BoolToArBool(res == 0);
}
ARGON_METHOD5(bytes_, str, "Convert bytes to str object."
""
"- Returns: new str object.", 0, false) {
auto *bytes = (Bytes *) self;
return StringNew((const char *) BUFFER_GET(bytes), BUFFER_LEN(bytes));
}
const NativeFunc bytes_methods[] = {
bytes_count_,
bytes_endswith_,
bytes_find_,
bytes_freeze_,
bytes_hex_,
bytes_isalnum_,
bytes_isalpha_,
bytes_isascii_,
bytes_isdigit_,
bytes_isfrozen_,
bytes_join_,
bytes_new_,
bytes_rfind_,
bytes_rmpostfix_,
bytes_rmprefix_,
bytes_split_,
bytes_startswith_,
bytes_str_,
ARGON_METHOD_SENTINEL
};
const ObjectSlots bytes_obj = {
bytes_methods,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
-1
};
ArObject *bytes_add(Bytes *self, ArObject *other) {
ArBuffer buffer = {};
Bytes *ret;
if (!IsBufferable(other))
return nullptr;
if (!BufferGet(other, &buffer, ArBufferFlags::READ))
return nullptr;
if ((ret = BytesNew(BUFFER_LEN(self) + buffer.len, true, false, self->frozen)) == nullptr) {
BufferRelease(&buffer);
return nullptr;
}
MemoryCopy(BUFFER_GET(ret), BUFFER_GET(self), BUFFER_LEN(self));
MemoryCopy(BUFFER_GET(ret) + BUFFER_LEN(self), buffer.buffer, buffer.len);
BufferRelease(&buffer);
return ret;
}
ArObject *bytes_mul(ArObject *left, ArObject *right) {
auto *bytes = (Bytes *) left;
auto *num = (Integer *) right;
Bytes *ret = nullptr;
ArSize len;
if (!AR_TYPEOF(bytes, type_bytes_)) {
bytes = (Bytes *) right;
num = (Integer *) left;
}
if (AR_TYPEOF(num, type_integer_)) {
len = BUFFER_LEN(bytes) * num->integer;
if ((ret = BytesNew(len, true, false, bytes->frozen)) != nullptr) {
for (ArSize i = 0; i < num->integer; i++)
MemoryCopy(BUFFER_GET(ret) + BUFFER_LEN(bytes) * i, BUFFER_GET(bytes), BUFFER_LEN(bytes));
}
}
return ret;
}
Bytes *ShiftBytes(Bytes *bytes, ArSSize pos) {
auto ret = BytesNew(BUFFER_LEN(bytes), true, false, bytes->frozen);
if (ret != nullptr) {
for (ArSize i = 0; i < BUFFER_LEN(bytes); i++)
ret->view.buffer[((BUFFER_LEN(bytes) + pos) + i) % BUFFER_LEN(bytes)] = BUFFER_GET(bytes)[i];
}
return ret;
}
ArObject *bytes_shl(ArObject *left, ArObject *right) {
if (AR_TYPEOF(left, type_bytes_) && AR_TYPEOF(right, type_integer_))
return ShiftBytes((Bytes *) left, -((Integer *) right)->integer);
return nullptr;
}
ArObject *bytes_shr(ArObject *left, ArObject *right) {
if (AR_TYPEOF(left, type_bytes_) && AR_TYPEOF(right, type_integer_))
return ShiftBytes((Bytes *) left, ((Integer *) right)->integer);
return nullptr;
}
ArObject *bytes_iadd(Bytes *self, ArObject *other) {
ArBuffer buffer = {};
Bytes *ret = self;
if (!IsBufferable(other))
return nullptr;
if (!BufferGet(other, &buffer, ArBufferFlags::READ))
return nullptr;
if (self->frozen) {
if ((ret = BytesNew(BUFFER_LEN(self) + buffer.len, true, false, true)) == nullptr) {
BufferRelease(&buffer);
return nullptr;
}
MemoryCopy(BUFFER_GET(ret), BUFFER_GET(self), BUFFER_LEN(self));
MemoryCopy(BUFFER_GET(ret) + BUFFER_LEN(self), buffer.buffer, buffer.len);
BufferRelease(&buffer);
return ret;
}
if (!BufferViewEnlarge(&self->view, buffer.len)) {
BufferRelease(&buffer);
return nullptr;
}
MemoryCopy(BUFFER_GET(ret) + BUFFER_LEN(ret), buffer.buffer, buffer.len);
ret->view.len += buffer.len;
BufferRelease(&buffer);
return IncRef(self);
}
OpSlots bytes_ops{
(BinaryOp) bytes_add,
nullptr,
bytes_mul,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
bytes_shl,
bytes_shr,
nullptr,
(BinaryOp) bytes_iadd,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr
};
ArObject *bytes_str(Bytes *self) {
StringBuilder sb = {};
// Calculate length of string
if (!StringBuilderResizeAscii(&sb, BUFFER_GET(self), BUFFER_LEN(self), 3)) // +3 b""
return nullptr;
// Build string
StringBuilderWrite(&sb, (const unsigned char *) "b\"", 2);;
StringBuilderWriteAscii(&sb, BUFFER_GET(self), BUFFER_LEN(self));
StringBuilderWrite(&sb, (const unsigned char *) "\"", 1);
return StringBuilderFinish(&sb);
}
ArObject *bytes_iter_get(Bytes *self) {
return IteratorNew(self, false);
}
ArObject *bytes_iter_rget(Bytes *self) {
return IteratorNew(self, true);
}
ArObject *bytes_compare(Bytes *self, ArObject *other, CompareMode mode) {
auto *o = (Bytes *) other;
int left = 0;
int right = 0;
int res;
if (!AR_SAME_TYPE(self, other))
return nullptr;
if (self != other) {
res = MemoryCompare(BUFFER_GET(self), BUFFER_GET(o), BUFFER_MAXLEN(self, o));
if (res < 0)
left = -1;
else if (res > 0)
right = -1;
else if (BUFFER_LEN(self) < BUFFER_LEN(o))
left = -1;
else if (BUFFER_LEN(self) > BUFFER_LEN(o))
right = -1;
}
ARGON_RICH_COMPARE_CASES(left, right, mode);
}
ArSize bytes_hash(Bytes *self) {
if (!self->frozen) {
ErrorFormat(type_unhashable_error_, "unable to hash unfrozen bytes object");
return 0;
}
if (self->hash == 0)
self->hash = HashBytes(BUFFER_GET(self), BUFFER_LEN(self));
return self->hash;
}
bool bytes_is_true(Bytes *self) {
return BUFFER_LEN(self) > 0;
}
void bytes_cleanup(Bytes *self) {
BufferViewDetach(&self->view);
}
const TypeInfo BytesType = {
TYPEINFO_STATIC_INIT,
"bytes",
nullptr,
sizeof(Bytes),
TypeInfoFlags::BASE,
nullptr,
(VoidUnaryOp) bytes_cleanup,
nullptr,
(CompareOp) bytes_compare,
(BoolUnaryOp) bytes_is_true,
(SizeTUnaryOp) bytes_hash,
(UnaryOp) bytes_str,
(UnaryOp) bytes_iter_get,
(UnaryOp) bytes_iter_rget,
&bytes_buffer,
nullptr,
nullptr,
nullptr,
&bytes_obj,
&bytes_sequence,
&bytes_ops,
nullptr,
nullptr
};
const TypeInfo *argon::object::type_bytes_ = &BytesType;
ArObject *argon::object::BytesSplit(Bytes *bytes, unsigned char *pattern, ArSize plen, ArSSize maxsplit) {
Bytes *tmp;
List *ret;
ArSize idx = 0;
ArSSize end;
ArSSize counter = 0;
if ((ret = ListNew()) == nullptr)
return nullptr;
if (maxsplit != 0) {
while ((end = support::Find(BUFFER_GET(bytes) + idx, BUFFER_LEN(bytes) - idx, pattern, plen)) >= 0) {
if ((tmp = BytesNew(bytes, idx, end - idx)) == nullptr)
goto error;
idx += end + plen;
if (!ListAppend(ret, tmp))
goto error;
Release(tmp);
if (maxsplit > -1 && ++counter >= maxsplit)
break;
}
}
if (BUFFER_LEN(bytes) - idx > 0) {
if ((tmp = BytesNew(bytes, idx, BUFFER_LEN(bytes) - idx)) == nullptr)
goto error;
if (!ListAppend(ret, tmp))
goto error;
Release(tmp);
}
return ret;
error:
Release(tmp);
Release(ret);
return nullptr;
}
Bytes *argon::object::BytesNew(ArObject *object) {
ArBuffer buffer = {};
Bytes *bs;
if (!IsBufferable(object))
return nullptr;
if (!BufferGet(object, &buffer, ArBufferFlags::READ))
return nullptr;
if ((bs = BytesNew(buffer.len, true, false, false)) != nullptr)
MemoryCopy(BUFFER_GET(bs), buffer.buffer, buffer.len);
BufferRelease(&buffer);
return bs;
}
Bytes *argon::object::BytesNew(Bytes *stream, ArSize start, ArSize len) {
auto bs = ArObjectNew<Bytes>(RCType::INLINE, type_bytes_);
if (bs != nullptr) {
BufferViewInit(&bs->view, &stream->view, start, len);
bs->hash = 0;
bs->frozen = stream->frozen;
}
return bs;
}
Bytes *argon::object::BytesNew(ArSize cap, bool same_len, bool fill_zero, bool frozen) {
auto bs = ArObjectNew<Bytes>(RCType::INLINE, type_bytes_);
if (bs != nullptr) {
if (!BufferViewInit(&bs->view, cap)) {
Release(bs);
return nullptr;
}
if (same_len)
bs->view.len = cap;
if (fill_zero)
MemoryZero(BUFFER_GET(bs), cap);
bs->hash = 0;
bs->frozen = frozen;
}
return bs;
}
Bytes *argon::object::BytesNew(unsigned char *buffer, ArSize len, bool frozen) {
auto *bytes = BytesNew(len, true, false, frozen);
if (bytes != nullptr)
MemoryCopy(BUFFER_GET(bytes), buffer, len);
return bytes;
}
Bytes *argon::object::BytesNewHoldBuffer(unsigned char *buffer, ArSize len, ArSize cap, bool frozen) {
auto bs = ArObjectNew<Bytes>(RCType::INLINE, type_bytes_);
if (bs != nullptr) {
if (!BufferViewHoldBuffer(&bs->view, buffer, len, cap)) {
Release(bs);
return nullptr;
}
bs->hash = 0;
bs->frozen = frozen;
}
return bs;
}
Bytes *argon::object::BytesFreeze(Bytes *stream) {
Bytes *ret;
if (stream->frozen)
return IncRef(stream);
if ((ret = BytesNew(stream, 0, BUFFER_LEN(stream))) == nullptr)
return nullptr;
ret->frozen = true;
Hash(ret);
return ret;
}
#undef BUFFER_GET
#undef BUFFER_LEN
#undef BUFFER_MAXLEN
| 27.728238
| 130
| 0.580283
|
ArgonLang
|
350513dd2d806fa3ce14db73d79f36710bdbc344
| 7,976
|
cpp
|
C++
|
Desktop/FOSSA-GroundStationControlPanel/FOSSAGSCP/3rdparty/FOSSACommsInterpreter/src/Message/FOSSASAT2/FOSSASAT2_Statistics.cpp
|
FOSSASystems/FOSSA-GroundStationControlPanel
|
af83a09619239abe9fca09e073ab41c68bfd4822
|
[
"MIT"
] | 2
|
2021-11-07T16:26:46.000Z
|
2022-03-20T10:14:41.000Z
|
Desktop/FOSSA-GroundStationControlPanel/FOSSAGSCP/3rdparty/FOSSACommsInterpreter/src/Message/FOSSASAT2/FOSSASAT2_Statistics.cpp
|
FOSSASystems/FOSSA-GroundStationControlPanel
|
af83a09619239abe9fca09e073ab41c68bfd4822
|
[
"MIT"
] | 18
|
2020-08-28T13:38:36.000Z
|
2020-09-30T11:08:42.000Z
|
Desktop/FOSSA-GroundStationControlPanel/FOSSAGSCP/3rdparty/FOSSACommsInterpreter/src/Message/FOSSASAT2/FOSSASAT2_Statistics.cpp
|
FOSSASystems/FOSSA-GroundStationControlPanel
|
af83a09619239abe9fca09e073ab41c68bfd4822
|
[
"MIT"
] | 2
|
2020-07-29T21:19:28.000Z
|
2021-08-16T03:58:14.000Z
|
// MIT LICENSE
//
// Copyright (c) 2020 FOSSA Systems
//
// 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 "FOSSASAT2_Statistics.h"
FOSSASAT2::Messages::Statistics::Statistics(Frame &frame)
{
uint8_t flagByte = frame.GetByteAt(0);
this->temperaturesIncluded = flagByte & 0x01;
this->currentsIncluded = (flagByte >> 1) & 0x01;
this->voltagesIncluded = (flagByte >> 2) & 0x01;
this->lightSensorsIncluded = (flagByte >> 3) & 0x01;
this->imuIncluded = (flagByte >> 4) & 0x01;
if (this->temperaturesIncluded)
{
for (int i = 0; i < 15; i++)
{
int startIndex = 1 + (i*2);
uint8_t lsb = frame.GetByteAt(startIndex);
uint8_t msb = frame.GetByteAt(startIndex + 1);
int16_t temperature = lsb | (msb << 8);
float temperaturesRealValue = temperature * 0.01f;
this->temperatures.push_back(temperaturesRealValue);
}
}
if (this->currentsIncluded)
{
for (int i = 0; i < 18; i++)
{
int startIndex = 31 + (i*2);
uint8_t lsb = frame.GetByteAt(startIndex);
uint8_t msb = frame.GetByteAt(startIndex + 1);
int16_t current = lsb | (msb << 8);
float currentsValue = current * 10;
this->currents.push_back(currentsValue);
}
}
if (this->voltagesIncluded)
{
for (int i = 0; i < 18; i++)
{
int startIndex = 67 + i;
float voltage = frame.GetByteAt(startIndex) * 20;
this->voltages.push_back(voltage);
}
}
if (this->lightSensorsIncluded)
{
for (int i = 0; i < 6; i++)
{
int startIndex = 85 + (i * 4);
uint8_t lsb = frame.GetByteAt(startIndex);
uint8_t a = frame.GetByteAt(startIndex + 1);
uint8_t b = frame.GetByteAt(startIndex + 2);
uint8_t msb = frame.GetByteAt(startIndex + 3);
uint32_t bytesVal = lsb;
bytesVal |= a << 8;
bytesVal |= b << 16;
bytesVal |= msb << 24;
float lightSensorValue = 0.0f;
memcpy(&lightSensorValue, &bytesVal, 4);
this->currents.push_back(lightSensorValue);
}
}
if (this->imuIncluded)
{
for (int i = 0; i < 16; i++)
{
int startIndex = 109 + (i * 4);
uint8_t lsb = frame.GetByteAt(startIndex);
uint8_t a = frame.GetByteAt(startIndex + 1);
uint8_t b = frame.GetByteAt(startIndex + 2);
uint8_t msb = frame.GetByteAt(startIndex + 3);
uint32_t bytesVal = lsb;
bytesVal |= a << 8;
bytesVal |= b << 16;
bytesVal |= msb << 24;
float imuValue = 0.0f;
memcpy(&imuValue, &bytesVal, 4);
this->imus.push_back(imuValue);
}
}
}
std::string FOSSASAT2::Messages::Statistics::ToString()
{
std::stringstream ss;
ss << "Satellite Version: FOSSASAT2" << std::endl;
ss << "Message Name: Statistics" << std::endl;
ss << "Temperatures included: " << this->temperaturesIncluded << std::endl;
ss << "Currents included: " << this->currentsIncluded << std::endl;
ss << "Voltages included: " << this->voltagesIncluded << std::endl;
ss << "Light sensors included: " << this->lightSensorsIncluded << std::endl;
ss << "IMU included: " << this->imuIncluded << std::endl;
ss << "Temperatures: " << std::endl;
for (float temp : this->temperatures)
{
ss << " " << temp << " deg. C" << std::endl;
}
ss << "Currents: " << std::endl;
for (float current : this->currents)
{
ss << " " << current << " uA" << std::endl;
}
ss << "Voltages: " << std::endl;
for (float voltage : this->voltages)
{
ss << " " << voltage << " mV" << std::endl;
}
ss << "Light sensors: " << std::endl;
for (float lightSensor : this->lightSensors)
{
ss << " " << lightSensor << std::endl;
}
ss << "IMU: " << std::endl;
for (float imu : this->imus)
{
ss << " " << imu << std::endl;
}
std::string out;
ss >> out;
return out;
}
std::string FOSSASAT2::Messages::Statistics::ToJSON()
{
std::stringstream ss;
ss << "{" << std::endl;
ss << "\"Satellite Version\": \"FOSSASAT2\"," << std::endl;
ss << "\"Message Name\": \"Statistics\"," << std::endl;
ss << "\"Temperatures included\": " << this->temperaturesIncluded << std::endl;
ss << "\"Currents included\": " << this->currentsIncluded << std::endl;
ss << "\"Voltages included\": " << this->voltagesIncluded << std::endl;
ss << "\"Light sensors included\": " << this->lightSensorsIncluded << std::endl;
ss << "\"IMU included\": " << this->imuIncluded << std::endl;
ss << "\"Temperatures\": " << std::endl;
ss << "{" << std::endl;
for (float temp : this->temperatures)
{
ss << temp << "," << std::endl;
}
ss << "\"Currents\": " << std::endl;
ss << "{" << std::endl;
for (float current : this->currents)
{
ss << " \"" << current << "\"," << std::endl;
}
ss << "}" << std::endl;
ss << "\"Voltages\": " << std::endl;
ss << "{" << std::endl;
for (float voltage : this->voltages)
{
ss << " \"" << voltage << "\"," << std::endl;
}
ss << "}" << std::endl;
ss << "\"Light sensors\": " << std::endl;
ss << "{" << std::endl;
for (float lightSensor : this->lightSensors)
{
ss << " \"" << lightSensor << "\"," << std::endl;
}
ss << "}" << std::endl;
ss << "\"IMU\": " << std::endl;
ss << "{" << std::endl;
for (float imu : this->imus)
{
ss << " \"" << imu << "\"," << std::endl;
}
ss << "}" << std::endl;
ss << "}" << std::endl;
std::string out;
ss >> out;
return out;
}
bool FOSSASAT2::Messages::Statistics::IsTemperaturesIncluded() const {
return temperaturesIncluded;
}
bool FOSSASAT2::Messages::Statistics::IsCurrentsIncluded() const {
return currentsIncluded;
}
bool FOSSASAT2::Messages::Statistics::IsVoltagesIncluded() const {
return voltagesIncluded;
}
bool FOSSASAT2::Messages::Statistics::IsLightSensorsIncluded() const {
return lightSensorsIncluded;
}
bool FOSSASAT2::Messages::Statistics::IsImuIncluded() const {
return imuIncluded;
}
const std::vector<float> &FOSSASAT2::Messages::Statistics::GetTemperatures() const {
return temperatures;
}
const std::vector<float> &FOSSASAT2::Messages::Statistics::GetCurrents() const {
return currents;
}
const std::vector<float> &FOSSASAT2::Messages::Statistics::GetVoltages() const {
return voltages;
}
const std::vector<float> &FOSSASAT2::Messages::Statistics::GetLightSensors() const {
return lightSensors;
}
const std::vector<float> &FOSSASAT2::Messages::Statistics::GetImus() const {
return imus;
}
| 30.676923
| 84
| 0.572342
|
FOSSASystems
|
35062bf4f84f1a2eee4898af77ad9d1364a24cca
| 808
|
cpp
|
C++
|
CD6/The K Weakest Rows in a Matrix.cpp
|
shtanriverdi/CS487-Introduction-to-Competitive-Programming-Progress
|
0d7a4fa4346ee08d9b2b2f628c3ffab7f3f81166
|
[
"MIT"
] | 4
|
2019-12-12T19:59:50.000Z
|
2020-01-20T15:44:44.000Z
|
CD6/The K Weakest Rows in a Matrix.cpp
|
shtanriverdi/CS487-Introduction-to-Competitive-Programming-Progress
|
0d7a4fa4346ee08d9b2b2f628c3ffab7f3f81166
|
[
"MIT"
] | null | null | null |
CD6/The K Weakest Rows in a Matrix.cpp
|
shtanriverdi/CS487-Introduction-to-Competitive-Programming-Progress
|
0d7a4fa4346ee08d9b2b2f628c3ffab7f3f81166
|
[
"MIT"
] | null | null | null |
// Question Link ---> https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/
class Solution {
public:
vector<int> kWeakestRows(vector<vector<int>>& mat, int k) {
vector<int> res;
multimap<int, int> soldierRow; // {soldier, row}
int M = mat.size();
int N = mat[0].size();
for (int i = 0; i < M; i++) {
int j = 1;
for (; j < N; j++) {
if (mat[i][j] != 0) {
mat[i][j] += mat[i][j - 1];
} else break;
}
soldierRow.insert({mat[i][j - 1], i});
}
auto it = soldierRow.begin();
for (int i = 0; i < k && it != soldierRow.end(); i++, it++) {
res.push_back(it->second);
}
return res;
}
};
| 33.666667
| 85
| 0.423267
|
shtanriverdi
|
3509e4223ac907ba34c262a651bf33350adfac20
| 3,167
|
cpp
|
C++
|
Xilinx_Reference_Platforms/zcu102_pl_ddr_stream/samples/pl_to_ps/host.cpp
|
streamblocks/Vitis_Embedded_Platform_Source
|
4f99d486681fd175b970a73f1d577ef0cdc7c688
|
[
"Apache-2.0"
] | 5
|
2020-11-18T11:02:33.000Z
|
2021-07-29T06:26:51.000Z
|
Xilinx_Reference_Platforms/zcu102_pl_ddr_stream/samples/pl_to_ps/host.cpp
|
xiekailiang/Vitis_Embedded_Platform_Source
|
4f99d486681fd175b970a73f1d577ef0cdc7c688
|
[
"Apache-2.0"
] | null | null | null |
Xilinx_Reference_Platforms/zcu102_pl_ddr_stream/samples/pl_to_ps/host.cpp
|
xiekailiang/Vitis_Embedded_Platform_Source
|
4f99d486681fd175b970a73f1d577ef0cdc7c688
|
[
"Apache-2.0"
] | 1
|
2021-05-05T12:25:41.000Z
|
2021-05-05T12:25:41.000Z
|
/*
* Copyright 2019 Xilinx, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <chrono>
#include <iostream>
#include <vector>
#define CL_USE_DEPRECATED_OPENCL_1_2_APIS
#include "ApiHandle.h"
#include "CL/opencl.h"
#include "Task.h"
int main(int argc, char *argv[])
{
// -- Environment / Usage Check -------------------------------------------
char *xcl_mode = getenv("XCL_EMULATION_MODE");
if (argc != 2) {
printf("\nUsage: %s "
"./xclbin/pass.<emulation_mode>.<dsa>.xclbin ",
argv[0]);
return EXIT_FAILURE;
}
char *binaryName = argv[1];
// -- Common Parameters ---------------------------------------------------
unsigned int numBuffers = 3;
bool oooQueue = false;
unsigned int bufferSize = 1024;
// -- Setup ---------------------------------------------------------------
ApiHandle api(binaryName, oooQueue);
std::cout << std::endl;
std::cout << std::endl;
std::vector<Task> tasks(numBuffers, Task(bufferSize));
auto fpga_begin = std::chrono::high_resolution_clock::now();
// -- Execution -----------------------------------------------------------
for (unsigned int i = 0; i < numBuffers; i++) {
tasks[i].run(api);
}
clFinish(api.getQueue());
// -- Testing -------------------------------------------------------------
auto fpga_end = std::chrono::high_resolution_clock::now();
bool outputOk = true;
for (unsigned int i = 0; i < numBuffers; i++) {
outputOk = tasks[i].outputOk() && outputOk;
}
if (!outputOk) {
std::cout << "FAIL: Output Corrupted" << std::endl;
return 1;
}
// -- Performance Statistics ----------------------------------------------
if (xcl_mode == NULL) {
std::chrono::duration<double> fpga_duration = fpga_end - fpga_begin;
double total = (double)bufferSize * numBuffers * 512 / (1024.0 * 1024.0);
std::cout << std::endl;
std::cout << " Total data: " << total << " MBits" << std::endl;
std::cout << " FPGA Time: " << fpga_duration.count()
<< " s" << std::endl;
std::cout << " FPGA Throughput: "
<< total / fpga_duration.count()
<< " MBits/s" << std::endl;
std::cout << "FPGA PCIe Throughput: "
<< (2 * total) / fpga_duration.count()
<< " MBits/s" << std::endl;
}
std::cout << "\nPASS: Simulation" << std::endl;
return 0;
}
| 32.989583
| 82
| 0.503631
|
streamblocks
|
350a46e5e7cfc9bef25eda4f7dc0cbc960c30320
| 6,210
|
hpp
|
C++
|
sprout/darkroom/renderers/whitted_style.hpp
|
jwakely/Sprout
|
a64938fad0a64608f22d39485bc55a1e0dc07246
|
[
"BSL-1.0"
] | 1
|
2018-09-21T23:50:44.000Z
|
2018-09-21T23:50:44.000Z
|
sprout/darkroom/renderers/whitted_style.hpp
|
jwakely/Sprout
|
a64938fad0a64608f22d39485bc55a1e0dc07246
|
[
"BSL-1.0"
] | null | null | null |
sprout/darkroom/renderers/whitted_style.hpp
|
jwakely/Sprout
|
a64938fad0a64608f22d39485bc55a1e0dc07246
|
[
"BSL-1.0"
] | null | null | null |
#ifndef SPROUT_DARKROOM_RENDERERS_WHITTED_STYLE_HPP
#define SPROUT_DARKROOM_RENDERERS_WHITTED_STYLE_HPP
#include <cstddef>
#include <limits>
#include <type_traits>
#include <sprout/config.hpp>
#include <sprout/tuple/functions.hpp>
#include <sprout/darkroom/access/access.hpp>
#include <sprout/darkroom/colors/rgb.hpp>
#include <sprout/darkroom/coords/vector.hpp>
#include <sprout/darkroom/rays/ray.hpp>
#include <sprout/darkroom/materials/material.hpp>
#include <sprout/darkroom/intersects/intersection.hpp>
#include <sprout/darkroom/objects/intersect.hpp>
namespace sprout {
namespace darkroom {
namespace renderers {
//
// whitted_mirror
//
class whitted_mirror {
private:
template<
typename Color,
typename Camera,
typename Objects,
typename Lights,
typename Ray,
typename Intersection,
typename Tracer,
typename Direction
>
SPROUT_CONSTEXPR Color color_1(
Camera const& camera,
Objects const& objs,
Lights const& lights,
Ray const& ray,
Intersection const& inter,
Tracer const& tracer,
std::size_t depth_max,
Direction const& reflect_dir
) const
{
return tracer.template operator()<Color>(
camera,
objs,
lights,
sprout::tuples::remake<Ray>(
ray,
sprout::darkroom::coords::add(
sprout::darkroom::intersects::point_of_intersection(inter),
sprout::darkroom::coords::scale(
reflect_dir,
std::numeric_limits<typename sprout::darkroom::access::unit<Direction>::type>::epsilon() * 256
)
// !!!
// sprout::darkroom::coords::scale(
// sprout::darkroom::intersects::normal(inter),
// std::numeric_limits<typename sprout::darkroom::access::unit<Direction>::type>::epsilon() * 256
// )
),
reflect_dir
),
depth_max - 1
);
}
public:
template<
typename Color,
typename Camera,
typename Objects,
typename Lights,
typename Ray,
typename Intersection,
typename Tracer
>
SPROUT_CONSTEXPR Color operator()(
Camera const& camera,
Objects const& objs,
Lights const& lights,
Ray const& ray,
Intersection const& inter,
Tracer const& tracer,
std::size_t depth_max
) const
{
typedef typename std::decay<
decltype(sprout::darkroom::materials::reflection(sprout::darkroom::intersects::material(inter)))
>::type reflection_type;
return depth_max > 0
&& sprout::darkroom::intersects::does_intersect(inter)
&& sprout::darkroom::materials::reflection(sprout::darkroom::intersects::material(inter))
> std::numeric_limits<reflection_type>::epsilon()
? color_1<Color>(
camera,
objs,
lights,
ray,
inter,
tracer,
depth_max,
sprout::darkroom::coords::reflect(
sprout::darkroom::rays::direction(ray),
sprout::darkroom::intersects::normal(inter)
)
)
: sprout::tuples::make<Color>(0, 0, 0)
;
}
};
//
// whitted_style
//
class whitted_style {
private:
template<
typename Color,
typename Ray,
typename Intersection
>
SPROUT_CONSTEXPR Color color_3(
Ray const& ray,
Intersection const& inter,
Color const& diffuse_color,
Color const& mirror_color
) const
{
return sprout::darkroom::intersects::does_intersect(inter)
? sprout::darkroom::colors::add(
sprout::darkroom::colors::mul(
diffuse_color,
1 - sprout::darkroom::materials::reflection(sprout::darkroom::intersects::material(inter))
),
sprout::darkroom::colors::mul(
sprout::darkroom::colors::filter(
sprout::darkroom::materials::color(sprout::darkroom::intersects::material(inter)),
mirror_color
),
sprout::darkroom::materials::reflection(sprout::darkroom::intersects::material(inter))
)
)
: sprout::darkroom::coords::normal_to_color<Color>(sprout::darkroom::rays::direction(ray))
;
}
template<
typename Color,
typename Camera,
typename Objects,
typename Lights,
typename Ray,
typename Intersection
>
SPROUT_CONSTEXPR Color color_2(
Camera const& camera,
Objects const& objs,
Lights const& lights,
Ray const& ray,
std::size_t depth_max,
Intersection const& inter,
Color const& diffuse_color
) const
{
return color_3<Color>(
ray,
inter,
diffuse_color,
sprout::darkroom::renderers::whitted_mirror().template operator()<Color>(
camera,
objs,
lights,
ray,
inter,
*this,
depth_max
)
);
}
template<
typename Color,
typename Camera,
typename Objects,
typename Lights,
typename Ray,
typename Intersection
>
SPROUT_CONSTEXPR Color color_1(
Camera const& camera,
Objects const& objs,
Lights const& lights,
Ray const& ray,
std::size_t depth_max,
Intersection const& inter
) const
{
return color_2<Color>(
camera,
objs,
lights,
ray,
depth_max,
inter,
lights.template operator()(inter, objs)
);
}
public:
template<
typename Color,
typename Camera,
typename Objects,
typename Lights,
typename Ray
>
SPROUT_CONSTEXPR Color operator()(
Camera const& camera,
Objects const& objs,
Lights const& lights,
Ray const& ray,
std::size_t depth_max
) const
{
return color_1<Color>(
camera,
objs,
lights,
ray,
depth_max,
sprout::darkroom::objects::intersect_list(objs, ray)
);
}
};
} // namespace renderers
} // namespace darkroom
} // namespace sprout
#endif // #ifndef SPROUT_DARKROOM_RENDERERS_WHITTED_STYLE_HPP
| 26.092437
| 106
| 0.597101
|
jwakely
|
350dd3935eb89bd0718345919593ae59d7f97d31
| 856
|
cpp
|
C++
|
nodes/BlackAndWhiteNode.cpp
|
zhyvchyky/filters
|
7158aa8a05fb004cdea63fdbd7d31111a1f4c796
|
[
"MIT"
] | null | null | null |
nodes/BlackAndWhiteNode.cpp
|
zhyvchyky/filters
|
7158aa8a05fb004cdea63fdbd7d31111a1f4c796
|
[
"MIT"
] | 2
|
2020-11-26T21:08:23.000Z
|
2020-12-03T15:22:09.000Z
|
nodes/BlackAndWhiteNode.cpp
|
zhyvchyky/filters
|
7158aa8a05fb004cdea63fdbd7d31111a1f4c796
|
[
"MIT"
] | null | null | null |
//
// Created by makstar on 01.12.2020.
//
#include "BlackAndWhiteNode.h"
void BlackAndWhiteNode::process() {
this->outputPtr = applyTransform(this->inputs[0]->getOutputPtr());
}
std::shared_ptr<Image> BlackAndWhiteNode::applyTransform(const std::shared_ptr<Image>& img) {
int width = img->getWidth();
int height = img->getHeight();
auto new_img = std::make_shared<Image>(height, width, 3, new Pixel[height * width]);
int grey; // max, min;
Pixel current;
for(int i = 0; i < height; i++){
for(int j = 0; j < width; j++){
current = img->getPixel(i, j);
grey = (current.red + current.green + current.blue) / 3;
new_img->setPixel(i, j, grey, grey, grey);
}
}
return new_img;
}
NodeType BlackAndWhiteNode::getNodeType() {
return NodeType::BlackAndWhiteNode;
}
| 25.176471
| 93
| 0.616822
|
zhyvchyky
|
350e25163ccba22d6848044a577366933e4aa0ac
| 11,962
|
cpp
|
C++
|
Analysis/Separator/SeparatorCmp.cpp
|
konradotto/TS
|
bf088bd8432b1e3f4b8c8c083650a30d9ef2ae2e
|
[
"Apache-2.0"
] | 125
|
2015-01-22T05:43:23.000Z
|
2022-03-22T17:15:59.000Z
|
Analysis/Separator/SeparatorCmp.cpp
|
konradotto/TS
|
bf088bd8432b1e3f4b8c8c083650a30d9ef2ae2e
|
[
"Apache-2.0"
] | 59
|
2015-02-10T09:13:06.000Z
|
2021-11-11T02:32:38.000Z
|
Analysis/Separator/SeparatorCmp.cpp
|
konradotto/TS
|
bf088bd8432b1e3f4b8c8c083650a30d9ef2ae2e
|
[
"Apache-2.0"
] | 98
|
2015-01-17T01:25:10.000Z
|
2022-03-18T17:29:42.000Z
|
/* Copyright (C) 2010 Ion Torrent Systems, Inc. All Rights Reserved */
#include <string>
#include <vector>
#include "OptArgs.h"
#include "Mask.h"
#include "NumericalComparison.h"
#include "Utils.h"
#include "IonH5File.h"
#include "IonH5Arma.h"
using namespace std;
using namespace arma;
/**
* Options about the two beadfind/separator results we're comparing.
* query is the test results and gold is the current stable version by
* convention.
*/
class SepCmpOpt {
public:
SepCmpOpt() {
min_corr = 1.0;
verbosity = 0;
threshold_percent = .02;
}
string gold_dir, query_dir;
double min_corr;
double threshold_percent;
string mode;
int verbosity;
};
/**
* Notes from a comparison,
*/
class ComparisonMsg {
public:
ComparisonMsg(const string &_name, double _min_corr, double _max_diff) : name(_name),
min_corr(_min_corr),
max_diff(_max_diff) {
equivalent = true;
}
void Append(const string &s) { msg += s; }
void ToStr(ostream &o, int verbosity) {
string status = "*FAILED*";
if (equivalent) {
status = "PASSED";
}
// 0 is no output
if (verbosity >= 1 || !equivalent) {
o << name << ":\t" << status;
o << endl;
if (verbosity > 1) {
if (cmp_names.size() > 0) {
o << " " << cmp_values[0].GetCount() << " entries." << endl;
}
for (size_t i = 0; i < cmp_names.size(); i++) {
o << " " << cmp_names[i] << "\t" << cmp_values[i].GetNumDiff() << "\t" << cmp_values[i].GetCorrelation() << endl;
}
}
}
}
string name;
string msg;
bool equivalent;
double min_corr;
double max_diff;
vector<string> cmp_names;
vector<NumericalComparison<double> > cmp_values;
};
/* utility function for messages to console. */
int global_verbosity = 0;
void StatusMsg(const string &s) {
if (global_verbosity > 0) {
cout << s << endl;
}
}
/* Is the query value significantly better than the gold. */
bool SigBetter(double query, double gold, double threshold_percent) {
if (gold * (1 + threshold_percent) <= query) {
return true;
}
return false;
}
/* Compare the masks from the two directories. */
void CompareMask(SepCmpOpt &sep, const string &mask_suffix, ComparisonMsg &msg ) {
string gold_file = sep.gold_dir + "/" + mask_suffix;
string query_file = sep.query_dir + "/" + mask_suffix;
Mask q_mask, g_mask;
StatusMsg("Loading: " + gold_file);
g_mask.LoadMaskAndAbortOnFailure(gold_file.c_str());
StatusMsg("Loading: " + query_file);
q_mask.LoadMaskAndAbortOnFailure(query_file.c_str());
msg.name = "Beadfind Mask";
msg.msg = "Results: ";
msg.equivalent = true;
if (g_mask.W() != q_mask.W() || g_mask.H() != g_mask.H()) {
msg.equivalent = false;
msg.Append("Masks are different sizes.");
return;
}
msg.cmp_names.push_back("values");
msg.cmp_names.push_back("library");
msg.cmp_names.push_back("ignore");
msg.cmp_names.push_back("empty");
msg.cmp_values.resize(msg.cmp_names.size());
size_t num_entries = g_mask.H() * g_mask.W();
StatusMsg("Checking mask entries.");
for (size_t i = 0; i < num_entries; i++) {
short g = g_mask[i];
short q = q_mask[i];
msg.cmp_values[0].AddPair(g, q);
msg.cmp_values[1].AddPair(g & MaskLib ? 1 : 0, q & MaskLib ? 1 : 0 );
msg.cmp_values[2].AddPair(g & MaskIgnore ? 1 : 0, q & MaskIgnore ? 1 : 0);
msg.cmp_values[3].AddPair(g & MaskEmpty ? 1 : 0, q & MaskEmpty ? 1 : 0);
}
for (size_t cmp_idx = 0; cmp_idx < msg.cmp_values.size(); cmp_idx++) {
if (!msg.cmp_values[cmp_idx].CorrelationOk(msg.min_corr)) {
msg.equivalent = false;
msg.msg += " " + msg.cmp_names[cmp_idx] + " min: " + ToStr(msg.min_corr) + " got: " + ToStr(msg.cmp_values[cmp_idx].GetCorrelation());
}
}
}
/* Compare the summary hdf5 values from the two directories. */
void CompareSummary(SepCmpOpt &opts, const string &summary_suffix, ComparisonMsg &msg) {
string gold_file = opts.gold_dir + "/" + summary_suffix;
string query_file = opts.query_dir + "/" + summary_suffix;
Mat<float> gold_matrix, query_matrix;
StatusMsg("Reading gold file: " + gold_file);
H5Arma::ReadMatrix(gold_file + ":/separator/summary", gold_matrix);
StatusMsg("Reading query file: " + query_file);
H5Arma::ReadMatrix(query_file + ":/separator/summary", query_matrix);
msg.name = "Summary Table";
msg.msg = "Results:";
msg.equivalent = true;
if (gold_matrix.n_rows != query_matrix.n_rows) {
msg.equivalent = false;
msg.Append("Summary table are different sizes.");
return;
}
msg.cmp_names.push_back("key"); // 0
msg.cmp_names.push_back("t0"); // 1
msg.cmp_names.push_back("snr"); // 2
msg.cmp_names.push_back("mad"); // 3
msg.cmp_names.push_back("sd"); // 4
msg.cmp_names.push_back("bf_metric"); // 5
msg.cmp_names.push_back("taub_a"); // 6
msg.cmp_names.push_back("taub_c"); // 7
msg.cmp_names.push_back("taub_g"); // 8
msg.cmp_names.push_back("taub_t"); // 9
msg.cmp_names.push_back("peak_sig"); // 10
msg.cmp_names.push_back("flag");
msg.cmp_names.push_back("good_live");
msg.cmp_names.push_back("is_ref");
msg.cmp_names.push_back("buffer_metric");
msg.cmp_names.push_back("trace_sd");
msg.cmp_values.resize(msg.cmp_names.size());
size_t num_entries = gold_matrix.n_rows;
StatusMsg("Checking summary entries.");
for (size_t row_ix = 0; row_ix < num_entries; row_ix++) {
for (size_t col_ix = 0; col_ix < msg.cmp_values.size(); col_ix++) {
msg.cmp_values[col_ix].AddPair(gold_matrix.at(row_ix,col_ix), query_matrix.at(row_ix,col_ix));
}
}
for (size_t cmp_idx = 0; cmp_idx < msg.cmp_values.size(); cmp_idx++) {
if (!msg.cmp_values[cmp_idx].CorrelationOk(msg.min_corr)) {
msg.equivalent = false;
msg.msg += " " + msg.cmp_names[cmp_idx] + " min: " + ToStr(msg.min_corr) + " got: " + ToStr(msg.cmp_values[cmp_idx].GetCorrelation());
}
}
}
/* some crumbs of documentation. */
void help_msg(ostream &o) {
o << "SeparatorCmp - Program to compare separator results from different" << endl
<< " versions of separator."
<< "options:" << endl
<< " -h,--help this message." << endl
<< " -g,--gold-dir trusted results to compare against [required]" << endl
<< " -q,--query-dir new results to check [required]" << endl
<< " -c,--min-corr minimum correlation to be considered equivalent [1.0]" << endl
<< " -m,--mode if 'research' output additional info ['exact']" << endl
<< " --signficance level for significantly better or worse in research mode [.02]" << endl
<< " --verbosity level of messages to print (higher is more verbose)" << endl
;
exit(1);
}
/* Output some reseach statistics */
void OutputResearch(SepCmpOpt &opts, ComparisonMsg &mask_msg, ComparisonMsg &summary_msg) {
const SampleStats<double> &gold_lib = mask_msg.cmp_values[1].GetXStats();
const SampleStats<double> &query_lib = mask_msg.cmp_values[1].GetYStats();
const SampleStats<double> &gold_ignore = mask_msg.cmp_values[2].GetXStats();
const SampleStats<double> &query_ignore = mask_msg.cmp_values[2].GetYStats();
const SampleStats<double> &gold_snr = summary_msg.cmp_values[2].GetXStats();
const SampleStats<double> &query_snr = summary_msg.cmp_values[2].GetYStats();
const SampleStats<double> &gold_mad = summary_msg.cmp_values[3].GetXStats();
const SampleStats<double> &query_mad = summary_msg.cmp_values[3].GetYStats();
const SampleStats<double> &gold_peak_sig = summary_msg.cmp_values[10].GetXStats();
const SampleStats<double> &query_peak_sig = summary_msg.cmp_values[10].GetYStats();
fprintf(stdout, "\nSeparator Results:\n");
fprintf(stdout, "Name Gold_Value Query_Value Change \n");
fprintf(stdout, "---- ---------- ----------- --------\n");
fprintf(stdout, "Lib %10.2f %10.2f %6.2f%%\n", gold_lib.GetMean(), query_lib.GetMean(), query_lib.GetMean()/ gold_lib.GetMean() * 100.0f);
fprintf(stdout, "Ignore %10.2f %10.2f %6.2f%%\n", gold_ignore.GetMean(), query_ignore.GetMean(), query_ignore.GetMean()/ gold_ignore.GetMean() * 100.0f);
fprintf(stdout, "SNR %10.2f %10.2f %6.2f%%\n", gold_snr.GetMean(), query_snr.GetMean(), query_snr.GetMean()/ gold_snr.GetMean() * 100.0f);
fprintf(stdout, "MAD %10.2f %10.2f %6.2f%%\n", gold_mad.GetMean(), query_mad.GetMean(), query_mad.GetMean()/ gold_mad.GetMean() * 100.0f);
fprintf(stdout, "Signal %10.2f %10.2f %6.2f%%\n", gold_peak_sig.GetMean(), query_peak_sig.GetMean(), query_peak_sig.GetMean()/ gold_peak_sig.GetMean() * 100.0f);
if ((SigBetter(query_lib.GetMean(), query_lib.GetMean(), opts.threshold_percent) && !SigBetter(gold_lib.GetMean(), query_lib.GetMean(), opts.threshold_percent)) ||
(SigBetter(query_snr.GetMean(), query_snr.GetMean(), opts.threshold_percent) && !SigBetter(gold_snr.GetMean(), gold_snr.GetMean(), opts.threshold_percent)) ||
(SigBetter(query_peak_sig.GetMean(), query_peak_sig.GetMean(), opts.threshold_percent) && !SigBetter(gold_peak_sig.GetMean(), gold_peak_sig.GetMean(), opts.threshold_percent)) ||
(!SigBetter(query_mad.GetMean(), query_mad.GetMean(), opts.threshold_percent) && SigBetter(gold_mad.GetMean(), gold_mad.GetMean(), opts.threshold_percent))) {
StatusMsg("Overall: **Better**");
}
else if ((!SigBetter(query_lib.GetMean(), query_lib.GetMean(), opts.threshold_percent) && SigBetter(gold_lib.GetMean(), query_lib.GetMean(), opts.threshold_percent)) ||
(!SigBetter(query_snr.GetMean(), query_snr.GetMean(), opts.threshold_percent) && SigBetter(gold_snr.GetMean(), gold_snr.GetMean(), opts.threshold_percent)) ||
(!SigBetter(query_peak_sig.GetMean(), query_peak_sig.GetMean(), opts.threshold_percent) && SigBetter(gold_peak_sig.GetMean(), gold_peak_sig.GetMean(), opts.threshold_percent)) ||
(SigBetter(query_mad.GetMean(), query_mad.GetMean(), opts.threshold_percent) && !SigBetter(gold_mad.GetMean(), gold_mad.GetMean(), opts.threshold_percent))) {
StatusMsg("Overall: **Worse**");
}
else {
StatusMsg("Overall: **About Same**");
}
StatusMsg("");
}
/* Everybody's favorite function. */
int main (int argc, const char *argv[]) {
const string mask_suffix = "separator.mask.bin";
const string h5_suffix = "separator.h5";
OptArgs o;
bool all_ok = true;
bool exit_help = false;
SepCmpOpt opts;
/* Get our command line options. */
o.ParseCmdLine(argc, argv);
o.GetOption(opts.gold_dir, "", 'g',"gold-dir");
o.GetOption(opts.query_dir, "", 'q',"query-dir");
o.GetOption(opts.min_corr, "1", 'c', "min-corr");
o.GetOption(opts.verbosity, "1", '-', "verbosity");
o.GetOption(opts.mode, "exact", 'm', "mode");
o.GetOption(exit_help, "false", 'h', "help");
global_verbosity = opts.verbosity;
/* If something wrong or help, then help exit. */
if (exit_help || opts.gold_dir.empty() || opts.query_dir.empty()) {
help_msg(cout);
}
/* Check the masks. */
ComparisonMsg mask_msg("mask_check", opts.min_corr, 0);
mask_msg.min_corr = opts.min_corr;
CompareMask(opts, mask_suffix, mask_msg);
mask_msg.ToStr(cout,opts.verbosity);
all_ok &= mask_msg.equivalent;
/* Compare the summary tables. */
ComparisonMsg summary_msg("summary_check", opts.min_corr, 0);
mask_msg.min_corr = opts.min_corr;
CompareSummary(opts, h5_suffix, summary_msg);
summary_msg.ToStr(cout,opts.verbosity);
all_ok &= summary_msg.equivalent;
if (opts.mode == "research") {
OutputResearch(opts, mask_msg, summary_msg);
}
/* If all was ok then return 0. */
if (all_ok) {
StatusMsg("Equivalent");
}
else {
StatusMsg("Not Equivalent");
}
StatusMsg("Done.");
return !all_ok;
}
| 41.391003
| 189
| 0.65265
|
konradotto
|
350e96dc5fbc370274c3005bb8d70ee22c033f4a
| 1,317
|
cpp
|
C++
|
Projects/CoX/Common/AuthProtocol/Events/ServerListResponse.cpp
|
teronis84/Segs
|
71ac841a079fd769c3a45836ac60f34e4fff32b9
|
[
"BSD-3-Clause"
] | null | null | null |
Projects/CoX/Common/AuthProtocol/Events/ServerListResponse.cpp
|
teronis84/Segs
|
71ac841a079fd769c3a45836ac60f34e4fff32b9
|
[
"BSD-3-Clause"
] | null | null | null |
Projects/CoX/Common/AuthProtocol/Events/ServerListResponse.cpp
|
teronis84/Segs
|
71ac841a079fd769c3a45836ac60f34e4fff32b9
|
[
"BSD-3-Clause"
] | null | null | null |
#include "ServerListResponse.h"
#ifdef _MSC_VER
#include <ciso646>
#endif
void ServerListResponse::serializeto( GrowingBuffer &buf ) const
{
assert(not m_serv_list.empty());
buf.uPut((uint8_t)4);
buf.uPut((uint8_t)m_serv_list.size());
buf.uPut((uint8_t)1); //preferred server number
for(const GameServerInfo &srv : m_serv_list)
{
buf.Put(srv.id);
uint32_t addr= srv.addr;
buf.Put((uint32_t)ACE_SWAP_LONG(addr)); //must be network byte order
buf.Put((uint32_t)srv.port);
buf.Put(uint8_t(0));
buf.Put(uint8_t(0));
buf.Put(srv.current_players);
buf.Put(srv.max_players);
buf.Put((uint8_t)srv.online);
}
}
void ServerListResponse::serializefrom( GrowingBuffer &buf )
{
uint8_t op,unused;
buf.uGet(op);
uint8_t server_list_size;
buf.uGet(server_list_size);
buf.uGet(m_preferred_server_idx); //preferred server number
for(int i = 0; i < server_list_size; i++)
{
GameServerInfo srv;
buf.Get(srv.id);
buf.Get(srv.addr); //must be network byte order
buf.Get(srv.port);
buf.Get(unused);
buf.Get(unused);
buf.Get(srv.current_players);
buf.Get(srv.max_players);
buf.Get(srv.online);
m_serv_list.push_back(srv);
}
}
| 28.021277
| 76
| 0.63022
|
teronis84
|
3510a2eabe92b719c86ea523f2c6683f3aae2a66
| 1,118
|
cpp
|
C++
|
alignment/distance/levenshtein.cpp
|
TianyiShi2001/bio-algorithms-cpp-edu
|
8f1ea4de0a2ed302f8bb1416d8c3afc9492cfdbb
|
[
"Apache-2.0"
] | null | null | null |
alignment/distance/levenshtein.cpp
|
TianyiShi2001/bio-algorithms-cpp-edu
|
8f1ea4de0a2ed302f8bb1416d8c3afc9492cfdbb
|
[
"Apache-2.0"
] | null | null | null |
alignment/distance/levenshtein.cpp
|
TianyiShi2001/bio-algorithms-cpp-edu
|
8f1ea4de0a2ed302f8bb1416d8c3afc9492cfdbb
|
[
"Apache-2.0"
] | null | null | null |
/*
Levenshtein distance
# Examples
$ ./levenshtein ABCDEFG ACEG
Levenshtein Distance: 3
$ ./levenshtein ABCDEFG AZCPEGM
Levenshtein Distance: 4
*/
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
size_t levenshtein(const string& x, const string& y) {
auto m{ x.size() };
auto n{ y.size() };
vector<size_t> dp(n + 1, 0);
for (size_t i = 1; i < n; i++)
{
dp[i] = i;
}
size_t s, e;
char p, q;
for (size_t i = 1; i <= m; i++)
{
s = i - 1;
e = i;
p = x[i - 1];
for (size_t j = 1; j <= n; j++)
{
q = y[j - 1];
e = min({ e + 1, dp[j] + 1, s + (p == q ? size_t{0} : size_t{1}) });
s = dp[j];
dp[j] = e;
}
}
return dp[n];
}
int main(int argc, char* argv[]) {
if (argc < 3) {
cout << "Please provide two strings!" << endl;
return 1;
}
string x = argv[1];
string y = argv[2];
auto res = levenshtein(x, y);
cout << "Levenshtein Distance: " << res << endl;
}
| 18.633333
| 80
| 0.457066
|
TianyiShi2001
|
351588f0ee7e13e664928b9cf2fc4949825c4512
| 17,987
|
cc
|
C++
|
ana/TTrackSeedAnaModule.cc
|
macndev/Stntuple
|
b5bb000edf015883eec32d87959cb7bd3ab88577
|
[
"Apache-2.0"
] | null | null | null |
ana/TTrackSeedAnaModule.cc
|
macndev/Stntuple
|
b5bb000edf015883eec32d87959cb7bd3ab88577
|
[
"Apache-2.0"
] | null | null | null |
ana/TTrackSeedAnaModule.cc
|
macndev/Stntuple
|
b5bb000edf015883eec32d87959cb7bd3ab88577
|
[
"Apache-2.0"
] | 6
|
2019-11-21T15:27:27.000Z
|
2022-02-28T20:57:13.000Z
|
//////////////////////////////////////////////////////////////////////////////
// use of tmp:
//
// Tmp(0) : nax seg
// Tmp(1) : nst seg
//
// use of debug bits: bits 0-2 are reserved
// 0 : all events
// 1 : passed events
// 2 : rejected events
//
// 3 : events with N(track seeds) = 0
///////////////////////////////////////////////////////////////////////////////
#include "TF1.h"
#include "TCanvas.h"
#include "TPad.h"
#include "TEnv.h"
#include "TSystem.h"
#include "Stntuple/loop/TStnAna.hh"
#include "Stntuple/obj/TStnHeaderBlock.hh"
#include "Stntuple/alg/TStntuple.hh"
// #include "Stntuple/geom/TDisk.hh"
#include "Stntuple/val/stntuple_val_functions.hh"
//------------------------------------------------------------------------------
// Mu2e offline includes
//-----------------------------------------------------------------------------
#include "Stntuple/ana/TTrackSeedAnaModule.hh"
ClassImp(stntuple::TTrackSeedAnaModule)
namespace stntuple {
//-----------------------------------------------------------------------------
TTrackSeedAnaModule::TTrackSeedAnaModule(const char* name, const char* title):
TStnModule(name,title)
{
fPtMin = 1.;
// fTrackNumber.Set(100);
//-----------------------------------------------------------------------------
// MC truth: define which MC particle to consider as signal
//-----------------------------------------------------------------------------
fPdgCode = 11;
fGeneratorCode = 2; // conversionGun, 28:StoppedParticleReactionGun
}
//-----------------------------------------------------------------------------
TTrackSeedAnaModule::~TTrackSeedAnaModule() {
}
//-----------------------------------------------------------------------------
void TTrackSeedAnaModule::BookTrackSeedHistograms (TrackSeedHist_t* Hist, const char* Folder){
HBook1F(Hist->fNHits ,"nhits" ,Form("%s: # of straw hits" ,Folder), 150, 0, 150,Folder);
HBook1F(Hist->fClusterTime ,"clusterTime",Form("%s: cluster time; t_{cluster}[ns]",Folder), 800, 400, 1700,Folder);
HBook1F(Hist->fClusterEnergy ,"clusterE" ,Form("%s: cluster energy; E [MeV] ",Folder), 400, 0, 200,Folder);
HBook1F(Hist->fRadius ,"radius" ,Form("%s: curvature radius; r [mm]" ,Folder), 500, 0, 500,Folder);
HBook1F(Hist->fMom ,"p" ,Form("%s: momentum; p [MeV/c]" ,Folder), 300, 50, 200,Folder);
HBook1F(Hist->fPt ,"pT" ,Form("%s: pT; pT [MeV/c]" ,Folder), 600, 0, 150,Folder);
HBook1F(Hist->fTanDip ,"tanDip" ,Form("%s: tanDip; tanDip" ,Folder), 300, 0, 3,Folder);
HBook1F(Hist->fChi2 ,"chi2" ,Form("%s: #chi^{2}-XY; #chi^{2}/ndof" ,Folder), 100, 0, 10,Folder);
HBook1F(Hist->fFitCons ,"FitCons" ,Form("%s: Fit consistency; Fit-cons" ,Folder), 100, 0, 1, Folder);
HBook1F(Hist->fD0 ,"d0" ,Form("%s: D0; d0 [mm]" ,Folder), 1600, -400, 400,Folder);
}
//-----------------------------------------------------------------------------
void TTrackSeedAnaModule::BookGenpHistograms(GenpHist_t* Hist, const char* Folder) {
// char name [200];
// char title[200];
HBook1F(Hist->fP ,"p" ,Form("%s: Momentum" ,Folder),1000, 0, 200,Folder);
HBook1F(Hist->fPdgCode[0],"pdg_code_0",Form("%s: PDG Code[0]" ,Folder),200, -100, 100,Folder);
HBook1F(Hist->fPdgCode[1],"pdg_code_1",Form("%s: PDG Code[1]" ,Folder),500, -2500, 2500,Folder);
HBook1F(Hist->fGenID ,"gen_id" ,Form("%s: Generator ID" ,Folder), 100, 0, 100,Folder);
HBook1F(Hist->fZ0 ,"z0" ,Form("%s: Z0" ,Folder), 500, 5400, 6400,Folder);
HBook1F(Hist->fT0 ,"t0" ,Form("%s: T0" ,Folder), 200, 0, 2000,Folder);
HBook1F(Hist->fR0 ,"r" ,Form("%s: R0" ,Folder), 100, 0, 100,Folder);
HBook1F(Hist->fCosTh ,"cos_th" ,Form("%s: Cos(Theta)" ,Folder), 200, -1., 1.,Folder);
}
//-----------------------------------------------------------------------------
void TTrackSeedAnaModule::BookEventHistograms(EventHist_t* Hist, const char* Folder) {
// char name [200];
// char title[200];
HBook1F(Hist->fEleCosTh ,"ce_costh" ,Form("%s: Conversion Electron Cos(Theta)" ,Folder),100,-1,1,Folder);
HBook1F(Hist->fEleMom ,"ce_mom" ,Form("%s: Conversion Electron Momentum" ,Folder),1000, 0,200,Folder);
HBook1F(Hist->fRv ,"rv" ,Form("%s: R(Vertex)" ,Folder), 100, 0, 1000,Folder);
HBook1F(Hist->fZv ,"zv" ,Form("%s: Z(Vertex)" ,Folder), 300, 0,15000,Folder);
HBook1F(Hist->fNTrackSeeds,"nts" ,Form("%s: Number of Reco Track Seeds" ,Folder),100,0,100,Folder);
HBook1F(Hist->fNGenp ,"ngenp" ,Form("%s: N(Gen Particles)" ,Folder),500,0,500,Folder);
}
//-----------------------------------------------------------------------------
void TTrackSeedAnaModule::BookSimpHistograms(SimpHist_t* Hist, const char* Folder) {
// char name [200];
// char title[200];
HBook1F(Hist->fPdgCode ,"pdg" ,Form("%s: PDG code" ,Folder),200,-100,100,Folder);
HBook1F(Hist->fNStrawHits,"nsth" ,Form("%s: n straw hits" ,Folder),200, 0,200,Folder);
HBook1F(Hist->fMomTargetEnd ,"ptarg" ,Form("%s: CE mom after Stopping Target" ,Folder),400, 90,110,Folder);
HBook1F(Hist->fMomTrackerFront ,"pfront",Form("%s: CE mom at the Tracker Front" ,Folder),400, 90,110,Folder);
}
//_____________________________________________________________________________
void TTrackSeedAnaModule::BookHistograms() {
// char name [200];
// char title[200];
TFolder* fol;
TFolder* hist_folder;
char folder_name[200];
DeleteHistograms();
hist_folder = (TFolder*) GetFolder()->FindObject("Hist");
//--------------------------------------------------------------------------------
// book trackSeed histograms
//--------------------------------------------------------------------------------
int book_trackSeed_histset[kNTrackSeedHistSets];
for (int i=0; i<kNTrackSeedHistSets; ++i) book_trackSeed_histset[i] = 0;
book_trackSeed_histset[0] = 1; // events with at least one trackSeed
book_trackSeed_histset[1] = 1; // events with at least one trackSeed with p > 80 MeV/c
book_trackSeed_histset[2] = 1; // events with at least one trackSeed with p > 90 MeV/c
book_trackSeed_histset[3] = 1; // events with at least one trackSeed with p > 100 MeV/c
book_trackSeed_histset[4] = 1; // events with at least one trackSeed with 10 < nhits < 15
book_trackSeed_histset[5] = 1; // events with at least one trackSeed with nhits >= 15
book_trackSeed_histset[6] = 1; // events with at least one trackSeed with nhits >= 15 and chi2(ZPhi)<4
for (int i=0; i<kNTrackSeedHistSets; i++) {
if (book_trackSeed_histset[i] != 0) {
sprintf(folder_name,"trkseed_%i",i);
fol = (TFolder*) hist_folder->FindObject(folder_name);
if (! fol) fol = hist_folder->AddFolder(folder_name,folder_name);
fHist.fTrackSeed[i] = new TrackSeedHist_t;
BookTrackSeedHistograms(fHist.fTrackSeed[i],Form("Hist/%s",folder_name));
}
}
//-----------------------------------------------------------------------------
// book event histograms
//-----------------------------------------------------------------------------
int book_event_histset[kNEventHistSets];
for (int i=0; i<kNEventHistSets; i++) book_event_histset[i] = 0;
book_event_histset[ 0] = 1; // all events
for (int i=0; i<kNEventHistSets; i++) {
if (book_event_histset[i] != 0) {
sprintf(folder_name,"evt_%i",i);
fol = (TFolder*) hist_folder->FindObject(folder_name);
if (! fol) fol = hist_folder->AddFolder(folder_name,folder_name);
fHist.fEvent[i] = new EventHist_t;
BookEventHistograms(fHist.fEvent[i],Form("Hist/%s",folder_name));
}
}
//-----------------------------------------------------------------------------
// book simp histograms
//-----------------------------------------------------------------------------
int book_simp_histset[kNSimpHistSets];
for (int i=0; i<kNSimpHistSets; i++) book_simp_histset[i] = 0;
book_simp_histset[ 0] = 1; // all events
for (int i=0; i<kNSimpHistSets; i++) {
if (book_simp_histset[i] != 0) {
sprintf(folder_name,"sim_%i",i);
fol = (TFolder*) hist_folder->FindObject(folder_name);
if (! fol) fol = hist_folder->AddFolder(folder_name,folder_name);
fHist.fSimp[i] = new SimpHist_t;
BookSimpHistograms(fHist.fSimp[i],Form("Hist/%s",folder_name));
}
}
//-----------------------------------------------------------------------------
// book Genp histograms
//-----------------------------------------------------------------------------
int book_genp_histset[kNGenpHistSets];
for (int i=0; i<kNGenpHistSets; i++) book_genp_histset[i] = 0;
book_genp_histset[0] = 1; // all particles
// book_genp_histset[1] = 1; // all crystals, e > 0
// book_genp_histset[2] = 1; // all crystals, e > 0.1
// book_genp_histset[3] = 1; // all crystals, e > 1.0
for (int i=0; i<kNGenpHistSets; i++) {
if (book_genp_histset[i] != 0) {
sprintf(folder_name,"gen_%i",i);
fol = (TFolder*) hist_folder->FindObject(folder_name);
if (! fol) fol = hist_folder->AddFolder(folder_name,folder_name);
fHist.fGenp[i] = new GenpHist_t;
BookGenpHistograms(fHist.fGenp[i],Form("Hist/%s",folder_name));
}
}
}
//-----------------------------------------------------------------------------
// need MC truth branch
//-----------------------------------------------------------------------------
void TTrackSeedAnaModule::FillEventHistograms(EventHist_t* Hist) {
double cos_th(-2), xv(-1.e6), yv(-1.e6), rv(-1.e6), zv(-1.e6), p(-1.);
// double e, m, r;
TLorentzVector mom;
if (fParticle) {
fParticle->Momentum(mom);
p = mom.P();
cos_th = mom.Pz()/p;
xv = fParticle->Vx()+3904.;
yv = fParticle->Vy();
rv = sqrt(xv*xv+yv*yv);
zv = fParticle->Vz();
}
Hist->fEleMom->Fill(p);
Hist->fEleCosTh->Fill(cos_th);
Hist->fRv->Fill(rv);
Hist->fZv->Fill(zv);
Hist->fNGenp->Fill(fNGenp);
Hist->fNTrackSeeds->Fill(fNTrackSeeds);
}
//--------------------------------------------------------------------------------
// function to fill TrasckSeedHit block
//--------------------------------------------------------------------------------
void TTrackSeedAnaModule::FillTrackSeedHistograms(TrackSeedHist_t* Hist, TStnTrackSeed* TrkSeed) {
int nhits = TrkSeed->NHits ();
double clusterT = TrkSeed->ClusterTime();
double clusterE = TrkSeed->ClusterEnergy();
double mm2MeV = 3/10.;
double pT = TrkSeed->Pt();
double radius = pT/mm2MeV;
double tanDip = TrkSeed->TanDip();
double p = pT/std::cos( std::atan(tanDip));
Hist->fNHits ->Fill(nhits);
Hist->fClusterTime->Fill(clusterT);
Hist->fClusterEnergy->Fill(clusterE);
Hist->fRadius ->Fill(radius);
Hist->fMom ->Fill(p);
Hist->fPt ->Fill(pT);
Hist->fTanDip ->Fill(tanDip);
Hist->fChi2 ->Fill(TrkSeed->Chi2());
Hist->fFitCons ->Fill(TrkSeed->FitCons());
Hist->fD0 ->Fill(TrkSeed->D0());
}
//-----------------------------------------------------------------------------
void TTrackSeedAnaModule::FillGenpHistograms(GenpHist_t* Hist, TGenParticle* Genp) {
int gen_id;
float p, cos_th, z0, t0, r0, x0, y0;
TLorentzVector mom, v;
Genp->Momentum(mom);
// Genp->ProductionVertex(v);
p = mom.P();
cos_th = mom.CosTheta();
x0 = Genp->Vx()+3904.;
y0 = Genp->Vy();
z0 = Genp->Vz();
t0 = Genp->T();
r0 = sqrt(x0*x0+y0*y0);
gen_id = Genp->GetStatusCode();
Hist->fPdgCode[0]->Fill(Genp->GetPdgCode());
Hist->fPdgCode[1]->Fill(Genp->GetPdgCode());
Hist->fGenID->Fill(gen_id);
Hist->fZ0->Fill(z0);
Hist->fT0->Fill(t0);
Hist->fR0->Fill(r0);
Hist->fP->Fill(p);
Hist->fCosTh->Fill(cos_th);
}
//-----------------------------------------------------------------------------
void TTrackSeedAnaModule::FillSimpHistograms(SimpHist_t* Hist, TSimParticle* Simp) {
Hist->fPdgCode->Fill(Simp->fPdgCode);
Hist->fMomTargetEnd->Fill(Simp->fMomTargetEnd);
Hist->fMomTrackerFront->Fill(Simp->fMomTrackerFront);
Hist->fNStrawHits->Fill(Simp->fNStrawHits);
}
//-----------------------------------------------------------------------------
// register data blocks and book histograms
//-----------------------------------------------------------------------------
int TTrackSeedAnaModule::BeginJob() {
//-----------------------------------------------------------------------------
// register data blocks
//-----------------------------------------------------------------------------
RegisterDataBlock("TrackSeedBlock","TStnTrackSeedBlock",&fTrackSeedBlock );
RegisterDataBlock("GenpBlock" ,"TGenpBlock" ,&fGenpBlock );
RegisterDataBlock("SimpBlock" ,"TSimpBlock" ,&fSimpBlock );
//-----------------------------------------------------------------------------
// book histograms
//-----------------------------------------------------------------------------
BookHistograms();
return 0;
}
//_____________________________________________________________________________
int TTrackSeedAnaModule::BeginRun() {
int rn = GetHeaderBlock()->RunNumber();
TStntuple::Init(rn);
return 0;
}
//_____________________________________________________________________________
void TTrackSeedAnaModule::FillHistograms() {
// double cos_th (-2.), cl_e(-1.);
// int disk_id(-1), alg_mask, nsh, nactive;
// float pfront, ce_pitch, reco_pitch, fcons, t0, sigt, sigp, p;
//-----------------------------------------------------------------------------
// event histograms
//-----------------------------------------------------------------------------
FillEventHistograms(fHist.fEvent[0]);
//-----------------------------------------------------------------------------
// Simp histograms
//-----------------------------------------------------------------------------
if (fSimp) {
FillSimpHistograms(fHist.fSimp[0],fSimp);
}
//--------------------------------------------------------------------------------
// track seed histograms
//--------------------------------------------------------------------------------
TStnTrackSeed* trkSeed;
for (int i=0; i<fNTrackSeeds; ++i) {
trkSeed = fTrackSeedBlock->TrackSeed(i);
FillTrackSeedHistograms(fHist.fTrackSeed[0], trkSeed);
int nhits = trkSeed->NHits();
double p = trkSeed->P();
double chi2 = trkSeed->Chi2();
if (p > 80.) FillTrackSeedHistograms(fHist.fTrackSeed[1], trkSeed);
if (p > 90.) FillTrackSeedHistograms(fHist.fTrackSeed[2], trkSeed);
if (p > 100.) FillTrackSeedHistograms(fHist.fTrackSeed[3], trkSeed);
if ( (nhits>10) && (nhits < 15)) FillTrackSeedHistograms(fHist.fTrackSeed[4], trkSeed);
if ( nhits>=15 ) FillTrackSeedHistograms(fHist.fTrackSeed[5], trkSeed);
if ( (chi2 < 4) && (nhits >= 15)) FillTrackSeedHistograms(fHist.fTrackSeed[6], trkSeed);
}
//-----------------------------------------------------------------------------
// fill GENP histograms
// GEN_0: all particles
//-----------------------------------------------------------------------------
TGenParticle* genp;
for (int i=0; i<fNGenp; i++) {
genp = fGenpBlock->Particle(i);
FillGenpHistograms(fHist.fGenp[0],genp);
}
}
//-----------------------------------------------------------------------------
// 2014-04-30: it looks that reading the straw hits takes a lot of time -
// turn off by default by commenting it out
//-----------------------------------------------------------------------------
int TTrackSeedAnaModule::Event(int ientry) {
double p;
// TEmuLogLH::PidData_t dat;
// TStnTrack* track;
// int id_word;
TLorentzVector mom;
// TDiskCalorimeter::GeomData_t disk_geom;
fTrackSeedBlock->GetEntry(ientry);
fGenpBlock->GetEntry(ientry);
fSimpBlock->GetEntry(ientry);
//-----------------------------------------------------------------------------
// assume electron in the first particle, otherwise the logic will need to
// be changed
//-----------------------------------------------------------------------------
fNGenp = fGenpBlock->NParticles();
fNTrackSeeds = fTrackSeedBlock->NTrackSeeds();
TGenParticle* genp;
int pdg_code, generator_code;
fParticle = NULL;
for (int i=fNGenp-1; i>=0; i--) {
genp = fGenpBlock->Particle(i);
pdg_code = genp->GetPdgCode();
generator_code = genp->GetStatusCode();
if ((abs(pdg_code) == fPdgCode) && (generator_code == fGeneratorCode)) {
fParticle = genp;
break;
}
}
// may want to revisit the definition of fSimp
fSimp = fSimpBlock->Particle(0);
if (fParticle) {
fParticle->Momentum(mom);
p = mom.P();
}
else p = 0.;
fEleE = sqrt(p*p+0.511*0.511);
FillHistograms();
Debug();
return 0;
}
//-----------------------------------------------------------------------------
void TTrackSeedAnaModule::Debug() {
if (GetDebugBit(3)) {
if (fNTrackSeeds == 0) GetHeaderBlock()->Print(Form("%s:bit:003 N(track seeds) = 0",GetName()));
}
}
//_____________________________________________________________________________
int TTrackSeedAnaModule::EndJob() {
printf("----- end job: ---- %s\n",GetName());
return 0;
}
//_____________________________________________________________________________
void TTrackSeedAnaModule::Test001() {
}
}
| 40.329596
| 123
| 0.503364
|
macndev
|
351cab46d129ddc96f83eb09c2af0bf60c0e6794
| 2,671
|
hpp
|
C++
|
src/common/backtrace/backtrace.hpp
|
acezen/libvineyard
|
eda51c5d858c7d0456aa871610355556ed0f4835
|
[
"Apache-2.0",
"CC0-1.0"
] | null | null | null |
src/common/backtrace/backtrace.hpp
|
acezen/libvineyard
|
eda51c5d858c7d0456aa871610355556ed0f4835
|
[
"Apache-2.0",
"CC0-1.0"
] | null | null | null |
src/common/backtrace/backtrace.hpp
|
acezen/libvineyard
|
eda51c5d858c7d0456aa871610355556ed0f4835
|
[
"Apache-2.0",
"CC0-1.0"
] | null | null | null |
/** Copyright 2020 Alibaba Group Holding Limited.
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.
*/
#ifndef SRC_COMMON_BACKTRACE_BACKTRACE_HPP_
#define SRC_COMMON_BACKTRACE_BACKTRACE_HPP_
#ifdef WITH_LIBUNWIND
#include <cxxabi.h>
#include <libunwind.h>
#include <iomanip>
#include <limits>
#include <memory>
#include <ostream>
namespace vineyard {
struct backtrace_info {
public:
static void backtrace(std::ostream& _out,
bool const compact = false) noexcept {
thread_local char symbol[1024];
unw_cursor_t cursor;
unw_context_t context;
unw_getcontext(&context);
unw_init_local(&cursor, &context);
_out << std::hex << std::uppercase;
while (0 < unw_step(&cursor)) {
unw_word_t ip = 0;
unw_get_reg(&cursor, UNW_REG_IP, &ip);
if (ip == 0) {
break;
}
unw_word_t sp = 0;
unw_get_reg(&cursor, UNW_REG_SP, &sp);
print_reg(_out, ip);
_out << ": (SP:";
print_reg(_out, sp);
_out << ") ";
unw_word_t offset = 0;
if (unw_get_proc_name(&cursor, symbol, sizeof(symbol), &offset) == 0) {
_out << "(" << get_demangled_name(symbol) << " + 0x" << offset << ")\n";
if (!compact) {
_out << "\n";
}
} else {
_out << "-- error: unable to obtain symbol name for this frame\n\n";
}
}
_out << std::flush;
}
static char const* get_demangled_name(char const* const symbol) noexcept {
thread_local std::unique_ptr<char, decltype(std::free)&> demangled_name{
nullptr, std::free};
if (!symbol) {
return "<null>";
}
int status = -4;
demangled_name.reset(abi::__cxa_demangle(symbol, demangled_name.release(),
nullptr, &status));
return ((status == 0) ? demangled_name.get() : symbol);
}
private:
static void print_reg(std::ostream& _out, unw_word_t reg) noexcept {
constexpr std::size_t address_width =
std::numeric_limits<std::uintptr_t>::digits / 4;
_out << "0x" << std::setfill('0') << std::setw(address_width) << reg;
}
};
} // namespace vineyard
#endif
#endif // SRC_COMMON_BACKTRACE_BACKTRACE_HPP_
| 29.677778
| 80
| 0.643205
|
acezen
|
3524ea825467f5174db113c933daa1dfe9c0ffb3
| 15,546
|
cc
|
C++
|
src/database-server/data-source/sqlitewrapper.cc
|
denisacostaq/DAQs
|
9c767562e91dc8532272492ef5bff6dcf9f7e7d4
|
[
"MIT"
] | 2
|
2019-07-15T02:10:17.000Z
|
2019-07-23T14:27:20.000Z
|
src/database-server/data-source/sqlitewrapper.cc
|
denisacostaq/DAQs
|
9c767562e91dc8532272492ef5bff6dcf9f7e7d4
|
[
"MIT"
] | 42
|
2019-06-21T13:26:27.000Z
|
2020-03-27T02:02:55.000Z
|
src/database-server/data-source/sqlitewrapper.cc
|
denisacostaq/DAQs
|
9c767562e91dc8532272492ef5bff6dcf9f7e7d4
|
[
"MIT"
] | null | null | null |
/*! \brief This file have the implementation for SQLiteWrapper class.
\file sqlitewrapper.cc
\author Alvaro Denis <denisacostaq@gmail.com>
\date 6/19/2019
\copyright
\attention <h1><center><strong>COPYRIGHT © 2019 </strong>
[<strong>denisacostaq</strong>][denisacostaq-URL].
All rights reserved.</center></h1>
\attention This file is part of [<strong>DAQs</strong>][DAQs-URL].
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 University nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS PRODUCT 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 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 PRODUCT, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
[denisacostaq-URL]: https://about.me/denisacostaq "Alvaro Denis Acosta"
[DAQs-URL]: https://github.com/denisacostaq/DAQs "DAQs"
*/
#include "src/database-server/data-source/sqlitewrapper.h"
#include <cerrno>
#include <cstring>
#include <exception>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <sqlite3.h>
#include "src/database-server/data-model/variable.h"
#include "src/database-server/data-model/varvalue.h"
SQLiteWrapper::SQLiteWrapper(const std::string &db_path) : IDataSource() {
int err = sqlite3_open(db_path.c_str(), &db_);
if (err != SQLITE_OK) {
std::cerr << sqlite3_errmsg(db_) << "\n";
std::cerr << std::strerror(sqlite3_system_errno(db_)) << "\n";
throw std::string{"Can't open database " + db_path};
} else {
std::clog << "Opened database successfully\n";
}
}
SQLiteWrapper::~SQLiteWrapper() { sqlite3_close(db_); }
IDataSource::Err SQLiteWrapper::create_scheme() noexcept {
std::vector<std::string> stataments;
stataments.reserve(2);
std::string sql =
"CREATE TABLE VARIABLE("
"ID INTEGER PRIMARY KEY AUTOINCREMENT,"
"COLOR CHAR(50),"
"NAME CHAR(50) NOT NULL UNIQUE);";
stataments.push_back(sql);
sql =
"CREATE TABLE VARIABLE_VALUE("
"ID INTEGER PRIMARY KEY AUTOINCREMENT,"
"VAL DOUBLE NOT NULL,"
"TIMESTAMP INTEGER NOT NULL,"
"VARIABLE_ID INT NOT NULL,"
"FOREIGN KEY (VARIABLE_ID) REFERENCES VARIABLE(ID));"; // FIXME(denisacostaq@gmail.com):
// add constrints
stataments.push_back(sql);
for (const auto &s : stataments) {
char *err = nullptr;
int rc = sqlite3_exec(db_, s.c_str(), nullptr, nullptr, &err);
if (rc != SQLITE_OK) {
std::cerr << "SQL error: " << err << "\n";
sqlite3_free(err);
return Err::Failed;
} else {
std::clog << "Table created successfully\n";
}
}
return Err::Ok;
}
IDataSource::Err SQLiteWrapper::add_variable(const Variable &var) noexcept {
std::string sql =
sqlite3_mprintf("INSERT INTO VARIABLE(NAME, COLOR) VALUES('%q', '%q')",
var.name().c_str(), var.color().c_str());
char *err = nullptr;
int res = sqlite3_exec(db_, sql.c_str(), nullptr, nullptr, &err);
if (res != SQLITE_OK) {
std::cerr << "Can not insert " << var.name() << ". " << err << "\n";
sqlite3_free(err);
return Err::Failed;
}
std::clog << "Insertion ok\n";
return Err::Ok;
}
IDataSource::Err SQLiteWrapper::add_variable_value(
const VarValue &var) noexcept {
auto now{std::chrono::system_clock::now()};
auto timestamp{std::chrono::duration_cast<std::chrono::milliseconds>(
now.time_since_epoch())};
char *err_msg = nullptr;
std::string sql = sqlite3_mprintf(
"INSERT INTO VARIABLE_VALUE(VAL, TIMESTAMP, VARIABLE_ID) VALUES(%f, %ld, "
"(SELECT ID FROM VARIABLE WHERE NAME = '%q'))",
var.val(), timestamp.count(), var.name().c_str());
if (sqlite3_exec(db_, sql.c_str(), nullptr, this, &err_msg) != SQLITE_OK) {
std::cerr << "error " << err_msg << "\n";
sqlite3_free(err_msg);
return Err::Failed;
}
return Err::Ok;
}
IDataSource::Err SQLiteWrapper::fetch_variables(
const std::function<void(const Variable &var, size_t index)>
&send_vale) noexcept {
char *err_msg = nullptr;
std::string query = "SELECT COLOR, NAME FROM VARIABLE";
using callbac_t = decltype(send_vale);
using unqualified_callbac_t =
std::remove_const_t<std::remove_reference_t<callbac_t>>;
if (sqlite3_exec(
db_, query.c_str(),
+[](void *callback, int argc, char **argv, char **azColName) {
Variable var{};
for (decltype(argc) i = 0; i < argc; i++) {
if (strcmp("NAME", azColName[i]) == 0) {
std::string name{""};
if (argv[i] != nullptr && std::strcmp(argv[i], "")) {
name = argv[i];
}
var.set_name(name);
} else if (strcmp("COLOR", azColName[i]) == 0) {
if (strcmp("COLOR", azColName[i]) == 0) {
std::string color{""};
if (argv[i] != nullptr && std::strcmp(argv[i], "")) {
color = argv[i];
}
var.set_color(color);
}
} else {
return -1;
}
}
static_cast<callbac_t> (
*static_cast<unqualified_callbac_t *>(callback))(var, 0);
return 0;
},
const_cast<unqualified_callbac_t *>(&send_vale),
&err_msg) != SQLITE_OK) {
std::cerr << "error " << err_msg << "\n";
sqlite3_free(err_msg);
return Err::Failed;
}
return Err::Ok;
}
namespace {
struct CountCallback {
size_t index;
std::function<void(const VarValue &val, size_t)> *send_vale;
};
}; // namespace
IDataSource::Err SQLiteWrapper::fetch_variable_values(
const std::string &var_name,
const std::function<void(const VarValue &val, size_t index)>
&send_vale) noexcept {
char *err_msg = nullptr;
std::string query = sqlite3_mprintf(
"SELECT VAL, TIMESTAMP FROM VARIABLE_VALUE WHERE VARIABLE_ID = (SELECT "
"ID FROM VARIABLE WHERE NAME = '%q')",
var_name.c_str());
CountCallback cc{
0,
const_cast<std::function<void(const VarValue &, size_t)> *>(&send_vale)};
if (sqlite3_exec(db_, query.c_str(),
+[](void *cc, int argc, char **argv, char **azColName) {
VarValue val{};
for (int i = 0; i < argc; i++) {
if (strcmp("VAL", azColName[i]) == 0) {
try {
size_t processed = 0;
val.set_val(std::stod(argv[i], &processed));
} catch (std::invalid_argument e) {
std::cerr << e.what();
return -1;
} catch (std::out_of_range e) {
std::cerr << e.what();
return -1;
}
} else if (strcmp("TIMESTAMP", azColName[i]) == 0) {
try {
size_t processed = 0;
val.set_timestamp(std::stoull(argv[i], &processed));
} catch (std::invalid_argument e) {
std::cerr << e.what();
return -1;
} catch (std::out_of_range e) {
std::cerr << e.what();
return -1;
}
}
}
auto count_callback{static_cast<CountCallback *>(cc)};
auto cb{count_callback->send_vale};
(*cb)(val, count_callback->index);
++count_callback->index;
return 0;
},
&cc, &err_msg) != SQLITE_OK) {
std::cerr << "error " << err_msg << "\n";
sqlite3_free(err_msg);
return Err::Failed;
}
return Err::Ok;
}
IDataSource::Err SQLiteWrapper::count_variable_values(
const std::string &var_name,
const std::function<void(size_t count)> &send_count) noexcept {
char *err_msg = nullptr;
std::string count_query = sqlite3_mprintf(
"SELECT COUNT(*) FROM VARIABLE_VALUE WHERE VARIABLE_ID = (SELECT "
"ID FROM VARIABLE WHERE NAME = '%q')",
var_name.c_str());
if (sqlite3_exec(
db_, count_query.c_str(),
+[](void *callback, int argc, char **argv, char **azColName) {
for (int i = 0; i < argc; ++i) {
if (strcmp("COUNT(*)", azColName[i]) == 0) {
size_t count{};
try {
size_t processed = 0;
count = std::stoull(argv[i], &processed);
} catch (std::invalid_argument e) {
std::cerr << e.what();
return -1;
} catch (std::out_of_range e) {
std::cerr << e.what();
return -1;
}
(*static_cast<std::function<void(size_t count)> *>(callback))(
count);
return 0;
}
}
return 0;
},
const_cast<std::function<void(size_t count)> *>(&send_count),
&err_msg) != SQLITE_OK) {
std::cerr << "error " << err_msg << "\n";
sqlite3_free(err_msg);
return Err::Failed;
}
return Err::Ok;
}
IDataSource::Err SQLiteWrapper::fetch_variable_values(
const std::string &var_name,
const std::chrono::system_clock::time_point &start_date,
const std::chrono::system_clock::time_point &end_date,
const std::function<void(const VarValue &val, size_t index)>
&send_vale) noexcept {
char *err_msg = nullptr;
const std::int64_t sd{
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::time_point_cast<std::chrono::milliseconds>(start_date)
.time_since_epoch())
.count()};
const std::int64_t ed{
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::time_point_cast<std::chrono::milliseconds>(end_date)
.time_since_epoch())
.count()};
std::string query = sqlite3_mprintf(
"SELECT VAL, TIMESTAMP FROM VARIABLE_VALUE WHERE VARIABLE_ID = (SELECT "
"ID FROM VARIABLE WHERE NAME = '%q') AND TIMESTAMP >= %ld AND TIMESTAMP "
"<= %ld;",
var_name.c_str(), sd, ed);
CountCallback cc{
0,
const_cast<std::function<void(const VarValue &, size_t)> *>(&send_vale)};
if (sqlite3_exec(db_, query.c_str(),
+[](void *cc, int argc, char **argv, char **azColName) {
VarValue val{};
for (int i = 0; i < argc; i++) {
if (strcmp("VAL", azColName[i]) == 0) {
try {
size_t processed = 0;
val.set_val(std::stod(argv[i], &processed));
} catch (std::invalid_argument e) {
std::cerr << e.what();
return -1;
} catch (std::out_of_range e) {
std::cerr << e.what();
return -1;
}
} else if (strcmp("TIMESTAMP", azColName[i]) == 0) {
try {
size_t processed = 0;
val.set_timestamp(std::stoull(argv[i], &processed));
} catch (std::invalid_argument e) {
std::cerr << e.what();
return -1;
} catch (std::out_of_range e) {
std::cerr << e.what();
return -1;
}
}
}
auto count_callback{static_cast<CountCallback *>(cc)};
auto cb{count_callback->send_vale};
(*cb)(val, count_callback->index);
++count_callback->index;
return 0;
},
&cc, &err_msg) != SQLITE_OK) {
std::cerr << "error " << err_msg << "\n";
sqlite3_free(err_msg);
return Err::Failed;
}
return Err::Ok;
}
IDataSource::Err SQLiteWrapper::count_variable_values(
const std::string &var_name,
const std::chrono::system_clock::time_point &start_date,
const std::chrono::system_clock::time_point &end_date,
const std::function<void(size_t count)> &send_count) noexcept {
char *err_msg = nullptr;
const std::int64_t sd{std::chrono::duration_cast<std::chrono::milliseconds>(
start_date.time_since_epoch())
.count()};
const std::int64_t ed{std::chrono::duration_cast<std::chrono::milliseconds>(
end_date.time_since_epoch())
.count()};
std::string count_query = sqlite3_mprintf(
"SELECT COUNT(*) FROM VARIABLE_VALUE WHERE VARIABLE_ID = (SELECT ID FROM "
"VARIABLE WHERE NAME = '%q') AND TIMESTAMP >= %ld AND TIMESTAMP <= %ld;",
var_name.c_str(), sd, ed);
if (sqlite3_exec(
db_, count_query.c_str(),
+[](void *callback, int argc, char **argv, char **azColName) {
for (int i = 0; i < argc; ++i) {
if (strcmp("COUNT(*)", azColName[i]) == 0) {
size_t count{};
try {
size_t processed = 0;
count = std::stoull(argv[i], &processed);
} catch (std::invalid_argument e) {
std::cerr << e.what();
return -1;
} catch (std::out_of_range e) {
std::cerr << e.what();
return -1;
}
(*static_cast<std::function<void(size_t count)> *>(callback))(
count);
return 0;
}
}
return 0;
},
const_cast<std::function<void(size_t)> *>(&send_count),
&err_msg) != SQLITE_OK) {
std::cerr << "error " << err_msg << "\n";
sqlite3_free(err_msg);
return Err::Failed;
}
return Err::Ok;
}
| 39.96401
| 95
| 0.538209
|
denisacostaq
|
352eb217fc7fec112baba5f6eaa82a3af6913fc4
| 17,529
|
cpp
|
C++
|
VTK_Operation.cpp
|
jhpark16/PHT3D-Viewer-3D
|
2f62d95364b664f3cc50af2d77f280c2fb62b543
|
[
"MIT"
] | null | null | null |
VTK_Operation.cpp
|
jhpark16/PHT3D-Viewer-3D
|
2f62d95364b664f3cc50af2d77f280c2fb62b543
|
[
"MIT"
] | null | null | null |
VTK_Operation.cpp
|
jhpark16/PHT3D-Viewer-3D
|
2f62d95364b664f3cc50af2d77f280c2fb62b543
|
[
"MIT"
] | null | null | null |
// VTK_Operation.cpp : implmentation of VTK operations to visualize a 3D model
//
// Author: Jungho Park (jhpark16@gmail.com)
// Date: May 2015
// Description:
//
/////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "resource.h"
VTK_Operation::VTK_Operation(HWND hwnd, HWND hwndParent)
{
CreateVTKObjects(hwnd, hwndParent);
}
void VTK_Operation::clear(void)
{
// vtkSmartPointers are deleted by assigning nullptr
// (or any other object) to the pointer
#ifdef OpenVR
actor.~vtkNew();
renderWindow.~vtkNew();
renderer.~vtkNew();
interactor.~vtkNew();
cam.~vtkNew();
// destroy text actor and mapper
// Additional variables
//reader = nullptr;
//mapper = nullptr;
//colors = nullptr;
#else
renderWindow.~vtkNew();
renderer.~vtkNew();
interactor.~vtkNew();
// destroy text actor and mapper
textMapper.~vtkNew();
textActor2D.~vtkNew();
scalarBar.~vtkNew();
// Additional variables
//reader = nullptr;
//mapper = nullptr;
//colors = nullptr;
actor.~vtkNew();
//backFace = nullptr;
#endif
}
VTK_Operation::~VTK_Operation()
{
clear();
}
int VTK_Operation::CreateVTKObjects(HWND hwnd, HWND hwndParent)
{
// We create the basic parts of a pipeline and connect them
#ifdef OpenVR
/* vtkNew<vtkActor> actor;
vtkNew<vtkOpenVRRenderer> renderer;
vtkNew<vtkOpenVRRenderWindow> renderWindow;
vtkNew<vtkOpenVRRenderWindowInteractor> interactor;
vtkNew<vtkOpenVRCamera> cam;*/
/* renderer = vtkSmartPointer<vtkOpenVRRenderer>::New();
renderWindow = vtkSmartPointer<vtkOpenVRRenderWindow>::New();
interactor = vtkSmartPointer<vtkOpenVRRenderWindowInteractor>::New();
cam = vtkSmartPointer<vtkOpenVRCamera>::New();*/
#else
/*
actor = vtkSmartPointer<vtkActor>::New();
renderer = vtkSmartPointer<vtkOpenGLRenderer>::New();
renderWindow = vtkSmartPointer<vtkWin32OpenGLRenderWindow>::New();
interactor = vtkSmartPointer<vtkWin32RenderWindowInteractor>::New();
*/
renderWindow->Register(NULL);
#endif
#ifdef OpenVR
renderWindow->AddRenderer(renderer.Get());
renderer->AddActor(actor.Get());
interactor->SetRenderWindow(renderWindow.Get());
renderer->SetActiveCamera(cam.Get());
vtkNew<vtkConeSource> cone;
vtkNew<vtkPolyDataMapper> mapper;
mapper->SetInputConnection(cone->GetOutputPort());
actor->SetMapper(mapper.Get());
//Reset camera to show the model at the centre
renderer->ResetCamera();
#else
renderWindow->AddRenderer(renderer);
interactor->SetInstallMessageProc(0);
// setup the parent window
renderWindow->SetWindowId(hwnd);
renderWindow->SetParentId(hwndParent);
interactor->SetRenderWindow(renderWindow);
interactor->Initialize();
vtkNew<vtkInteractorStyleTrackballCamera> style;
interactor->SetInteractorStyle(style);
// Setup Text Actor
//textMapper = vtkSmartPointer<vtkTextMapper>::New();
textMapper->SetInput("MODFLOW Model");
//textActor2D = vtkSmartPointer<vtkActor2D>::New();
textActor2D->SetDisplayPosition(450, 550);
textMapper->GetTextProperty()->SetFontSize(30);
textMapper->GetTextProperty()->SetColor(1.0, 1.0, 1.0);
textActor2D->SetMapper(textMapper);
// Add Axis
//axes = vtkSmartPointer<vtkAxesActor>::New();
axes->SetNormalizedLabelPosition(1.2, 1.2, 1.2);
axes->GetXAxisCaptionActor2D()->SetHeight(0.025);
axes->GetYAxisCaptionActor2D()->SetHeight(0.025);
axes->GetZAxisCaptionActor2D()->SetHeight(0.025);
#ifndef OpenVR
//widget = vtkSmartPointer<vtkOrientationMarkerWidget>::New();
widget->SetOutlineColor(0.9300, 0.5700, 0.1300);
widget->SetOrientationMarker(axes);
widget->SetInteractor(interactor);
widget->SetEnabled(1);
#endif
// Prevent the interaction to fix the location of the coordinate axes triad
// at the left bottom
//widget->InteractiveOff(); // Trigger WM_SIZE
widget->SetViewport(-0.8, -0.8, 0.25, 0.25);
//Add the Actors
renderer->AddActor(textActor2D);
//renderer->SetBackground(colors->GetColor3d("Wheat").GetData());
renderer->SetBackground(.1, .2, .4);
//Reset camera to show the model at the centre
renderer->ResetCamera();
#endif
//renderer->SetBackground(0.0, 0.0, 0.25);
return(1);
}
int VTK_Operation::DestroyVTKObjects()
{
ATLTRACE("DestroyVTKObjects\n");
return(1);
}
int VTK_Operation::StepObjects(int count)
{
return(1);
}
void VTK_Operation::WidgetInteractiveOff(void)
{
#ifndef OpenVR
widget->InteractiveOff(); // Trigger WM_SIZE
#endif
}
void VTK_Operation::Render()
{
if (renderWindow) {
renderWindow->Render();
//interactor->Render();
}
}
void VTK_Operation::OnSize(CSize size)
{
if (renderWindow) {
//int *val1;
//val1 = renderWindow->GetSize();
renderWindow->SetSize(size.cx, size.cy);
if (textMapper && renderer->GetVTKWindow()) {
int width = textMapper->GetWidth(renderer);
this->size = size;
textActor2D->SetDisplayPosition((size.cx - width) / 2, size.cy - 50);
//interactor->UpdateSize(size.cx, size.cy);
//interactor->SetSize(size.cx, size.cy);
}
}
}
void VTK_Operation::OnTimer(HWND hWnd, UINT uMsg)
{
#ifndef OpenVR
interactor->OnTimer(hWnd, uMsg);
#endif
}
void VTK_Operation::OnLButtonDblClk(HWND hWnd, UINT uMsg, CPoint point)
{
#ifndef OpenVR
interactor->OnLButtonDown(hWnd, uMsg, point.x, point.y, 1);
#endif
}
void VTK_Operation::OnLButtonDown(HWND hWnd, UINT uMsg, CPoint point)
{
#ifndef OpenVR
interactor->OnLButtonDown(hWnd, uMsg, point.x, point.y, 0);
#endif
}
void VTK_Operation::OnMButtonDown(HWND hWnd, UINT uMsg, CPoint point)
{
#ifndef OpenVR
interactor->OnMButtonDown(hWnd, uMsg, point.x, point.y, 0);
#endif
}
void VTK_Operation::OnRButtonDown(HWND hWnd, UINT uMsg, CPoint point)
{
#ifndef OpenVR
interactor->OnRButtonDown(hWnd, uMsg, point.x, point.y, 0);
#endif
}
void VTK_Operation::OnLButtonUp(HWND hWnd, UINT uMsg, CPoint point)
{
#ifndef OpenVR
interactor->OnLButtonUp(hWnd, uMsg, point.x, point.y);
#endif
}
void VTK_Operation::OnMButtonUp(HWND hWnd, UINT uMsg, CPoint point)
{
#ifndef OpenVR
interactor->OnMButtonUp(hWnd, uMsg, point.x, point.y);
#endif
}
void VTK_Operation::OnRButtonUp(HWND hWnd, UINT uMsg, CPoint point)
{
#ifndef OpenVR
interactor->OnRButtonUp(hWnd, uMsg, point.x, point.y);
#endif
}
void VTK_Operation::OnMouseMove(HWND hWnd, UINT uMsg, CPoint point)
{
#ifndef OpenVR
interactor->OnMouseMove(hWnd, uMsg, point.x, point.y);
#endif
}
void VTK_Operation::OnChar(HWND hWnd, UINT nChar, UINT nRepCnt, UINT nFlags)
{
#ifndef OpenVR
interactor->OnChar(hWnd, nChar, nRepCnt, nFlags);
#endif
}
void VTK_Operation::FileNew()
{
renderer->RemoveActor(actor);
renderer->RemoveActor(scalarBar);
}
void VTK_Operation::FileOpen(PHT3D_Model& mPHT3DM, CString fileName)
{
// Model Data
//read all the data from the file
/*
vtkSmartPointer<vtkXMLUnstructuredGridReader> reader =
vtkSmartPointer<vtkXMLUnstructuredGridReader>::New();
reader->SetFileName(_T("D:\\Study\\MODFLOW\\RegionalGroundwaterModelingwithMODFLOWandFlopy\\vtuFiles\\Model1_HD_Heads.vtu"));
reader->Update();
vtkSmartPointer<vtkUnstructuredGrid> output = reader->GetOutput();
output->GetCellData()->SetScalars(output->GetCellData()->GetArray(0));
*/
//vtkUnstructuredGrid construction
vtkNew<vtkUnstructuredGrid> unstGrid;
vtkNew<vtkFloatArray> fArr;
vtkNew<vtkDoubleArray> dArr;
vtkNew<vtkIntArray> iArr;
vtkNew<vtkCellArray> cellArr;
vtkNew<vtkIdTypeArray> cellIdType;
vtkNew<vtkPoints> points;
MODFLOWClass& mf = mPHT3DM.MODFLOW;
double minVal=0, maxVal = 0;
if (1) {
OpenModel(mPHT3DM, fileName);
int nCol = mf.DIS_NCOL + 1;
int nRow = mf.DIS_NROW + 1;
int nLay = mf.DIS_NLAY + 1;
float *xLoc = new float[nCol]{};
float *yLoc = new float[nRow]{};
float *zLoc = new float[nRow*nCol]{};
xLoc[0] = 0; yLoc[0] = 0;
for (int i = 0; i < nCol-1; i++) {
xLoc[i + 1] = xLoc[i] + mf.DIS_DELR[i];
}
for (int i = 0; i < nRow-1; i++) {
yLoc[i + 1] = yLoc[i] + mf.DIS_DELC[i];
}
// Reverse Y for correct model display
for (int i = 0; i < (nRow-1)/2; i++) {
int iTmp = yLoc[i];
yLoc[i] = yLoc[nRow - 1 - i];
yLoc[nRow - 1 - i] = iTmp;
}
int nPoints = (mf.DIS_NLAY + 1)*(mf.DIS_NROW + 1)*(mf.DIS_NCOL + 1);
unique_ptr<float[]> locations(new float[3 * nPoints]);
//float *locations = new float[3 * nPoints]{};
unique_ptr<int[]> connectivity(new int[9 * ((nLay - 1)*(nRow - 1)*(nCol - 1))]);
unique_ptr<double[]> dVal(new double[((nLay - 1)*(nRow - 1)*(nCol - 1))]);
//int *connectivity = new int[9*((nLay - 1)*(nRow - 1)*(nCol - 1))]{};
//int *connectivity = new int[(nLay-1)*(nRow-1)*(nCol-1)] {};
// The heights are not aligned at each nodal points. So, it is necessary to estimate the height
// at each node using interpolation of heights
CPPMatrix2<double> *elevation = &(mf.DIS_TOP);
for (int k = 0; k < nLay; k++) {
// Takes care of four corners
if (k == 0) {
// The elevation of the top layer is from the DIS_TOP
elevation = &(mf.DIS_TOP);
}
else {
// The bottom elevation is used for most layers
elevation = &(mf.DIS_BOTMS[k - 1]);
}
zLoc[0 * nCol + 0] = (*elevation)[0][0];
zLoc[0 * nCol + (nCol-1)] = (*elevation)[0][nCol-2];
zLoc[(nRow - 1) * nCol + 0] = (*elevation)[nRow-2][0];
zLoc[(nRow - 1) * nCol + (nCol-1)] = (*elevation)[nRow-2][nCol-2];
// Interpolate edges along X direction
for (int i = 1; i < nCol-1; i++) {
zLoc[0*nCol + i] = ((*elevation)[0][i-1] +
(*elevation)[0][i])/2.0;
zLoc[(nRow-1)*nCol + i] = ((*elevation)[nRow-2][i-1] +
(*elevation)[nRow - 2][i])/2.0;
}
// Interpolate edges along Y direction
for (int j = 1; j < nRow - 1; j++) {
zLoc[(j * nCol) + 0] = ((*elevation)[j-1][0] +
(*elevation)[j][0]) / 2.0;
zLoc[(j * nCol) + nCol-1] = ((*elevation)[j-1][nCol-2] +
(*elevation)[j][nCol-2]) / 2.0;
}
// Interpolate the remaining part of the 3D model
for (int j = 1; j < nRow-1; j++) {
for (int i = 1; i < nCol-1; i++) {
zLoc[(j * nCol) + i] = ((*elevation)[j - 1][i - 1] +
(*elevation)[j][i - 1] + (*elevation)[j - 1][i] +
(*elevation)[j][i]) / 4.0;
}
}
// Set the X, Y, Z of all nodal points
for (int j = 0; j < nRow; j++) {
for (int i = 0; i < nCol; i++) {
locations[3 * (k*(nRow*nCol) + j*(nCol)+i) + 0] = xLoc[i]; //X value
locations[3 * (k*(nRow*nCol) + j*(nCol)+i) + 1] = yLoc[j]; //Y value
locations[3 * (k*(nRow*nCol) + j*(nCol)+i) + 2] = zLoc[j*nCol+i]; //Z value
}
}
}
int numCells = 0;
minVal = DBL_MAX;
maxVal = -DBL_MAX;
for (int k = 0; k < nLay-1; k++) {
for (int j = 0; j < nRow-1; j++) {
for (int i = 0; i < nCol-1; i++) {
if (mf.BAS_IBOUND[k][j][i]) {
connectivity[9 * numCells + 0] = 8;
connectivity[9 * numCells + 1] = (k + 1)*(nRow*nCol) + (j + 1)*nCol + (i);
connectivity[9 * numCells + 2] = (k + 1)*(nRow*nCol) + (j + 1)*nCol + (i + 1);
connectivity[9 * numCells + 3] = (k+1)*(nRow*nCol) + (j)*nCol + (i+1);
connectivity[9 * numCells + 4] = (k + 1)*(nRow*nCol) + (j)*nCol + (i);
connectivity[9 * numCells + 5] = (k)*(nRow*nCol) + (j + 1)*nCol + (i);
connectivity[9 * numCells + 6] = (k)*(nRow*nCol) + (j + 1)*nCol + (i + 1);
connectivity[9 * numCells + 7] = (k)*(nRow*nCol) + (j)*nCol + (i + 1);
connectivity[9 * numCells + 8] = (k)*(nRow*nCol) + (j)*nCol + (i);
double tVal = mf.BAS_STRT[k][j][i];
dVal[numCells] = tVal;
if (tVal < minVal) minVal = tVal;
if (tVal > maxVal) maxVal = tVal;
numCells++;
}
}
}
}
cellIdType->SetArray(connectivity.get(), numCells*9, 1);
connectivity.release();
fArr->SetNumberOfComponents(3); //3D data points
fArr->SetArray(locations.get(), 3 * nPoints, 0);
locations.release(); // Must release the pointer to prevent crash
points->SetData(fArr); // The array should be allocated on the heap
points->SetDataTypeToFloat();
// Setup cell array using the raw data
cellArr->SetCells(numCells, cellIdType);
dArr->SetNumberOfComponents(1);
dArr->SetArray(dVal.get(), numCells, 1);
dVal.release(); // Must release the pointer to prevent crash
for (int i = 1; i < numCells; i++) {
}
//dArr->SetTuple1(0, 0.1); dArr->SetTuple1(1, 0.5);
// Assemble the unstructured grid
unstGrid->SetPoints(points);
unstGrid->SetCells(12, cellArr); // 12 is the cell type
unstGrid->GetCellData()->SetScalars(dArr);
}
else {
int nPoints = 12;
int numCells = 2;
//cellIdType->SetNumberOfValues(18);
int *iCon = new int[numCells*9]{ 8, 0, 1, 2, 3, 4, 5, 6, 7,
8, 4, 5, 6, 7, 8, 9, 10, 11 };
cellIdType->SetArray(iCon, numCells * 9, 1);
/*
cellIdType->SetValue(0, 8); cellIdType->SetValue(1, 0); cellIdType->SetValue(2, 1);
cellIdType->SetValue(3, 2); cellIdType->SetValue(4, 3); cellIdType->SetValue(5, 4);
cellIdType->SetValue(6, 5); cellIdType->SetValue(7, 6); cellIdType->SetValue(8, 7);
cellIdType->SetValue(9, 8); cellIdType->SetValue(10, 4); cellIdType->SetValue(11, 5);
cellIdType->SetValue(12, 6); cellIdType->SetValue(13, 7); cellIdType->SetValue(14, 8);
cellIdType->SetValue(15, 9); cellIdType->SetValue(16, 10); cellIdType->SetValue(17, 11);
*/
cellArr->SetCells(numCells, cellIdType);
// Set points
double *(val[12]);
float *fPos = new float[nPoints * 3]{ 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0,
1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0,
2, 0, 0, 2, 0, 1, 2, 1, 1, 2, 1, 0 };
fArr->SetNumberOfComponents(3); //3D data points
//fArr->SetNumberOfTuples(12); // 12 set of 3D data points (not necessary)
fArr->SetArray(fPos, nPoints*3, 0);
points->SetData(fArr); // The array should be allocated on the heap
points->SetDataTypeToFloat();
/*
for (int i = 0; i<12; i++)
val[i] = points->GetPoint(i);
points->SetNumberOfPoints(12);
points->SetPoint(0, 0, 0, 0.); points->SetPoint(1, 0, 0, 1.); points->SetPoint(2, 0, 1, 1.);
points->SetPoint(3, 0, 1, 0.); points->SetPoint(4, 1, 0, 0.); points->SetPoint(5, 1, 0, 1.);
points->SetPoint(6, 1, 1, 1.); points->SetPoint(7, 1, 1, 0.); points->SetPoint(8, 2, 0, 0.);
points->SetPoint(9, 2, 0, 1.); points->SetPoint(10, 2, 1, 1.); points->SetPoint(11, 2, 1, 0.);
points->SetDataTypeToFloat(); // Point set should be float type
for (int i = 0; i<12; i++)
val[i] = points->GetPoint(i);
*/
cellArr->SetCells(numCells, cellIdType);
dArr->SetNumberOfComponents(1);
//dArr->SetNumberOfTuples(2);
minVal = 0, maxVal = 1;
dArr->SetArray(new double[numCells] {0.1,0.5}, numCells, 1);
//dArr->SetTuple1(0, 0.1); dArr->SetTuple1(1, 0.5);
unstGrid->SetPoints(points);
unstGrid->SetCells(12, cellArr); // 12 is the cell type
unstGrid->GetCellData()->SetScalars(dArr);
}
// Setup Model Actor
vtkNew<vtkDataSetMapper> mapper;
//mapper->SetInputConnection(reader->GetOutputPort());
mapper->SetInputData(unstGrid);
//mapper->ScalarVisibilityOff();
mapper->ScalarVisibilityOn();
// Scale bar actor for the Colormap
//scalarBar = vtkSmartPointer<vtkScalarBarActor>::New();
scalarBar->SetLookupTable(mapper->GetLookupTable());
scalarBar->SetUnconstrainedFontSize(true);
scalarBar->SetTitle("Head (ft)");
scalarBar->SetVerticalTitleSeparation(5);
scalarBar->GetTitleTextProperty()->SetFontSize(20);
scalarBar->GetTitleTextProperty()->ItalicOff();
scalarBar->SetLabelFormat("%.1f");
scalarBar->GetLabelTextProperty()->ItalicOff();
scalarBar->GetLabelTextProperty()->SetFontSize(15);
scalarBar->SetPosition(0.87, 0.2);
scalarBar->SetHeight(0.5);
scalarBar->SetWidth(0.11);
scalarBar->SetNumberOfLabels(4);
// Jet color scheme
vtkNew<vtkLookupTable> jet;
jet->SetNumberOfColors(257);
jet->Build();
for (int i = 0; i <= 64; i++) {
jet->SetTableValue(i, 0, i / 64.0, 1, 1);
}
for (int i = 65; i <= 128; i++) {
jet->SetTableValue(i, 0, 1, 1.0 - (i - 64.0) / 64.0, 1);
}
for (int i = 129; i <= 192; i++) {
jet->SetTableValue(i, (i - 128.0) / 64.0, 1, 0, 1);
}
for (int i = 193; i <= 256; i++) {
jet->SetTableValue(i, 1, 1 - (i - 192.0) / 64.0, 0, 1);
}
//jet->SetTableRange(3407.6445, 4673.021);
mapper->SetLookupTable(jet);
scalarBar->SetLookupTable(jet);
mapper->SetColorModeToMapScalars();
//mapper->SetScalarRange(3407.6445, 4673.021); // min max range cannot be switched
mapper->SetScalarRange(minVal, maxVal); // min max range cannot be switched
mapper->SetUseLookupTableScalarRange(false);
// Set scalar mode
mapper->SetScalarModeToUseCellData();
//mapper->SetScalarModeToUsePointData();
actor->SetMapper(mapper);
// True for grid lines
if (true) {
actor->GetProperty()->SetLineWidth(0.001); // This should not be zero => OpenGL error (invalid value)
actor->GetProperty()->EdgeVisibilityOn();
}
else
actor->GetProperty()->EdgeVisibilityOff();
// Backface setup
vtkNew<vtkNamedColors> colors;
vtkNew<vtkProperty> backFace;
backFace->SetColor(colors->GetColor3d("tomato").GetData());
actor->SetBackfaceProperty(backFace);
renderer->AddActor(actor);
renderer->AddActor(scalarBar);
//Reset camera to show the model at the centre
renderer->ResetCamera();
#ifdef OpenVR
renderWindow->Render();
interactor->Start();
#endif
}
| 33.011299
| 127
| 0.641223
|
jhpark16
|
352ee369a17dd68ee11d4caa98cd63e6c8139c18
| 128
|
hpp
|
C++
|
libraries/hayai/src/hayai-fixture.hpp
|
nuernber/Theia
|
4bac771b09458a46c44619afa89498a13cd39999
|
[
"BSD-3-Clause"
] | 1
|
2021-02-02T13:30:52.000Z
|
2021-02-02T13:30:52.000Z
|
libraries/hayai/src/hayai-fixture.hpp
|
nuernber/Theia
|
4bac771b09458a46c44619afa89498a13cd39999
|
[
"BSD-3-Clause"
] | null | null | null |
libraries/hayai/src/hayai-fixture.hpp
|
nuernber/Theia
|
4bac771b09458a46c44619afa89498a13cd39999
|
[
"BSD-3-Clause"
] | 1
|
2020-09-28T08:43:13.000Z
|
2020-09-28T08:43:13.000Z
|
#include "hayai-test.hpp"
#ifndef __HAYAI_FIXTURE
#define __HAYAI_FIXTURE
namespace Hayai
{
typedef Test Fixture;
}
#endif
| 12.8
| 25
| 0.765625
|
nuernber
|
3530a42f19105f68de15729c843f332ac5da3526
| 1,361
|
cpp
|
C++
|
1052/Seminar3/Seminar3/Source.cpp
|
catalinboja/cpp_2018
|
e4525fa48bc4a42ce84e4b9320c90761dde2ba93
|
[
"Apache-2.0"
] | null | null | null |
1052/Seminar3/Seminar3/Source.cpp
|
catalinboja/cpp_2018
|
e4525fa48bc4a42ce84e4b9320c90761dde2ba93
|
[
"Apache-2.0"
] | null | null | null |
1052/Seminar3/Seminar3/Source.cpp
|
catalinboja/cpp_2018
|
e4525fa48bc4a42ce84e4b9320c90761dde2ba93
|
[
"Apache-2.0"
] | 2
|
2018-11-21T16:43:45.000Z
|
2019-06-30T08:44:11.000Z
|
#include <iostream>
using namespace std;
void printArray(int* array, int n, const char* message);
//a function that inits an array
void initArray(int* array, int n, int value) {
for (int i = 0; i < n; i++) {
array[i] = value;
}
}
//IT'S WRONG
//DON'T USE IT
int resizeArray(int* array, int n) {
int newSize;
cout << endl << "New size is:";
cin >> newSize;
//delete[] array;
//array = new int[newSize];
cout << endl << "Values:";
for (int i = 0; i < newSize; i++) {
cout << endl << "value " << i + 1 << ": ";
cin >> array[i];
}
return newSize;
}
int main() {
std::cout << endl << "Hello World !";
int array1[5];
int n1 = 5;
int array2[10];
int n2 = 10;
int n3 = 5;
int* array3 = new int[n3];
//init the arrays
initArray(array1, n1, 1);
initArray(array2, n2, 20);
initArray(array3, n3, 50);
cout << endl << "Array 1:";
for (int i = 0; i < n1; i++)
cout << array1[i] << " ";
//they have the same type
//array3 = array1;
printArray(array2, n2, "Array 2:");
printArray(array3, n3, "Array 3:");
//resize them
n1 = resizeArray(array2, n2);
printArray(array1, n1, "Array 1:");
printArray(array2, n2, "Array 2:");
}
//function for printing an array
void printArray(int* array, int n, const char* message) {
//message[0] = 'A';
cout << endl << message;
for (int i = 0; i < n; i++)
cout << array[i] << " ";
}
| 18.391892
| 57
| 0.58266
|
catalinboja
|
35316c5c53df9191da565bef5f333ee9e71b0e3f
| 1,070
|
cpp
|
C++
|
POO 2 - Survival Game/Map.cpp
|
xaddee/Survival-Game
|
633beb24f93e313a0764521625c1d45d64875ba9
|
[
"MIT"
] | 1
|
2018-12-13T19:31:29.000Z
|
2018-12-13T19:31:29.000Z
|
POO 2 - Survival Game/Map.cpp
|
xaddee/Survival-Game
|
633beb24f93e313a0764521625c1d45d64875ba9
|
[
"MIT"
] | null | null | null |
POO 2 - Survival Game/Map.cpp
|
xaddee/Survival-Game
|
633beb24f93e313a0764521625c1d45d64875ba9
|
[
"MIT"
] | null | null | null |
#include "Map.h"
Map::Map()
{
_size = 0;
}
Map::~Map()
{
for (int i = 0; i < _size; i++)
{
delete[] _map_matrix[i];
}
delete[] _map_matrix;
}
void Map::resize(int size)
{
_size = size;
_map_matrix = new char*[size];
for (int i = 0; i < size; i++)
{
_map_matrix[i] = new char[size];
for (int j = 0; j < size; j++)
{
_map_matrix[i][j] = ' ';
if (j == 0 || j == size - 1)
_map_matrix[i][j] = '=';
if (i == 0 || i == size - 1)
_map_matrix[i][j] = '=';
}
}
}
int Map::showSize()
{
return _size;
}
void Map::show()
{
for (int i = 0; i < _size; i++)
{
for (int j = 0; j < _size; j++)
{
std::cout << _map_matrix[i][j];
}
std::cout << std::endl;
}
}
void Map::setValueAtCoords(Position position, char value)
{
_map_matrix[position.x][position.y] = value;
}
char Map::showValueAtCoords(Position position)
{
if (position.x > _size - 2 || position.y > _size - 2 || position.x < 1 || position.y < 1)
return 'n'; // functia returneaza 'n' pt tot ce e in afara mapei
return _map_matrix[position.x][position.y];
}
| 15.507246
| 90
| 0.55514
|
xaddee
|
35321a538499b25e6b808f7ffead51b6339a414c
| 450
|
hpp
|
C++
|
Util/timer.hpp
|
arumakan1727/kyopro-cpplib
|
b39556b3616c231579937fb86b696c692aa4ef74
|
[
"MIT"
] | null | null | null |
Util/timer.hpp
|
arumakan1727/kyopro-cpplib
|
b39556b3616c231579937fb86b696c692aa4ef74
|
[
"MIT"
] | null | null | null |
Util/timer.hpp
|
arumakan1727/kyopro-cpplib
|
b39556b3616c231579937fb86b696c692aa4ef74
|
[
"MIT"
] | null | null | null |
#pragma once
#include <chrono>
/**
* @brief Timer (実行時間計測)
*/
class Timer {
std::chrono::system_clock::time_point m_start;
public:
Timer() = default;
inline void start() {
m_start = std::chrono::system_clock::now();
}
inline uint64_t elapsedMilli() const {
using namespace std::chrono;
const auto end = system_clock::now();
return duration_cast<milliseconds>(end - m_start).count();
}
};
| 19.565217
| 66
| 0.617778
|
arumakan1727
|
35326c829dc6ab9ccfadeb519a0ecc1242f9474d
| 446
|
cpp
|
C++
|
1301/1301A Three Strings/1301A Three Strings.cpp
|
Poohdxx/codeforces
|
e0d95eba325d5e720e5589798c7c06894de882f4
|
[
"MIT"
] | null | null | null |
1301/1301A Three Strings/1301A Three Strings.cpp
|
Poohdxx/codeforces
|
e0d95eba325d5e720e5589798c7c06894de882f4
|
[
"MIT"
] | null | null | null |
1301/1301A Three Strings/1301A Three Strings.cpp
|
Poohdxx/codeforces
|
e0d95eba325d5e720e5589798c7c06894de882f4
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <string>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
int t;
cin >> t;
for (int i = 0; i < t; i++) {
string a, b, c;
cin >> a >> b >> c;
int n = a.size();
bool pass = true;
for (int j = 0; j < n; j++) {
if (c[j] != a[j] && c[j] != b[j]) {
pass = false;
break;
}
}
if (pass) {
cout << "YES" << endl;
}
else {
cout << "NO" << endl;
}
}
return 0;
}
| 14.387097
| 38
| 0.466368
|
Poohdxx
|