hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 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 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 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 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4be4f6d0c663dc6f11321869cdc9aa68e3a41206 | 8,648 | cpp | C++ | src/Pegasus/Compiler/cimmofRepositoryInterface.cpp | natronkeltner/openpegasus | e64f383c1ed37826041fc63e83b4e65fc1c679ae | [
"ICU",
"Unlicense",
"OpenSSL",
"MIT"
] | 1 | 2021-11-12T21:28:50.000Z | 2021-11-12T21:28:50.000Z | src/Pegasus/Compiler/cimmofRepositoryInterface.cpp | natronkeltner/openpegasus | e64f383c1ed37826041fc63e83b4e65fc1c679ae | [
"ICU",
"Unlicense",
"OpenSSL",
"MIT"
] | 39 | 2021-01-18T19:28:41.000Z | 2022-03-27T20:55:36.000Z | src/Pegasus/Compiler/cimmofRepositoryInterface.cpp | natronkeltner/openpegasus | e64f383c1ed37826041fc63e83b4e65fc1c679ae | [
"ICU",
"Unlicense",
"OpenSSL",
"MIT"
] | 4 | 2021-07-09T12:52:33.000Z | 2021-12-21T15:05:59.000Z | //%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements. Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// License.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////
//
//%/////////////////////////////////////////////////////////////////////////////
#include <Pegasus/Common/Config.h>
#include <Pegasus/Common/CIMQualifierDecl.h>
#include <Pegasus/Common/CIMClass.h>
#include <Pegasus/Common/CIMInstance.h>
#include "cimmofRepository.h"
#include "cimmofClient.h"
#include "cimmofParser.h"
#include "cimmofMessages.h"
#include "cimmofRepositoryInterface.h"
#ifdef PEGASUS_ENABLE_MRR_GENERATION
# include "cimmofMRR.h"
#endif
PEGASUS_USING_PEGASUS;
cimmofRepositoryInterface::cimmofRepositoryInterface() :
_repository(0),
_client(0),
_mrr(0),
_ot(compilerCommonDefs::USE_REPOSITORY)
{
}
cimmofRepositoryInterface::~cimmofRepositoryInterface()
{
delete _repository;
delete _client;
#ifdef PEGASUS_ENABLE_MRR_GENERATION
delete _mrr;
#endif
}
// The descriptions parameter controls inclusion of descriptions in
// mof output. When false, descriptions are not used. Today it is
// used only with the MRR Generation because that is where size is
// critical and the description qualifiers add significant size.
void cimmofRepositoryInterface::init(_repositoryType type, String location,
Uint32 mode,
compilerCommonDefs::operationType ot,
bool descriptions)
{
String message;
cimmofMessages::arglist arglist;
_ot = ot;
if (type == REPOSITORY_INTERFACE_LOCAL)
{
// create a cimmofRepository object and put it in _repository
cimmofParser *p = cimmofParser::Instance();
const String NameSpace = p->getDefaultNamespacePath();
if (location != "")
{
try
{
_repository = new cimmofRepository(location, mode, _ot);
}
catch(Exception &e)
{
arglist.append(location);
arglist.append(e.getMessage());
cimmofMessages::getMessage(message,
cimmofMessages::REPOSITORY_CREATE_ERROR,
arglist);
p->elog(message);
delete _repository;
_repository = 0;
}
}
}
else if (type == REPOSITORY_INTERFACE_CLIENT)
{
// create a CIMClient object and put it in _client
_client = new cimmofClient();
try
{
_client->init(ot);
}
catch (const CannotConnectException &)
{
delete _client;
_client = 0;
throw;
}
catch(Exception &e)
{
arglist.append(location);
arglist.append(e.getMessage());
cimmofMessages::getMessage(message,
cimmofMessages::REPOSITORY_CREATE_ERROR,
arglist);
cimmofParser *p = cimmofParser::Instance();
p->elog(message);
delete _client;
_client = 0;
}
}
#ifdef PEGASUS_ENABLE_MRR_GENERATION
else if (type == REPOSITORY_INTERFACE_MRR)
{
// create memory-resident repository handler.
_mrr = new cimmofMRR(descriptions);
}
else // Not valid type
{
arglist.append(location);
arglist.append("Compiler Internal Error");
cimmofMessages::getMessage(message,
cimmofMessages::REPOSITORY_CREATE_ERROR,
arglist);
cimmofParser *p = cimmofParser::Instance();
p->elog(message);
}
#else
else // not valid type
{
// hide the compiler warning that the descriptions parameter is not
// used except with MRR generation
(void)descriptions;
// Generate error message and Terminate
arglist.append(location);
arglist.append("Compiler Internal Error");
cimmofMessages::getMessage(message,
cimmofMessages::REPOSITORY_CREATE_ERROR,
arglist);
cimmofParser *p = cimmofParser::Instance();
p->elog(message);
}
#endif
}
void cimmofRepositoryInterface::addClass(const CIMNamespaceName &nameSpace,
CIMClass &Class) const
{
if (_repository)
_repository->addClass(nameSpace, &Class);
if (_client)
_client->addClass(nameSpace, Class);
#ifdef PEGASUS_ENABLE_MRR_GENERATION
if (_mrr)
_mrr->addClass(nameSpace, Class);
#endif
}
void cimmofRepositoryInterface::addQualifier(const CIMNamespaceName &nameSpace,
CIMQualifierDecl &qualifier) const
{
if (_repository)
_repository->addQualifier(nameSpace, &qualifier);
if (_client)
_client->addQualifier(nameSpace, qualifier);
#ifdef PEGASUS_ENABLE_MRR_GENERATION
if (_mrr)
_mrr->addQualifier(nameSpace, qualifier);
#endif
}
void cimmofRepositoryInterface::addInstance(const CIMNamespaceName &nameSpace,
CIMInstance &instance) const
{
if (_repository)
_repository->addInstance(nameSpace, &instance);
if (_client)
_client->addInstance(nameSpace, instance);
#ifdef PEGASUS_ENABLE_MRR_GENERATION
if (_mrr)
_mrr->addInstance(nameSpace, instance);
#endif
}
CIMQualifierDecl cimmofRepositoryInterface::getQualifierDecl(
const CIMNamespaceName &nameSpace,
const CIMName &qualifierName) const
{
if (_repository)
return (_repository->getQualifierDecl(nameSpace, qualifierName));
else if (_client)
return (_client->getQualifierDecl(nameSpace, qualifierName));
#ifdef PEGASUS_ENABLE_MRR_GENERATION
else if (_mrr)
return (_mrr->getQualifierDecl(nameSpace, qualifierName));
#endif
else
return CIMQualifierDecl();
}
CIMClass cimmofRepositoryInterface::getClass(const CIMNamespaceName &nameSpace,
const CIMName &className) const
{
if (_repository)
return (_repository->getClass(nameSpace, className));
else if (_client)
return (_client->getClass(nameSpace, className));
#ifdef PEGASUS_ENABLE_MRR_GENERATION
else if (_mrr)
return (_mrr->getClass(nameSpace, className));
#endif
else
return CIMClass();
}
void cimmofRepositoryInterface::modifyClass(const CIMNamespaceName &nameSpace,
CIMClass &Class) const
{
if (_repository)
{
_repository->modifyClass(nameSpace, &Class);
}
if (_client)
{
_client->modifyClass(nameSpace, Class);
}
#ifdef PEGASUS_ENABLE_MRR_GENERATION
if (_mrr)
{
_mrr->modifyClass(nameSpace, Class);
}
#endif
}
void cimmofRepositoryInterface::createNameSpace(
const CIMNamespaceName &nameSpace) const
{
if (_repository)
_repository->createNameSpace(nameSpace);
else if (_client)
{
_client->createNameSpace(nameSpace);
}
#ifdef PEGASUS_ENABLE_MRR_GENERATION
else if (_mrr)
{
_mrr->createNameSpace(nameSpace);
}
#endif
}
void cimmofRepositoryInterface::start()
{
#ifdef PEGASUS_ENABLE_MRR_GENERATION
if (_mrr)
_mrr->start();
#endif
}
void cimmofRepositoryInterface::finish()
{
#ifdef PEGASUS_ENABLE_MRR_GENERATION
if (_mrr)
_mrr->finish();
#endif
}
| 30.34386 | 80 | 0.652058 | [
"object"
] |
4be4f751056e2a5ae55f750e7f2f2f09a6636698 | 26,418 | cpp | C++ | Source/gameplay/GameBoard.cpp | leduyquang753/tetrec | 9f1da4485b1a6412af5b244ad99aa462b65a374b | [
"MIT"
] | 16 | 2021-08-03T07:44:15.000Z | 2022-01-17T15:14:17.000Z | Source/gameplay/GameBoard.cpp | leduyquang753/tetrec | 9f1da4485b1a6412af5b244ad99aa462b65a374b | [
"MIT"
] | 1 | 2021-08-03T23:36:55.000Z | 2021-08-04T03:01:36.000Z | Source/gameplay/GameBoard.cpp | leduyquang753/tetrec | 9f1da4485b1a6412af5b244ad99aa462b65a374b | [
"MIT"
] | null | null | null | #include <algorithm>
#include <cmath>
#include <cstdint>
#include <memory>
#include <random>
#include <string>
#include <utility>
#include "common/Graphics.h"
#include "gameplay/PlayScreen.h"
#include "gameplay/PlayScreenHelpers.h"
#include "gameplay/Tetrimino.h"
#include "gameplay/GameBoard.h"
using namespace std::string_literals;
std::array<long, 11> GameBoard::rewardAmounts = {
100, 300, 500, 800,
100, 200, 400,
400, 800, 1200, 1600
};
std::array<bool, 11> GameBoard::rewardTriggersBackToBack = {
false, false, false, true,
false, false, true,
false, true, true, true
};
std::array<char, 3> GameBoard::rewardIndexMapping = {-1, 4, 7};
std::array<std::array<std::string, 2>, 11> GameBoard::rewardNames = {{
{""s, ""s}, {""s, ""s}, {""s, ""s}, {"TETRIS"s, ""s},
{"T-spin"s, "mini"s}, {"T-spin"s, "mini single"s},
{"T-spin"s, "mini double"s},
{"T-spin"s, ""s}, {"T-spin"s, "single"s},
{"T-spin"s, "double"s}, {"T-spin"s, "triple"s},
}};
std::array<std::array<float, 3>, 24> GameBoard::cubeData = {{
{0, 1, -1}, {1, 1, -1}, {1, 0, -1}, {0, 0, -1},
{0, 1, 0}, {0, 1, -1}, {0, 0, -1}, {0, 0, 0},
{1, 1, 0}, {0, 1, 0}, {0, 0, 0}, {1, 0, 0},
{1, 1, -1}, {1, 1, 0}, {1, 0, 0}, {1, 0, -1},
{1, 1, -1}, {0, 1, -1}, {0, 1, 0}, {1, 1, 0},
{0, 0, -1}, {1, 0, -1}, {1, 0, 0}, {0, 0, 0}
}};
std::array<std::array<float, 2>, 4> GameBoard::textureCoords = {{
{0.25, 0}, {0, 0}, {0, 0.25}, {0.25, 0.25}
}};
Texture GameBoard::minoTexture;
bool GameBoard::staticResourcesLoaded = false;
GameBoard::GameBoard(PlayScreen *const owner):
owner(owner),
autoRepeatDelay(owner->commonResources.settings.autoRepeatDelay),
autoRepeatPeriod(owner->commonResources.settings.autoRepeatPeriod),
stopMovementOnRotate(owner->commonResources.settings.stopMovementOnRotate),
stopMovementOnHardDrop(
owner->commonResources.settings.stopMovementOnHardDrop
),
renderGhostTetrimino(owner->commonResources.settings.ghostTetrimino),
previewTetriminoes(owner->commonResources.settings.previews)
{
if (!staticResourcesLoaded) {
loadStaticResources();
staticResourcesLoaded = true;
}
springX.doBumps = springY.doBumps
= owner->commonResources.settings.doBoardBumps;
std::uniform_int_distribution<std::uint32_t> seedGenerator(0);
random.seed(seedGenerator(owner->randomEngine));
}
void GameBoard::loadStaticResources() {
minoTexture.load("Assets/Minoes.png"s);
}
void GameBoard::init() {
pushToQueue();
}
void GameBoard::start() {
nextTetrimino();
}
void GameBoard::advanceGameTime(const long timePassed) {
if (over) {
if ((lost || animateClearOnFinish) && clearAnimationTime != 0)
clearAnimationTime = std::max(0l, clearAnimationTime - timePassed);
return;
}
for (const auto &event : eventEmitters)
event->processTimePassed(*this, timePassed);
if (clearAnimationTime != 0)
clearAnimationTime = std::max(0l, clearAnimationTime - timePassed);
owner->advanceGameTime(timePassed);
}
long GameBoard::getNextEventTime() {
nextEvent = nullptr;
long lowestTime;
for (const auto &event : eventEmitters) {
long time = event->getNextEventTime(*this);
if (time != -1 && (nextEvent == nullptr || time < lowestTime)) {
nextEvent = event.get();
lowestTime = time;
}
}
return nextEvent == nullptr ? -1 : lowestTime;
}
void GameBoard::processNextEvent() {
nextEvent->processEvent(*this);
}
long GameBoard::getSoftDropScore() {
return 1;
}
void GameBoard::fall() {
if (current == nullptr) return;
if (++current->y > tetriminoMaxY) {
tetriminoMaxY = current->y;
moveCounter = 0;
}
current->onMove();
wasBlocked = false;
if (buttonStates.softDrop) score += getSoftDropScore();
fallTimes.push_back(owner->gameTime);
long oneSecondAgo = owner->gameTime - 1000;
while (!fallTimes.empty() && fallTimes.front() < oneSecondAgo)
fallTimes.pop_front();
if (!current->canFall(*this)) {
springY.knock(-0.2*fallTimes.size());
fallTimes.clear();
}
}
void GameBoard::countMove() {
if (tetriminoOnGround && moveCounter != 15) {
lockTime = 0;
moveCounter++;
}
}
void GameBoard::move(const char &offset) {
if (current == nullptr) {
wasBlocked = true;
return;
}
const char newX = current->x + offset;
if (current->checkCollision(*this, newX, current->y, current->state)) {
wasBlocked = true;
} else {
current->x = newX;
current->onMove();
if (current->checkCollision(
*this, newX + offset, current->y, current->state
)) springX.knock(offset * 2);
countMove();
if (owner->moveSoundsWaiting != 1) owner->moveSoundsWaiting++;
}
}
void GameBoard::stopMovement() {
auto &buttonStates = owner->commonResources.keybindingHandler.buttonStates;
buttonStates.moveLeft = buttonStates.moveRight = false;
}
void GameBoard::onRotate() {
countMove();
wasBlocked = false;
if (stopMovementOnRotate) stopMovement();
if (owner->rotateSoundsWaiting != 1) owner->rotateSoundsWaiting++;
if (current->getTSpinType(*this) != 0)
owner->playSound(owner->tSpinningSound);
}
void GameBoard::rotateClockwise() {
if (current == nullptr || current->rotateClockwise(*this) == 0) return;
onRotate();
}
void GameBoard::rotateCounterClockwise() {
if (
current == nullptr || current->rotateCounterClockwise(*this) == 0
) return;
onRotate();
}
long GameBoard::getHardDropScore(const int count) {
return 2 * count;
}
void GameBoard::hardDrop() {
if (current == nullptr) return;
int count = 0;
while (current->canFall(*this)) {
current->y++;
count++;
}
if (count) current->onMove();
score += getHardDropScore(count);
springY.knock(-0.3*count-0.2*fallTimes.size());
const char left = current->x;
for (const auto &piece : current->getHardDropDepthData()) {
const int pos = left + piece[0];
hardDropTrails.push_back({
pos, pos + 1,
40 - current->getCurrentTopY(), count, piece[1], 400
});
}
lock();
if (stopMovementOnHardDrop) stopMovement();
}
void GameBoard::doHold() {
if (current == nullptr) return;
if (holdSwitched) return;
auto oldHold = std::move(hold);
hold = std::move(current);
hold->reset();
if (oldHold == nullptr) {
nextTetrimino();
} else {
current = std::move(oldHold);
fallTime = 0;
lockTime = 0;
moveCounter = 0;
checkGameOver();
}
wasBlocked = false;
holdSwitched = true;
fallTimes.clear();
}
void GameBoard::activateZone() {}
void GameBoard::lock() {
if (current == nullptr) return;
const char baseline = current->getCurrentBaseY();
const char color = current->getColor();
const char tSpinType = current->getTSpinType(*this);
for (const auto &offset : current->getMinoes()) {
const char
x = current->x + offset.x,
y = current->y + offset.y;
board[y][x] = color;
board[y].minoCount++;
}
totalMinoes += 4;
const int clearedLineCount = clearLines();
owner->playFallSound();
addReward(rewardIndexMapping[tSpinType] + clearedLineCount);
if (tSpinType != 0 && shouldDoClearActions)
owner->playSound(owner->tSpinSound);
if (clearedLineCount != 0) {
if ((totalMinoes -= 10*clearedLineCount) == 0) {
awardAllClear();
if (!allClearDisplays.empty())
(allClearDisplays.end()-1)->fadeOut();
allClearDisplays.emplace_back();
}
current = nullptr;
if (shouldDoClearActions) {
clearTime = 500;
clearAnimationTime = 500;
lines += clearedLineCount;
}
}
if (baseline < 20) {
current = nullptr;
gameOver();
return;
}
if (clearTime == 0) nextTetrimino();
}
void GameBoard::spawnLineClearParticles(
const float flyRange,
const long lifetimeBase, const long lifetimeRange
) {
if (clearedLines.empty()) return;
for (const char &line : clearedLines) {
const float
particleYBase = 39 - line + springY.position,
flyTotalRange = flyRange * 2;
for (int i = 0; i != 1000; i++) {
const long lifetime
= lifetimeBase
+ lifetimeRange*owner->floatRandom(owner->randomEngine);
owner->spawnParticle({
springX.position
+ 10.f*owner->floatRandom(owner->randomEngine),
particleYBase
+ owner->floatRandom(owner->randomEngine),
owner->floatRandom(owner->randomEngine),
-flyRange
+ flyTotalRange*owner->floatRandom(owner->randomEngine),
-flyRange
+ flyTotalRange*owner->floatRandom(owner->randomEngine),
-flyRange
+ flyTotalRange*owner->floatRandom(owner->randomEngine),
0.3f * owner->floatRandom(owner->randomEngine),
lifetime, lifetime
});
}
}
}
int GameBoard::clearLines() {
int clearedLineCount = 0;
int nextY = 39;
clearedLines.clear();
for (int y = 39; y != -1; y--) {
if (board[y].minoCount == 10) {
board[y].clear();
clearedLineCount++;
clearedLines.push_back(y);
} else {
board[y].clearingOffset = nextY - y;
std::swap(board[y], board[nextY--]);
}
}
return clearedLineCount;
}
void GameBoard::addReward(const int reward) {
long rewardAmount = 0;
if (reward != -1) {
rewardAmount = rewardAmounts[reward];
const std::array<std::string, 2> rewardName = rewardNames[reward];
if (!rewardName[0].empty()) {
if (!rewardDisplays.empty())
(rewardDisplays.end()-1)->fadeOut();
rewardDisplays.emplace_back(rewardName[0], rewardName[1]);
}
if (rewardTriggersBackToBack[reward]) {
if (backToBack) {
rewardAmount += rewardAmount >> 1;
if (!backToBackDisplays.empty())
(backToBackDisplays.end()-1)->fadeOut();
backToBackDisplays.emplace_back();
} else {
backToBack = true;
}
} else backToBack = backToBack && reward > 2;
}
if (reward != -1 && reward != 4 && reward != 7) {
if (++combo > 0) {
if (combo == 1) {
comboTextOldAlpha = getCurrentComboTextAlpha();
comboTextFadingIn = true;
comboTextFadeTime = 0;
} else {
(comboNumbers.end()-1)->fadeOut();
}
rewardAmount += 50 * combo;
comboNumbers.emplace_back(combo);
}
} else if (combo != -1) {
if (combo > 0) {
(comboNumbers.end()-1)->fadeOut();
comboTextOldAlpha = getCurrentComboTextAlpha();
comboTextFadingIn = false;
comboTextFadeTime = 0;
}
combo = -1;
}
processRewardAmount(rewardAmount);
score += rewardAmount;
}
void GameBoard::processRewardAmount(long &rewardAmount) {}
void GameBoard::awardAllClear() {
score += 1000;
}
void GameBoard::processLeftoverClear(const long timePassed) {
if ((lost || animateClearOnFinish) && clearAnimationTime != 0)
clearAnimationTime = std::max(0l, clearAnimationTime - timePassed);
}
void GameBoard::afterClear() {
nextTetrimino();
oldButtonStates.rotateClockwise
= oldButtonStates.rotateCounterClockwise
= oldButtonStates.hardDrop
= oldButtonStates.hold
= false;
}
bool GameBoard::hasMinoAt(const char &x, const char &y) {
return
x < 0 || x > 9
|| y < 0 || y > 39
|| board[y][x] != 0;
}
void GameBoard::pushToQueue() {
std::array<std::unique_ptr<Tetrimino>, 7> bag = {
std::make_unique<TetriminoI>(),
std::make_unique<TetriminoJ>(),
std::make_unique<TetriminoL>(),
std::make_unique<TetriminoO>(),
std::make_unique<TetriminoS>(),
std::make_unique<TetriminoT>(),
std::make_unique<TetriminoZ>()
};
for (int i = 6; i != 0; i--) {
std::uniform_int_distribution<int> distribution(0, i);
bag[i].swap(bag[random.getInt(i+1)]);
queue.emplace_back(std::move(bag[i]));
}
queue.emplace_back(std::move(bag[0]));
}
void GameBoard::nextTetrimino() {
current = std::move(queue.front());
queue.pop_front();
if (queue.size() < 6) pushToQueue();
holdSwitched = false;
fallTime = 0;
lockTime = 0;
moveCounter = 0;
wasBlocked = false;
fallTimes.clear();
checkGameOver();
}
void GameBoard::reset() {
for (auto &row : board) row.clear();
over = false;
lost = false;
totalMinoes = 0;
score = 0;
lines = 0;
current = nullptr;
hold = nullptr;
queue.clear();
combo = -1;
backToBack = false;
tetriminoOnGround = false;
tetriminoMaxY = 19;
moveCounter = 0;
fallTimes.clear();
fallTime = 0;
lockTime = 0;
moveLock = 0;
autoRepeatStage = 0;
wasBlocked = false;
moveTime = 0;
holdSwitched = false;
clearTime = 0;
clearAnimationTime = 0;
comboNumbers.clear();
comboTextOldAlpha = 0;
comboTextFadingIn = false;
comboTextFadeTime = 200;
rewardDisplays.clear();
backToBackDisplays.clear();
allClearDisplays.clear();
clearedLines.clear();
springX = springY = {};
hardDropTrails.clear();
loseFlyingMinoes.clear();
pushToQueue();
}
void GameBoard::gameOver() {
over = true;
clearTime = -1;
lost = true;
clearedLines.clear();
for (int i = 0; i != 40; i++) {
int row = 39 - i;
auto &rowObject = board[row];
for (int j = 0; j != 10; j++) {
if (rowObject[j] == 0) continue;
loseFlyingMinoes.push_back({
(char)(rowObject[j] - 1),
j+0.5f, 39.5f - row, 0.5f,
-1 + 2*owner->floatRandom(owner->randomEngine),
4 + 1*owner->floatRandom(owner->randomEngine),
-1 + 2*owner->floatRandom(owner->randomEngine),
0,
owner->floatRandom(owner->randomEngine) - 0.5f,
owner->floatRandom(owner->randomEngine) - 0.5f,
owner->floatRandom(owner->randomEngine) - 0.5f,
100 * owner->floatRandom(owner->randomEngine)
});
}
rowObject.clear();
}
}
void GameBoard::checkGameOver() {
if (
current->checkCollision(*this, current->x, current->y, current->state)
) {
current->reset();
queue.emplace_front(std::move(current));
current = nullptr;
gameOver();
return;
}
if (current->canFall(*this)) current->y++;
tetriminoMaxY = current->y;
}
float GameBoard::getFallPeriod() {
const int level = 1;
return std::pow(0.8 - level*0.007, level)*1000;
}
long GameBoard::getLockDelay() {
return 500;
}
void GameBoard::renderTetrimino(
const std::unique_ptr<Tetrimino> &tetrimino,
const char &state,
float x, float y, const float z, const float scale,
bool applyOffset
) {
glPushMatrix();
glTranslatef(x, y, z);
glScalef(scale, scale, scale);
if (applyOffset) {
const auto &offset = tetrimino->getQueueOffset();
glTranslatef(offset[0], offset[1], 0);
}
glBegin(GL_QUADS);
const auto color = tetrimino->getColor()-1;
for (const auto &offset : tetrimino->getMinoes(state))
renderMino(offset.x, -offset.y, 0, color);
glEnd();
glPopMatrix();
}
void GameBoard::renderGhostMesh(
const char &ghostX, const char &ghostY
) {
glBegin(GL_QUADS);
for (const auto offset : current->getMinoes()) {
const float
x = ghostX + offset.x,
y = 39 - (ghostY + offset.y);
glVertex3f(x+1, y+1, 0);
glVertex3f(x, y+1, 0);
glVertex3f(x, y, 0);
glVertex3f(x+1, y, 0);
}
glEnd();
}
float GameBoard::clearCurve(const float in) {
return in > 0.1 ? 0.7 + 0.3*in : 7.3*in;
}
float GameBoard::getCurrentComboTextAlpha() {
if (comboTextFadeTime == 200) return comboTextFadingIn ? 1 : 0;
const float fadeProgress = comboTextFadeTime / 200.f;
return comboTextFadingIn
? comboTextOldAlpha + (1-comboTextOldAlpha)*fadeProgress
: comboTextOldAlpha * (1-fadeProgress);
}
void GameBoard::renderFrameAdditions(const long timePassed) {}
void GameBoard::renderOtherSolidObjects(const long timePassed) {}
void GameBoard::renderOtherObjects(const long timePassed) {}
void GameBoard::renderMino(
const float x, const float y, const float z, const char &color
) {
const float
textureX = (color & 0b11) * 0.25,
textureY = (color >> 2) * 0.25;
for (int i = 0; i != 24; i++) {
auto vertex = cubeData[i];
auto textureCoord = textureCoords[i & 0b11];
glTexCoord2f(textureX+textureCoord[0], textureY+textureCoord[1]);
glVertex3f(vertex[0]+x, vertex[1]+y, vertex[2]+z);
}
}
void GameBoard::renderSolid(const long timePassed) {
bool paused = owner->gameState == PAUSED;
// Tick animated elements.
if (!paused) {
if (!hardDropTrails.empty()) {
for (auto &trail : hardDropTrails) {
trail.lifetime -= timePassed;
}
while (!hardDropTrails.empty()) {
if (hardDropTrails.front().lifetime > 0) break;
else hardDropTrails.pop_front();
}
}
if (!comboNumbers.empty()) {
for (auto &comboNumber : comboNumbers) comboNumber.tick(timePassed);
while (!comboNumbers.empty()) {
if (!comboNumbers.front().isDone()) break;
else comboNumbers.pop_front();
}
}
if (comboTextFadeTime != 200)
comboTextFadeTime = std::min(200l, comboTextFadeTime + timePassed);
if (!rewardDisplays.empty()) {
for (auto &rewardDisplay : rewardDisplays)
rewardDisplay.tick(timePassed);
while (!rewardDisplays.empty()) {
if (!rewardDisplays.front().isDone()) break;
else rewardDisplays.pop_front();
}
}
if (!backToBackDisplays.empty()) {
for (auto &backToBackDisplay : backToBackDisplays)
backToBackDisplay.tick(timePassed);
while (!backToBackDisplays.empty()) {
if (!backToBackDisplays.front().isDone()) break;
else backToBackDisplays.pop_front();
}
}
if (!allClearDisplays.empty()) {
for (auto &allClearDisplay : allClearDisplays)
allClearDisplay.tick(timePassed);
while (!allClearDisplays.empty()) {
if (!allClearDisplays.front().isDone()) break;
else allClearDisplays.pop_front();
}
}
for (auto &row : board)
if (row.animationTime != 500) row.animationTime =
std::min(500l, row.animationTime + timePassed);
}
if (!loseFlyingMinoes.empty()) {
int diedCount = 0;
auto end = loseFlyingMinoes.end();
for (auto mino = loseFlyingMinoes.begin(); mino != end;) {
mino->time += timePassed;
if (
mino->startY + mino->directionY*std::pow(mino->time/1000.f, 2)
< 60
) {
mino++;
} else {
*mino = *(end - 1);
diedCount++;
end--;
}
}
loseFlyingMinoes.resize(loseFlyingMinoes.size() - diedCount);
}
auto rawColor = owner->rawColor;
// Board minoes.
owner->manager->set3D(owner->viewAngle);
glEnable(GL_TEXTURE_2D);
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glTranslatef(-5, -10, owner->getCameraPosition());
glPushMatrix();
glTranslatef(springX.position, springY.position, 0);
glColor3f(1, 1, 1);
if (!paused) {
minoTexture.bind();
for (int row = 0; row != 40; row++) {
glPushMatrix();
auto rowObject = board[row];
if (rowObject.minoCount == 0) continue;
if (
rowObject.animationTime != 500 && rowObject.clearingOffset != 0
) {
if (rowObject.minoCount == 10) {
glTranslatef(
0,
39.5 - row
+ std::pow(1-rowObject.animationTime/500.f, 2)
* rowObject.clearingOffset,
-std::pow(rowObject.animationTime/250.f - 1, 2) + 0.5
);
if (rowObject.clearingOffset >= 1)
glRotatef(360.f*rowObject.animationTime/500.f, 1, 0, 0);
glTranslatef(0, -0.5, 0.5);
} else {
glTranslatef(
0,
39 - row
- std::pow(1-rowObject.animationTime/500.f, 2)
* rowObject.clearingOffset,
0
);
}
} else {
glTranslatef(
0,
39 - row
+ clearCurve(clearAnimationTime/500.f)
* rowObject.clearingOffset,
0
);
}
glBegin(GL_QUADS);
for (int col = 0; col != 10; col++) {
auto mino = rowObject[col];
if (mino == 0) continue;
mino--;
renderMino(col, 0, 0, mino);
}
glEnd();
glPopMatrix();
}
// Zone cleared lines overlay.
glDisable(GL_DEPTH_TEST);
glDepthMask(GL_FALSE);
glDisable(GL_TEXTURE_2D);
glBegin(GL_QUADS);
for (int row = 0; row != 40; row++) {
auto rowObject = board[row];
if (rowObject.minoCount != 10) continue;
float y, z;
if (
rowObject.animationTime != 500 && rowObject.clearingOffset != 0
) {
y = 39 - row
+ std::pow(1-rowObject.animationTime/500.f, 2)
* rowObject.clearingOffset;
z = -std::pow(rowObject.animationTime/300.f - 1, 2) + 1;
} else {
y = 39 - row;
z = 0;
}
const float top = y + 1;
glColor4f(
0.9, 0.9, 0.9,
(1 - std::pow(1 - rowObject.animationTime/500.f, 2)) * 0.85
);
glVertex3f(10, top, z);
glVertex3f(0, top, z);
glVertex3f(0, y, z);
glVertex3f(10, y, z);
}
glEnd();
glEnable(GL_TEXTURE_2D);
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_TRUE);
glColor3f(1, 1, 1);
// Ghost outline.
if (renderGhostTetrimino && current != nullptr) {
glDisable(GL_TEXTURE_2D);
glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
glDepthMask(GL_FALSE);
glEnable(GL_STENCIL_TEST);
glStencilFunc(GL_ALWAYS, 1, 0xFFFFFFFF);
glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);
char ghostX = current->x, ghostY = current->y;
while (!current->checkCollision(
*this, current->x, ++ghostY, current->state)
);
ghostY--;
renderGhostMesh(ghostX, ghostY);
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
glDepthMask(GL_TRUE);
glStencilFunc(GL_EQUAL, 0, 0xFFFFFFFF);
glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
glLineWidth(2);
glPolygonMode(GL_FRONT, GL_LINE);
glColor3f(1, 1, 1);
renderGhostMesh(ghostX, ghostY);
glDisable(GL_STENCIL_TEST);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glDepthMask(GL_TRUE);
}
}
// Board frame.
glDepthFunc(GL_LESS);
glDisable(GL_TEXTURE_2D);
glColor3f(rawColor.r*0.5, rawColor.g*0.5, rawColor.b*0.5);
glBegin(GL_QUADS);
glVertex3f(-0.1, 20, 0);
glVertex3f(-0.1, 20, -1.1);
glVertex3f(-0.1, -0.1, -1.1);
glVertex3f(-0.1, -0.1, 0);
glVertex3f(21.1, 20, -1.1);
glVertex3f(21.1, 20, 0);
glVertex3f(21.1, -0.1, 0);
glVertex3f(21.1, -0.1, -1.1);
glVertex3f(0, 20, -1);
glVertex3f(0, 20, 0);
glVertex3f(0, 0, 0);
glVertex3f(0, 0, -1);
glVertex3f(10, 20, 0);
glVertex3f(10, 20, -1);
glVertex3f(10, 0, -1);
glVertex3f(10, 0, 0);
glVertex3f(0, 20, -1.1);
glVertex3f(-0.1, 20, -1.1);
glVertex3f(-0.1, 20, 0);
glVertex3f(0, 20, 0);
glVertex3f(10, 20, -1.1);
glVertex3f(0, 20, -1.1);
glVertex3f(0, 20, 0);
glVertex3f(10, 20, 0);
glVertex3f(10.1, 20, -1.1);
glVertex3f(10, 20, -1.1);
glVertex3f(10, 20, 0);
glVertex3f(10.1, 20, 0);
glVertex3f(10, 0, -1);
glVertex3f(0, 0, -1);
glVertex3f(0, 0, 0);
glVertex3f(10, 0, 0);
glVertex3f(-0.1, -0.1, -1.1);
glVertex3f(10.1, -0.1, -1.1);
glVertex3f(10.1, -0.1, 0);
glVertex3f(-0.1, -0.1, 0);
glColor3f(rawColor.r, rawColor.g, rawColor.b);
glVertex3f(0, 20, 0);
glVertex3f(-0.1, 20, 0);
glVertex3f(-0.1, -0.1, 0);
glVertex3f(0, -0.1, 0);
glVertex3f(10, 0, 0);
glVertex3f(0, 0, 0);
glVertex3f(0, -0.1, 0);
glVertex3f(10, -0.1, 0);
glVertex3f(10.1, 20, 0);
glVertex3f(10, 20, 0);
glVertex3f(10, -0.1, 0);
glVertex3f(10.1, -0.1, 0);
glEnd();
glDepthMask(GL_FALSE);
glColor4f(0, 0, 0, 0.75);
glBegin(GL_QUADS);
glVertex3f(-0.1, 20, -1.1);
glVertex3f(21.1, 20, -1.1);
glVertex3f(21.1, -0.1, -1.1);
glVertex3f(-0.1, -0.1, -1.1);
glVertex3f(10, 20, -1);
glVertex3f(0, 20, -1);
glVertex3f(0, 0, -1);
glVertex3f(10, 0, -1);
glEnd();
glEnable(GL_TEXTURE_2D);
glDepthMask(GL_TRUE);
// Current tetrimino.
if (!paused) {
const long lockDelay = getLockDelay();
const float lockMultiplier
= lockDelay < 0 ? 1 : 1 - 0.5 * lockTime / lockDelay;
glColor3f(lockMultiplier, lockMultiplier, lockMultiplier);
if (current != nullptr) renderTetrimino(
current, current->state,
current->x, 39 - current->y,
0, 1
);
}
glDepthMask(GL_FALSE);
// Final cleared lines.
if (
!animateClearOnFinish
&& owner->gameState == FINISHED && !lost && owner->sceneTime < 2000
) {
glDisable(GL_TEXTURE_2D);
glDisable(GL_CULL_FACE);
glColor4f(
1, 1, 1,
owner->sceneTime < 1000 ? 1 : (2000 - owner->sceneTime) / 1000.f
);
glBegin(GL_QUADS);
for (const char &row : clearedLines) {
const float y = 39 - row;
for (int i = 0; i != 10; i++)
renderMino(i, y, 0, 0);
}
glEnd();
glEnable(GL_TEXTURE_2D);
glEnable(GL_CULL_FACE);
}
// Hard drop trails.
if (!hardDropTrails.empty()) {
glDisable(GL_TEXTURE_2D);
glDepthMask(GL_FALSE);
glBegin(GL_QUADS);
for (auto &trail : hardDropTrails) {
const float alpha = trail.lifetime / 400.f;
if (trail.depth != 0) {
const int deepest = trail.bottom - trail.depth;
glColor4f(1, 1, 1, (trail.length==0 ? 0.1 : 0.5)*alpha);
glVertex3f(trail.right, trail.bottom, 0);
glVertex3f(trail.left, trail.bottom, 0);
glVertex3f(trail.left, deepest, 0);
glVertex3f(trail.right, deepest, 0);
}
const int middle = trail.bottom + trail.length;
if (trail.length != 0) {
glColor4f(1, 1, 1, 0.2*alpha);
glVertex3f(trail.right, middle, 0);
glVertex3f(trail.left, middle, 0);
glColor4f(1, 1, 1, 0.5*alpha);
glVertex3f(trail.left, trail.bottom, 0);
glVertex3f(trail.right, trail.bottom, 0);
}
if (trail.length < 5) {
const int top = trail.bottom + 5;
glColor4f(1, 1, 1, 0.1*alpha);
glVertex3f(trail.right, top, 0);
glVertex3f(trail.left, top, 0);
glVertex3f(trail.left, middle, 0);
glVertex3f(trail.right, middle, 0);
}
}
glEnd();
glEnable(GL_TEXTURE_2D);
}
glDepthFunc(GL_LEQUAL);
renderFrameAdditions(timePassed);
glPopMatrix();
glColor3f(1, 1, 1);
glDepthMask(GL_TRUE);
// Hold and queue.
glEnable(GL_TEXTURE_2D);
if (!paused) {
glColor3f(1, 1, 1);
float queueY = 18;
for (int i = 0; i != previewTetriminoes; i++) {
renderTetrimino(queue[i], 0, 11.3, queueY, 0, 0.65, true);
queueY -= 2.6;
}
if (hold != nullptr) renderTetrimino(hold, 0, -3.9, 18, 0, 0.65, true);
}
// Other solid objects.
if (!loseFlyingMinoes.empty()) {
for (const auto &mino : loseFlyingMinoes) {
const float time = mino.time/1000.f;
glPushMatrix();
glTranslatef(
mino.startX + mino.directionX*time,
mino.startY + mino.directionY*std::pow(time, 2),
mino.startZ + mino.directionZ*time
);
if (mino.startRotation != 0) glRotatef(mino.startRotation, 1, 0, 0);
glRotatef(
mino.rotationSpeed*time,
mino.rotationX, mino.rotationY, mino.rotationZ
);
glBegin(GL_QUADS);
renderMino(-0.5, -0.5, 0.5, mino.color);
glEnd();
glPopMatrix();
}
}
renderOtherSolidObjects(timePassed);
}
void GameBoard::renderTransparent(const long timePassed) {
auto rawColor = owner->rawColor;
// HUD.
for (const auto &comboNumber : comboNumbers)
comboNumber.render(owner->commonResources, rawColor);
for (const auto &rewardDisplay : rewardDisplays)
rewardDisplay.render(owner->commonResources);
for (const auto &backToBackDisplay : backToBackDisplays)
backToBackDisplay.render(owner->commonResources);
for (const auto &allClearDisplay : allClearDisplays)
allClearDisplay.render(owner->commonResources);
if (comboTextFadingIn || comboTextFadeTime != 200) {
const float comboTextAlpha = getCurrentComboTextAlpha();
owner->commonResources.font.render(
"COMBO"s, -1, 14.5, 0, 0.8, 1, true, 0, 1, 0, false, 0,
{1, 1, 1, comboTextAlpha}, {0, 0, 0, comboTextAlpha}
);
}
renderOtherObjects(timePassed);
} | 26.470942 | 76 | 0.657733 | [
"render",
"solid"
] |
4be5ae78d1a74e560d27ef6ffdc40206ac5eef99 | 4,580 | cc | C++ | edas/src/model/UpdateApplicationBaseInfoResult.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | edas/src/model/UpdateApplicationBaseInfoResult.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | edas/src/model/UpdateApplicationBaseInfoResult.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/edas/model/UpdateApplicationBaseInfoResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Edas;
using namespace AlibabaCloud::Edas::Model;
UpdateApplicationBaseInfoResult::UpdateApplicationBaseInfoResult() :
ServiceResult()
{}
UpdateApplicationBaseInfoResult::UpdateApplicationBaseInfoResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
UpdateApplicationBaseInfoResult::~UpdateApplicationBaseInfoResult()
{}
void UpdateApplicationBaseInfoResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto applcationNode = value["Applcation"];
if(!applcationNode["AppId"].isNull())
applcation_.appId = applcationNode["AppId"].asString();
if(!applcationNode["Name"].isNull())
applcation_.name = applcationNode["Name"].asString();
if(!applcationNode["RegionId"].isNull())
applcation_.regionId = applcationNode["RegionId"].asString();
if(!applcationNode["Description"].isNull())
applcation_.description = applcationNode["Description"].asString();
if(!applcationNode["Owner"].isNull())
applcation_.owner = applcationNode["Owner"].asString();
if(!applcationNode["InstanceCount"].isNull())
applcation_.instanceCount = std::stoi(applcationNode["InstanceCount"].asString());
if(!applcationNode["RunningInstanceCount"].isNull())
applcation_.runningInstanceCount = std::stoi(applcationNode["RunningInstanceCount"].asString());
if(!applcationNode["Port"].isNull())
applcation_.port = std::stoi(applcationNode["Port"].asString());
if(!applcationNode["UserId"].isNull())
applcation_.userId = applcationNode["UserId"].asString();
if(!applcationNode["SlbId"].isNull())
applcation_.slbId = applcationNode["SlbId"].asString();
if(!applcationNode["SlbIp"].isNull())
applcation_.slbIp = applcationNode["SlbIp"].asString();
if(!applcationNode["SlbPort"].isNull())
applcation_.slbPort = std::stoi(applcationNode["SlbPort"].asString());
if(!applcationNode["ExtSlbId"].isNull())
applcation_.extSlbId = applcationNode["ExtSlbId"].asString();
if(!applcationNode["ExtSlbIp"].isNull())
applcation_.extSlbIp = applcationNode["ExtSlbIp"].asString();
if(!applcationNode["SlbName"].isNull())
applcation_.slbName = applcationNode["SlbName"].asString();
if(!applcationNode["ExtSlbName"].isNull())
applcation_.extSlbName = applcationNode["ExtSlbName"].asString();
if(!applcationNode["ApplicationType"].isNull())
applcation_.applicationType = applcationNode["ApplicationType"].asString();
if(!applcationNode["ClusterType"].isNull())
applcation_.clusterType = std::stoi(applcationNode["ClusterType"].asString());
if(!applcationNode["ClusterId"].isNull())
applcation_.clusterId = applcationNode["ClusterId"].asString();
if(!applcationNode["Dockerize"].isNull())
applcation_.dockerize = applcationNode["Dockerize"].asString() == "true";
if(!applcationNode["Cpu"].isNull())
applcation_.cpu = std::stoi(applcationNode["Cpu"].asString());
if(!applcationNode["Memory"].isNull())
applcation_.memory = std::stoi(applcationNode["Memory"].asString());
if(!applcationNode["HealthCheckUrl"].isNull())
applcation_.healthCheckUrl = applcationNode["HealthCheckUrl"].asString();
if(!applcationNode["BuildPackageId"].isNull())
applcation_.buildPackageId = std::stol(applcationNode["BuildPackageId"].asString());
if(!applcationNode["CreateTime"].isNull())
applcation_.createTime = std::stol(applcationNode["CreateTime"].asString());
if(!value["Code"].isNull())
code_ = std::stoi(value["Code"].asString());
if(!value["Message"].isNull())
message_ = value["Message"].asString();
}
std::string UpdateApplicationBaseInfoResult::getMessage()const
{
return message_;
}
UpdateApplicationBaseInfoResult::Applcation UpdateApplicationBaseInfoResult::getApplcation()const
{
return applcation_;
}
int UpdateApplicationBaseInfoResult::getCode()const
{
return code_;
}
| 39.826087 | 98 | 0.753057 | [
"model"
] |
4bece2501c6922fcd60e92e6f4485dbc42cf353e | 673 | cc | C++ | CPP/No133.cc | hxz1998/funny_leetcode | 1d2c425af09b57a030fc018ddc1e1a5ffb966cd0 | [
"Apache-2.0"
] | null | null | null | CPP/No133.cc | hxz1998/funny_leetcode | 1d2c425af09b57a030fc018ddc1e1a5ffb966cd0 | [
"Apache-2.0"
] | null | null | null | CPP/No133.cc | hxz1998/funny_leetcode | 1d2c425af09b57a030fc018ddc1e1a5ffb966cd0 | [
"Apache-2.0"
] | null | null | null | /**
* Created by Xiaozhong on 2020/8/12.
* Copyright (c) 2020/8/12 Xiaozhong. All rights reserved.
*/
#include "simple_node.h"
#include "map"
#include "queue"
using namespace std;
class Solution {
public:
Node *cloneGraph(Node *node) {
return dfs(node);
}
private:
map<Node *, Node *> visited;
Node *dfs(Node *root) {
if (!root) return nullptr;
if (visited.count(root)) return visited[root];
vector<Node *> neighbors;
Node *clone = new Node(root->val, neighbors);
visited[root] = clone;
for (Node *node : root->neighbors) clone->neighbors.push_back(dfs(node));
return clone;
}
};
| 21.03125 | 81 | 0.606241 | [
"vector"
] |
4bf2ff8734875a963fb0a38847043acd6acdbea9 | 2,986 | hpp | C++ | src/lib/chainComplexExtraction.hpp | AppliedMathematicsANU/diamorse | 3416d7a6ffa13b2fce7d83c560ac6bc83f1faa44 | [
"Unlicense",
"MIT"
] | 13 | 2016-04-19T06:36:11.000Z | 2022-03-22T18:41:47.000Z | src/lib/chainComplexExtraction.hpp | AppliedMathematicsANU/diamorse | 3416d7a6ffa13b2fce7d83c560ac6bc83f1faa44 | [
"Unlicense",
"MIT"
] | 6 | 2016-06-07T08:55:27.000Z | 2017-07-17T22:41:42.000Z | src/lib/chainComplexExtraction.hpp | AppliedMathematicsANU/diamorse | 3416d7a6ffa13b2fce7d83c560ac6bc83f1faa44 | [
"Unlicense",
"MIT"
] | 11 | 2016-01-29T15:45:52.000Z | 2021-06-18T19:08:52.000Z | /** -*-c++-*-
*
* Copyright 2014 The Australian National University
*
* chainComplexExtraction.hpp
*
* Computes a Morse chain complex given a gradient vector field.
*
* Olaf Delgado-Friedrichs jan 14
*
*/
#ifndef ANU_AM_DIAMORSE_CHAINCOMPLEXEXTRACTION_HPP
#define ANU_AM_DIAMORSE_CHAINCOMPLEXEXTRACTION_HPP
#include <memory>
#include "CubicalComplex.hpp"
#include "traversals.hpp"
#include "restricted.hpp"
namespace anu_am
{
namespace diamorse
{
template<class Field, class Vectors, class Incidences>
std::shared_ptr<std::vector<bool> >
connectingPaths(
CubicalComplex const& complex,
Field const& field,
Vectors const& V,
Vectors const& coV,
Incidences const& I,
Incidences const& coI)
{
typedef CubicalComplex::cell_id_type Cell;
std::vector<Cell> critical;
for (Cell cell = 0; cell <= complex.cellIdLimit(); ++cell)
if (complex.isCell(cell) and field.isCritical(cell))
critical.push_back(cell);
std::vector<Cell> downstreamSources;
std::vector<Cell> upstreamSources;
std::vector<Cell> downstreamTargets;
std::vector<Cell> upstreamTargets;
for (size_t i = 0; i < critical.size(); ++i)
{
Cell const cell = critical.at(i);
switch(complex.cellDimension(cell))
{
case 0:
downstreamTargets.push_back(cell);
break;
case 1:
downstreamSources.push_back(cell);
downstreamTargets.push_back(cell);
break;
case 2:
downstreamSources.push_back(cell);
upstreamSources.push_back(cell);
break;
case 3:
upstreamTargets.push_back(cell);
break;
default:
break;
}
}
return connectingPaths(complex.cellIdLimit(),
downstreamSources, upstreamSources,
downstreamTargets, upstreamTargets,
V, coV, I, coI);
}
template<class Field>
std::map<CubicalComplex::cell_id_type,
std::vector<std::pair<CubicalComplex::cell_id_type, int> > >
chainComplex(CubicalComplex const& complex, Field const& field)
{
typedef CubicalComplex::cell_id_type Cell;
typedef RestrictedIncidences<Facets> Incidences;
typedef std::vector<std::pair<Cell, int> > Boundary;
Facets I(complex.xdim(), complex.ydim(), complex.zdim(), false);
Facets coI(complex.xdim(), complex.ydim(), complex.zdim(), true);
typename Field::Vectors V = field.V();
typename Field::Vectors coV = field.coV();
Incidences rI(I, connectingPaths(complex, field, V, coV, I, coI));
std::map<Cell, Boundary> result;
for (Cell cell = 0; cell <= complex.cellIdLimit(); ++cell)
if (complex.isCell(cell) and field.isCritical(cell))
result[cell] = morseBoundary(cell, V, rI);
return result;
}
} // namespace diamorse
} // namespace anu_am
#endif // !ANU_AM_DIAMORSE_CHAINCOMPLEXEXTRACTION_HPP
| 26.192982 | 70 | 0.643001 | [
"vector"
] |
4bf993ff03245b1a158a361d5273d4832769b8e6 | 61,170 | cpp | C++ | src/mrt/compiler-rt/src/collector/collector_ms.cpp | MapleSystem/OpenArkCompiler | fc250857642ca38ac8b83ae7486513fadf3ab742 | [
"MulanPSL-1.0"
] | 5 | 2019-09-02T04:44:52.000Z | 2021-11-08T12:23:51.000Z | src/mrt/compiler-rt/src/collector/collector_ms.cpp | MapleSystem/OpenArkCompiler | fc250857642ca38ac8b83ae7486513fadf3ab742 | [
"MulanPSL-1.0"
] | 2 | 2020-07-21T01:22:01.000Z | 2021-12-06T08:07:16.000Z | src/mrt/compiler-rt/src/collector/collector_ms.cpp | MapleSystem/OpenArkCompiler | fc250857642ca38ac8b83ae7486513fadf3ab742 | [
"MulanPSL-1.0"
] | 4 | 2019-09-02T04:46:52.000Z | 2020-09-10T11:30:03.000Z | /*
* Copyright (c) [2020] Huawei Technologies Co.,Ltd.All rights reserved.
*
* OpenArkCompiler is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR
* FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "collector/collector_ms.h"
#include <cassert>
#include <cstddef>
#include <cinttypes>
#include <atomic>
#include <fstream>
#include "mm_config.h"
#include "address.h"
#include "chosen.h"
#include "collector/mrt_bitmap.h"
#include "collector/stats.h"
#include "yieldpoint.h"
#include "profile.h"
#include "collector/native_gc.h"
#include "mutator_list.h"
#include "collie.h"
#include "mrt_class_api.h"
namespace maplert {
// number of nanoseconds in a microsecond.
constexpr uint64_t kNsPerUs = 1000;
#if BT_CLEANUP_PROFILE
size_t BTCleanupStats::rootSetSize;
size_t BTCleanupStats::totalRemain;
size_t BTCleanupStats::reachableRemain;
size_t BTCleanupStats::unreachableRemain;
#endif
// Small queue implementation, for prefetching.
#define MRT_MAX_PREFETCH_QUEUE_SIZE_LOG 5UL
#define MRT_MAX_PREFETCH_QUEUE_SIZE (1UL << MRT_MAX_PREFETCH_QUEUE_SIZE_LOG)
#if MRT_MAX_PREFETCH_QUEUE_SIZE <= MARK_PREFETCH_DISTANCE
#error Prefetch queue size must be strictly greater than prefetch distance.
#endif
class PrefetchQueue {
public:
explicit PrefetchQueue(size_t d) : elems {}, distance(d), tail(0), head(0) {}
~PrefetchQueue() {}
inline void Add(address_t objaddr) {
size_t t = tail;
elems[t] = objaddr;
tail = (t + 1) & (MRT_MAX_PREFETCH_QUEUE_SIZE - 1UL);
__builtin_prefetch(reinterpret_cast<void*>(objaddr - kJavaObjAlignment), 1, kPrefetchLocality);
__builtin_prefetch(reinterpret_cast<void*>(objaddr), 0, kPrefetchLocality);
}
inline address_t Remove() {
size_t h = head;
address_t objaddr = elems[h];
head = (h + 1) & (MRT_MAX_PREFETCH_QUEUE_SIZE - 1UL);
return objaddr;
}
inline size_t Length() const {
return (tail - head) & (MRT_MAX_PREFETCH_QUEUE_SIZE - 1UL);
}
inline bool Empty() const {
return head == tail;
}
inline bool Full() const {
return Length() == distance;
}
private:
static constexpr int kPrefetchLocality = 3;
address_t elems[MRT_MAX_PREFETCH_QUEUE_SIZE];
size_t distance;
size_t tail;
size_t head;
}; // End of small queue implementation
class MarkTask : public MplTask {
public:
MarkTask(MarkSweepCollector &tc,
MplThreadPool *pool,
size_t workStackSize,
TracingCollector::WorkStack::iterator workStackData,
bool isFollowReferent)
: collector(tc), threadPool(pool), followReferent(isFollowReferent) {
workStack.reserve(workStackSize + kMaxMarkTaskSize);
workStack.insert(workStack.begin(), workStackData, workStackData + workStackSize);
}
// single work task without thread pool
MarkTask(MarkSweepCollector &tc, TracingCollector::WorkStack &stack, bool isFollowReferent)
: collector(tc), threadPool(nullptr), followReferent(isFollowReferent) {
workStack.reserve(stack.size());
workStack.insert(workStack.begin(), stack.begin(), stack.end());
}
virtual ~MarkTask() {
threadPool = nullptr;
}
void Execute(size_t workerID __attribute__((unused))) override {
size_t nNewlyMarked = 0;
const size_t prefetchDistance = kMarkPrefetchDistance;
PrefetchQueue pq(prefetchDistance);
for (;;) {
// Prefetch as much as possible.
while (!pq.Full() && !workStack.empty()) {
address_t objaddr = workStack.back();
pq.Add(objaddr);
workStack.pop_back();
}
// End if pq is empty. This implies that workStack is also empty.
if (pq.Empty()) {
break;
}
address_t objaddr = pq.Remove();
bool wasMarked = collector.MarkObject(objaddr);
if (!wasMarked) {
LOG2FILE(kLogTypeMix) << "Newly marked: 0x%" << objaddr << std::endl;
++nNewlyMarked;
// If we mark before enqueing, we should have checked if it has children.
if (!HasChildRef(objaddr)) {
continue;
}
if (LIKELY(!IsObjReference(objaddr)) || UNLIKELY(followReferent)) {
collector.EnqueueNeighbors(objaddr, workStack);
} else {
collector.EnqueueNeighborsForRef(objaddr, workStack);
}
if (threadPool != nullptr && UNLIKELY(workStack.size() > kMaxMarkTaskSize)) {
// Mark stack overflow, give 1/2 the stack to the thread pool as a new work task.
size_t newSize = workStack.size() >> 1;
threadPool->AddTask(new (std::nothrow) MarkTask(collector,
threadPool,
workStack.size() - newSize,
workStack.begin() + newSize,
followReferent));
workStack.resize(newSize);
}
} else {
LOG2FILE(kLogTypeMix) << "Already marked: 0x" << objaddr << std::endl;
}
} // for loop
// newly marked statistics.
(void)collector.newlyMarked.fetch_add(nNewlyMarked, std::memory_order_relaxed);
}
private:
TracingCollector::WorkStack workStack;
MarkSweepCollector &collector;
MplThreadPool *threadPool;
bool followReferent;
};
class ConcurrentMarkTask : public MplTask {
public:
ConcurrentMarkTask(MarkSweepCollector &tc,
MplThreadPool *pool,
TracingCollector::WorkStack::iterator workStackStart,
size_t workStackSize)
: collector(tc), threadPool(pool) {
workStack.reserve(workStackSize + kMaxMarkTaskSize);
workStack.insert(workStack.begin(), workStackStart, workStackStart + workStackSize);
}
// create concurrent mark task without thread pool.
ConcurrentMarkTask(MarkSweepCollector &tc, TracingCollector::WorkStack &&stack)
: collector(tc), threadPool(nullptr), workStack(std::move(stack)) {}
virtual ~ConcurrentMarkTask() {
threadPool = nullptr;
}
// when parallel is enabled, fork new task if work stack overflow.
inline void TryForkTask() {
if (threadPool != nullptr && UNLIKELY(workStack.size() > kMaxMarkTaskSize)) {
// Mark stack overflow, give 1/2 the stack to the thread pool as a new work task.
size_t newSize = workStack.size() >> 1;
threadPool->AddTask(new (std::nothrow) ConcurrentMarkTask(collector, threadPool, workStack.begin() + newSize,
workStack.size() - newSize));
workStack.resize(newSize);
}
}
// Mark object.
// return true if success set object from unmarked to marked.
inline bool Mark(address_t obj) {
// try to mark object and load old mark state.
bool wasMarked = collector.MarkObject(obj);
// return false if object already marked.
if (UNLIKELY(wasMarked)) {
return false;
}
// make success.
++newlyMarked;
return true;
}
// run concurrent marking task.
void Execute(size_t) override {
// loop until work stack empty.
for (;;) {
if (workStack.empty()) {
break;
}
// get next object from work stack.
address_t objaddr = workStack.back();
workStack.pop_back();
// skip dangling reference (such as: object already released).
if (UNLIKELY(!IsAllocatedByAllocator(objaddr))) {
// kAllocatedBit not set, means the object address is a dangling reference.
LOG(ERROR) << "Mark encounter dangling reference: " << objaddr << maple::endl;
continue;
}
bool wasMarked = collector.MarkObject(objaddr);
if (!wasMarked) {
if (!HasChildRef(objaddr)) {
continue;
}
collector.CopyChildRefs(objaddr, workStack);
}
// try to fork new task if need.
TryForkTask();
} // end of mark loop.
// newly marked statistics.
(void)collector.newlyMarked.fetch_add(newlyMarked, std::memory_order_relaxed);
}
private:
MarkSweepCollector &collector;
MplThreadPool *threadPool;
TracingCollector::WorkStack workStack;
size_t newlyMarked = 0;
};
#if MRT_TEST_CONCURRENT_MARK
struct RootInfo {
std::unordered_set<address_t> staticRoots;
std::unordered_set<address_t> extRoots;
std::unordered_set<address_t> stringRoots;
std::unordered_set<address_t> refRoots;
std::unordered_set<address_t> allocatorRoots;
std::unordered_set<address_t> classloaderRoots;
std::unordered_set<address_t> stackRoots;
std::string WhatRoot(address_t obj) const {
std::ostringstream oss;
if (staticRoots.count(obj) != 0) {
oss << ":static";
}
if (extRoots.count(obj) != 0) {
oss << ":ext";
}
if (stringRoots.count(obj) != 0) {
oss << ":string";
}
if (refRoots.count(obj) != 0) {
oss << ":ref";
}
if (allocatorRoots.count(obj) != 0) {
oss << ":alloc";
}
if (classloaderRoots.count(obj) != 0) {
oss << ":cloader";
}
if (stackRoots.count(obj) != 0) {
oss << ":stack";
}
return oss.str();
};
};
static void GCLogPrintObjects(const char *title, const std::vector<address_t> &objects, MrtBitmap &bitmap,
bool findOwner = false, const RootInfo *rootInfo = nullptr) {
constexpr size_t kMaxPrintCount = 10;
LOG2FILE(kLogtypeGc) << title << '\n';
for (size_t i = 0; i < objects.size() && i < kMaxPrintCount; ++i) {
address_t obj = objects.at(i);
MClass *cls = reinterpret_cast<MObject*>(obj)->GetClass();
const char *cname = (cls == nullptr) ? "<null>" : cls->GetName();
LOG2FILE(kLogtypeGc) << reinterpret_cast<void*>(obj) <<
std::hex <<
" rc:" << RefCountLVar(obj) <<
" hd:" << GCHeader(obj) <<
std::dec <<
" mark:" << bitmap.IsObjectMarked(obj) <<
" " << ((rootInfo != nullptr) ? rootInfo->WhatRoot(obj) : "") <<
" " << cname <<
'\n';
if (findOwner) {
(*theAllocator).ForEachObj([obj, rootInfo, &bitmap](address_t owner) {
auto refFunc = [rootInfo, &bitmap, owner, obj](reffield_t &field, uint64_t kind) {
if ((static_cast<address_t>(field) == obj) && (kind != kUnownedRefBits)) {
address_t fieldOffset = (address_t)(&field) - owner;
MClass *ownerCls = reinterpret_cast<MObject*>(owner)->GetClass();
const char *ownerCname = (ownerCls == nullptr) ? "<null>" : ownerCls->GetClass();
LOG2FILE(kLogtypeGc) << (kind == kNormalRefBits ? " owner: " : " weak owner: ") <<
reinterpret_cast<void*>(owner) <<
std::hex <<
" +0x" << fieldOffset <<
" rc:" << RefCount(owner) <<
" hd:" << GCHeader(owner) <<
std::dec <<
" mark:" << bitmap.IsObjectMarked(owner) <<
" " << ((rootInfo != nullptr) ? rootInfo->WhatRoot(owner) : "") <<
" " << ownerCname <<
'\n';
}
};
ForEachRefField(owner, refFunc);
});
}
}
}
// we need some Bitmap debug functions when testing concurrent mark.
#if !(MRT_DEBUG_BITMAP)
#error "Please enable MRT_DEBUG_BITMAP in bitmap.h when MRT_TEST_CONCURRENT_MARK enabled."
#endif
static void CompareBitmap(const MrtBitmap &bitmap1,
const MrtBitmap &bitmap2,
std::vector<address_t> &unmarked1,
std::vector<address_t> &unmarked2) {
const address_t heapStart = (*theAllocator).HeapLowerBound();
auto words1 = bitmap1.Data();
auto words2 = bitmap2.Data();
size_t nWords = bitmap1.Size() >> kLogBytesPerWord;
using WordType = decltype(*words1);
// compare word by word.
for (size_t i = 0; i < nWords; ++i) {
WordType w1 = words1[i];
WordType w2 = words2[i];
// continue if two words are equal.
if (w1 == w2) {
continue;
}
// compare bit by bit in the word.
for (size_t nBit = 0; nBit < kBitsPerWord; ++nBit) {
WordType mask = ((WordType)1 << nBit);
bool bit1 = ((w1 & mask) != 0);
bool bit2 = ((w2 & mask) != 0);
// continue if two bits are equal.
if (bit1 == bit2) {
continue;
}
// calculate object address by bit position.
address_t obj = heapStart + ((i * kBitsPerWord + (kBitsPerWord - 1 - nBit)) << kLogObjAlignment);
if (bit1) {
// bitmap1 marked, but bitmap2 unmarked.
unmarked2.push_back(obj);
} else {
// bitmap2 marked, but bitmap1 unmakred.
unmarked1.push_back(obj);
}
}
}
}
#endif // MRT_TEST_CONCURRENT_MARK
void MarkSweepCollector::ParallelMark(WorkStack &workStack, bool followReferent) {
LOG2FILE(kLogTypeMix) << "Parallel mark work stack size: " << workStack.size() << std::endl;
newlyMarked.store(0, std::memory_order_relaxed);
if (workStack.size() > kMaxMarkTaskSize) {
MplThreadPool *threadPool = GetThreadPool();
__MRT_ASSERT(threadPool != nullptr, "null thread pool");
const int32_t threadCount = GetThreadCount(false);
__MRT_ASSERT(threadCount > 1, "incorrect thread count");
const size_t kChunkSize = std::min(workStack.size() / threadCount + 1, kMaxMarkTaskSize);
// Split the current work stack into work tasks.
auto end = workStack.end();
for (auto it = workStack.begin(); it < end;) {
const size_t delta = std::min(static_cast<size_t>(end - it), kChunkSize);
threadPool->AddTask(new (std::nothrow) MarkTask(*this, threadPool, delta, it, followReferent));
it += delta;
}
workStack.clear();
threadPool->SetMaxActiveThreadNum(threadCount - 1);
threadPool->Start();
threadPool->WaitFinish(true);
LOG2FILE(kLogtypeGc) << "Parallel Newly Marked " << newlyMarked.load(std::memory_order_relaxed) <<
" objects in this phase.\n";
} else {
// serial marking with a single mark task.
MarkTask markTask(*this, workStack, followReferent);
markTask.Execute(0);
}
}
void MarkSweepCollector::AddMarkTask(RootSet &rs) {
if (rs.size() == 0) {
return;
}
MplThreadPool *threadPool = GetThreadPool();
const size_t kChunkSize = kMaxMarkTaskSize;
bool followReferent = false;
auto end = rs.end();
for (auto it = rs.begin(); it < end;) {
const size_t delta = std::min(static_cast<size_t>(end - it), kChunkSize);
threadPool->AddTask(new (std::nothrow) MarkTask(*this, threadPool, delta, it, followReferent));
it += delta;
}
rs.clear();
}
void MarkSweepCollector::ParallelScanMark(RootSet *rootSets, bool processWeak, bool rootString) {
MplThreadPool *threadPool = GetThreadPool();
const size_t kThreadCount = threadPool->GetMaxThreadNum() + 1;
// task to scan external roots.
threadPool->AddTask(new (std::nothrow) MplLambdaTask([this, processWeak, rootSets](size_t workerID) {
ScanExternalRoots(rootSets[workerID], processWeak);
AddMarkTask(rootSets[workerID]);
}));
// task to scan reference, allocator and classloader roots.
// those scan are very fast, so we combine them into one single task.
threadPool->AddTask(new (std::nothrow) MplLambdaTask([this, rootSets](size_t workerID) {
ScanReferenceRoots(rootSets[workerID]);
ScanAllocatorRoots(rootSets[workerID]);
ScanClassLoaderRoots(rootSets[workerID]);
AddMarkTask(rootSets[workerID]);
}));
// task to scan zterp static field roots.
threadPool->AddTask(new (std::nothrow) MplLambdaTask([this, rootSets](size_t workerID) {
ScanZterpStaticRoots(rootSets[workerID]);
AddMarkTask(rootSets[workerID]);
}));
// task to scan static field roots.
staticRootsTaskIndex.store(0);
for (size_t t = 0; t < kThreadCount; ++t) {
threadPool->AddTask(new (std::nothrow) MplLambdaTask([this, rootSets](size_t workerID) {
while (true) {
size_t old = staticRootsTaskIndex.fetch_add(1, std::memory_order_release);
address_t **list = nullptr;
size_t len = 0;
{
// Even in STW, *.so loading is in safeRegion, we also need to add a lock to avoid racing.
bool success = GCRegisteredRoots::Instance().GetRootsLocked(old, list, len);
if (!success) {
break;
}
for (size_t i = 0; i < len; ++i) {
MaybeAddRoot(LoadStaticRoot(list[i]), rootSets[workerID], true);
}
}
}
AddMarkTask(rootSets[workerID]);
}));
}
// task to scan stack roots.
stackTaskIndex.store(0);
for (size_t t = 0; t < kThreadCount; ++t) {
threadPool->AddTask(new (std::nothrow) MplLambdaTask([this, rootSets](size_t workerID) {
RootSet &rs = rootSets[workerID];
auto &mutatorList = MutatorList::Instance().List();
const size_t mutatorLen = mutatorList.size();
while (true) {
size_t old = stackTaskIndex.fetch_add(1, std::memory_order_release);
if (old >= mutatorLen) {
break;
}
auto it = mutatorList.begin();
size_t nop = 0;
while (nop < old) {
++it;
++nop;
}
if (doConservativeStackScan) {
ScanStackRoots(**it, rs);
} else {
// for nearly-precise stack scanning
(*it)->VisitJavaStackRoots([&rs](address_t ref) {
// currently only scan & collect the local var
if (LIKELY((*theAllocator).AccurateIsValidObjAddr(ref))) {
rs.push_back(ref);
}
});
}
// both conservtive and accurate scan, need scan scoped local refs
(*it)->VisitNativeStackRoots([&rs](address_t &ref) {
if (LIKELY((*theAllocator).AccurateIsValidObjAddr(ref))) {
rs.push_back(ref);
}
});
}
AddMarkTask(rootSets[workerID]);
}));
}
// task to scan string roots.
if (rootString) {
threadPool->AddTask(new (std::nothrow) MplLambdaTask([this, rootSets](size_t workerID) {
ScanStringRoots(rootSets[workerID]);
AddMarkTask(rootSets[workerID]);
}));
}
PostParallelScanMark(processWeak);
}
void MarkSweepCollector::DoWeakGRT() {
size_t numIterated = 0;
size_t numCleared = 0;
RefVisitor rootVisitor = [this, &numIterated, &numCleared](address_t &obj) {
++numIterated;
if (InHeapBoundry(obj) && IsGarbage(obj)) {
__MRT_ASSERT(obj != DEADVALUE, "must be a valid obj");
++numCleared;
DecReferentUnsyncCheck(obj, true);
obj = DEADVALUE;
}
};
maple::GCRootsVisitor::VisitWeakGRT(rootVisitor);
LOG2FILE(kLogtypeGc) << " iterated WeakGRT = " << numIterated << '\n';
LOG2FILE(kLogtypeGc) << " cleared WeakGRT = " << numCleared << '\n';
}
void MarkSweepCollector::ConcurrentPrepareResurrection() {
const size_t vectorCapacity = 100;
resurrectCandidates.reserve(vectorCapacity);
function<void(address_t)> visitor = [this](address_t objAddr) {
if (UNLIKELY(IsUnmarkedResurrectable(objAddr))) {
resurrectCandidates.push_back(objAddr);
}
};
// an unsafe scan of the heap, only works because we are in concurrent mark
// this assumes no objs are actually released by the allocator
// assumes it won't crash when we scan any uninitialised memory (e.g., uninitialised obj)
// assumes all new objs are marked
// assumes the finalizable count always >= actual finalizable objs in page
// assumes all resurrected obj during cm must not unset enqueue flag
(*theAllocator).ForEachObjUnsafe(visitor, OnlyVisit::kVisitFinalizable);
}
void MarkSweepCollector::ConcurrentMarkFinalizer() {
WorkStack workStack = resurrectCandidates;
size_t markedObjs = 0;
// loop until work stack and prefetch queue empty.
for (;;) {
if (workStack.empty()) {
break;
}
// get next object from prefetch queue.
address_t objAddr = workStack.back();
workStack.pop_back();
// skip dangling reference (such as: object already released).
if (UNLIKELY(!IsAllocatedByAllocator(objAddr))) {
// kAllocatedBit not set, means the object address is a dangling reference.
LOG(ERROR) << "Mark encounter dangling reference: " << objAddr << maple::endl;
continue;
}
// skip if the object already marked.
if (markBitmap.IsObjectMarked(objAddr) || finalBitmap.IsObjectMarked(objAddr)) {
continue;
}
// if object has no child refs.
if (!HasChildRef(objAddr)) {
++markedObjs;
// mark object and skip child refs.
(void)MarkObjectForFinalizer(objAddr);
continue;
}
// handle child refs.
// remember work stack size before child refs added,
// so that we can discard newly added refs if needed.
const size_t kOldWorkStackSize = workStack.size();
// check dirty bit.
bool dirty = IsDirty(objAddr);
if (LIKELY(!dirty)) {
// if object was not modified,
// try to copy object child refs into work stack.
CopyChildRefs(objAddr, workStack, true);
std::atomic_thread_fence(std::memory_order_acq_rel);
dirty = IsDirty(objAddr);
}
if (UNLIKELY(dirty)) {
// discard copied child refs in work stack.
workStack.resize(kOldWorkStackSize);
} else {
++markedObjs;
(void)MarkObjectForFinalizer(objAddr);
}
} // end of mark loop.
LOG2FILE(kLogtypeGc) << "\tmarked objects for finalizer: " << markedObjs << "\n";
}
void MarkSweepCollector::ConcurrentAddFinalizerToRP() {
size_t nResurrected = 0;
WorkStack deadFinalizers;
deadFinalizers.reserve(resurrectCandidates.size());
for (auto addr : resurrectCandidates) {
if (IsGarbageBeforeResurrection(addr) && IsObjResurrectable(addr)) {
++nResurrected;
deadFinalizers.push_back(addr);
}
}
ReferenceProcessor::Instance().AddFinalizables(
deadFinalizers.data(), static_cast<uint32_t>(deadFinalizers.size()), true);
LOG2FILE(kLogtypeGc) << nResurrected << " objects resurrected in " << resurrectCandidates.size() << " candidates.\n";
}
void MarkSweepCollector::DoResurrection(WorkStack&) {
if (Type() == kNaiveRCMarkSweep) {
size_t nResurrected = 0;
for (auto addr : resurrectCandidates) {
if (IsUnmarkedResurrectable(addr)) {
++nResurrected;
ReferenceProcessor::Instance().AddFinalizable(addr, false);
}
}
LOG2FILE(kLogtypeGc) << nResurrected << " objects resurrected in " << resurrectCandidates.size() << " candidates\n";
} else {
// gc need discover Reference
for (auto ref : finalizerFindReferences) {
GCReferenceProcessor::Instance().DiscoverReference(ref);
}
}
useFinalBitmap = true;
}
void MarkSweepCollector::ResurrectionCleanup() {
WorkStack().swap(resurrectCandidates);
WorkStack().swap(finalizerFindReferences);
}
void MarkSweepCollector::ParallelResurrection(WorkStack &workStack) {
if (VLOG_IS_ON(dumpgarbage)) {
DumpFinalizeGarbage();
}
// WARNING: Cannot use vector on the outer level. We don't know how many
// threads the thread pool has. Lists never invalidate references to its
// elements when adding new elements, while vectors may need to be
// re-allocated when resizing, causing all references to existing elements to
// be invalidated.
list<vector<address_t>> finalizablesFromEachTask;
// The factory is called when creating each task.
Allocator::VisitorFactory visitorFactory = [&finalizablesFromEachTask]() {
// NOTE: No locking here, because (1) tasks are created sequentially, and
// (2) even if new tasks can be created when old tasks are running,
// emplace_back on std::list adds new nodes, but does not modify or
// reallocate existing **elements**.
finalizablesFromEachTask.emplace_back();
vector<address_t> &myFinalizables = finalizablesFromEachTask.back();
// NOTE: my_finalizables is an L-value of an element of the
// finalizablesFromEachTask vector. Each returned lambda function
// captures a different element of the finalizablesFromEachTask by
// reference (capturing the address), therefore different tasks (and
// threads) do not share any vectors.
return [&myFinalizables](address_t objaddr) {
if (IsUnmarkedResurrectable(objaddr)) {
myFinalizables.push_back(objaddr); // No need for locking because each task uses its own vector
}
};
};
if (UNLIKELY(!(*theAllocator).ParallelForEachObj(*GetThreadPool(), visitorFactory,
OnlyVisit::kVisitFinalizable))) {
LOG(ERROR) << "(*theAllocator).ParallelForEachObj() in TracingCollector::ParallelResurrection() return false.";
}
GCLog().Stream() << "Number of parallel tasks: " << finalizablesFromEachTask.size() << std::endl;
size_t numResurrected = 0;
for (auto &finalizables : finalizablesFromEachTask) {
for (auto objaddr : finalizables) {
#if __MRT_DEBUG
if (!IsUnmarkedResurrectable(objaddr)) {
LOG(FATAL) << "Attempted to resurrect non-resurrectable object. " <<
reinterpret_cast<MObject*>(reinterpret_cast<uintptr_t>(objaddr))->GetClass()->GetName() << maple::endl;
}
#endif
// Add to the finalization queue instead of freeing the object
// NOTE: __MRT_addFinalizableObj internally holds a mutex before adding
// the object to the queue, so it may be faster to create a batch version,
// such as __MRT_addManyFinalizableObj. But tests show that the current
// single-threaded performance is good enough for now because the mutex is
// never contended.
ReferenceProcessor::Instance().AddFinalizable(objaddr, true);
{
++numResurrected;
// Put it into the tracing work stack so that we continue marking from it.
Enqueue(objaddr, workStack);
}
}
}
LOG2FILE(kLogtypeGc) << numResurrected << " objects resurrected.\n";
}
void MarkSweepCollector::EnqueueNeighbors(address_t objAddr, WorkStack &workStack) {
auto refFunc = [this, &workStack, objAddr](reffield_t &field, uint64_t kind) {
address_t ref = RefFieldToAddress(field);
if ((kind != kUnownedRefBits) && InHeapBoundry(ref)) {
LOG2FILE(kLogTypeMix) << "enqueueing neighbor: 0x" << std::hex << ref << std::endl;
// This might hurt cache
if (UNLIKELY(!IsAllocatedByAllocator(ref))) {
LOG(ERROR) << "EnqueueNeighbors Adding released object into work queue " << std::hex <<
ref << " " << RCHeader(ref) << " " << GCHeader(ref) <<
" " << reinterpret_cast<MObject*>(ref)->GetClass()->GetName() <<
objAddr << " " << RCHeader(objAddr) << " " << GCHeader(objAddr) <<
" " << reinterpret_cast<MObject*>(objAddr)->GetClass()->GetName() <<
std::dec << maple::endl;
HandleRCError(ref);
}
Enqueue(ref, workStack);
}
};
ForEachRefField(objAddr, refFunc);
}
void MarkSweepCollector::EnqueueNeighborsForRef(address_t objAddr, WorkStack &workStack) {
address_t referentOffset = WellKnown::kReferenceReferentOffset;
MClass *klass = reinterpret_cast<MObject*>(objAddr)->GetClass();
uint32_t classFlag = klass->GetFlag();
if ((classFlag & modifier::kClassSoftReference) && !ReferenceProcessor::Instance().ShouldClearReferent(gcReason)) {
referentOffset = 0;
}
auto refFunc = [this, &workStack, objAddr, referentOffset](reffield_t &field, uint64_t kind) {
address_t ref = RefFieldToAddress(field);
if ((kind != kUnownedRefBits) && InHeapBoundry(ref)) {
LOG2FILE(kLogTypeMix) << " enqueueing neighbor for ref: 0x" << std::hex << ref << std::endl;
if (static_cast<int32_t>(reinterpret_cast<address_t>(&field) - objAddr) !=
static_cast<int32_t>(referentOffset)) {
if (UNLIKELY(!IsAllocatedByAllocator(ref))) {
LOG(ERROR) << "EnqueueNeighbors Adding released object into work queue " << std::hex <<
ref << " " << RCHeader(ref) << " " << GCHeader(ref) <<
" " << reinterpret_cast<MObject*>(ref)->GetClass()->GetName() <<
objAddr << " " << RCHeader(objAddr) << " " << GCHeader(objAddr) <<
" " << reinterpret_cast<MObject*>(objAddr)->GetClass()->GetName() <<
std::dec << maple::endl;
HandleRCError(ref);
}
Enqueue(ref, workStack);
} else if (Type() != kNaiveRCMarkSweep) {
// visit referent and running with GC
if (ref != 0 && ReferenceGetPendingNext(objAddr) == 0 && IsGarbage(ref)) {
GCReferenceProcessor::Instance().DiscoverReference(objAddr);
}
}
}
};
ForEachRefField(objAddr, refFunc);
}
#if MRT_TEST_CONCURRENT_MARK
static MrtBitmap snapshotBitmap;
#endif
void MarkSweepCollector::ConcurrentMSPreSTW1() {
SatbBuffer::Instance().Init(&markBitmap);
}
void MarkSweepCollector::ConcurrentMarkPrepare() {
#if MRT_TEST_CONCURRENT_MARK
// To test the correctness of concurrent mark, we run a marking
// in stop-the-world-1 stage before concurrent mark started, after
// concurrent mark finished we compare their mark bitmaps to find
// out objects which are not correctlly marked.
{
LOG2FILE(kLogtypeGc) << "TestConcurrentMark: snapshot mark...\n";
MRT_PHASE_TIMER("TestConcurrentMark: snapshot mark");
WorkStack workStack;
ParallelScanRoots(workStack, true, false);
ParallelMark(workStack);
// save bitmap to snapshotBitmap.
snapshotBitmap.CopyBitmap(markBitmap);
markBitmap.ResetBitmap();
}
#endif
// reset statistic.
newlyMarked.store(0, std::memory_order_relaxed);
newObjDuringMarking.store(0, std::memory_order_relaxed);
freedObjDuringMarking.store(0, std::memory_order_relaxed);
renewObjDuringMarking.store(0, std::memory_order_relaxed);
// set flag to indicate that concurrent marking is started.
SetConcurrentMarkRunning(true);
for (Mutator *mutator : MutatorList::Instance().List()) {
mutator->SetConcurrentMarking(true);
}
}
void MarkSweepCollector::ScanStackAndMark(Mutator &mutator) {
TracingCollector::WorkStack workStack;
if (doConservativeStackScan) {
mutator.VisitStackSlotsContent(
[&workStack](address_t ref) {
// most of stack slots are not java heap address.
if (UNLIKELY((*theAllocator).AccurateIsValidObjAddrConcurrent(ref))) {
workStack.push_back(ref);
}
}
);
mutator.VisitJavaStackRoots([&workStack](address_t ref) {
// currently only scan & collect the local var
if (LIKELY((*theAllocator).AccurateIsValidObjAddrConcurrent(ref))) {
workStack.push_back(ref);
}
});
} else {
mutator.VisitJavaStackRoots([&workStack](address_t ref) {
// currently only scan & collect the local var
if (LIKELY((*theAllocator).AccurateIsValidObjAddrConcurrent(ref))) {
workStack.push_back(ref);
}
});
}
// add a mark task
if (workStack.size() > 0) {
MplThreadPool *threadPool = GetThreadPool();
threadPool->AddTask(new (std::nothrow) ConcurrentMarkTask(*this, threadPool, workStack.begin(), workStack.size()));
}
// the stack is scanned, dec needScanMutators
if (numMutatorToBeScan.fetch_sub(1, std::memory_order_relaxed) == 1) {
// notify gc thread
concurrentPhaseBarrier.notify_all();
}
}
void MarkSweepCollector::StackScanBarrierInMutator() {
// check if need to scan
Mutator &mutator = TLMutator();
if (mutator.TrySetScanState(true)) {
// help gc thread to finish
// scan the stack of the mutator
ScanStackAndMark(mutator);
mutator.FinishStackScan(false);
std::lock_guard<std::mutex> guard(snapshotMutex);
snapshotMutators.erase(&mutator);
}
}
void MarkSweepCollector::ConcurrentStackScan() {
while (true) {
Mutator *mutator = nullptr;
bool needScan = false;
{
std::lock_guard<std::mutex> guard(snapshotMutex);
if (snapshotMutators.size() != 0) {
mutator = *(snapshotMutators.begin());
snapshotMutators.erase(mutator);
} else {
return;
}
needScan = mutator->TrySetScanState(false);
}
if (needScan) {
// scan the stack of the mutator
ScanStackAndMark(*mutator);
mutator->FinishStackScan(true);
}
}
}
void MarkSweepCollector::ScanSingleStaticRoot(address_t *rootAddr, TracingCollector::WorkStack &workStack) {
const reffield_t ref = LoadStaticRoot(rootAddr);
// most of static fields are null or non-heap objects (e.g. literal strings).
if (UNLIKELY(InHeapBoundry(ref))) {
address_t value = RefFieldToAddress(ref);
if (LIKELY(!IsObjectMarked(value))) {
workStack.push_back(ref);
}
}
}
void MarkSweepCollector::ConcurrentStaticRootsScan(bool parallel) {
TracingCollector::WorkStack workStack;
// scan static field roots.
address_t **staticList;
size_t staticListLen;
size_t index = 0;
while (GCRegisteredRoots::Instance().GetRootsLocked(index++, staticList, staticListLen)) {
for (size_t i = 0; i < staticListLen; ++i) {
ScanSingleStaticRoot(staticList[i], workStack);
}
}
// zterp static field roots
address_t spaceAddr = (*zterpStaticRootAllocator).GetStartAddr();
for (size_t i = 0; i < (*zterpStaticRootAllocator).GetObjNum(); ++i) {
ScanSingleStaticRoot(*(reinterpret_cast<address_t**>(spaceAddr)), workStack);
spaceAddr += ZterpStaticRootAllocator::singleObjSize;
}
// add a concurrent mark task.
MplThreadPool *threadPool = GetThreadPool();
if (parallel && threadPool != nullptr) {
AddConcurrentMarkTask(workStack);
} else {
// serial marking with a single mark task.
ConcurrentMarkTask markTask(*this, std::move(workStack));
markTask.Execute(0);
}
}
void MarkSweepCollector::ConcurrentMark(WorkStack &workStack, bool parallel, bool scanRoot) {
__MRT_ASSERT(IsConcurrentMarkRunning(), "running flag not set");
// enable parallel marking if we have thread pool.
MplThreadPool *threadPool = GetThreadPool();
__MRT_ASSERT(threadPool != nullptr, "thread pool is null");
if (parallel) {
// parallel marking.
AddConcurrentMarkTask(workStack);
workStack.clear();
threadPool->Start();
if (scanRoot) {
// precise stack scan
ConcurrentStackScan();
// concurrent mark static roots.
ConcurrentStaticRootsScan(parallel);
}
threadPool->WaitFinish(true);
} else {
if (scanRoot) {
// scan stack roots and add into task queue
ConcurrentStackScan();
// mark static roots.
ConcurrentStaticRootsScan(false);
}
// serial marking with a single mark task.
ConcurrentMarkTask markTask(*this, std::move(workStack));
markTask.Execute(0);
threadPool->DrainTaskQueue(); // drain stack roots task
}
// wait if the mutator is scanning the stack
if (numMutatorToBeScan.load(std::memory_order_relaxed) != 0) {
std::unique_lock<std::mutex> lk(snapshotMutex);
concurrentPhaseBarrier.wait(lk, [this]{
return numMutatorToBeScan.load(std::memory_order_relaxed) == 0;
});
}
}
void MarkSweepCollector::ConcurrentReMark(bool parallel) {
constexpr int kReMarkRounds = 2;
for (int i = 0; i < kReMarkRounds; ++i) {
// find out unmarked dirty objects.
WorkStack remarkStack;
{
MRT_PHASE_TIMER("Get re-mark stack");
SatbBuffer::Instance().GetRetiredObjects(remarkStack);
}
MplThreadPool *threadPool = GetThreadPool();
if (remarkStack.empty() && (threadPool->GetTaskNumber() == 0)) {
// stop re-mark if work stack is empty.
return;
}
LOG2FILE(kLogtypeGc) << " re-mark stack: " << Pretty(remarkStack.size()) << '\n';
// run re-mark if remarkStack not empty.
{
MRT_PHASE_TIMER("Run re-mark");
ConcurrentMark(remarkStack, parallel && (remarkStack.size() > kMaxMarkTaskSize), false);
}
}
}
// should be called in the beginning of stop-the-world-2.
void MarkSweepCollector::ConcurrentMarkCleanup() {
__MRT_ASSERT(IsConcurrentMarkRunning(), "running flag not set");
// statistics.
const size_t markObjects = newlyMarked.load(std::memory_order_relaxed);
const size_t newObjects = newObjDuringMarking.load(std::memory_order_relaxed);
const size_t freeObjects = freedObjDuringMarking.load(std::memory_order_relaxed);
const size_t renewObjects = renewObjDuringMarking.load(std::memory_order_relaxed);
LOG2FILE(kLogtypeGc) << " mark " << Pretty(markObjects) << '\n' <<
" new " << Pretty(newObjects) << '\n' <<
" free " << Pretty(freeObjects) << '\n' <<
" renew " << Pretty(renewObjects) << '\n';
#if MRT_TEST_CONCURRENT_MARK
// compare concurrent mark bitmap with snapshot bitmap.
std::vector<address_t> stwUnmarked;
std::vector<address_t> cmUnmarked;
CompareBitmap(snapshotBitmap, markBitmap, stwUnmarked, cmUnmarked);
LOG2FILE(kLogtypeGc) << "TestConcurrentMark:\n" <<
" snapshot unmarked: " << Pretty(stwUnmarked.size()) << '\n' <<
" concurrent unmarked: " << Pretty(cmUnmarked.size()) << '\n';
if (cmUnmarked.size() > 0) {
GCLogPrintObjects("=== concurrent unmarked ===", cmUnmarked, markBitmap, true);
LOG2FILE(kLogtypeGc) << "TestConcurrentMark failed!" << std::endl; // flush gclog.
LOG(FATAL) << "TestConcurrentMark failed! found unmarked alives: " << cmUnmarked.size() << maple::endl;
}
stwUnmarked.clear();
cmUnmarked.clear();
#endif
// find out unmarked dirty objects.
WorkStack remarkStack;
{
MRT_PHASE_TIMER("Find re-mark objects");
SatbBuffer::Instance().GetRetiredObjects(remarkStack);
auto func = [&](Mutator *mutator) {
const SatbBuffer::Node *node = mutator->GetSatbBufferNode();
mutator->SetConcurrentMarking(false);
if (node != nullptr) {
node->GetObjects(remarkStack);
mutator->ResetSatbBufferNode();
}
};
MutatorList::Instance().VisitMutators(func);
}
LOG2FILE(kLogtypeGc) << " stw re-mark stack: " << Pretty(remarkStack.size()) << '\n';
#if MRT_TEST_CONCURRENT_MARK
// print remark stack if test is enabled.
if (remarkStack.size() > 0) {
GCLogPrintObjects("=== Need Re-mark ===", remarkStack, markBitmap);
}
#endif
// start re-mark if needed, re-mark is marking on heap snapshot.
// we are more likely have an empty remark stack because of concurrent re-marking.
MplThreadPool *threadPool = GetThreadPool();
if (UNLIKELY((remarkStack.size() > 0) || (threadPool->GetTaskNumber() > 0))) {
MRT_PHASE_TIMER("Re-mark");
ConcurrentMark(remarkStack, (remarkStack.size() > kMaxMarkTaskSize) || (threadPool->GetTaskNumber() > 0), false);
}
// set flag to indicate that concurrent marking is done.
SetConcurrentMarkRunning(false);
// update heap bound again in the beginning of STW-2 stage.
InitTracing();
#if MRT_TEST_CONCURRENT_MARK
// To test the correctness of concurrent mark, we run a marking again
// after concurrent mark finished in stop-the-world-2 stage, and then
// compare their mark bitmaps to find out objects which are not
// correctlly marked.
LOG2FILE(kLogtypeGc) << "TestConcurrentMark...\n";
MRT_PHASE_TIMER("TestConcurrentMark");
// before we start another marking, make a copy of current mark bitmap,
// and then reset current mark bitmap.
MrtBitmap bitmap;
bitmap.CopyBitmap(markBitmap);
markBitmap.ResetBitmap();
// scan roots and marking.
{
MRT_PHASE_TIMER("TestConcurrentMark: scan roots & mark");
WorkStack workStack;
ParallelScanRoots(workStack, true, false);
ParallelMark(workStack);
}
// compare two bitmaps to find out error.
CompareBitmap(markBitmap, bitmap, stwUnmarked, cmUnmarked);
// We treat objects which are marked by concurrent marking, but
// not marked by STW marking, and not released as floating garbages.
size_t nFloatingGarbages = 0;
for (address_t obj : stwUnmarked) {
if (!HasReleasedBit(obj)) {
++nFloatingGarbages;
}
}
LOG2FILE(kLogtypeGc) << "TestConcurrentMark:\n" <<
" stw unmarked: " << stwUnmarked.size() << '\n' <<
" floating garbages: " << nFloatingGarbages << '\n' <<
" unmarked live objects: " << cmUnmarked.size() << '\n';
if (cmUnmarked.size() > 0) {
// scan root info.
RootInfo rootInfo;
std::vector<address_t> rs;
ScanStaticFieldRoots(rs);
rootInfo.staticRoots.insert(rs.begin(), rs.end());
rs.clear();
ScanExternalRoots(rs, true);
rootInfo.extRoots.insert(rs.begin(), rs.end());
rs.clear();
ScanStringRoots(rs);
rootInfo.stringRoots.insert(rs.begin(), rs.end());
rs.clear();
ScanReferenceRoots(rs);
rootInfo.refRoots.insert(rs.begin(), rs.end());
rs.clear();
ScanAllocatorRoots(rs);
rootInfo.allocatorRoots.insert(rs.begin(), rs.end());
rs.clear();
ScanClassLoaderRoots(rs);
rootInfo.classloaderRoots.insert(rs.begin(), rs.end());
rs.clear();
ScanAllStacks(rs);
rootInfo.stackRoots.insert(rs.begin(), rs.end());
rs.clear();
GCLogPrintObjects("=== unmarked live objects ===", cmUnmarked, markBitmap, true, &rootInfo);
LOG2FILE(kLogtypeGc) << "WARNING: check unmarked objects!" << std::endl; // flush gclog.
// we set rc to 0 for unmarked objects, so that 'inc/dec from 0' occurs if mutator access them.
for (address_t obj : cmUnmarked) {
RefCountLVal(obj) = 0;
}
}
LOG2FILE(kLogtypeGc) << "TestConcurrentMark done." << std::endl; // flush gclog.
// restore bitmap after test.
markBitmap.CopyBitmap(bitmap);
#endif // MRT_TEST_CONCURRENT_MARK
}
void MarkSweepCollector::ConcurrentMSPostSTW2() {
SatbBuffer::Instance().Reset();
}
void MarkSweepCollector::RunFullCollection(uint64_t gcIndex) {
// prevent other threads stop-the-world during GC.
ScopedLockStopTheWorld lockStopTheWorld;
PreMSHook();
// Run mark-and-sweep gc.
RunMarkAndSweep(gcIndex);
PostMSHook(gcIndex);
}
void MarkSweepCollector::RunMarkAndSweep(uint64_t gcIndex) {
// prepare thread pool.
MplThreadPool *threadPool = GetThreadPool();
const int32_t threadCount = GetThreadCount(false);
__MRT_ASSERT(threadCount > 1, "unexpected thread count");
threadPool->SetPriority(maple::kGCThreadStwPriority);
threadPool->SetMaxActiveThreadNum(threadCount);
const uint64_t gcStartNs = timeutils::NanoSeconds();
const GCReason reason = gcReason;
const bool concurrent = IsConcurrent(reason);
LOG(INFO) << "[GC] Start " << reasonCfgs[reason].name << " gcIndex= " << gcIndex << maple::endl;
stats::gcStats->BeginGCRecord();
stats::gcStats->CurrentGCRecord().reason = reason;
stats::gcStats->CurrentGCRecord().async = reasonCfgs[reason].IsNonBlockingGC();
stats::gcStats->CurrentGCRecord().isConcurrentMark = concurrent;
// run mark & sweep.
if (LIKELY(concurrent)) {
ConcurrentMarkAndSweep();
} else {
ParallelMarkAndSweep();
}
// releaes mark bitmap memory after GC.
ResetBitmap();
// it's the end of boot phase or it's a user_ni GC
GCReleaseSoType releaseSoType = reasonCfgs[reason].ShouldReleaseSo();
if (releaseSoType != kReleaseNone) {
MRT_PHASE_TIMER("ReleaseBootMemory");
MRT_ClearMetaProfile();
LinkerAPI::Instance().ClearAllMplFuncProfile();
LOG(INFO) << "Force GC finished" << maple::endl;
// release boot-phase maple*.so memory
LinkerAPI::Instance().ReleaseBootPhaseMemory(false, (releaseSoType == kReleaseAppSo) ? IsSystem() : true);
}
// release pages in PagePool
PagePool::Instance().Trim();
// update NativeGCStats after gc finished.
NativeGCStats::Instance().OnGcFinished();
// total GC time.
uint64_t gcTimeNs = timeutils::NanoSeconds() - gcStartNs;
stats::gcStats->CurrentGCRecord().totalGcTime = gcTimeNs;
LOG2FILE(kLogtypeGc) << "Total GC time: " << Pretty(gcTimeNs / kNsPerUs) << "us" << "\n";
// trigger reference processor after GC finished.
ReferenceProcessor::Instance().Notify(true);
}
void MarkSweepCollector::PreMSHook() {
// Notify that GC has started. We need to set the gc_running_ flag here
// because it is a guarantee that when TriggerGCAsync returns, the caller sees GC running.
SetGcRunning(true);
}
void MarkSweepCollector::PreSweepHook() {
}
void MarkSweepCollector::PostMSHook(uint64_t gcIndex) {
if (UNLIKELY(VLOG_IS_ON(allocatorfragmentlog))) {
if (IsConcurrent(gcReason)) {
ScopedStopTheWorld stopTheWorld;
std::stringstream ss;
(*theAllocator).PrintPageFragment(ss, "AfterGC");
LOG2FILE(kLogTypeAllocFrag) << ss.str() << std::flush;
}
}
GCReason reason = gcReason;
SetGcRunning(false);
NotifyGCFinished(gcIndex);
// some jobs can be done after NotifyGCFinished(), if they don't block the waiting threads
{
MRT_PHASE_TIMER("Post-MS hook: release free pages");
bool aggressive = reasonCfgs[reason].ShouldTrimHeap();
// release the physical memory of free pages
if (!(*theAllocator).ReleaseFreePages(aggressive)) {
LOG(INFO) << "no page released";
}
}
// commit gc statistics.
stats::gcStats->CommitGCRecord();
// flush gclog.
GCLog().OnGCEnd();
}
// stop the world parallel mark & sweep.
void MarkSweepCollector::ParallelMarkAndSweep() {
ScopedStopTheWorld stw;
const uint64_t stwStartNs = timeutils::NanoSeconds();
PrepareTracing();
ParallelMarkPhase();
ResurrectionPhase(false);
ParallelSweepPhase();
FinishTracing();
DumpAfterGC();
const uint64_t stwTimeNs = timeutils::NanoSeconds() - stwStartNs;
stats::gcStats->CurrentGCRecord().stw1Time = stwTimeNs;
stats::gcStats->CurrentGCRecord().stw2Time = 0;
TheAllocMutator::gcIndex++;
LOG2FILE(kLogtypeGc) << "Stop-the-world time: " << Pretty(stwTimeNs / kNsPerUs) << "us\n";
}
// concurrent mark & sweep.
void MarkSweepCollector::ConcurrentMarkAndSweep() {
ConcurrentMSPreSTW1();
WorkStack workStack = NewWorkStack();
WorkStack inaccurateRoots = NewWorkStack();
{
ScopedStopTheWorld stw1;
const uint64_t stw1StartNs = timeutils::NanoSeconds();
PrepareTracing();
ConcurrentMarkPreparePhase(workStack, inaccurateRoots);
const uint64_t stw1TimeNs = timeutils::NanoSeconds() - stw1StartNs;
stats::gcStats->CurrentGCRecord().stw1Time = stw1TimeNs;
LOG2FILE(kLogtypeGc) << "Stop-the-world-1 time: " << Pretty(stw1TimeNs / kNsPerUs) << "us\n";
}
ConcurrentMarkPhase(std::move(workStack), std::move(inaccurateRoots));
{
ScopedStopTheWorld stw2;
const uint64_t stw2StartNs = timeutils::NanoSeconds();
ConcurrentMarkCleanupPhase();
ResurrectionPhase(true);
ConcurrentSweepPreparePhase();
FinishTracing();
const uint64_t stw2TimeNs = timeutils::NanoSeconds() - stw2StartNs;
stats::gcStats->CurrentGCRecord().stw2Time = stw2TimeNs;
TheAllocMutator::gcIndex++;
LOG2FILE(kLogtypeGc) << "Stop-the-world-2 time: " << Pretty(stw2TimeNs / kNsPerUs) << "us\n";
}
ConcurrentMSPostSTW2();
ConcurrentSweepPhase();
}
void MarkSweepCollector::PrepareTracing() {
GCLog().OnGCStart();
LOG2FILE(kLogtypeGc) << "GCReason: " << reasonCfgs[gcReason].name << '\n';
if (VLOG_IS_ON(opengclog)) {
(*theAllocator).DumpContention(GCLog().Stream());
}
if (VLOG_IS_ON(allocatorfragmentlog)) {
std::stringstream ss;
(*theAllocator).PrintPageFragment(ss, "BeforeGC");
LOG2FILE(kLogTypeAllocFrag) << ss.str() << std::flush;
}
if (VLOG_IS_ON(dumpheapbeforegc)) {
DumpHeap("before_gc");
}
#if RC_HOT_OBJECT_DATA_COLLECT
DumpHotObj();
#endif
InitTracing();
}
void MarkSweepCollector::FinishTracing() {
EndTracing();
// Call the registerd callback before starting the world.
{
MRT_PHASE_TIMER("Calling GC-finish callback");
GCFinishCallBack();
}
}
void MarkSweepCollector::DumpAfterGC() {
if (VLOG_IS_ON(dumpheapaftergc)) {
DumpHeap("after_gc");
}
if (VLOG_IS_ON(allocatorfragmentlog)) {
std::stringstream ss;
(*theAllocator).PrintPageFragment(ss, "AfterGC");
LOG2FILE(kLogTypeAllocFrag) << ss.str() << std::flush;
}
}
void MarkSweepCollector::ParallelMarkPhase() {
MplThreadPool *threadPool = GetThreadPool();
const size_t threadCount = threadPool->GetMaxThreadNum() + 1;
clockid_t cid[threadCount];
struct timespec workerStart[threadCount];
struct timespec workerEnd[threadCount];
uint64_t workerCpuTime[threadCount];
#ifdef __ANDROID__
// qemu does not support sys_call: sched_getcpu()
// do not support profile executing cpu of workers
const bool profileSchedCore = true;
#else
const bool profileSchedCore = false;
#endif
// record executing cpu of workers in each sampling point
std::vector<int> schedCores[threadCount];
if (GCLog().IsWriteToFile(kLogTypeMix)) {
// debug functionality: set sched_core and cputime
size_t index = 1;
for (auto worker: threadPool->GetThreads()) {
pthread_t thread = worker->GetThread();
worker->schedCores = profileSchedCore ? &schedCores[index] : nullptr;
pthread_getcpuclockid(thread, &cid[index]);
clock_gettime(cid[index], &workerStart[index]);
++index;
}
pthread_getcpuclockid(pthread_self(), &cid[0]);
clock_gettime(cid[0], &workerStart[0]);
}
{
MRT_PHASE_TIMER("Parallel Scan Roots & Mark");
// prepare
threadPool->Start();
RootSet rootSets[threadCount];
ParallelScanMark(rootSets, true, false);
threadPool->WaitFinish(true, profileSchedCore ? &schedCores[0] : nullptr);
}
if (GCLog().IsWriteToFile(kLogTypeMix)) {
// debug functionality: print cputime & sched core
for (size_t i = 0; i < threadCount; ++i) {
clock_gettime(cid[i], &workerEnd[i]);
workerCpuTime[i] = static_cast<uint64_t>(workerEnd[i].tv_sec - workerStart[i].tv_sec) *
maple::kSecondToNanosecond + static_cast<uint64_t>((workerEnd[i].tv_nsec - workerStart[i].tv_nsec));
}
int cpus[threadCount][threadCount];
errno_t ret = memset_s(cpus, sizeof(cpus), 0, sizeof(cpus));
if (UNLIKELY(ret != EOK)) {
LOG(ERROR) << "memset_s(cpus, sizeof(cpus), 0, sizeof(cpus)) in ParallelMarkPhase return " <<
ret << " rather than 0." << maple::endl;
}
for (size_t i = 0; i < threadCount; ++i) {
for (auto num: schedCores[i]) {
cpus[i][num % static_cast<int>(threadCount)] += 1;
}
}
for (size_t i = 0; i < threadCount; ++i) {
LOG2FILE(kLogtypeGc) << "worker " << i << " cputime:" << workerCpuTime[i] << ",\t";
for (size_t j = 0; j < threadCount; ++j) {
LOG2FILE(kLogtypeGc) << cpus[i][j] << "\t";
}
LOG2FILE(kLogtypeGc) << '\n';
}
}
}
void MarkSweepCollector::ResurrectionPhase(bool isConcurrent) {
if (Type() == kNaiveRCMarkSweep) {
MRT_PHASE_TIMER("Reference: Release Queue");
#if __MRT_DEBUG
MrtVisitReferenceRoots([this](address_t obj) {
// As stack scan is conservative, it is poissble that released object on stack and marked
if (!(InHeapBoundry(obj) && (IsGarbage(obj) || IsRCCollectable(obj)))) {
LOG(FATAL) << "Live object in release queue. " <<
std::hex << obj << std::dec <<
" IsObjectMarked=" << IsObjectMarked(obj) <<
" refCount=" << RefCount(obj) <<
" weakRefCount=" << WeakRefCount(obj) <<
" resurrect weakRefCount=" << ResurrectWeakRefCount(obj) <<
(IsWeakCollected(obj) ? " weak collected " : " not weak collected ") <<
reinterpret_cast<MObject*>(obj)->GetClass()->GetName() << maple::endl;
return;
}
}, RPMask(kRPReleaseQueue));
#endif
RCReferenceProcessor::Instance().ClearAsyncReleaseObjs();
}
// Handle Soft/Weak Reference.
if (UNLIKELY(VLOG_IS_ON(dumpgarbage))) {
DumpWeakSoft();
}
if (Type() == kNaiveRCMarkSweep) {
if (LIKELY(isConcurrent)) {
MRT_PHASE_TIMER("Soft/Weak Refinement");
ReferenceRefinement(RPMask(kRPSoftRef) | RPMask(kRPWeakRef));
} else {
MRT_PHASE_TIMER("Parallel Reference: Soft/Weak");
if (Type() == kNaiveRCMarkSweep) {
ParallelDoReference(RPMask(kRPSoftRef) | RPMask(kRPWeakRef));
}
}
} else {
MRT_PHASE_TIMER("Soft/Weak Discover Processing");
GCReferenceProcessor::Instance().ProcessDiscoveredReference(RPMask(kRPSoftRef) | RPMask(kRPWeakRef));
}
// Finalizable resurrection phase.
WorkStack workStack = NewWorkStack();
{
MRT_PHASE_TIMER("Parallel Resurrection");
if (isConcurrent) {
DoResurrection(workStack);
} else {
ParallelResurrection(workStack);
}
}
LOG2FILE(kLogtypeGc) << "Mark 2:\n" << " workStack size = " << workStack.size() << '\n';
if (!isConcurrent) {
MRT_PHASE_TIMER("Parallel Mark 2");
ParallelMark(workStack);
}
if (UNLIKELY(VLOG_IS_ON(dumpgarbage))) {
DumpCleaner();
}
// Handle Cleaner.
if (Type() == kNaiveRCMarkSweep) {
if (LIKELY(isConcurrent)) {
MRT_PHASE_TIMER("Cleaner Refinement");
ReferenceRefinement(RPMask(kRPPhantomRef));
} else {
MRT_PHASE_TIMER("Parallel Reference: Cleaner");
ParallelDoReference(RPMask(kRPPhantomRef));
}
} else {
MRT_PHASE_TIMER("Cleaner: Discover Processing");
uint32_t rpFlag = RPMask(kRPSoftRef) | RPMask(kRPWeakRef) | RPMask(kRPPhantomRef);
GCReferenceProcessor::Instance().ProcessDiscoveredReference(rpFlag);
}
{
MRT_PHASE_TIMER("Reference: WeakGRT");
DoWeakGRT();
}
}
void MarkSweepCollector::ConcurrentMarkPreparePhase(WorkStack& workStack, WorkStack& inaccurateRoots) {
{
// use fast root scan for concurrent marking.
MRT_PHASE_TIMER("Fast Root scan");
FastScanRoots(workStack, inaccurateRoots, true, false);
}
// prepare for concurrent marking.
ConcurrentMarkPrepare();
}
void MarkSweepCollector::ConcurrentMarkPhase(WorkStack&& workStack, WorkStack&& inaccurateRoots) {
// prepare root set before mark, filter out inaccurate roots.
{
MRT_PHASE_TIMER("Prepare root set");
const size_t accurateSize = workStack.size();
const size_t inaccurateSize = inaccurateRoots.size();
PrepareRootSet(workStack, std::move(inaccurateRoots));
LOG2FILE(kLogtypeGc) << "accurate: " << accurateSize <<
" inaccurate: " << inaccurateSize <<
" final roots: " << workStack.size() <<
'\n';
}
// BT statistic for root size.
BTCleanupStats::rootSetSize = workStack.size();
MplThreadPool *threadPool = GetThreadPool();
__MRT_ASSERT(threadPool != nullptr, "null thread pool");
// use fewer threads and lower priority for concurrent mark.
const int32_t stwWorkers = threadPool->GetMaxActiveThreadNum();
const int32_t maxWorkers = GetThreadCount(true) - 1;
if (maxWorkers > 0) {
threadPool->SetMaxActiveThreadNum(maxWorkers);
threadPool->SetPriority(maple::kGCThreadConcurrentPriority);
}
MRT_SetThreadPriority(maple::GetTid(), maple::kGCThreadConcurrentPriority);
LOG2FILE(kLogtypeGc) << "Concurrent mark with " << (maxWorkers + 1) << " threads" <<
", workStack: " << workStack.size() << '\n';
// run concurrent marking.
{
MRT_PHASE_TIMER("Concurrent marking");
ConcurrentMark(workStack, maxWorkers > 0, true);
}
// concurrent do references
if (Type() == kNaiveRCMarkSweep) {
InitReferenceWorkSet();
{
MRT_PHASE_TIMER("Concurrent Do Reference: Soft/Weak");
ConcurrentDoReference(RPMask(kRPSoftRef) | RPMask(kRPWeakRef));
}
{
MRT_PHASE_TIMER("Concurrent Do Reference: Cleaner");
ConcurrentDoReference(RPMask(kRPPhantomRef));
}
} else {
MRT_PHASE_TIMER("Concurrent Do Reference");
GCReferenceProcessor::Instance().ConcurrentProcessDisovered();
}
{
MRT_PHASE_TIMER("Concurrent prepare resurrection");
ConcurrentPrepareResurrection();
}
{
MRT_PHASE_TIMER("Concurrent mark finalizer");
ConcurrentMarkFinalizer();
}
// run concurrent re-marking.
{
MRT_PHASE_TIMER("Concurrent re-marking");
ConcurrentReMark(maxWorkers > 0);
}
// restore thread pool max workers and priority after concurrent marking.
if (maxWorkers > 0) {
threadPool->SetMaxActiveThreadNum(stwWorkers);
threadPool->SetPriority(maple::kGCThreadStwPriority);
}
MRT_SetThreadPriority(maple::GetTid(), maple::kGCThreadStwPriority);
}
// concurrent marking clean-up, run in STW2.
void MarkSweepCollector::ConcurrentMarkCleanupPhase() {
MRT_PHASE_TIMER("Concurrent marking clean-up");
ConcurrentMarkCleanup();
}
void MarkSweepCollector::ConcurrentSweepPreparePhase() {
if (VLOG_IS_ON(dumpgarbage)) {
DumpGarbage();
}
PreSweepHook();
{
MRT_PHASE_TIMER("Sweep: prepare concurrent for StringTable");
StringPrepareConcurrentSweeping();
}
{
MRT_PHASE_TIMER("Sweep: prepare concurrent sweep");
(*theAllocator).PrepareConcurrentSweep();
}
}
void MarkSweepCollector::ConcurrentSweepPhase() {
// reduce the number of thread in concurrent stage.
MplThreadPool *threadPool = GetThreadPool();
const int32_t maxWorkers = GetThreadCount(true) - 1;
if (maxWorkers > 0) {
threadPool->SetMaxActiveThreadNum(maxWorkers);
threadPool->SetPriority(maple::kGCThreadConcurrentPriority);
}
MRT_SetThreadPriority(maple::GetTid(), maple::kGCThreadConcurrentPriority);
if (Type() != kNaiveRCMarkSweep) {
// concurrent sweep only sweep unmarked objects in both bitmap.
// it's safe to concurrent add finalizer to reference processor.
MRT_PHASE_TIMER("Concurrent Add Finalizer");
ConcurrentAddFinalizerToRP();
}
{
MRT_PHASE_TIMER("Resurrection cleanup");
ResurrectionCleanup();
}
{
MRT_PHASE_TIMER("Concurrent sweep");
(*theAllocator).ConcurrentSweep((maxWorkers > 0) ? threadPool : nullptr);
}
{
MRT_PHASE_TIMER("Concurrent sweep StringTable");
size_t deadStrings = ConcurrentSweepDeadStrings((maxWorkers > 0) ? threadPool : nullptr);
LOG2FILE(kLogtypeGc) << " Dead strings in StringTable: " << deadStrings << '\n';
}
if (Type() == kNaiveRCMarkSweep) {
ResetReferenceWorkSet();
}
MRT_SetThreadPriority(maple::GetTid(), maple::kGCThreadPriority);
}
void MarkSweepCollector::ParallelSweepPhase() {
MRT_PHASE_TIMER("Parallel Sweep");
size_t oldLiveBytes = (*theAllocator).AllocatedMemory();
size_t oldLiveObjBytes = (*theAllocator).RequestedMemory();
size_t oldTotalObjects = (*theAllocator).AllocatedObjs();
if (VLOG_IS_ON(dumpgarbage)) {
DumpGarbage();
}
PreSweepHook();
size_t deadStrings;
{
MRT_PHASE_TIMER("Sweep: Removing String from StringTable");
deadStrings = RemoveDeadStringFromPool();
}
MRT_PHASE_TIMER("Parallel Sweep: enumerating and sweeping");
auto sweeper = [this](address_t addr) {
return CheckAndPrepareSweep(addr);
};
#if CONFIG_JSAN
auto checkAndSweep = [&sweeper](address_t addr) {
if (sweeper(addr)) {
(*theAllocator).FreeObj(addr);
}
};
(*theAllocator).ParallelForEachObj(*GetThreadPool(), [&checkAndSweep] {
return checkAndSweep;
}, OnlyVisit::kVisitAll);
#else
if (UNLIKELY(!(*theAllocator).ParallelFreeAllIf(*GetThreadPool(), sweeper))) {
LOG(ERROR) << "(*theAllocator).ParallelFreeAllIf() in ParallelSweepPhase() return false." << maple::endl;
}
#endif
size_t newLiveBytes = (*theAllocator).AllocatedMemory();
size_t newLiveObjBytes = (*theAllocator).RequestedMemory();
size_t newTotalObjects = (*theAllocator).AllocatedObjs();
size_t totalObjBytesCollected = oldLiveObjBytes - newLiveObjBytes;
size_t totalBytesCollected = oldLiveBytes - newLiveBytes;
size_t totalBytesSurvived = newLiveBytes;
size_t totalGarbages = oldTotalObjects - newTotalObjects;
stats::gcStats->CurrentGCRecord().objectsCollected = totalGarbages;
stats::gcStats->CurrentGCRecord().bytesCollected = totalBytesCollected;
stats::gcStats->CurrentGCRecord().bytesSurvived = totalBytesSurvived;
LOG2FILE(kLogtypeGc) << "End of parallel sweeping.\n" <<
" Total objects: " << oldTotalObjects << '\n' <<
" Live objects: " << newTotalObjects << '\n' <<
" Total garbages: " << totalGarbages << '\n' <<
" Object Survived(bytes) " << Pretty(newLiveObjBytes) <<
" Object Collected(bytes) " << Pretty(totalObjBytesCollected) << '\n' <<
" Total Survived(bytes) " << Pretty(totalBytesSurvived) <<
" Total Collected(bytes) " << Pretty(totalBytesCollected) << '\n' <<
" Dead strings in StringTable: " << deadStrings << '\n';
}
void MarkSweepCollector::Fini() {
TracingCollector::Fini();
}
void MarkSweepCollector::AddConcurrentMarkTask(RootSet &rs) {
if (rs.size() == 0) {
return;
}
MplThreadPool *threadPool = GetThreadPool();
size_t threadCount = threadPool->GetMaxActiveThreadNum() + 1;
const size_t kChunkSize = std::min(rs.size() / threadCount + 1, kMaxMarkTaskSize);
// Split the current work stack into work tasks.
auto end = rs.end();
for (auto it = rs.begin(); it < end;) {
const size_t delta = std::min(static_cast<size_t>(end - it), kChunkSize);
threadPool->AddTask(new (std::nothrow) ConcurrentMarkTask(*this, threadPool, it, delta));
it += delta;
}
}
} // namespace maplert
| 34.69654 | 120 | 0.668579 | [
"object",
"vector"
] |
4bff2317d1a3f1a417f22af64f2d49d7e538f613 | 7,662 | cpp | C++ | oi/uoj/P277/main.cpp | Riteme/test | b511d6616a25f4ae8c3861e2029789b8ee4dcb8d | [
"BSD-Source-Code"
] | 3 | 2018-08-30T09:43:20.000Z | 2019-12-03T04:53:43.000Z | oi/uoj/P277/main.cpp | Riteme/test | b511d6616a25f4ae8c3861e2029789b8ee4dcb8d | [
"BSD-Source-Code"
] | null | null | null | oi/uoj/P277/main.cpp | Riteme/test | b511d6616a25f4ae8c3861e2029789b8ee4dcb8d | [
"BSD-Source-Code"
] | null | null | null | #include <cmath>
#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>
#include <algorithm>
#include <unordered_map>
using namespace std;
#define EPS 1e-8
#define INF 1e99
template <typename T>
inline bool eq(T x, decltype(x) y) {
return abs(x - y) < EPS;
}
#define NMAX 500
#define MMAX 5000000
struct vec {
vec() : x(0), y(0) {}
vec(double _x, double _y) : x(_x), y(_y) {}
double x, y;
double len() const {
return hypot(x, y);
}
double len2() const {
return x * x + y * y;
}
int region() const {
if (x >= 0 && y >= 0) return 1;
if (x <= 0 && y >= 0) return 2;
if (x <= 0 && y <= 0) return 3;
return 4;
}
vec operator+(const vec &z) const {
return {x + z.x, y + z.y};
}
vec operator-(const vec &z) const {
return {x - z.x, y - z.y};
}
vec operator-() const {
return {-x, -y};
}
vec operator*(double k) const {
return {x * k, y * k};
}
vec &operator/=(double k) {
x /= k;
y /= k;
return *this;
}
// unreliable: intended for unordered_map
bool operator==(const vec &z) const {
return x == z.x && y == z.y;
}
};
double dot(const vec &u, const vec &v) {
return u.x * v.x + u.y * v.y;
}
double cross(const vec &u, const vec &v) {
return u.x * v.y - u.y * v.x;
}
struct cir {
vec c;
double r;
};
struct line {
vec p, u;
};
struct seg {
vec u, v;
double len() const {
return (u - v).len();
}
};
enum TangentStatus {
TPOINT = 1,
TNORMAL = 2,
TINNERT = 3,
TCROSS = 4,
TOUTERT = 5,
TCONTAIN = 6
};
struct TangentResult {
seg s[4];
TangentStatus stat;
bool swapped;
};
TangentResult tangent(cir a, cir b) {
// assert: a.c != b.c
bool swapped = false;
if (a.r < b.r) {
swap(a, b);
swapped = true;
}
vec p = b.c - a.c;
double R = a.r, r = b.r, d = p.len();
TangentStatus stat;
if (eq(r, 0)) stat = TPOINT;
else if (R + r <= d - EPS) stat = TNORMAL;
else if (eq(R + r, d)) stat = TINNERT;
else if (d - EPS >= R - r) stat = TCROSS;
else if (eq(R - r, d)) stat = TOUTERT;
else stat = TCONTAIN;
// branch out if optimization is needed.
double
k = r / R,
t1 = (R - r) / d, t2 = (R + r) / d,
L1 = R * t1, H1 = R * sqrt(max(0.0, 1 - t1 * t1)), // max: prevent nan
L2 = R * t2, H2 = R * sqrt(max(0.0, 1 - t2 * t2)),
l1 = L1 * k, h1 = H1 * k,
l2 = L2 * k, h2 = H2 * k;
p /= d;
vec o = {p.y, -p.x};
vec P1 = a.c + p * L1, P2 = a.c + p * L2;
vec O1 = o * H1, O2 = o * H2;
vec p1 = b.c + p * l1, p2 = b.c - p * l2;
vec o1 = o * h1, o2 = o * h2;
return {{
{P1 + O1, p1 + o1},
{P1 - O1, p1 - o1},
{P2 + O2, p2 - o2},
{P2 - O2, p2 + o2}
}, stat, swapped};
}
double pldist(const vec &v, const line &l) {
return abs(cross(v - l.p, l.u) / l.u.len());
}
double psdist(const vec &v, const seg &s) {
vec p = s.v - s.u;
if (dot(v - s.u, p) > -EPS &&
dot(v - s.v, -p) > -EPS)
return pldist(v, {s.u, p});
return INF; // optimization for this problem
//return min((v - s.u).len(), (v - s.v).len());
}
double p2arc(const cir &c, const vec &u, const vec &v) {
// avoid float inaccuracy
if (eq(u.x, v.x) && eq(u.y, v.y))
return 0;
double d = dot(u, v);
double cr = cross(u, v);
double t = acos(d / c.r / c.r);
return c.r * (cr > 0 ? t : 2 * M_PI - t);
}
bool no_intersect(const seg &s, const cir &c) {
vec p = s.v - s.u;
return
dot(c.c - s.u, p) <= EPS ||
dot(c.c - s.v, -p) <= EPS ||
abs(cross(c.c - s.u, p)) > (c.r - EPS) * p.len();
}
struct Edge {
int v;
double w;
};
static vec sp, tp;
static int n, m;
static cir C[NMAX + 10];
static vector<pair<vec, int>> P[NMAX + 10];
static vector<Edge> G[MMAX + 10];
void link(int u, int v, double w) {
G[u].push_back({v, w});
G[v].push_back({u, w});
}
void connect(const cir &c1, const cir &c2, int i, int j) {
auto r = tangent(c1, c2);
if (r.swapped)
swap(i, j);
int c;
switch (r.stat) {
case TPOINT: c = 2; break;
case TNORMAL: c = 4; break;
case TINNERT: c = 3; break;
default: c = 0;
}
for (int k = 0; k < c; k++) {
seg &s = r.s[k];
bool ok = true;
for (int p = 1; ok && p <= n; p++) if (p != i && p != j)
ok &= no_intersect(s, C[p]);
if (!ok) continue;
int u = i > 0 ? ++m : -i;
int v = j > 0 ? ++m : -j;
if (i > 0) P[i].push_back({s.u - C[i].c, u});
if (j > 0) P[j].push_back({s.v - C[j].c, v});
//fprintf(stderr, "[%d](%.4lf, %.4lf) - [%d](%.4lf, %.4lf): %.4lf\n",
// u, s.u.x, s.u.y,
// v, s.v.x, s.v.y, s.len());
link(u, v, s.len());
}
}
double shortest(int s, int t) {
static double dist[MMAX + 10];
for (int i = 1; i <= m; i++)
dist[i] = INF;
dist[s] = 0;
struct State {
int u;
double t;
bool operator<(const State &z) const {
return t > z.t;
}
};
priority_queue<State> q;
q.push({s, 0});
while (!q.empty()) {
auto _ = q.top();
q.pop();
int u = _.u;
if (_.t > dist[u])
continue;
for (auto &e : G[u]) {
int v = e.v;
if (dist[v] > dist[u] + e.w) {
dist[v] = dist[u] + e.w;
q.push({v, dist[v]});
}
}
}
return dist[t];
}
int main() {
scanf("%lf%lf%lf%lf%d", &sp.x, &sp.y, &tp.x, &tp.y, &n);
int s = ++m, t = ++m;
for (int i = 1; i <= n; i++)
scanf("%lf%lf%lf", &C[i].c.x, &C[i].c.y, &C[i].r);
bool ok = true;
for (int i = 1; ok && i <= n; i++)
ok &= no_intersect({sp, tp}, C[i]);
if (ok)
link(s, t, (sp - tp).len());
for (int i = 1; i <= n; i++) {
connect({sp, 0}, C[i], -s, i);
connect({tp, 0}, C[i], -t, i);
}
for (int i = 1; i <= n; i++)
for (int j = i + 1; j <= n; j++)
connect(C[i], C[j], i, j);
for (int i = 1; i <= n; i++) {
sort(P[i].begin(), P[i].end(),
[](const pair<vec, int> &_u, const pair<vec, int> &_v) {
const vec &u = _u.first;
const vec &v = _v.first;
int ui = u.region();
int vi = v.region();
return ui < vi ||
(ui == vi && cross(u, v) > 0);
});
double sum = 0;
for (int j = 0; j < P[i].size(); j++) {
int k = j + 1 < P[i].size() ? j + 1 : 0;
pair<vec, int> &u = P[i][j], &v = P[i][k];
double w = p2arc(C[i], u.first, v.first);
sum += w;
//fprintf(stderr, "[%d](%.4lf, %.4lf) - [%d](%.4lf, %.4lf): %.4lf\n",
// u.second, u.first.x, u.first.y,
// v.second, v.first.x, v.first.y, w);
link(u.second, v.second, w);
}
//fprintf(stderr, "sum = %.4lf\n", sum);
}
printf("%.1lf\n", shortest(s, t));
return 0;
}
/*
int main() {
cir a, b;
while (
scanf("%lf%lf%lf%lf%lf%lf",
&a.c.x, &a.c.y, &a.r, &b.c.x, &b.c.y, &b.r) != EOF
) {
auto ret = tangent(a, b);
for (int i = 0; i < 4; i++) {
auto &u = ret.s[i].u, &v = ret.s[i].v;
printf("(%.4lf, %.4lf) - (%.4lf, %.4lf) [%d]\n",
u.x, u.y, v.x, v.y, ret.stat);
}
}
return 0;
}
*/
| 22.94012 | 81 | 0.429522 | [
"vector"
] |
ef04810e2da04496d4cb9c793aec17bae6de3dd3 | 909 | cpp | C++ | b/324.cpp | Arafatk/codeforces | 314e8aa64c0b678866dab0d7a7694b9d30dc7f51 | [
"MIT"
] | null | null | null | b/324.cpp | Arafatk/codeforces | 314e8aa64c0b678866dab0d7a7694b9d30dc7f51 | [
"MIT"
] | null | null | null | b/324.cpp | Arafatk/codeforces | 314e8aa64c0b678866dab0d7a7694b9d30dc7f51 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> ii;
int main() {
int n;
scanf("%d", &n);
int a[n+1], b[n+1];
for (int i = 1; i <= n; ++i)
scanf("%d", a+i);
for (int i = 1; i <= n; ++i)
scanf("%d", b+i);
int desired_pos[n+1];
for (int i = 1; i <= n; ++i)
desired_pos[b[i]] = i;
int acc = 0;
vector<ii> ans;
for (int i = n; i >= 1; --i) {
int pos = i;
for (int j = i+1; j <= desired_pos[a[pos]]; ++j) {
if (desired_pos[a[j]] <= pos) {
acc += abs(j-pos);
ans.emplace_back(pos, j);
swap(a[pos], a[j]);
pos = j;
}
}
}
printf("%d\n", acc);
printf("%d\n", (int) ans.size());
for (const ii x : ans)
printf("%d %d\n", x.first, x.second);
}
| 23.921053 | 58 | 0.427943 | [
"vector"
] |
ef0637648d15eefd669e03a8f45fbcb7e34a55c3 | 8,382 | cpp | C++ | lib/Backends/OpenCL/OpenCLDeviceManager.cpp | waynehpc/pytorch-glow | 3f5baa2426010937fce5c8746daebbf6f9d2db62 | [
"Apache-2.0"
] | null | null | null | lib/Backends/OpenCL/OpenCLDeviceManager.cpp | waynehpc/pytorch-glow | 3f5baa2426010937fce5c8746daebbf6f9d2db62 | [
"Apache-2.0"
] | null | null | null | lib/Backends/OpenCL/OpenCLDeviceManager.cpp | waynehpc/pytorch-glow | 3f5baa2426010937fce5c8746daebbf6f9d2db62 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (c) 2017-present, Facebook, 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.
*/
#define DEBUG_TYPE "opencl"
// Silence Apple's warning about the deprecation of OpenCL.
#define CL_SILENCE_DEPRECATION
// Silence warnings about using deprecated OpenCL 1.2 functions.
#define CL_USE_DEPRECATED_OPENCL_1_2_APIS
#include "OpenCLDeviceManager.h"
#include "OpenCL.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/raw_ostream.h"
using namespace glow;
using namespace glow::runtime;
namespace glow {
namespace runtime {
DeviceManager *createOCLDeviceManager(llvm::StringRef name) {
return new OpenCLDeviceManager(name);
}
} // namespace runtime
} // namespace glow
cl_mem OpenCLDeviceManager::allocDeviceBuffer(uint64_t size) {
const uint64_t alignment = 128;
// Always allocate buffers properly aligned to hold values of any type.
size = alignedSize(size, alignment);
auto buf =
clCreateBuffer(context_, CL_MEM_READ_WRITE, size, nullptr, nullptr);
GLOW_ASSERT(buf && "Allocation failed!");
return buf;
}
OpenCLDeviceManager::OpenCLDeviceManager(llvm::StringRef name)
: QueueBackedDeviceManager(BackendKind::OpenCL, name) {
name_ = name.str();
}
ResultCode OpenCLDeviceManager::init() {
// For now we have a string, if the first digit is
// an int use it, otherwise
// use 0 as the default.
// There are flags in the OpenCLBackend to select devices. Once we refactor
// more functionality out of the OCLCompiledFunction we can move those flags
// here.
auto deviceId{0};
if (llvm::isDigit(name_[0])) {
deviceId = std::stoi(name_.substr(0, 1));
}
cl_uint numPlatforms{0};
cl_int err = clGetPlatformIDs(0, NULL, &numPlatforms);
if (err != CL_SUCCESS) {
llvm::outs() << "clGetPlatformIDs Failed. \n";
return ResultCode::Failed;
}
std::vector<cl_platform_id> platform_ids(numPlatforms);
err = clGetPlatformIDs(numPlatforms, platform_ids.data(), NULL);
// Take the first platform.
cl_platform_id platform_id_used = platform_ids[0];
cl_uint num{0};
err = clGetDeviceIDs(platform_id_used, CL_DEVICE_TYPE_ALL, 0, nullptr, &num);
if (err != CL_SUCCESS) {
llvm::outs() << "clGetDeviceIDs Failed.\n";
return ResultCode::Failed;
}
if (num < deviceId) {
llvm::outs()
<< "Should have at least one GPU/CPU/FPGA for running OpenCL\n";
return ResultCode::Failed;
}
std::vector<cl_device_id> devices(num);
err = clGetDeviceIDs(platform_id_used, CL_DEVICE_TYPE_ALL, num,
devices.data(), nullptr);
if (err != CL_SUCCESS) {
llvm::outs() << "clGetDeviceIDs Failed.\n";
return ResultCode::Failed;
}
deviceId_ = devices[deviceId];
context_ = clCreateContext(nullptr, 1, &deviceId_, nullptr, nullptr, nullptr);
if (!context_) {
llvm::outs() << "clCreateContext Failed.\n";
return ResultCode::Failed;
}
commands_ = clCreateCommandQueue(
context_, deviceId_, (doProfile_) ? CL_QUEUE_PROFILING_ENABLE : 0, &err);
if (!commands_) {
llvm::outs() << "clCreateCommandQueue Failed.\n";
return ResultCode::Failed;
}
cl_ulong mem_size;
err = clGetDeviceInfo(deviceId_, CL_DEVICE_GLOBAL_MEM_SIZE, sizeof(cl_ulong),
&mem_size, NULL);
if (err != CL_SUCCESS) {
llvm::outs() << "Error getting device memory limit.\n";
return ResultCode::Failed;
}
maxMemoryBytes_ = mem_size;
return ResultCode::Executed;
}
OpenCLDeviceManager::~OpenCLDeviceManager() {
clReleaseCommandQueue(commands_);
clReleaseContext(context_);
buffers_.clear();
}
uint64_t OpenCLDeviceManager::getMaximumMemory() const {
return maxMemoryBytes_;
}
uint64_t OpenCLDeviceManager::getAvailableMemory() const {
return maxMemoryBytes_ - usedMemoryBytes_;
}
bool OpenCLDeviceManager::isMemoryAvailable(uint64_t estimate) const {
return maxMemoryBytes_ >= (usedMemoryBytes_ + estimate);
}
void OpenCLDeviceManager::addNetworkImpl(const Module *module,
FunctionMapTy functions,
ReadyCBTy readyCB) {
// First check for uniqueness of the function name.
for (const auto &func : functions) {
if (functions_.count(func.first) != 0) {
llvm::errs() << "Failed to add network: already have a function called "
<< func.first << ".\n";
readyCB(module, ResultCode::Failed);
return;
}
if (func.second->getCompileBackendKind() != BackendKind::OpenCL) {
llvm::errs() << "Failed to add network: function " << func.first
<< " is not an OpenCL Function.\n";
readyCB(module, ResultCode::Failed);
}
}
// Collect constants once, since currently the bundle grabs everything in the
// module.
auto &bundle = functions.begin()->second->getRuntimeBundle();
if (bundle.getConstants() == nullptr) {
bundle.collectConstants(module);
}
size_t sizeInBytes = bundle.getConstantWeightSize();
if (usedMemoryBytes_ + sizeInBytes > maxMemoryBytes_) {
llvm::errs() << "Failed to add network: not enough memory.\n";
// Free the constants.
bundle.freeConstants();
readyCB(module, ResultCode::Failed);
return;
}
// Copy constants to device.
auto size = bundle.getConstantWeightSize() + bundle.getMutableWeightSize() +
bundle.getActivationsSize();
auto deviceBuffer = allocDeviceBuffer(size);
auto buffer = std::make_shared<OpenCLBuffer>(deviceBuffer, size);
if (bundle.getConstants()) {
auto buf = bundle.getConstants();
size_t valueOffset = 0;
cl_event event{nullptr};
cl_int err = clEnqueueWriteBuffer(
commands_, buffer->getBuffer(), /* blocking_write */ CL_FALSE,
valueOffset, sizeInBytes, buf, /* num_events_in_wait_list */ 0,
/* event_list */ nullptr, /* event */ doProfile_ ? &event : nullptr);
GLOW_ASSERT(err == CL_SUCCESS && "Unable to copy data to the device");
clFinish(commands_);
}
usedMemoryBytes_ += sizeInBytes;
// Add to the function name lookup map.
// Add shared pointer to buffer to buffers. This way buffer will be freed
// after last reference is removed.
for (const auto &func : functions) {
functions_.emplace(func.first, func.second);
buffers_.emplace(func.first, buffer);
buffer->incrementUsers();
}
assert(usedMemoryBytes_ <= maxMemoryBytes_);
// Fire the ready CB.
readyCB(module, ResultCode::Ready);
}
void OpenCLDeviceManager::evictNetworkImpl(std::string functionName,
EvictFunctionCBTy evictCB) {
ResultCode resultCode = ResultCode::Failed;
if (functions_.erase(functionName)) {
auto buffer = buffers_[functionName];
auto users = buffer->decrementUsers();
auto size = buffer->getSize();
buffers_.erase(functionName);
if (users == 0) {
assert(usedMemoryBytes_ >= size);
usedMemoryBytes_ -= size;
}
resultCode = ResultCode::Executed;
}
if (evictCB) {
evictCB(functionName, resultCode);
}
}
void OpenCLDeviceManager::runFunctionImpl(RunIdentifierTy id,
std::string function,
std::unique_ptr<Context> ctx,
ResultCBTy resultCB) {
auto funcIt = functions_.find(function);
if (funcIt == functions_.end()) {
llvm::errs() << "Failed to run function: name " << function
<< " not found.\n";
resultCB(id, ResultCode::Failed, std::move(ctx));
return;
}
CompiledFunction *func = funcIt->second;
// Run that function.
// Until we have executionInfo object need to call setup/teardown and pin to
// single device.
func->setupRuns();
func->beforeRun(*ctx.get());
func->execute(ctx.get());
func->afterRun(*ctx.get());
// Fire the resultCB.
resultCB(id, ResultCode::Executed, std::move(ctx));
}
| 34.212245 | 80 | 0.67645 | [
"object",
"vector"
] |
ef130644518a52c9f812c06ae9c1098feba28de0 | 2,381 | cpp | C++ | CefRender/V8ExtensionHandler.cpp | caozhiyi/DuiLib_c | 92a26553c2be970015cc3a5d7cbfd5839a89387c | [
"BSD-3-Clause"
] | 36 | 2016-09-25T01:22:17.000Z | 2022-01-23T09:56:34.000Z | CefRender/V8ExtensionHandler.cpp | caozhiyi/DuiLib_c | 92a26553c2be970015cc3a5d7cbfd5839a89387c | [
"BSD-3-Clause"
] | null | null | null | CefRender/V8ExtensionHandler.cpp | caozhiyi/DuiLib_c | 92a26553c2be970015cc3a5d7cbfd5839a89387c | [
"BSD-3-Clause"
] | 23 | 2016-09-25T01:22:19.000Z | 2021-10-02T14:47:08.000Z | #include "V8ExtensionHandler.h"
#include "include/cef_values.h"
namespace DuiLib
{
CV8ExtensionHandler::CV8ExtensionHandler() {
}
CV8ExtensionHandler::~CV8ExtensionHandler() {
if (handle_name_pipe_ != INVALID_HANDLE_VALUE) {
DisconnectNamedPipe(handle_name_pipe_);
CloseHandle(handle_name_pipe_);
}
function_name_.clear();
}
bool CV8ExtensionHandler::Execute(const CefString& name,
CefRefPtr<CefV8Value> object,
const CefV8ValueList& arguments,
CefRefPtr<CefV8Value>& retval,
CefString& exception) {
CefRefPtr<CefProcessMessage> msg= CefProcessMessage::Create(name);
CefRefPtr<CefListValue> args = msg->GetArgumentList();
for (int i = 0; i < arguments.size(); i++) {
if (arguments[i]->IsBool()) {
args->SetBool(i, arguments[i]->GetBoolValue());
} else if (arguments[i]->IsInt()) {
args->SetInt(i, arguments[i]->GetIntValue());
} else if (arguments[i]->IsString()) {
args->SetString(i, arguments[i]->GetStringValue());
} else if (arguments[i]->IsDouble()) {
args->SetDouble(i, arguments[i]->GetDoubleValue());
}
}
browser_->SendProcessMessage(PID_BROWSER, msg);
wchar_t buf[1024] = {0};
DWORD dwRead;
ReadFile(handle_name_pipe_, buf, 1024, &dwRead, NULL);
if (wcscmp(buf, L"DONE") == 0) {
return true;
} else {
retval = CefV8Value::CreateString(buf);
return true;
}
}
void CV8ExtensionHandler::OnContextCreated(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefRefPtr<CefV8Context> context) {
browser_ = browser;
//Retrieve the context's window object.
CefRefPtr<CefV8Value> object = context->GetGlobal();
for (auto iter = function_name_.begin(); iter != function_name_.end(); ++iter) {
//Create the "NativeLogin" function.
CefRefPtr<CefV8Value> func = CefV8Value::CreateFunction((*iter), this);
//Add the "NativeLogin" function to the "window" object.
object->SetValue((*iter), func, V8_PROPERTY_ATTRIBUTE_NONE);
}
}
void CV8ExtensionHandler::SetFunction(const CefString& name) {
function_name_.push_back(name);
}
void CV8ExtensionHandler::ConnectionNamePipe(const CefString& pipe_name) {
if (WaitNamedPipe(pipe_name.ToWString().c_str(), NMPWAIT_WAIT_FOREVER)) {
handle_name_pipe_ = CreateFile(pipe_name.ToWString().c_str(), GENERIC_READ | GENERIC_WRITE,
0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
}
}
}
| 31.328947 | 95 | 0.708946 | [
"object"
] |
ef16c13c5abe9f3aa2f7c1244c780f954cd413d8 | 674 | hpp | C++ | src/algorithms/simple_components.hpp | pythseq/odgi | 6bd50cf655a721e7fdfa3df05f32a3ed69aadcf9 | [
"MIT"
] | 1 | 2021-04-06T08:41:42.000Z | 2021-04-06T08:41:42.000Z | src/algorithms/simple_components.hpp | pythseq/odgi | 6bd50cf655a721e7fdfa3df05f32a3ed69aadcf9 | [
"MIT"
] | null | null | null | src/algorithms/simple_components.hpp | pythseq/odgi | 6bd50cf655a721e7fdfa3df05f32a3ed69aadcf9 | [
"MIT"
] | null | null | null | #pragma once
#include <iostream>
#include <vector>
#include <set>
#include <unordered_set>
#include <omp.h>
#include <handlegraph/types.hpp>
#include <handlegraph/util.hpp>
#include <handlegraph/path_handle_graph.hpp>
#include "flat_hash_map.hpp"
#include "perfect_neighbors.hpp"
#include "dset64-gccAtomic.hpp"
#include "BooPHF.h"
namespace odgi {
namespace algorithms {
using namespace handlegraph;
typedef boomphf::mphf<uint64_t, boomphf::SingleHashFunctor<uint64_t>> boophf_uint64_t;
std::vector<std::vector<handle_t>> simple_components(
const PathHandleGraph &graph, const uint64_t& min_size, const bool& return_all_handles, const uint64_t& nthreads);
}
}
| 21.741935 | 118 | 0.777448 | [
"vector"
] |
fa9c3a91b7aa43a9083ea1a3b19ccb20802c9bc9 | 73,770 | cxx | C++ | ds/ds/src/common/atq/atqmain.cxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | ds/ds/src/common/atq/atqmain.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | ds/ds/src/common/atq/atqmain.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*++
Copyright (c) 1995 Microsoft Corporation
Module Name :
atqmain.cxx
Abstract:
This module implements entry points for ATQ - Asynchronous Thread Queue.
Author:
Murali R. Krishnan ( MuraliK ) 8-Apr-1996
Environment:
User Mode -- Win32
Project:
Internet Services Common DLL
Functions Exported:
BOOL AtqInitialize();
BOOL AtqTerminate();
DWORD AtqSetInfo();
DWORD AtqGetInfo();
BOOL AtqGetStatistics();
BOOL AtqClearStatistics();
BOOL AtqAddAcceptExSockets();
BOOL AtqAddAsyncHandle();
DWORD AtqContextSetInfo();
VOID AtqCloseSocket();
VOID AtqFreeContext();
BOOL AtqReadFile();
BOOL AtqWriteFile();
BOOL AtqTransmitFile();
BOOL AtqPostCompletionStatus();
PVOID AtqAllocateBandwidthInfo();
BOOL AtqFreeBandwidthInfo();
DWORD AtqBandwidthSetInfo();
--*/
#include "isatq.hxx"
#include <inetsvcs.h>
#include "sched.hxx"
# define ATQ_REG_DEF_THREAD_TIMEOUT_PWS (30*60) // 30 minutes
/************************************************************
* Globals
************************************************************/
// ------------------------------
// Configuration for ATQ package
// ------------------------------
extern CHAR g_PSZ_ATQ_CONFIG_PARAMS_REG_KEY[];
// ----------------------------------------
// # of CPUs in machine (for thread-tuning)
// ----------------------------------------
extern DWORD g_cCPU;
//
// Used for guarding the initialization code
//
extern CRITICAL_SECTION MiscLock;
//
// concurrent # of threads to run per processor
//
DWORD g_cConcurrency = ATQ_REG_DEF_PER_PROCESSOR_CONCURRENCY;
//
// Amount of time (in ms) a worker thread will be idle before suicide
//
DWORD g_msThreadTimeout = ATQ_REG_DEF_THREAD_TIMEOUT * 1000;
BOOL g_fUseAcceptEx = TRUE; // Use AcceptEx if available
//
// The absolute thread limit
//
LONG g_cMaxThreadLimit = ATQ_REG_DEF_POOL_THREAD_LIMIT;
//
// Should we use fake completion port
//
BOOL g_fUseFakeCompletionPort = FALSE;
//
// Assumed minimum file transfer rate
//
DWORD g_cbMinKbSec = ATQ_REG_DEF_MIN_KB_SEC;
//
// Size of buffers for fake xmits
//
DWORD g_cbXmitBufferSize = ATQ_REG_DEF_NONTF_BUFFER_SIZE;
//
// number of active context list
//
DWORD g_dwNumContextLists = ATQ_NUM_CONTEXT_LIST;
//
// Max winsock datagram send.
//
DWORD g_cbMaxDGramSend = 2048;
/*
Winsock functions that need to be filled in
*/
LPFN_GETACCEPTEXSOCKADDRS g_pfnGetAcceptExSockaddrs = NULL;
LPFN_ACCEPTEX g_pfnAcceptEx = NULL;
LPFN_WSARECVMSG g_pfnWSARecvMsg = NULL;
BOOL g_bUseRecvMsg = FALSE;
/*
g_pfnExitThreadCallback()
This routine sets the callback routine to be called when one of the
Atq threads exit so that thread state data can be cleaned up. Currently
support is for a single routine. One way to support multiple routines would
be for the caller to save the return value. Such an application would not
be able to delete the "saved" callback routine.
*/
ATQ_THREAD_EXIT_CALLBACK g_pfnExitThreadCallback = NULL;
//
// g_pfnUpdatePerfCountersCallback()
// This routine is used to update PerfMon counters that are located in the
// DS core.
//
ATQ_UPDATE_PERF_CALLBACK g_pfnUpdatePerfCounterCallback = NULL;
// ----------------------------------
// Fake Completion port
// -----------------------------------
//
// Used to gauge pool thread creation. This variable shows number of
// ATQ contexts // ready to be processed by ATQ pool thread. Basically
// this is length of outcoming queue in SIO module and is modified by
// routines there
//
DWORD g_AtqWaitingContextsCount = 0;
// ------------------------------
// Current State Information
// ------------------------------
HANDLE* g_rghCompPort = NULL; // Handles for the completion port (hashed by ideal processor)
LONG g_cThreads = 0; // number of thread in the pool
LONG g_cAvailableThreads = 0; // # of threads waiting on the port.
//
// Is the NTS driver in use
//
BOOL g_fUseDriver = FALSE;
//
// Current thread limit
//
LONG g_cMaxThreads = ATQ_REG_DEF_PER_PROCESSOR_ATQ_THREADS;
DWORD g_cListenBacklog = ATQ_REG_DEF_LISTEN_BACKLOG;
BOOL g_fShutdown = FALSE; // if set, indicates that we are shutting down
// in that case, all threads should exit.
HANDLE g_hShutdownEvent = NULL; // set when all running threads shutdown
// ------------------------------
// Bandwidth Throttling Info
// ------------------------------
PBANDWIDTH_INFO g_pBandwidthInfo = NULL;
// ------------------------------
// Various State/Object Lists
// ------------------------------
//
// Used to switch context between lists
//
DWORD AtqGlobalContextCount = 0;
//
// List of active context
//
ATQ_CONTEXT_LISTHEAD AtqActiveContextList[ATQ_NUM_CONTEXT_LIST];
//
// List of Endpoints in ATQ - one per listen socket
//
LIST_ENTRY AtqEndpointList;
CRITICAL_SECTION AtqEndpointLock;
PALLOC_CACHE_HANDLER g_pachAtqContexts;
#ifdef IIS_AUX_COUNTERS
LONG g_AuxCounters[NUM_AUX_COUNTERS];
#endif // IIS_AUX_COUNTERS
// ------------------------------
// local to this module
// ------------------------------
LONG sg_AtqInitializeCount = -1;
BOOL g_fSpudInitialized = FALSE;
DWORD
I_AtqGetGlobalConfiguration(VOID);
DWORD
I_NumAtqEndpointsOpen(VOID);
VOID
WaitForWinsockCallback(
IN DWORD dwError,
IN DWORD cbTransferred,
IN LPWSAOVERLAPPED lpOverlapped,
IN DWORD dwFlags
);
BOOL
WaitForWinsockToInitialize(
VOID
);
/************************************************************
* Functions
************************************************************/
BOOL
AtqInitialize(
IN DWORD dwFlags
)
/*++
Routine Description:
Initializes the ATQ package
Arguments:
dwFlags - DWORD containing the flags for use to initialize ATQ library.
Notably in many cases one may not need the SPUD driver initialized
for processes other than the IIS main process. This dword helps
to shut off the unwanted flags.
This is an ugly way to initialize/shutdown SPUD, but that is what we
will do. SPUD supports only ONE completion port and hence when we use
ATQ in multiple processes we should be careful to initialize SPUD only
once and hopefully in the IIS main process!
Return Value:
TRUE if successful, FALSE on error (call GetLastError)
Note:
As of 4/16/97 the pszRegKey that is sent is no more utilized.
We always load the internal configuration parameters from
one single registry entry specified by PSZ_ATQ_CONFIG_PARAMS_REG_KEY
The parameter is left in the command line for compatibility
with old callers :( - NYI: Need to change this.
--*/
{
DWORD i;
DWORD dwErr;
//
// We need to acquire a lock here to make this thread safe
//
AcquireLock(&MiscLock);
if ( InterlockedIncrement( &sg_AtqInitializeCount) != 0) {
IF_DEBUG( API_ENTRY) {
ATQ_PRINTF(( DBG_CONTEXT,
"AtqInitialize( %08x). ATQ is already initialized.\n",
dwFlags));
}
//
// we are already initialized. Ignore the new registry settings
//
ReleaseLock(&MiscLock);
return ( TRUE);
}
IF_DEBUG( API_ENTRY) {
ATQ_PRINTF(( DBG_CONTEXT,
"AtqInitialize[%08x]. Initializing....\n",
dwFlags));
}
DBG_REQUIRE( ALLOC_CACHE_HANDLER::Initialize());
IF_DEBUG( INIT_CLEAN ) {
DBGPRINTF(( DBG_CONTEXT, "Alloc Cache initialized\n" ));
}
if ( !SchedulerInitialize()) {
DBGPRINTF(( DBG_CONTEXT, "Initializing Scheduler Failed\n"));
InterlockedDecrement( &sg_AtqInitializeCount);
ReleaseLock(&MiscLock);
return FALSE;
}
DBG_REQUIRE( ALLOC_CACHE_HANDLER::SetLookasideCleanupInterval() );
IF_DEBUG( INIT_CLEAN ) {
DBGPRINTF(( DBG_CONTEXT, "Scheduler Initialized\n" ));
}
//
// Initialize context lists and crit sects
//
ATQ_CONTEXT_LISTHEAD * pacl;
for ( pacl = AtqActiveContextList;
pacl < (AtqActiveContextList + g_dwNumContextLists);
pacl++) {
pacl->Initialize();
}
InitializeListHead( &AtqEndpointList );
InitializeCriticalSection( &AtqEndpointLock );
//
// init bandwidth throttling
//
ATQ_REQUIRE( BANDWIDTH_INFO::AbwInitialize() );
//
// Read registry configurable Atq options. We have to read these now
// because concurrency is set for the completion port at creation time.
//
DWORD dwError = I_AtqGetGlobalConfiguration();
if ( NO_ERROR != dwError) {
SetLastError( dwError);
InterlockedDecrement( &sg_AtqInitializeCount);
IIS_PRINTF((buff,"GetGlobal failed\n"));
ReleaseLock(&MiscLock);
return ( FALSE);
}
//
// Setup an allocation cache for the ATQ Contexts
// NYI: Auto-tune the threshold limit
//
{
ALLOC_CACHE_CONFIGURATION acConfig;
DWORD nCachedAtq = ATQ_CACHE_LIMIT_NTS;
if ( TsIsWindows95()) { nCachedAtq = ATQ_CACHE_LIMIT_W95; }
acConfig.nConcurrency = 1;
acConfig.nThreshold = nCachedAtq;
acConfig.cbSize = sizeof(ATQ_CONTEXT);
g_pachAtqContexts = new ALLOC_CACHE_HANDLER( "ATQ", &acConfig);
if ( NULL == g_pachAtqContexts) {
IIS_PRINTF((buff,"alloc failed %d\n", GetLastError()));
goto cleanup;
}
}
//
// Create the shutdown event
//
g_hShutdownEvent = IIS_CREATE_EVENT(
"g_hShutdownEvent",
&g_hShutdownEvent,
TRUE, // Manual reset
FALSE // Not signalled
);
if ( !g_hShutdownEvent ) {
OutputDebugString( " Create shutdown event failed\n");
goto cleanup;
}
//
// Create the completion port
//
g_rghCompPort = new HANDLE[ g_cCPU ];
if ( !g_rghCompPort ) {
IIS_PRINTF((buff,"alloc failed %d\n", GetLastError()));
goto cleanup;
}
ZeroMemory( g_rghCompPort, g_cCPU * sizeof( HANDLE ) );
g_rghCompPort[0] = CreateIoCompletionPort(INVALID_HANDLE_VALUE,
NULL,
(DWORD) NULL,
g_cConcurrency
);
if ( !g_rghCompPort[0] ) {
OutputDebugString( " Create IoComp port failed\n");
goto cleanup;
}
for ( size_t iCPU = 1; iCPU < g_cCPU; iCPU++ ) {
if ( !DuplicateHandle(
GetCurrentProcess(),
g_rghCompPort[ 0 ],
GetCurrentProcess(),
&g_rghCompPort[ iCPU ],
NULL,
FALSE,
DUPLICATE_SAME_ACCESS ) ) {
OutputDebugString( " Create IoComp port failed\n");
goto cleanup;
}
}
//
// initialize spud driver
//
if ( dwFlags & ATQ_INIT_SPUD_FLAG ) {
(VOID) I_AtqSpudInitialize(g_rghCompPort[ 0 ]);
g_fSpudInitialized = TRUE;
}
//
// Ensure all other initializations also are done
//
g_cThreads = 0;
g_fShutdown = FALSE;
g_cAvailableThreads = 0;
if ( !I_AtqStartTimeoutProcessing( NULL ) ) {
IIS_PRINTF((buff,"Start processing failed\n"));
goto cleanup;
}
IF_DEBUG(INIT_CLEAN) {
DBGPRINTF(( DBG_CONTEXT,
"fUseAcceptEx[%d] NT CompPort[%d] Platform[%d]"
" fUseDriver[%d]\n",
g_fUseAcceptEx, !g_fUseFakeCompletionPort,
IISPlatformType(),
g_fUseDriver
));
}
//
// Create the initial ATQ thread.
//
(VOID)I_AtqCheckThreadStatus( (PVOID)UIntToPtr(ATQ_INITIAL_THREAD) );
//
// Create a second thread if we are NTS
//
if ( TsIsNtServer() ) {
(VOID)I_AtqCheckThreadStatus( (PVOID)UIntToPtr(ATQ_INITIAL_THREAD) );
}
dwErr = I_AtqStartThreadMonitor();
ATQ_ASSERT( dwErr != FALSE );
IF_DEBUG( API_EXIT) {
ATQ_PRINTF(( DBG_CONTEXT,
"AtqInitialize( %08x) returns %d.\n",
dwFlags, TRUE));
}
WaitForWinsockToInitialize();
ReleaseLock(&MiscLock);
return TRUE;
cleanup:
IIS_PRINTF((buff,"cleanup!!!\n"));
for (i=0; i<g_dwNumContextLists; i++) {
AtqActiveContextList[i].Cleanup();
}
DeleteCriticalSection( &AtqEndpointLock);
if ( g_hShutdownEvent != NULL ) {
CloseHandle( g_hShutdownEvent );
g_hShutdownEvent = NULL;
}
if ( g_rghCompPort != NULL ) {
for ( size_t iCPU = 0; iCPU < g_cCPU; iCPU++ ) {
if ( g_rghCompPort[ iCPU ] ) {
CloseHandle( g_rghCompPort[ iCPU ] );
}
}
delete [] g_rghCompPort;
g_rghCompPort = NULL;
}
if ( NULL != g_pachAtqContexts) {
delete g_pachAtqContexts;
g_pachAtqContexts = NULL;
}
ATQ_REQUIRE( BANDWIDTH_INFO::AbwTerminate());
IF_DEBUG( API_EXIT) {
ATQ_PRINTF(( DBG_CONTEXT,
"AtqInitialize( %08x) returns %d.\n",
dwFlags, FALSE));
}
InterlockedDecrement( &sg_AtqInitializeCount);
ReleaseLock(&MiscLock);
return(FALSE);
} // AtqInitialize()
BOOL
AtqTerminate(
VOID
)
/*++
Routine Description:
Cleans up the ATQ package. Should only be called after all of the
clients of ATQ have been shutdown.
Arguments:
None.
Return Value:
TRUE, if ATQ was shutdown properly
FALSE, otherwise
--*/
{
DWORD currentThreadCount;
ATQ_CONTEXT_LISTHEAD * pacl;
// there are outstanding users, don't fully terminate
if ( InterlockedDecrement( &sg_AtqInitializeCount) >= 0) {
IF_DEBUG( API_ENTRY) {
ATQ_PRINTF(( DBG_CONTEXT,
"AtqTerminate() - there are other users."
" Not terminating now\n"
));
}
return (TRUE);
}
IF_DEBUG( API_ENTRY) {
ATQ_PRINTF(( DBG_CONTEXT,
"AtqTerminate() - Terminating ATQ ...\n"
));
}
//
// All the ATQ endpoints should have been terminated before calling
// this ATQTerminate() function. If not, sorry return failure.
//
DWORD nEndpointsToBeClosed = I_NumAtqEndpointsOpen();
if ( nEndpointsToBeClosed > 0) {
DBGPRINTF(( DBG_CONTEXT,
" There are %d endpoints remaining to be closed."
" Somebody above stream did not close endpoints."
" BUG IN CODE ABOVE ATQ\n"
,
nEndpointsToBeClosed
));
SetLastError( ERROR_NETWORK_BUSY);
return ( FALSE);
}
if ( (g_hShutdownEvent == NULL) || g_fShutdown ) {
//
// We have not been intialized or have already terminated.
//
SetLastError( ERROR_NOT_READY );
return FALSE;
}
// Cleanup variables in ATQ Bandwidth throttle module
if ( !BANDWIDTH_INFO::AbwTerminate()) {
// there may be a few blocked IO. We should avoid them all.
// All clients should have cleaned themselves up before coming here.
return (FALSE);
}
//
// All clients should have cleaned themselves up before calling us.
//
for ( pacl = AtqActiveContextList;
pacl < (AtqActiveContextList + g_dwNumContextLists);
pacl++) {
pacl->Lock();
if ( !IsListEmpty(&pacl->ActiveListHead)) {
ATQ_ASSERT( IsListEmpty( &pacl->ActiveListHead));
pacl->Unlock();
IF_DEBUG( API_EXIT) {
ATQ_PRINTF(( DBG_CONTEXT,
"AtqTerminate() - ContextList(%08x) has "
"Active Contexts. Failed Termination.\n",
pacl
));
}
return FALSE;
}
pacl->Unlock();
} // for
//
// Note that we are shutting down and prevent any more handles from
// being added to the completion port.
//
g_fShutdown = TRUE;
//
// Attempt and remove the TimeOut Context from scheduler queue
//
DBG_REQUIRE( I_AtqStopTimeoutProcessing());
DBG_REQUIRE( I_AtqStopThreadMonitor() );
currentThreadCount = g_cThreads;
if (currentThreadCount > 0) {
DWORD i;
BOOL fRes;
OVERLAPPED overlapped;
//
// Post a message to the completion port for each worker thread
// telling it to exit. The indicator is a NULL context in the
// completion.
//
ZeroMemory( &overlapped, sizeof(OVERLAPPED) );
for (i=0; i<currentThreadCount; i++) {
fRes = PostQueuedCompletionStatus( g_rghCompPort[ 0 ],
0,
0,
&overlapped );
ATQ_ASSERT( (fRes == TRUE) ||
( (fRes == FALSE) &&
(GetLastError() == ERROR_IO_PENDING) )
);
}
}
//
// Now wait for the pool threads to shutdown.
//
DWORD dwErr =
WaitForSingleObject( g_hShutdownEvent, ATQ_WAIT_FOR_THREAD_DEATH);
#if 0
DWORD dwWaitCount = 0;
while ( dwErr == WAIT_TIMEOUT) {
dwWaitCount++;
DebugBreak();
Sleep( 10*1000); // sleep for some time
dwErr =
WaitForSingleObject( g_hShutdownEvent, ATQ_WAIT_FOR_THREAD_DEATH);
} // while
# endif // 0
//
// At this point, no other threads should be left running.
//
//
// g_cThreads counter is decremented by AtqPoolThread().
// AtqTerminate() is called during the DLL termination
// But at DLL termination, all ATQ pool threads are killed =>
// no one is decrementing the count. Hence this assert will always fail.
//
// ATQ_ASSERT( !g_cThreads );
ATQ_REQUIRE( CloseHandle( g_hShutdownEvent ) );
g_hShutdownEvent = NULL;
for ( size_t iCPU = 0; iCPU < g_cCPU; iCPU++ ) {
CloseHandle( g_rghCompPort[ iCPU ] );
}
delete [] g_rghCompPort;
g_rghCompPort = NULL;
//
// Cleanup our synchronization resources
//
for ( pacl = AtqActiveContextList;
pacl < (AtqActiveContextList + g_dwNumContextLists);
pacl++) {
PLIST_ENTRY pEntry;
pacl->Lock();
if ( !IsListEmpty( &pacl->PendingAcceptExListHead)) {
for ( pEntry = pacl->PendingAcceptExListHead.Flink;
pEntry != &pacl->PendingAcceptExListHead;
pEntry = pEntry->Flink ) {
PATQ_CONT pContext =
CONTAINING_RECORD( pEntry, ATQ_CONTEXT, m_leTimeout );
ATQ_ASSERT( pContext->Signature == ATQ_CONTEXT_SIGNATURE );
pContext->Print();
} // for
}
pacl->Unlock();
pacl->Cleanup();
}
//
// Free all the elements in the Allocation caching list
//
if ( NULL != g_pachAtqContexts) {
delete g_pachAtqContexts;
g_pachAtqContexts = NULL;
}
DeleteCriticalSection( &AtqEndpointLock);
//
// cleanup driver
//
if ( g_fSpudInitialized ) {
(VOID)I_AtqSpudTerminate();
g_fSpudInitialized = FALSE;
}
//
// Cleanup scheduler
//
DBG_REQUIRE( ALLOC_CACHE_HANDLER::ResetLookasideCleanupInterval() );
SchedulerTerminate();
DBG_REQUIRE( ALLOC_CACHE_HANDLER::Cleanup());
IF_DEBUG( API_EXIT) {
ATQ_PRINTF(( DBG_CONTEXT,
"AtqTerminate() - Successfully cleaned up.\n"
));
}
return TRUE;
} // AtqTerminate()
DWORD_PTR
AtqSetInfo(
IN ATQ_INFO atqInfo,
IN DWORD_PTR Data
)
/*++
Routine Description:
Sets various bits of information for the ATQ module
Arguments:
atqInfo - Data item to set
data - New value for item
Return Value:
The old value of the parameter
--*/
{
DWORD_PTR dwOldVal = 0;
switch ( atqInfo ) {
case AtqBandwidthThrottle:
ATQ_ASSERT( g_pBandwidthInfo != NULL );
dwOldVal = g_pBandwidthInfo->SetBandwidthLevel( (DWORD)Data );
break;
case AtqBandwidthThrottleMaxBlocked:
ATQ_ASSERT( g_pBandwidthInfo != NULL );
dwOldVal = g_pBandwidthInfo->SetMaxBlockedListSize( (DWORD)Data );
break;
case AtqExitThreadCallback:
dwOldVal = (DWORD_PTR) g_pfnExitThreadCallback;
g_pfnExitThreadCallback = (ATQ_THREAD_EXIT_CALLBACK ) Data;
break;
case AtqMaxPoolThreads:
// the value is per processor values
// internally we maintain value for all processors
dwOldVal = g_cMaxThreads/g_cCPU;
g_cMaxThreads = (DWORD)Data * g_cCPU;
break;
//
// Increment or decrement the max thread count. In this instance, we
// do not scale by the number of CPUs
//
case AtqIncMaxPoolThreads:
InterlockedIncrement( (LONG *) &g_cMaxThreads );
dwOldVal = TRUE;
break;
case AtqDecMaxPoolThreads:
InterlockedDecrement( (LONG *) &g_cMaxThreads );
dwOldVal = TRUE;
break;
case AtqMaxConcurrency:
dwOldVal = g_cConcurrency;
g_cConcurrency = (DWORD)Data;
break;
case AtqThreadTimeout:
dwOldVal = g_msThreadTimeout/1000; // convert back to seconds
g_msThreadTimeout = (DWORD)Data * 1000; // convert value to millisecs
break;
case AtqUseAcceptEx:
dwOldVal = g_fUseAcceptEx;
if ( !TsIsWindows95() ) {
g_fUseAcceptEx = (DWORD)Data;
}
break;
case AtqMinKbSec:
//
// Ignore it if the value is zero
//
if ( Data ) {
dwOldVal = g_cbMinKbSec;
g_cbMinKbSec = (DWORD)Data;
}
break;
default:
ATQ_ASSERT( FALSE );
break;
}
return dwOldVal;
} // AtqSetInfo()
DWORD_PTR
AtqGetInfo(
IN ATQ_INFO atqInfo
)
/*++
Routine Description:
Gets various bits of information for the ATQ module
Arguments:
atqInfo - Data item to set
Return Value:
The old value of the parameter
--*/
{
DWORD_PTR dwVal = 0;
switch ( atqInfo ) {
case AtqBandwidthThrottle:
ATQ_ASSERT( g_pBandwidthInfo != NULL );
dwVal = g_pBandwidthInfo->QueryBandwidthLevel();
break;
case AtqExitThreadCallback:
dwVal = (DWORD_PTR) g_pfnExitThreadCallback;
break;
case AtqMaxPoolThreads:
dwVal = g_cMaxThreads/g_cCPU;
break;
case AtqMaxConcurrency:
dwVal = g_cConcurrency;
break;
case AtqThreadTimeout:
dwVal = g_msThreadTimeout/1000; // convert back to seconds
break;
case AtqUseAcceptEx:
dwVal = g_fUseAcceptEx;
break;
case AtqMinKbSec:
dwVal = g_cbMinKbSec;
break;
case AtqMaxDGramSend:
dwVal = g_cbMaxDGramSend;
break;
default:
ATQ_ASSERT( FALSE );
break;
} // switch
return dwVal;
} // AtqGetInfo()
BOOL
AtqGetStatistics(IN OUT ATQ_STATISTICS * pAtqStats)
{
if ( pAtqStats != NULL) {
return g_pBandwidthInfo->GetStatistics( pAtqStats );
} else {
SetLastError( ERROR_INVALID_PARAMETER);
return (FALSE);
}
} // AtqGetStatistics()
BOOL
AtqClearStatistics( VOID)
{
return g_pBandwidthInfo->ClearStatistics();
} // AtqClearStatistics()
DWORD_PTR
AtqContextSetInfo(
PATQ_CONTEXT patqContext,
enum ATQ_CONTEXT_INFO atqInfo,
DWORD_PTR Data
)
/*++
Routine Description:
Sets various bits of information for this context
Arguments:
patqContext - pointer to ATQ context
atqInfo - Data item to set
data - New value for item
Return Value:
The old value of the parameter
--*/
{
PATQ_CONT pContext = (PATQ_CONT) patqContext;
DWORD_PTR dwOldVal = 0;
ATQ_ASSERT( pContext );
ATQ_ASSERT( pContext->Signature == ATQ_CONTEXT_SIGNATURE );
if ( pContext && pContext->Signature == ATQ_CONTEXT_SIGNATURE )
{
switch ( atqInfo ) {
case ATQ_INFO_TIMEOUT:
dwOldVal = pContext->TimeOut;
pContext->TimeOut = CanonTimeout( (DWORD)Data );
break;
case ATQ_INFO_RESUME_IO:
//
// set back the max timeout from pContext->TimeOut
// This will ensure that timeout processing can go on
// peacefully.
//
{
DWORD currentTime = AtqGetCurrentTick( );
DWORD timeout;
dwOldVal = pContext->NextTimeout;
timeout = pContext->TimeOut;
//
// Set the new timeout
//
I_SetNextTimeout(pContext);
//
// Return the old
//
if ( currentTime >= dwOldVal ) {
ATQ_ASSERT((dwOldVal & ATQ_INFINITE) == 0);
dwOldVal = 0;
} else if ( (dwOldVal & ATQ_INFINITE) == 0 ) {
dwOldVal -= currentTime;
}
// return correct units
dwOldVal = UndoCanonTimeout( (DWORD)dwOldVal );
}
break;
case ATQ_INFO_COMPLETION:
dwOldVal = (DWORD_PTR) pContext->pfnCompletion;
pContext->pfnCompletion = (ATQ_COMPLETION) Data;
break;
case ATQ_INFO_COMPLETION_CONTEXT:
ATQ_ASSERT( Data != 0 ); // NULL context not allowed
dwOldVal = (DWORD_PTR) pContext->ClientContext;
pContext->ClientContext = (void *) Data;
break;
case ATQ_INFO_BANDWIDTH_INFO:
{
ATQ_ASSERT( Data != 0 );
PBANDWIDTH_INFO pBandwidthInfo = (PBANDWIDTH_INFO) Data;
ATQ_ASSERT( pBandwidthInfo->QuerySignature() ==
ATQ_BW_INFO_SIGNATURE );
if ( !pBandwidthInfo->IsFreed() )
{
pContext->m_pBandwidthInfo = (PBANDWIDTH_INFO) Data;
pContext->m_pBandwidthInfo->Reference();
}
break;
}
case ATQ_INFO_ABORTIVE_CLOSE:
dwOldVal = pContext->IsFlag( ACF_ABORTIVE_CLOSE );
if ( Data )
{
pContext->SetFlag( ACF_ABORTIVE_CLOSE );
}
else
{
pContext->ResetFlag( ACF_ABORTIVE_CLOSE );
}
break;
default:
ATQ_ASSERT( FALSE );
}
}
return dwOldVal;
} // AtqContextSetInfo()
BOOL
AtqAddAsyncHandle(
PATQ_CONTEXT * ppatqContext,
PVOID EndpointObject,
PVOID ClientContext,
ATQ_COMPLETION pfnCompletion,
DWORD TimeOut,
HANDLE hAsyncIO
)
/*++
Routine Description:
Adds a handle to the thread queue
The client should call this after the IO handle is opened
and before the first IO request is made
Even in the case of failure, client should call AtqFreeContext() and
free the memory associated with this object.
Arguments:
ppatqContext - Receives allocated ATQ Context
Context - Context to call client with
pfnCompletion - Completion to call when IO completes
TimeOut - Time to wait (sec) for IO completion (INFINITE is valid)
hAsyncIO - Handle with pending read or write
Return Value:
TRUE if successful, FALSE on error (call GetLastError)
--*/
{
return ( I_AtqAddAsyncHandle( (PATQ_CONT *) ppatqContext,
(PATQ_ENDPOINT) EndpointObject,
ClientContext,
pfnCompletion,
TimeOut,
hAsyncIO)
&&
I_AddAtqContextToPort( *((PATQ_CONT *) ppatqContext))
);
} // AtqAddAsyncHandle()
VOID
AtqGetAcceptExAddrs(
IN PATQ_CONTEXT patqContext,
OUT SOCKET * pSock,
OUT PVOID * ppvBuff,
OUT PVOID * pEndpointContext,
OUT SOCKADDR * * ppsockaddrLocal,
OUT SOCKADDR * * ppsockaddrRemote
)
{
PATQ_CONT pContext = (PATQ_CONT ) patqContext;
INT cbsockaddrLocal;
INT cbsockaddrRemote;
DWORD cb;
ATQ_ASSERT( g_fUseAcceptEx);
ATQ_ASSERT( pContext->pEndpoint);
*pSock = (SOCKET) pContext->hAsyncIO;
*pEndpointContext = pContext->pEndpoint->Context;
//
// The buffer not only receives the initial received data, it also
// gets the sock addrs, which must be at least sockaddr_in + 16 bytes
// large
//
g_pfnGetAcceptExSockaddrs( pContext->pvBuff,
(cb = pContext->pEndpoint->InitialRecvSize),
MIN_SOCKADDR_SIZE,
MIN_SOCKADDR_SIZE,
ppsockaddrLocal,
&cbsockaddrLocal,
ppsockaddrRemote,
&cbsockaddrRemote );
*ppvBuff = ( ( cb == 0) ? NULL : pContext->pvBuff);
return;
} // AtqGetAcceptExAddrs()
BOOL
AtqCloseSocket(
PATQ_CONTEXT patqContext,
BOOL fShutdown
)
/*++
Routine Description:
Closes the socket in this atq structure if it wasn't
closed by transmitfile. This function should be called only
if the embedded handle in AtqContext is a Socket.
Arguments:
patqContext - Context whose socket should be closed.
fShutdown - If TRUE, means we call shutdown and always close the socket.
Note that if TransmitFile closed the socket, it will have done the
shutdown for us
Returns:
TRUE on success and FALSE if there is a failure.
--*/
{
PATQ_CONT pContext = (PATQ_CONT ) patqContext;
if ( pContext ) {
ATQ_ASSERT( pContext->Signature == ATQ_CONTEXT_SIGNATURE );
BOOL fAbortiveClose;
fAbortiveClose = pContext->IsFlag( ACF_ABORTIVE_CLOSE );
pContext->ResetFlag( ACF_ABORTIVE_CLOSE );
//
// Don't delete the socket if we don't have to
//
if ( pContext->IsState( ACS_SOCK_UNCONNECTED |
ACS_SOCK_CLOSED)
) {
//
// Do nothing
//
} else {
// default:
// case ACS_SOCK_LISTENING:
// case ACS_SOCK_CONNECTED: {
HANDLE hIO;
PATQ_ENDPOINT pEndpoint;
pEndpoint = pContext->pEndpoint;
pContext->MoveState( ACS_SOCK_CLOSED);
//
// During shutdown, the socket may be closed while this thread
// is doing processing, so only give a warning if any of the
// following fail
//
hIO = (HANDLE )InterlockedExchangePointer((PVOID *) &pContext->hAsyncIO,
NULL);
if ( hIO == NULL ) {
//
// No socket - it is already closed - do nothing.
//
} else {
if ( pContext->fDatagramContext ) {
return TRUE;
}
if (fAbortiveClose || fShutdown ) {
//
// If this is an AcceptEx socket, we must first force a
// user mode context update before we can call shutdown
//
if ( (pEndpoint != NULL) && (pEndpoint->UseAcceptEx) ) {
if ( setsockopt( (SOCKET) hIO,
SOL_SOCKET,
SO_UPDATE_ACCEPT_CONTEXT,
(char *) &pEndpoint->ListenSocket,
sizeof(SOCKET) ) == SOCKET_ERROR ) {
ATQ_PRINTF(( DBG_CONTEXT,
"[AtqCloseSocket] Warning- setsockopt "
"failed, error %d, socket = %x,"
" Context= %08x, Listen = %lx\n",
GetLastError(),
hIO,
pContext,
pEndpoint->ListenSocket ));
}
}
} // setsock-opt call
if ( fAbortiveClose ) {
LINGER linger;
linger.l_onoff = TRUE;
linger.l_linger = 0;
if ( setsockopt( (SOCKET) hIO,
SOL_SOCKET,
SO_LINGER,
(char *) &linger,
sizeof(linger) ) == SOCKET_ERROR
) {
ATQ_PRINTF(( DBG_CONTEXT,
"[AtqCloseSocket] Warning- setsockopt "
"failed, error %d, socket = %x,"
" Context= %08x, Listen = %lx\n",
GetLastError(),
hIO,
pContext,
pEndpoint->ListenSocket ));
}
} // set up linger
if ( fShutdown ) {
//
// Note that shutdown can fail in instances where the
// client aborts in the middle of a TransmitFile.
// This is an acceptable failure case
//
shutdown( HandleToUlong(hIO), 1 );
}
DBG_ASSERT( hIO != NULL);
if ( closesocket( HandleToUlong(hIO)) ) {
ATQ_PRINTF(( DBG_CONTEXT,
"[AtqCloseSocket] Warning- closesocket "
" failed, Context = %08x, error %d,"
" socket = %x\n",
pContext,
GetLastError(),
hIO ));
}
} // if (hIO != NULL)
}
return TRUE;
}
DBGPRINTF(( DBG_CONTEXT, "[AtqCloseSocket] Warning - NULL Atq context\n"));
SetLastError( ERROR_INVALID_PARAMETER );
return FALSE;
} // AtqCloseSocket()
BOOL
AtqShutdownSocket(
PATQ_CONTEXT patqContext,
AtqShutdownFlag flags
)
/*++
Routine Description:
Performs a shutdown on an ATQ_CONTEXT socket.
Arguments:
patqContext - Context whose socket should be closed.
Returns:
TRUE on success and FALSE if there is a failure.
--*/
{
PATQ_CONT pContext = (PATQ_CONT ) patqContext;
HANDLE hIO = pContext->hAsyncIO;
PATQ_ENDPOINT pEndpoint = pContext->pEndpoint;
ATQ_ASSERT( patqContext );
ATQ_ASSERT( pContext->Signature == ATQ_CONTEXT_SIGNATURE );
#if 0
// AtqShutdownSocket should not be called on a closed context.
ATQ_ASSERT( !(pContext->IsState( ACS_SOCK_UNCONNECTED | ACS_SOCK_CLOSED)) );
#endif
if ( pContext->IsState( ACS_SOCK_UNCONNECTED | ACS_SOCK_CLOSED)) {
//
// The socket has already been closed. Do nothing.
//
return TRUE;
}
if ( pContext->fDatagramContext ) {
return TRUE;
}
//
// If this is an AcceptEx socket, we must first force a
// user mode context update before we can call shutdown
//
if ( (pEndpoint != NULL) && (pEndpoint->UseAcceptEx) ) {
if ( setsockopt( (SOCKET) hIO,
SOL_SOCKET,
SO_UPDATE_ACCEPT_CONTEXT,
(char *) &pEndpoint->ListenSocket,
sizeof(SOCKET) ) == SOCKET_ERROR ) {
ATQ_PRINTF(( DBG_CONTEXT,
"[AtqCloseSocket] Warning- setsockopt "
"failed, error %d, socket = %x,"
" Context= %08x, Listen = %lx\n",
GetLastError(),
hIO,
pContext,
pEndpoint->ListenSocket ));
}
}
//
// Note that shutdown can fail in instances where the
// client aborts in the middle of a TransmitFile.
// This is an acceptable failure case
//
shutdown( HandleToUlong(hIO), flags );
return TRUE;
} // AtqCloseSocket()
BOOL
AtqCloseFileHandle(
PATQ_CONTEXT patqContext
)
/*++
Routine Description:
Closes the file handle in this atq structure.
This function should be called only if the embedded handle
in AtqContext is a file handle.
Arguments:
patqContext - Context whose file handle should be closed.
Returns:
TRUE on success and FALSE if there is a failure.
Note:
THIS FUNCTIONALITY IS ADDED TO SERVE A SPECIAL REQUEST!!!
Most of the ATQ code thinks that the handle here is a socket.
Except of course this function...
--*/
{
PATQ_CONT pContext = (PATQ_CONT ) patqContext;
if ( pContext != NULL ) {
HANDLE hIO;
ATQ_ASSERT( pContext->Signature == ATQ_CONTEXT_SIGNATURE );
ATQ_ASSERT( !pContext->IsAcceptExRootContext());
ATQ_ASSERT( !TsIsWindows95() ); // NYI
hIO =
(HANDLE ) InterlockedExchangePointer((PVOID *) &pContext->hAsyncIO,
NULL);
if ( (hIO == NULL) || !CloseHandle( hIO ) ) {
ATQ_PRINTF(( DBG_CONTEXT,
"[AtqCloseFileHandle] Warning- CloseHandle failed, "
" Context = %08x, error %d, handle = %x\n",
pContext,
GetLastError(),
hIO ));
}
return TRUE;
}
DBGPRINTF(( DBG_CONTEXT, "[AtqCloseSocket] Warning - NULL Atq context\n"));
SetLastError( ERROR_INVALID_PARAMETER );
return FALSE;
} // AtqCloseFileHandle()
VOID
AtqFreeContext(
PATQ_CONTEXT patqContext,
BOOL fReuseContext
)
/*++
Routine Description:
Frees the context created in AtqAddAsyncHandle.
Call this after the async handle has been closed and all outstanding
IO operations have been completed. The context is invalid after this call.
Call AtqFreeContext() for same context only ONCE.
Arguments:
patqContext - Context to free
fReuseContext - TRUE if this can context can be reused in the context of
the calling thread. Should be FALSE if the calling thread will exit
soon (i.e., isn't an AtqPoolThread).
--*/
{
PATQ_CONT pContext = (PATQ_CONT)patqContext;
ATQ_ASSERT( pContext != NULL );
IF_DEBUG( API_ENTRY) {
ATQ_PRINTF(( DBG_CONTEXT, "AtqFreeContext( %08x (handle=%08x,"
" nIOs = %d), fReuse=%d)\n",
patqContext, patqContext->hAsyncIO,
pContext->m_nIO,
fReuseContext));
}
if ( pContext ) {
ATQ_ASSERT( pContext->Signature == ATQ_CONTEXT_SIGNATURE );
#if 1
//
// !! DS change
//
//
//
// If the socket is an AcceptEx socket, redo the AcceptEx and put
// it back on the in use list
//
PATQ_ENDPOINT pEndpoint = pContext->pEndpoint;
//
// If we have plenty of outstanding sockets (the number requested),
// don't re-use this one.
//
if (pEndpoint != NULL) {
if ( pEndpoint->nSocketsAvail >
(LONG )(pEndpoint->nAcceptExOutstanding) ) {
fReuseContext= FALSE;
}
}
#endif
if ( fReuseContext ) {
pContext->SetFlag( ACF_REUSE_CONTEXT);
} else {
pContext->ResetFlag( ACF_REUSE_CONTEXT);
}
if ( InterlockedDecrement( &pContext->m_nIO) == 0) {
//
// The number of outstanding ref holders is ZERO.
// Free up this ATQ context.
//
// We really do not free up the context - but try to reuse
// it if possible
//
DBG_ASSERT( pContext->lSyncTimeout == 0);
AtqpReuseOrFreeContext( pContext, fReuseContext);
}
}
return;
} // AtqFreeContext()
BOOL
AtqReadFile(
IN PATQ_CONTEXT patqContext,
IN LPVOID lpBuffer,
IN DWORD BytesToRead,
IN OVERLAPPED * lpo OPTIONAL
)
/*++
Routine Description:
Does an async read using the handle defined in the context.
Arguments:
patqContext - pointer to ATQ context
lpBuffer - Buffer to put read data in
BytesToRead - number of bytes to read
lpo - Overlapped structure to use
Returns:
TRUE on success and FALSE if there is a failure.
--*/
{
BOOL fRes;
DWORD cbRead; // discarded after usage ( since this is Async)
PATQ_CONT pContext = (PATQ_CONT ) patqContext;
PBANDWIDTH_INFO pBandwidthInfo = pContext->m_pBandwidthInfo;
ATQ_ASSERT( pContext->Signature == ATQ_CONTEXT_SIGNATURE );
ATQ_ASSERT( pContext->arInfo.atqOp == AtqIoNone);
ATQ_ASSERT( pBandwidthInfo != NULL );
ATQ_ASSERT( pBandwidthInfo->QuerySignature() == ATQ_BW_INFO_SIGNATURE );
InterlockedIncrement( &pContext->m_nIO);
I_SetNextTimeout(pContext);
pContext->BytesSent = 0;
if ( !lpo ) {
lpo = &pContext->Overlapped;
}
if (NULL == pContext->hAsyncIO) {
// Only socket handles are used by ATQ, thus NULL is not allowed,
// and indicates that ATQ has closed the socket.
InterlockedDecrement( &pContext->m_nIO );
SetLastError(WSAENOTSOCK);
return FALSE;
}
fRes = ( ReadFile( pContext->hAsyncIO,
lpBuffer,
BytesToRead,
&cbRead,
lpo ) ||
GetLastError() == ERROR_IO_PENDING);
if (!fRes) { InterlockedDecrement( &pContext->m_nIO); };
return fRes;
} // AtqReadFile()
BOOL
AtqReadSocket(
IN PATQ_CONTEXT patqContext,
IN LPWSABUF pwsaBuffers,
IN DWORD dwBufferCount,
IN OVERLAPPED * lpo OPTIONAL
)
/*++
Routine Description:
Does an async recv using the handle defined in the context
as a socket.
Arguments:
patqContext - pointer to ATQ context
lpBuffer - Buffer to put read data in
BytesToRead - number of bytes to read
lpo - Overlapped structure to use
Returns:
TRUE on success and FALSE if there is a failure.
--*/
{
BOOL fRes;
DWORD cbRead; // discarded after usage ( since this is Async)
PATQ_CONT pContext = (PATQ_CONT ) patqContext;
PBANDWIDTH_INFO pBandwidthInfo = pContext->m_pBandwidthInfo;
ATQ_ASSERT( pContext->Signature == ATQ_CONTEXT_SIGNATURE );
ATQ_ASSERT( pContext->arInfo.atqOp == AtqIoNone);
ATQ_ASSERT( pBandwidthInfo != NULL );
ATQ_ASSERT( pBandwidthInfo->QuerySignature() == ATQ_BW_INFO_SIGNATURE );
IF_DEBUG(API_ENTRY) {
ATQ_PRINTF(( DBG_CONTEXT,
"AtqReadSocket(%08lx) called.\n", pContext));
}
if (pContext->IsFlag( ACF_RECV_ISSUED)) {
IF_DEBUG( SPUD ) {
ATQ_PRINTF(( DBG_CONTEXT,
"AtqReadSocket -> WSARecv bypassed.\n"));
}
pContext->BytesSent = 0;
pContext->SetFlag( ACF_RECV_CALLED);
return TRUE;
}
I_SetNextTimeout(pContext);
// count the number of bytes
DBG_ASSERT( dwBufferCount >= 1);
pContext->BytesSent = 0;
InterlockedIncrement( &pContext->m_nIO);
if ( !lpo ) {
lpo = &pContext->Overlapped;
}
DWORD lpFlags = 0;
//
// See if the connection has already been closed.
//
if (pContext->hAsyncIO == NULL) {
InterlockedDecrement( &pContext->m_nIO );
SetLastError(WSAENOTSOCK);
return FALSE;
}
fRes = ( (WSARecv( (SOCKET ) pContext->hAsyncIO,
pwsaBuffers,
dwBufferCount,
&cbRead,
&lpFlags, // no flags
lpo,
NULL // no completion routine
) == 0) ||
(WSAGetLastError() == WSA_IO_PENDING));
if (!fRes) { InterlockedDecrement( &pContext->m_nIO); };
return fRes;
} // AtqReadSocket()
BOOL
AtqWriteFile(
IN PATQ_CONTEXT patqContext,
IN LPCVOID lpBuffer,
IN DWORD BytesToWrite,
IN OVERLAPPED * lpo OPTIONAL
)
/*++
Routine Description:
Does an async write using the handle defined in the context.
Arguments:
patqContext - pointer to ATQ context
lpBuffer - Buffer to write
BytesToWrite - number of bytes to write
lpo - Overlapped structure to use
Returns:
TRUE on success and FALSE if there is a failure.
--*/
{
BOOL fRes;
DWORD cbWritten; // discarded after usage ( since this is Async)
PATQ_CONT pContext = (PATQ_CONT ) patqContext;
PBANDWIDTH_INFO pBandwidthInfo = pContext->m_pBandwidthInfo;
ATQ_ASSERT( pContext->Signature == ATQ_CONTEXT_SIGNATURE );
ATQ_ASSERT( pContext->arInfo.atqOp == AtqIoNone);
ATQ_ASSERT( !TsIsWindows95() ); // NYI
ATQ_ASSERT( pBandwidthInfo != NULL );
ATQ_ASSERT( pBandwidthInfo->QuerySignature() == ATQ_BW_INFO_SIGNATURE );
I_SetNextTimeout(pContext);
pContext->BytesSent = BytesToWrite;
if ( !lpo ) {
lpo = &pContext->Overlapped;
}
InterlockedIncrement( &pContext->m_nIO);
if (NULL == pContext->hAsyncIO) {
// Only socket handles are used by ATQ, thus NULL is not allowed,
// and indicates that ATQ has closed the socket.
InterlockedDecrement( &pContext->m_nIO );
SetLastError(WSAENOTSOCK);
return FALSE;
}
fRes = ( WriteFile( pContext->hAsyncIO,
lpBuffer,
BytesToWrite,
&cbWritten,
lpo ) ||
GetLastError() == ERROR_IO_PENDING);
if (!fRes) { InterlockedDecrement( &pContext->m_nIO); };
return fRes;
} // AtqWriteFile()
BOOL
AtqWriteSocket(
IN PATQ_CONTEXT patqContext,
IN LPWSABUF pwsaBuffers,
IN DWORD dwBufferCount,
IN OVERLAPPED * lpo OPTIONAL
)
/*++
Routine Description:
Does an async write using the handle defined in the context as a socket.
Arguments:
patqContext - pointer to ATQ context
pwsaBuffer - pointer to Winsock Buffers for scatter/gather
dwBufferCount - DWORD containing the count of buffers pointed
to by pwsaBuffer
lpo - Overlapped structure to use
Returns:
TRUE on success and FALSE if there is a failure.
--*/
{
BOOL fRes;
DWORD cbWritten; // discarded after usage ( since this is Async)
PATQ_CONT pContext = (PATQ_CONT ) patqContext;
PBANDWIDTH_INFO pBandwidthInfo = pContext->m_pBandwidthInfo;
ATQ_ASSERT( pContext->Signature == ATQ_CONTEXT_SIGNATURE );
ATQ_ASSERT( pContext->arInfo.atqOp == AtqIoNone);
ATQ_ASSERT( pBandwidthInfo != NULL );
ATQ_ASSERT( pBandwidthInfo->QuerySignature() == ATQ_BW_INFO_SIGNATURE );
I_SetNextTimeout(pContext);
//
// count the number of bytes
//
DBG_ASSERT( dwBufferCount >= 1);
pContext->BytesSent = pwsaBuffers->len;
if ( dwBufferCount > 1) {
LPWSABUF pWsaBuf;
for ( pWsaBuf = pwsaBuffers + 1;
pWsaBuf < (pwsaBuffers + dwBufferCount);
pWsaBuf++) {
pContext->BytesSent += pWsaBuf->len;
}
}
if ( lpo == NULL ) {
lpo = &pContext->Overlapped;
}
InterlockedIncrement( &pContext->m_nIO);
//
// See if the connection has already been closed.
//
if (pContext->hAsyncIO == NULL) {
InterlockedDecrement( &pContext->m_nIO );
SetLastError(WSAENOTSOCK);
return FALSE;
}
fRes = ( (WSASend( (SOCKET ) pContext->hAsyncIO,
pwsaBuffers,
dwBufferCount,
&cbWritten,
0, // no flags
lpo,
NULL // no completion routine
) == 0) ||
(WSAGetLastError() == WSA_IO_PENDING));
if (!fRes) { InterlockedDecrement( &pContext->m_nIO); };
return fRes;
} // AtqWriteSocket()
BOOL
AtqSyncWsaSend(
IN PATQ_CONTEXT patqContext,
IN LPWSABUF pwsaBuffers,
IN DWORD dwBufferCount,
OUT LPDWORD pcbWritten
)
/*++
Routine Description:
Does a sync write of an array of wsa buffers using WSASend.
Arguments:
patqContext - pointer to ATQ context
pwsaBuffer - pointer to Winsock Buffers for scatter/gather
dwBufferCount - DWORD containing the count of buffers pointed
to by pwsaBuffer
pcbWritten - ptr to count of bytes written
Returns:
TRUE on success and FALSE if there is a failure.
--*/
{
BOOL fRes = FALSE;
PATQ_CONT pContext = (PATQ_CONT ) patqContext;
ATQ_ASSERT( pContext->Signature == ATQ_CONTEXT_SIGNATURE );
ATQ_ASSERT( pContext->arInfo.atqOp == AtqIoNone);
InterlockedIncrement( &pContext->m_nIO );
//
// See if the connection has already been closed.
//
if (pContext->hAsyncIO == NULL) {
InterlockedDecrement( &pContext->m_nIO );
SetLastError(WSAENOTSOCK);
return FALSE;
}
fRes = ( WSASend( (SOCKET ) pContext->hAsyncIO,
pwsaBuffers,
dwBufferCount,
pcbWritten,
0, // no flags
NULL, // lpo == NULL for sync write
NULL // no completion routine
) == 0);
InterlockedDecrement( &pContext->m_nIO );
return fRes;
} // AtqSyncWsaSend()
BOOL
AtqTransmitFile(
IN PATQ_CONTEXT patqContext,
IN HANDLE hFile,
IN DWORD dwBytesInFile,
IN LPTRANSMIT_FILE_BUFFERS lpTransmitBuffers,
IN DWORD dwFlags
)
/*++
Routine Description:
Does a TransmitFile using the handle defined in the context.
Arguments:
patqContext - pointer to ATQ context
hFile - handle of file to read from
dwBytesInFile - Bytes to transmit
lpTransmitBuffers - transmit buffer structure
dwFlags - Transmit file flags
Returns:
TRUE on success and FALSE if there is a failure.
--*/
{
#if 0
BOOL fRes;
PATQ_CONT pContext = (PATQ_CONT) patqContext;
PBANDWIDTH_INFO pBandwidthInfo = pContext->m_pBandwidthInfo;
ATQ_ASSERT( pContext->Signature == ATQ_CONTEXT_SIGNATURE );
ATQ_ASSERT( pContext->arInfo.atqOp == AtqIoNone);
ATQ_ASSERT( pBandwidthInfo != NULL );
ATQ_ASSERT( pBandwidthInfo->QuerySignature() == ATQ_BW_INFO_SIGNATURE );
//
// For large file sends, the client's default timeout may not be
// adequte for slow links. Scale based on bytes being sent
//
I_SetNextTimeout(pContext);
pContext->BytesSent = dwBytesInFile;
if ( dwFlags == 0 ) {
//
// If no flags are set, then we can attempt to use the special
// write-behind flag. This flag can cause the TransmitFile to
// complete immediately, before the send actually completes.
// This can be a significant performance improvement inside the
// system.
//
dwFlags = TF_WRITE_BEHIND;
} else if ( dwFlags & TF_DISCONNECT ) {
//
// If the socket is getting disconnected, mark it appropriately
//
pContext->MoveState( ( ( dwFlags & TF_REUSE_SOCKET )?
ACS_SOCK_UNCONNECTED:
ACS_SOCK_CLOSED
)
);
}
InterlockedIncrement( &pContext->m_nIO);
fRes = (TransmitFile( (SOCKET ) pContext->hAsyncIO,
hFile,
dwBytesInFile,
0,
&pContext->Overlapped,
lpTransmitBuffers,
dwFlags ) ||
(GetLastError() == ERROR_IO_PENDING));
if (!fRes) { InterlockedDecrement( &pContext->m_nIO); };
//
// Restore the socket state if we failed so that the handle gets freed
//
if ( !fRes )
{
pContext->MoveState( ACS_SOCK_CONNECTED);
}
return fRes;
#else
DBG_ASSERT(FALSE);
return FALSE;
#endif
} // AtqTransmitFile()
BOOL
AtqReadDirChanges(IN PATQ_CONTEXT patqContext,
IN LPVOID lpBuffer,
IN DWORD BytesToRead,
IN BOOL fWatchSubDir,
IN DWORD dwNotifyFilter,
IN OVERLAPPED * lpo
)
/*++
AtqReadDirChanges()
Description:
This function submits an Async ReadDirectoryChanges() call for
the Async handle in the ATQ context supplied.
It always requires a non-NULL overlapped pointer for processing
this call.
Arguments:
patqContext - pointer to ATQ Context
lpBuffer - buffer for the data to be read from ReadDirectoryChanges()
BytesToRead - count of bytes to read into buffer
fWatchSubDir - should we watch for sub directory changes
dwNotifyFilter - DWORD containing the flags for Notification
lpo - pointer to overlapped structure.
Returns:
TRUE if ReadDirectoryChanges() is successfully submitted.
FALSE if there is any failure in submitting IO.
--*/
{
BOOL fRes;
DWORD cbRead; // discarded after usage ( since this is Async)
PATQ_CONT pContext = (PATQ_CONT ) patqContext;
ATQ_ASSERT( pContext->Signature == ATQ_CONTEXT_SIGNATURE );
ATQ_ASSERT( pContext->arInfo.atqOp == AtqIoNone);
#if 0
if ( lpo == NULL ) {
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
I_SetNextTimeout(pContext);
pContext->BytesSent = 0;
InterlockedIncrement( &pContext->m_nIO);
fRes = ReadDirectoryChangesW( pContext->hAsyncIO,
lpBuffer,
BytesToRead,
fWatchSubDir,
dwNotifyFilter,
&cbRead,
lpo,
NULL);
if (!fRes) { InterlockedDecrement( &pContext->m_nIO); };
return fRes;
#else
return FALSE;
#endif
} // AtqReadDirChanges()
BOOL
AtqPostCompletionStatus(
IN PATQ_CONTEXT patqContext,
IN DWORD BytesTransferred
)
/*++
Routine Description:
Posts a completion status on the completion port queue
An IO pending error code is treated as a success error code
Arguments:
patqContext - pointer to ATQ context
Everything else as in the Win32 API
NOTES:
Return Value:
TRUE if successful, FALSE on error (call GetLastError)
--*/
{
BOOL fRes;
PATQ_CONT pAtqContext = (PATQ_CONT ) patqContext;
PBANDWIDTH_INFO pBandwidthInfo = pAtqContext->m_pBandwidthInfo;
ATQ_ASSERT( (pAtqContext)->Signature == ATQ_CONTEXT_SIGNATURE );
ATQ_ASSERT( pBandwidthInfo != NULL );
ATQ_ASSERT( pBandwidthInfo->QuerySignature() == ATQ_BW_INFO_SIGNATURE );
if ( !pAtqContext->IsBlocked()) {
InterlockedIncrement( &pAtqContext->m_nIO);
fRes = ( PostQueuedCompletionStatus( g_rghCompPort[ NtCurrentTeb()->IdealProcessor ],
BytesTransferred,
(DWORD_PTR) patqContext,
&pAtqContext->Overlapped ) ||
(GetLastError() == ERROR_IO_PENDING));
if (!fRes) { InterlockedDecrement( &pAtqContext->m_nIO); };
} else {
//
// Forcibly remove the context from blocking list.
//
fRes = pBandwidthInfo->RemoveFromBlockedList(pAtqContext);
// There is a possibility of race conditions!
// If we cant remove an item from blocking list before
// its IO operation is scheduled.
// there wont be any call back generated for this case!
}
return fRes;
} // AtqPostCompletionStatus
DWORD
I_AtqGetGlobalConfiguration(VOID)
/*++
Description:
This function sets several global config params for the ATQ package.
It also reads the global configuration from registry for ATQ.
The values if present will override the defaults
Returns:
Win32 Errorcode - NO_ERROR on success and anything else for error
--*/
{
DWORD dwError = NO_ERROR;
DWORD dwDefaultThreadTimeout = ATQ_REG_DEF_THREAD_TIMEOUT;
//
// If this is a NTW, do the right thing
//
MEMORYSTATUS ms;
//
// get the memory size
//
ms.dwLength = sizeof(MEMORYSTATUS);
GlobalMemoryStatus( &ms );
//
// attempt to use driver
//
g_fUseDriver = FALSE;
//
// Alloc two threads per MB of memory.
//
g_cMaxThreadLimit = (LONG)(ms.dwTotalPhys >> 19) + 2;
if ( g_cMaxThreadLimit < ATQ_REG_MIN_POOL_THREAD_LIMIT ) {
g_cMaxThreadLimit = ATQ_REG_MIN_POOL_THREAD_LIMIT;
} else if ( g_cMaxThreadLimit > ATQ_REG_MAX_POOL_THREAD_LIMIT ) {
g_cMaxThreadLimit = ATQ_REG_MAX_POOL_THREAD_LIMIT;
}
AtqSetInfo( AtqMaxConcurrency, ATQ_REG_DEF_PER_PROCESSOR_CONCURRENCY);
AtqSetInfo( AtqUseAcceptEx, TRUE );
AtqSetInfo( AtqMaxPoolThreads, ATQ_REG_DEF_PER_PROCESSOR_ATQ_THREADS);
AtqSetInfo( AtqThreadTimeout, ATQ_REG_DEF_THREAD_TIMEOUT);
return ( dwError);
} // I_AtqGetGlobalConfiguration()
DWORD
I_NumAtqEndpointsOpen(VOID)
/*++
Description:
This function counts the number of Enpoints that remain open.
Arguments:
None
Returns:
DWORD containing the number of endpoints that are open.
--*/
{
DWORD nEPOpen = 0;
AcquireLock( &AtqEndpointLock);
PLIST_ENTRY plEP;
for( plEP = AtqEndpointList.Flink;
plEP != &AtqEndpointList;
plEP = plEP->Flink ) {
nEPOpen++;
} // for
ReleaseLock( &AtqEndpointLock);
return ( nEPOpen);
} // I_NumAtqEndpointsOpen()
#define WINSOCK_INIT_WAIT_TIME (25 * 1000) // 25 seconds
#define WINSOCK_INIT_WAIT_RETRIES 4
BOOL
WaitForWinsockToInitialize(
VOID
)
/*++
Routine Description:
Spin until winsock comes up.
Arguments:
None.
Return Value:
TRUE if winsock is up. FALSE, if something bad happened.
--*/
{
INT err;
WSADATA wsaData;
SOCKET s = INVALID_SOCKET;
SOCKADDR_IN sockAddr;
INT retryCount = WINSOCK_INIT_WAIT_RETRIES;
BOOL fRet = FALSE;
BOOL fTCP = FALSE;
BOOL fSignaled = TRUE;
BOOL fAddr = FALSE;
DWORD dwErr;
DWORD dwBytes;
DWORD cbMaxDGramSend;
OVERLAPPED Overlapped;
HANDLE hConfig = NULL;
err = WSAStartup(MAKEWORD(2,0), &wsaData);
if ( err != 0 ) {
ATQ_PRINTF((DBG_CONTEXT,"err %d in WSAStartup\n", err));
return FALSE;
}
Overlapped.hEvent = CreateEvent(NULL, // default SD
FALSE, // auto reset the event
FALSE, // initialize as non signaled
NULL); // no name
if (NULL == Overlapped.hEvent) {
goto cleanup;
}
s = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, NULL, WSA_FLAG_OVERLAPPED);
if (INVALID_SOCKET != s) {
fTCP = TRUE;
} else {
// TCP is not installed or setup. Wait a reasonable amount of time for it
// to be setup and then bail.
// Get the initial handle so we will be sure and not miss it when/if
// tcp is installed. We don't need an overlapped structure for the
// first call since it will complete emediately.
if (WSAProviderConfigChange(&hConfig, NULL, NULL)) {
ATQ_PRINTF(( DBG_CONTEXT, "WaitForWinsockToInitialize WSAProviderConfigChange returned 0x%x\n", WSAGetLastError()));
goto cleanup;
}
s = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, NULL, WSA_FLAG_OVERLAPPED);
if (INVALID_SOCKET != s) {
fTCP = TRUE;
}
while (retryCount && !fTCP) {
if (fSignaled) {
err = WSAProviderConfigChange(&hConfig,
&Overlapped,
NULL);
if (err && (WSA_IO_PENDING != WSAGetLastError())) {
ATQ_PRINTF(( DBG_CONTEXT, "WaitForWinsockToInitialize ConfigChange failed with 0x%x\n", WSAGetLastError()));
goto cleanup;
}
}
ATQ_PRINTF(( DBG_CONTEXT, "WaitForWinsockToInitialize waiting for socket . . .\n"));
dwErr = WaitForSingleObject(Overlapped.hEvent, WINSOCK_INIT_WAIT_TIME);
switch (dwErr) {
default:
// Something went pretty wrong here.
ATQ_PRINTF(( DBG_CONTEXT, "WaitForWinsockToInitialize Failed at WaitForSingleObject with 0x%x\n", GetLastError()));
goto cleanup;
case WAIT_OBJECT_0:
//
// See if we have TCP now.
//
fSignaled = TRUE;
s = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, NULL, WSA_FLAG_OVERLAPPED);
if (INVALID_SOCKET != s) {
//
// This will cause us to exit the retry loop
//
fTCP = TRUE;
}
break;
case WAIT_TIMEOUT:
// try again. The event wasn't signaled so don't bother
// calling WSAProviderConfigChange again.
ATQ_PRINTF(( DBG_CONTEXT, "WaitForWinsockToInitialize waiting for TCP timed out.\n"));
fSignaled = FALSE;
break;
}
retryCount--;
}
}
if (fTCP) {
ATQ_ASSERT(TRUE == fSignaled);
retryCount = WINSOCK_INIT_WAIT_RETRIES;
// init sockAddr
ZeroMemory(&sockAddr, sizeof(sockAddr));
sockAddr.sin_family = AF_INET;
sockAddr.sin_port = 0;
sockAddr.sin_addr.s_addr = INADDR_ANY;
err = bind(s, (PSOCKADDR)&sockAddr, sizeof(sockAddr));
if ( err != SOCKET_ERROR ) {
fAddr = TRUE;
} else {
err = WSAIoctl(s,
SIO_ADDRESS_LIST_CHANGE,
NULL, // no input buffer
0, // size of input buffer
NULL, // don't need an ouput buffer either
0, // size of out buffer
&dwBytes, // bytes returned
&Overlapped, // overlapped structure
NULL); // no callback routine
if (err && (WSAGetLastError() != WSA_IO_PENDING)) {
ATQ_PRINTF(( DBG_CONTEXT, "WaitForWinsockToInitialize Failed at WSAIoctl with 0x%x\n", WSAGetLastError()));
goto cleanup;
}
err = bind(s, (PSOCKADDR)&sockAddr, sizeof(sockAddr));
if ( err != SOCKET_ERROR ) {
fAddr = TRUE;
}
while (retryCount && !fAddr) {
ATQ_PRINTF(( DBG_CONTEXT, "WaitWinsockToInitialize waiting for address . . .\n"));
dwErr = WaitForSingleObject(Overlapped.hEvent, WINSOCK_INIT_WAIT_TIME);
switch (dwErr) {
default:
// Something went pretty wrong here.
ATQ_PRINTF(( DBG_CONTEXT, "WaitWinsockToInitialize Failed at WaitForSingleObject with 0x%x\n", GetLastError()));
goto cleanup;
case WAIT_OBJECT_0:
//
// Register for address change notification again so that
// nothing is missed in case there still aren't any TCP
// addresses.
//
err = WSAIoctl(s,
SIO_ADDRESS_LIST_CHANGE,
NULL, // no input buffer
0, // size of input buffer
NULL, // don't need an ouput buffer either
0, // size of out buffer
&dwBytes, // bytes returned
&Overlapped, // overlapped structure
NULL); // no callback routine
if (err && (WSA_IO_PENDING != WSAGetLastError())) {
ATQ_PRINTF(( DBG_CONTEXT, "WaitWinsockToInitialize Failed at WSAIoctl with 0x%x\n", WSAGetLastError()));
goto cleanup;
}
//
// See if we have an address to bind to now.
//
err = bind(s, (PSOCKADDR)&sockAddr, sizeof(sockAddr));
if (SOCKET_ERROR != err) {
//
// This will cause us to exit the retry loop
//
fAddr = TRUE;
}
break;
case WAIT_TIMEOUT:
// try again. The event wasn't signaled so don't bother
// calling WSAIoctl again.
ATQ_PRINTF(( DBG_CONTEXT, "WaitForWinsockToInitialize waiting for addr's timed out.\n"));
break;
}
retryCount--;
} // while
} // if err != SOCKET_ERROR
} // if fTCP
if (fTCP && fAddr) {
SOCKET s2;
INT size = sizeof(cbMaxDGramSend);
GUID RecvMsgGuid = WSAID_WSARECVMSG;
GUID AcceptExGuid = WSAID_ACCEPTEX;
GUID GetAccptExAddrsGuid = WSAID_GETACCEPTEXSOCKADDRS;
//
// Set the return value as TRUE
//
fRet = TRUE;
// record the largest possible datagram send.
s2 = WSASocket(AF_INET, SOCK_DGRAM, IPPROTO_UDP, NULL, NULL, 0);
if ( s == INVALID_SOCKET) {
err = WSAGetLastError();
ATQ_PRINTF(( DBG_CONTEXT, "WSASocket failed with %d.\n", err));
} else {
err = getsockopt(s,
SOL_SOCKET,
SO_MAX_MSG_SIZE,
(PCHAR)&cbMaxDGramSend,
&size);
if ( err == 0 ) {
g_cbMaxDGramSend = cbMaxDGramSend;
ATQ_PRINTF(( DBG_CONTEXT, "Setting g_cbMaxDGramSend to 0x%x\n", g_cbMaxDGramSend));
} else {
ATQ_PRINTF(( DBG_CONTEXT, "Cannot query max datagram size [err %d]\n",
WSAGetLastError()));
}
err = WSAIoctl(s2,
SIO_GET_EXTENSION_FUNCTION_POINTER,
&RecvMsgGuid,
sizeof(GUID),
&g_pfnWSARecvMsg,
sizeof(g_pfnWSARecvMsg),
&dwBytes,
NULL,
NULL
);
if (err) {
ATQ_PRINTF(( DBG_CONTEXT, "Failed to query for the WSARecvMsg pointer [err 0x%x]\n",
WSAGetLastError()));
} else {
g_bUseRecvMsg = TRUE;
}
closesocket(s2);
}
err = WSAIoctl(s,
SIO_GET_EXTENSION_FUNCTION_POINTER,
&AcceptExGuid,
sizeof(GUID),
&g_pfnAcceptEx,
sizeof(g_pfnAcceptEx),
&dwBytes,
NULL,
NULL
);
if (err) {
ATQ_PRINTF(( DBG_CONTEXT, "Failed to query for the WSAAcceptEx pointer [err 0x%x]\n",
WSAGetLastError()));
g_pfnAcceptEx = AcceptEx;
}
err = WSAIoctl(s,
SIO_GET_EXTENSION_FUNCTION_POINTER,
&GetAccptExAddrsGuid,
sizeof(GUID),
&g_pfnGetAcceptExSockaddrs,
sizeof(g_pfnGetAcceptExSockaddrs),
&dwBytes,
NULL,
NULL
);
if (err) {
ATQ_PRINTF(( DBG_CONTEXT, "Failed to query for the GetAcceptExAddrs pointer [err 0x%x]\n",
WSAGetLastError()));
g_pfnGetAcceptExSockaddrs = GetAcceptExSockaddrs;
}
}
cleanup:
if (NULL != hConfig) {
CloseHandle(hConfig);
}
if (INVALID_SOCKET != s) {
closesocket(s);
}
if (NULL != Overlapped.hEvent) {
CloseHandle(Overlapped.hEvent);
}
if (!fRet) {
WSACleanup();
}
IF_DEBUG(ERROR) {
if (!fRet) {
if (!fTCP) {
ATQ_PRINTF(( DBG_CONTEXT, "WaitForWinsockToInitialize there's no sockets.\n"));
} else {
ATQ_PRINTF(( DBG_CONTEXT, "WaitForWinsockToInitialize there's no ip addresses.\n"));
}
}
}
return fRet;
} // WaitForWinsockToInitialize
| 27.639565 | 133 | 0.528887 | [
"object"
] |
fa9de51c260a4bd040028a85b59bc18a52cf61c5 | 2,719 | cc | C++ | src/tests/test_segment.cc | fossabot/xtp | e82cc53f23e213d09da15da80ada6e32ac031a07 | [
"Apache-2.0"
] | null | null | null | src/tests/test_segment.cc | fossabot/xtp | e82cc53f23e213d09da15da80ada6e32ac031a07 | [
"Apache-2.0"
] | null | null | null | src/tests/test_segment.cc | fossabot/xtp | e82cc53f23e213d09da15da80ada6e32ac031a07 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* 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.
*
*/
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE segment_test
// Standard includes
#include <vector>
// Third party includes
#include <boost/test/unit_test.hpp>
// Local VOTCA includes
#include "votca/xtp/checkpoint.h"
#include "votca/xtp/segment.h"
using namespace votca::tools;
using namespace votca::xtp;
using votca::Index;
BOOST_AUTO_TEST_SUITE(segment_test)
BOOST_AUTO_TEST_CASE(getElementtest) {
Segment seg("one", 1);
Atom atm1(1, "C", Eigen::Vector3d::Zero());
Atom atm2(2, "H", Eigen::Vector3d::UnitX());
Atom atm3(3, "N", Eigen::Vector3d::UnitY());
Atom atm4(4, "Au", Eigen::Vector3d::UnitZ());
Atom atm5(5, "C", 2 * Eigen::Vector3d::UnitZ());
seg.push_back(atm1);
seg.push_back(atm2);
seg.push_back(atm2);
seg.push_back(atm3);
seg.push_back(atm4);
seg.push_back(atm3);
seg.push_back(atm5);
std::vector<std::string> unique_ele = seg.FindUniqueElements();
std::vector<std::string> unique_ele_ref = {"C", "H", "N", "Au"};
BOOST_CHECK_EQUAL(unique_ele.size(), unique_ele_ref.size());
for (Index i = 0; i < Index(unique_ele.size()); i++) {
BOOST_CHECK_EQUAL(unique_ele[i], unique_ele_ref[i]);
}
}
BOOST_AUTO_TEST_CASE(writehdf5) {
Segment seg("one", 1);
Atom atm1(1, "C", Eigen::Vector3d::Zero());
Atom atm2(2, "H", Eigen::Vector3d::UnitX());
Atom atm3(3, "N", Eigen::Vector3d::UnitY());
Atom atm4(4, "Au", Eigen::Vector3d::UnitZ());
Atom atm5(5, "C", 2 * Eigen::Vector3d::UnitZ());
seg.push_back(atm1);
seg.push_back(atm2);
seg.push_back(atm2);
seg.push_back(atm3);
seg.push_back(atm4);
seg.push_back(atm3);
seg.push_back(atm5);
{
CheckpointFile f("segment_test.hdf5");
CheckpointWriter w = f.getWriter();
seg.WriteToCpt(w);
}
CheckpointFile f("segment_test.hdf5");
CheckpointReader r = f.getReader();
Segment seg2(r);
for (Index i = 0; i < seg2.size(); i++) {
const Atom& a1 = seg[i];
const Atom& a2 = seg2[i];
BOOST_CHECK_EQUAL(a1.getName(), a2.getName());
bool pos_equal = a1.getPos().isApprox(a2.getPos(), 1e-9);
BOOST_CHECK_EQUAL(pos_equal, true);
}
}
BOOST_AUTO_TEST_SUITE_END()
| 28.322917 | 75 | 0.684443 | [
"vector"
] |
fa9f0501c28cd6c7fe382fd328941fbe7e02ebfe | 7,065 | cpp | C++ | src/frontends/lean/info_manager.cpp | avigad/lean | 5410178203ab5ae854b5804586ace074ffd63aae | [
"Apache-2.0"
] | 2 | 2017-05-31T08:41:28.000Z | 2018-08-01T18:11:49.000Z | src/frontends/lean/info_manager.cpp | avigad/lean | 5410178203ab5ae854b5804586ace074ffd63aae | [
"Apache-2.0"
] | null | null | null | src/frontends/lean/info_manager.cpp | avigad/lean | 5410178203ab5ae854b5804586ace074ffd63aae | [
"Apache-2.0"
] | 1 | 2017-02-27T21:02:16.000Z | 2017-02-27T21:02:16.000Z | /*
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#include <algorithm>
#include <vector>
#include <set>
#include <string>
#include "kernel/type_checker.h"
#include "library/trace.h"
#include "library/documentation.h"
#include "library/scoped_ext.h"
#include "library/vm/vm.h"
#include "library/vm/vm_nat.h"
#include "library/vm/vm_format.h"
#include "library/vm/vm_list.h"
#include "library/vm/vm_pos_info.h"
#include "library/tactic/tactic_state.h"
#include "frontends/lean/json.h"
#include "frontends/lean/info_manager.h"
#include "frontends/lean/interactive.h"
namespace lean {
class type_info_data : public info_data_cell {
protected:
expr m_expr;
public:
type_info_data(expr const & e): m_expr(e) {}
expr const & get_type() const { return m_expr; }
virtual void instantiate_mvars(metavar_context const & mctx) override {
m_expr = metavar_context(mctx).instantiate_mvars(m_expr);
}
#ifdef LEAN_JSON
virtual void report(io_state_stream const & ios, json & record) const override {
interactive_report_type(ios.get_environment(), ios.get_options(), m_expr, record);
}
#endif
};
class identifier_info_data : public info_data_cell {
name m_full_id;
public:
identifier_info_data(name const & full_id): m_full_id(full_id) {}
#ifdef LEAN_JSON
virtual void report(io_state_stream const & ios, json & record) const override {
record["full-id"] = m_full_id.to_string();
add_source_info(ios.get_environment(), m_full_id, record);
if (auto doc = get_doc_string(ios.get_environment(), m_full_id))
record["doc"] = *doc;
}
#endif
};
#ifdef LEAN_JSON
void hole_info_data::report(io_state_stream const & ios, json & record) const {
type_context ctx = mk_type_context_for(m_state);
interactive_report_type(ios.get_environment(), ios.get_options(), ctx.infer(m_state.main()), record);
}
#endif
hole_info_data const * is_hole_info_data(info_data const & d) {
return dynamic_cast<hole_info_data const *>(d.raw());
}
hole_info_data const & to_hole_info_data(info_data const & d) {
lean_assert(is_hole_info_data(d));
return *static_cast<hole_info_data const *>(d.raw());
}
#ifdef LEAN_JSON
void vm_obj_format_info::report(io_state_stream const & ios, json & record) const {
if (!m_cache) {
vm_state S(m_env, ios.get_options());
scope_vm_state scope(S);
vm_obj thunk = m_thunk.to_vm_obj();
const_cast<vm_obj_format_info*>(this)->m_cache = to_format(S.invoke(thunk, mk_vm_unit()));
}
std::ostringstream ss;
ss << mk_pair(*m_cache, ios.get_options());
record["state"] = ss.str();
}
#endif
info_data mk_type_info(expr const & e) { return info_data(new type_info_data(e)); }
info_data mk_identifier_info(name const & full_id) { return info_data(new identifier_info_data(full_id)); }
info_data mk_vm_obj_format_info(environment const & env, vm_obj const & thunk) { return info_data(new vm_obj_format_info(env, thunk)); }
info_data mk_hole_info(tactic_state const & s, expr const & hole_args, pos_info const & begin, pos_info end) {
return info_data(new hole_info_data(s, hole_args, begin, end));
}
void info_manager::add_info(pos_info pos, info_data data) {
#ifdef LEAN_NO_INFO
return;
#endif
line_info_data_set line_set = m_line_data[pos.first];
line_set.insert(pos.second, cons<info_data>(data, line_set[pos.second]));
m_line_data.insert(pos.first, line_set);
}
line_info_data_set info_manager::get_line_info_set(unsigned l) const {
if (auto it = m_line_data.find(l))
return *it;
return {};
}
void info_manager::instantiate_mvars(metavar_context const & mctx) {
m_line_data.for_each([&](unsigned, line_info_data_set const & set) {
set.for_each([&](unsigned, list<info_data> const & data) {
for (info_data const & info : data)
info.instantiate_mvars(mctx);
});
});
}
void info_manager::merge(info_manager const & info) {
#ifdef LEAN_NO_INFO
return;
#endif
info.m_line_data.for_each([&](unsigned line, line_info_data_set const & set) {
set.for_each([&](unsigned col, list<info_data> const & data) {
buffer<info_data> b;
to_buffer(data, b);
unsigned i = b.size();
while (i > 0) {
--i;
add_info({line, col}, b[i]);
}
});
});
}
void info_manager::add_type_info(pos_info pos, expr const & e) {
#ifdef LEAN_NO_INFO
return;
#endif
add_info(pos, mk_type_info(e));
}
void info_manager::add_identifier_info(pos_info pos, name const & full_id) {
#ifdef LEAN_NO_INFO
return;
#endif
add_info(pos, mk_identifier_info(full_id));
}
void info_manager::add_const_info(environment const & env, pos_info pos, name const & full_id) {
add_identifier_info(pos, full_id);
add_type_info(pos, env.get(full_id).get_type());
}
void info_manager::add_hole_info(pos_info const & begin_pos, pos_info const & end_pos, tactic_state const & s, expr const & hole_args) {
#ifdef LEAN_NO_INFO
return;
#endif
info_data d = mk_hole_info(s, hole_args, begin_pos, end_pos);
add_info(begin_pos, d);
}
void info_manager::add_vm_obj_format_info(pos_info pos, environment const & env, vm_obj const & thunk) {
#ifdef LEAN_NO_INFO
return;
#endif
add_info(pos, mk_vm_obj_format_info(env, thunk));
}
#ifdef LEAN_JSON
void info_manager::get_info_record(environment const & env, options const & o, io_state const & ios, pos_info pos,
json & record, std::function<bool (info_data const &)> pred) const {
type_context tc(env, o);
io_state_stream out = regular(env, ios, tc).update_options(o);
get_line_info_set(pos.first).for_each([&](unsigned c, list<info_data> const & ds) {
if (c == pos.second) {
for (auto const & d : ds) {
if (!pred || pred(d))
d.report(out, record);
}
}
});
}
#endif
LEAN_THREAD_PTR(info_manager, g_info_m);
scoped_info_manager::scoped_info_manager(info_manager *infom) {
m_old = g_info_m;
g_info_m = infom;
}
scoped_info_manager::~scoped_info_manager() {
g_info_m = m_old;
}
info_manager * get_global_info_manager() {
return g_info_m;
}
vm_obj tactic_save_info_thunk(vm_obj const & pos, vm_obj const & thunk, vm_obj const & s) {
try {
if (g_info_m) {
auto _pos = to_pos_info(pos);
g_info_m->add_vm_obj_format_info(_pos, tactic::to_state(s).env(), thunk);
}
return tactic::mk_success(tactic::to_state(s));
} catch (exception & ex) {
return tactic::mk_exception(ex, tactic::to_state(s));
}
}
void initialize_info_manager() {
DECLARE_VM_BUILTIN(name({"tactic", "save_info_thunk"}), tactic_save_info_thunk);
}
void finalize_info_manager() {
}
}
| 32.408257 | 136 | 0.676292 | [
"vector"
] |
faa6ea3828a478b773b2430323f13c682daab7ba | 2,977 | cc | C++ | examples/graphics/earth/pepper_plugin.cc | nachooya/naclports-1 | 43e9f13a836c1f6c609bb1418f672bd2041c3888 | [
"BSD-3-Clause"
] | 1 | 2019-01-17T23:49:48.000Z | 2019-01-17T23:49:48.000Z | examples/graphics/earth/pepper_plugin.cc | nachooya/naclports-1 | 43e9f13a836c1f6c609bb1418f672bd2041c3888 | [
"BSD-3-Clause"
] | null | null | null | examples/graphics/earth/pepper_plugin.cc | nachooya/naclports-1 | 43e9f13a836c1f6c609bb1418f672bd2041c3888 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2011 The Native Client Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifdef __native_client__
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <ppapi/cpp/instance.h>
#include <ppapi/cpp/module.h>
#include <ppapi/cpp/rect.h>
#include <ppapi/cpp/size.h>
#include <SDL_video.h>
extern int SDL_main(int argc, const char *argv[]);
#include <SDL.h>
#include <SDL_nacl.h>
// By declaring kill here, we prevent it from being pulled from libnosys.a
// thereby avoiding the compiler warning, and getting a potentially useful
// printf if somebody actually tries to use kill().
extern "C" int kill(pid_t pid, int sig) {
printf("WARNING: kill(%d, %d). Kill is not implemented for Native Client\n",
pid, sig);
return -1;
}
class PluginInstance : public pp::Instance {
public:
explicit PluginInstance(PP_Instance instance) : pp::Instance(instance),
sdl_main_thread_(0),
width_(0),
height_(0) {
printf("PluginInstance\n");
}
~PluginInstance() {
if (sdl_main_thread_) {
pthread_join(sdl_main_thread_, NULL);
}
}
virtual void DidChangeView(const pp::Rect& position, const pp::Rect& clip) {
printf("did change view, new %dx%d, old %dx%d\n",
position.size().width(), position.size().height(),
width_, height_);
if (position.size().width() == width_ &&
position.size().height() == height_)
return; // Size didn't change, no need to update anything.
if (sdl_thread_started_ == false) {
width_ = position.size().width();
height_ = position.size().height();
SDL_NACL_SetInstance(pp_instance(), width_, height_);
// It seems this call to SDL_Init is required. Calling from
// sdl_main() isn't good enough.
// Perhaps it must be called from the main thread?
int lval = SDL_Init(SDL_INIT_VIDEO);
assert(lval >= 0);
if (0 == pthread_create(&sdl_main_thread_, NULL, sdl_thread, this)) {
sdl_thread_started_ = true;
}
}
}
bool HandleInputEvent(const PP_InputEvent& event) {
SDL_NACL_PushEvent(&event);
return true;
}
bool Init(int argc, const char* argn[], const char* argv[]) {
return true;
}
private:
bool sdl_thread_started_;
pthread_t sdl_main_thread_;
int width_;
int height_;
static void* sdl_thread(void* param) {
SDL_main(0, NULL);
return NULL;
}
};
class PepperModule : public pp::Module {
public:
// Create and return a PluginInstanceInstance object.
virtual pp::Instance* CreateInstance(PP_Instance instance) {
printf("CreateInstance\n");
return new PluginInstance(instance);
}
};
namespace pp {
Module* CreateModule() {
printf("CreateModule\n");
return new PepperModule();
}
} // namespace pp
#endif // __native_client__
| 27.82243 | 78 | 0.655694 | [
"object"
] |
fab1ee985488529a6a46319f6c26ca7569e313d3 | 2,174 | cpp | C++ | aws-cpp-sdk-databrew/source/model/DatabaseInputDefinition.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-databrew/source/model/DatabaseInputDefinition.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-databrew/source/model/DatabaseInputDefinition.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/databrew/model/DatabaseInputDefinition.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace GlueDataBrew
{
namespace Model
{
DatabaseInputDefinition::DatabaseInputDefinition() :
m_glueConnectionNameHasBeenSet(false),
m_databaseTableNameHasBeenSet(false),
m_tempDirectoryHasBeenSet(false),
m_queryStringHasBeenSet(false)
{
}
DatabaseInputDefinition::DatabaseInputDefinition(JsonView jsonValue) :
m_glueConnectionNameHasBeenSet(false),
m_databaseTableNameHasBeenSet(false),
m_tempDirectoryHasBeenSet(false),
m_queryStringHasBeenSet(false)
{
*this = jsonValue;
}
DatabaseInputDefinition& DatabaseInputDefinition::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("GlueConnectionName"))
{
m_glueConnectionName = jsonValue.GetString("GlueConnectionName");
m_glueConnectionNameHasBeenSet = true;
}
if(jsonValue.ValueExists("DatabaseTableName"))
{
m_databaseTableName = jsonValue.GetString("DatabaseTableName");
m_databaseTableNameHasBeenSet = true;
}
if(jsonValue.ValueExists("TempDirectory"))
{
m_tempDirectory = jsonValue.GetObject("TempDirectory");
m_tempDirectoryHasBeenSet = true;
}
if(jsonValue.ValueExists("QueryString"))
{
m_queryString = jsonValue.GetString("QueryString");
m_queryStringHasBeenSet = true;
}
return *this;
}
JsonValue DatabaseInputDefinition::Jsonize() const
{
JsonValue payload;
if(m_glueConnectionNameHasBeenSet)
{
payload.WithString("GlueConnectionName", m_glueConnectionName);
}
if(m_databaseTableNameHasBeenSet)
{
payload.WithString("DatabaseTableName", m_databaseTableName);
}
if(m_tempDirectoryHasBeenSet)
{
payload.WithObject("TempDirectory", m_tempDirectory.Jsonize());
}
if(m_queryStringHasBeenSet)
{
payload.WithString("QueryString", m_queryString);
}
return payload;
}
} // namespace Model
} // namespace GlueDataBrew
} // namespace Aws
| 20.704762 | 80 | 0.75299 | [
"model"
] |
fab8e1f54b0bf4c50ff634b96a93c093b54a78c6 | 3,618 | cpp | C++ | main.cpp | himanshushekharb16/hostspot | 1d080e611ac7092e1f99d2b32a542a2d1490e241 | [
"Apache-2.0"
] | null | null | null | main.cpp | himanshushekharb16/hostspot | 1d080e611ac7092e1f99d2b32a542a2d1490e241 | [
"Apache-2.0"
] | null | null | null | main.cpp | himanshushekharb16/hostspot | 1d080e611ac7092e1f99d2b32a542a2d1490e241 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <cstring>
#include <string>
using namespace std;
struct configs
{
string connToBridge;
string bridgeOver;// 0 for Ethernet and 1 for Wifi
string ssid;
string key;
};
configs* getData()
{
configs *newConfig = new configs;
int x;
cout << "Enter interface to share (internet source) " << endl;
cout << "1 : Ethernet\n2 : Wi-Fi \n";
cin >> x;
switch(x) {
case 1 : cout << "Ethernet network is to be shared over WiFi" << endl;
newConfig->connToBridge = "Ethernet";
newConfig->bridgeOver = "Wi-Fi";
break;
case 2 : cout << "WiFi is to be shared over Ethernet" << endl;
newConfig->connToBridge = "Wi-Fi";
newConfig->bridgeOver = "Ethernet";
break;
default : cout << "Invalid input :("; exit(EXIT_FAILURE);
}
cout << "Enter SSID (name of hotspot) : " ; cin >> newConfig->ssid;
do {
cout << "Enter password (at least 8 characters) : "; cin >> newConfig->key;
} while ((newConfig->key).length() < 8);
return newConfig;
}
int main()
{
cout << "blah blah blah" << endl;
fstream file;
file.open("script.ps1", ios::out);
configs *conf;
conf = getData();
// Register the HNetCfg library (once)
file << "regsvr32 hnetcfg.dll" << endl;
// create a NetSharingManager object
file << "$m = New-Object -ComObject HNetCfg.HNetShare" << endl;
//find desired connection
file << "$c = $m.EnumEveryConnection \|\? \{ $m.NetConnectionProps.Invoke($_).Name -eq \"" << conf->connToBridge << "\" \}" << endl;
//get sharing information and enable sharing
file << "$config = $m.INetSharingConfigurationForINetConnection.Invoke\($c\)" << endl;
file << "$config.EnableSharing\(0\)" << endl;
//disable sharing for the other device
//file << "$p = $m.EnumEveryConnection \|\? \{ $m.NetConnectionProps.Invoke($_).Name -eq \"" << conf->bridgeOver << "\" \}" << endl;
//get sharing information and enable sharing
//file << "$tempconfig = $m.INetSharingConfigurationForINetConnection.Invoke\($p\)" << endl;
//file << "$tempconfig.DisableSharing\(\)" << endl;
//starting hostednetwork
string netsh_arg;
if (conf->bridgeOver == "Wi-Fi") netsh_arg = "wlan";
else if (conf->bridgeOver == "Ethernet") netsh_arg = "lan";
else exit(EXIT_FAILURE);
cout << "Use proxy settings (y/n) ? ";
char c; cin >> c;
if (c == 'y' || c == 'Y') file << "netsh winhttp import proxy source=ie" << endl;
else file << "netsh winhttp reset proxy" << endl;
file << "netsh " << netsh_arg << " set hostednetwork mode=allow ssid=" << conf->ssid << " key=" << conf->key << " keyUsage=temporary"<< endl;
file << "netsh " << netsh_arg << " start hostednetwork" << endl;
file << "$var = \"going\"" << endl;
//create a loop
file << "Write-Host \"I won't take much of System\'s resources. So you can sit back and watch me work\"" << endl;
file << "Write-Host \"Type 'q' anytime you want to stop the hotspot\"" << endl;
file << "DO \{ $var = Read-Host \} While \($var.CompareTo\(\"q\"\)\)" << endl;
file << "netsh " << netsh_arg << " stop hostednetwork" << endl;
file << "$config.DisableSharing\(\)" << endl;
//file << "set-executionpolicy unrestricted";
file.close();
cout << "Script is ready, you can run script.bat and enjoy.";
return 0;
}
| 37.298969 | 146 | 0.57518 | [
"object"
] |
fac11b8a33f05fd5039eacba41e6003e07ab02a4 | 21,414 | cc | C++ | tubemq-client-twins/tubemq-client-cpp/src/tubemq_config.cc | keyihao/incubator-tubemq | 36b4a6757c9336a90f52419b8b4ba582aa8fff6e | [
"Apache-2.0"
] | null | null | null | tubemq-client-twins/tubemq-client-cpp/src/tubemq_config.cc | keyihao/incubator-tubemq | 36b4a6757c9336a90f52419b8b4ba582aa8fff6e | [
"Apache-2.0"
] | null | null | null | tubemq-client-twins/tubemq-client-cpp/src/tubemq_config.cc | keyihao/incubator-tubemq | 36b4a6757c9336a90f52419b8b4ba582aa8fff6e | [
"Apache-2.0"
] | null | null | null | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#include "tubemq/tubemq_config.h"
#include <sstream>
#include <vector>
#include "const_config.h"
#include "const_rpc.h"
#include "utils.h"
namespace tubemq {
using std::set;
using std::stringstream;
using std::vector;
BaseConfig::BaseConfig() {
master_addrinfo_ = "";
auth_enable_ = false;
auth_usrname_ = "";
auth_usrpassword_ = "";
tls_enabled_ = false;
tls_trust_store_path_ = "";
tls_trust_store_password_ = "";
rpc_read_timeout_ms_ = tb_config::kRpcTimoutDefMs;
heartbeat_period_ms_ = tb_config::kHeartBeatPeriodDefMs;
max_heartbeat_retry_times_ = tb_config::kHeartBeatFailRetryTimesDef;
heartbeat_period_afterfail_ms_ = tb_config::kHeartBeatSleepPeriodDefMs;
}
BaseConfig::~BaseConfig() {
//
}
BaseConfig& BaseConfig::operator=(const BaseConfig& target) {
if (this != &target) {
master_addrinfo_ = target.master_addrinfo_;
auth_enable_ = target.auth_enable_;
auth_usrname_ = target.auth_usrname_;
auth_usrpassword_ = target.auth_usrpassword_;
tls_enabled_ = target.tls_enabled_;
tls_trust_store_path_ = target.tls_trust_store_path_;
tls_trust_store_password_ = target.tls_trust_store_password_;
rpc_read_timeout_ms_ = target.rpc_read_timeout_ms_;
heartbeat_period_ms_ = target.heartbeat_period_ms_;
max_heartbeat_retry_times_ = target.max_heartbeat_retry_times_;
heartbeat_period_afterfail_ms_ = target.heartbeat_period_afterfail_ms_;
}
return *this;
}
bool BaseConfig::SetMasterAddrInfo(string& err_info, const string& master_addrinfo) {
// check parameter masterAddrInfo
string trimed_master_addr_info = Utils::Trim(master_addrinfo);
if (trimed_master_addr_info.empty()) {
err_info = "Illegal parameter: master_addrinfo is blank!";
return false;
}
if (trimed_master_addr_info.length() > tb_config::kMasterAddrInfoMaxLength) {
stringstream ss;
ss << "Illegal parameter: over max ";
ss << tb_config::kMasterAddrInfoMaxLength;
ss << " length of master_addrinfo parameter!";
err_info = ss.str();
return false;
}
// parse and verify master address info
// master_addrinfo's format like ip1:port1,ip2:port2,ip3:port3
map<string, int32_t> tgt_address_map;
Utils::Split(master_addrinfo, tgt_address_map, delimiter::kDelimiterComma,
delimiter::kDelimiterColon);
if (tgt_address_map.empty()) {
err_info = "Illegal parameter: unrecognized master_addrinfo address information!";
return false;
}
master_addrinfo_ = trimed_master_addr_info;
err_info = "Ok";
return true;
}
bool BaseConfig::SetTlsInfo(string& err_info, bool tls_enable, const string& trust_store_path,
const string& trust_store_password) {
tls_enabled_ = tls_enable;
if (tls_enable) {
string trimed_trust_store_path = Utils::Trim(trust_store_path);
if (trimed_trust_store_path.empty()) {
err_info = "Illegal parameter: trust_store_path is empty!";
return false;
}
string trimed_trust_store_password = Utils::Trim(trust_store_password);
if (trimed_trust_store_password.empty()) {
err_info = "Illegal parameter: trust_store_password is empty!";
return false;
}
tls_trust_store_path_ = trimed_trust_store_path;
tls_trust_store_password_ = trimed_trust_store_password;
} else {
tls_trust_store_path_ = "";
tls_trust_store_password_ = "";
}
err_info = "Ok";
return true;
}
bool BaseConfig::SetAuthenticInfo(string& err_info, bool authentic_enable, const string& usr_name,
const string& usr_password) {
auth_enable_ = authentic_enable;
if (authentic_enable) {
string trimed_usr_name = Utils::Trim(usr_name);
if (trimed_usr_name.empty()) {
err_info = "Illegal parameter: usr_name is empty!";
return false;
}
string trimed_usr_password = Utils::Trim(usr_password);
if (trimed_usr_password.empty()) {
err_info = "Illegal parameter: usr_password is empty!";
return false;
}
auth_usrname_ = trimed_usr_name;
auth_usrpassword_ = trimed_usr_password;
} else {
auth_usrname_ = "";
auth_usrpassword_ = "";
}
err_info = "Ok";
return true;
}
const string& BaseConfig::GetMasterAddrInfo() const { return master_addrinfo_; }
bool BaseConfig::IsTlsEnabled() { return tls_enabled_; }
const string& BaseConfig::GetTrustStorePath() const { return tls_trust_store_path_; }
const string& BaseConfig::GetTrustStorePassword() const { return tls_trust_store_password_; }
bool BaseConfig::IsAuthenticEnabled() { return auth_enable_; }
const string& BaseConfig::GetUsrName() const { return auth_usrname_; }
const string& BaseConfig::GetUsrPassWord() const { return auth_usrpassword_; }
void BaseConfig::SetRpcReadTimeoutMs(int rpc_read_timeout_ms) {
if (rpc_read_timeout_ms >= tb_config::kRpcTimoutMaxMs) {
rpc_read_timeout_ms_ = tb_config::kRpcTimoutMaxMs;
} else if (rpc_read_timeout_ms <= tb_config::kRpcTimoutMinMs) {
rpc_read_timeout_ms_ = tb_config::kRpcTimoutMinMs;
} else {
rpc_read_timeout_ms_ = rpc_read_timeout_ms;
}
}
int32_t BaseConfig::GetRpcReadTimeoutMs() { return rpc_read_timeout_ms_; }
void BaseConfig::SetHeartbeatPeriodMs(int32_t heartbeat_period_ms) {
heartbeat_period_ms_ = heartbeat_period_ms;
}
int32_t BaseConfig::GetHeartbeatPeriodMs() { return heartbeat_period_ms_; }
void BaseConfig::SetMaxHeartBeatRetryTimes(int32_t max_heartbeat_retry_times) {
max_heartbeat_retry_times_ = max_heartbeat_retry_times;
}
int32_t BaseConfig::GetMaxHeartBeatRetryTimes() { return max_heartbeat_retry_times_; }
void BaseConfig::SetHeartbeatPeriodAftFailMs(int32_t heartbeat_period_afterfail_ms) {
heartbeat_period_afterfail_ms_ = heartbeat_period_afterfail_ms;
}
int32_t BaseConfig::GetHeartbeatPeriodAftFailMs() { return heartbeat_period_afterfail_ms_; }
string BaseConfig::ToString() {
stringstream ss;
ss << "BaseConfig={master_addrinfo_='";
ss << master_addrinfo_;
ss << "', authEnable=";
ss << auth_enable_;
ss << ", auth_usrname_='";
ss << auth_usrname_;
ss << "', auth_usrpassword_='";
ss << auth_usrpassword_;
ss << "', tls_enabled_=";
ss << tls_enabled_;
ss << ", tls_trust_store_path_='";
ss << tls_trust_store_path_;
ss << "', tls_trust_store_password_='";
ss << tls_trust_store_password_;
ss << "', rpc_read_timeout_ms_=";
ss << rpc_read_timeout_ms_;
ss << ", heartbeat_period_ms_=";
ss << heartbeat_period_ms_;
ss << ", max_heartbeat_retry_times_=";
ss << max_heartbeat_retry_times_;
ss << ", heartbeat_period_afterfail_ms_=";
ss << heartbeat_period_afterfail_ms_;
ss << "}";
return ss.str();
}
ConsumerConfig::ConsumerConfig() {
group_name_ = "";
is_bound_consume_ = false;
session_key_ = "";
source_count_ = 0;
is_select_big_ = true;
consume_position_ = kConsumeFromLatestOffset;
is_rollback_if_confirm_timout_ = true;
max_subinfo_report_intvl_ = tb_config::kSubInfoReportMaxIntervalTimes;
max_part_check_period_ms_ = tb_config::kMaxPartCheckPeriodMsDef;
part_check_slice_ms_ = tb_config::kPartCheckSliceMsDef;
msg_notfound_wait_period_ms_ = tb_config::kMsgNotfoundWaitPeriodMsDef;
reb_confirm_wait_period_ms_ = tb_config::kRebConfirmWaitPeriodMsDef;
max_confirm_wait_period_ms_ = tb_config::kConfirmWaitPeriodMsMax;
shutdown_reb_wait_period_ms_ = tb_config::kRebWaitPeriodWhenShutdownMs;
}
ConsumerConfig::~ConsumerConfig() {
//
}
ConsumerConfig& ConsumerConfig::operator=(const ConsumerConfig& target) {
if (this != &target) {
// parent class
BaseConfig::operator=(target);
// child class
group_name_ = target.group_name_;
sub_topic_and_filter_map_ = target.sub_topic_and_filter_map_;
is_bound_consume_ = target.is_bound_consume_;
session_key_ = target.session_key_;
source_count_ = target.source_count_;
is_select_big_ = target.is_select_big_;
part_offset_map_ = target.part_offset_map_;
consume_position_ = target.consume_position_;
max_subinfo_report_intvl_ = target.max_subinfo_report_intvl_;
msg_notfound_wait_period_ms_ = target.msg_notfound_wait_period_ms_;
is_rollback_if_confirm_timout_ = target.is_rollback_if_confirm_timout_;
reb_confirm_wait_period_ms_ = target.reb_confirm_wait_period_ms_;
max_confirm_wait_period_ms_ = target.max_confirm_wait_period_ms_;
shutdown_reb_wait_period_ms_ = target.shutdown_reb_wait_period_ms_;
}
return *this;
}
bool ConsumerConfig::SetGroupConsumeTarget(string& err_info, const string& group_name,
const set<string>& subscribed_topicset) {
string tgt_group_name;
bool is_success = Utils::ValidGroupName(err_info, group_name, tgt_group_name);
if (!is_success) {
return false;
}
if (subscribed_topicset.empty()) {
err_info = "Illegal parameter: subscribed_topicset is empty!";
return false;
}
string topic_name;
map<string, set<string> > tmp_sub_map;
for (set<string>::iterator it = subscribed_topicset.begin(); it != subscribed_topicset.end();
++it) {
topic_name = Utils::Trim(*it);
is_success =
Utils::ValidString(err_info, topic_name, false, true, true, tb_config::kTopicNameMaxLength);
if (!is_success) {
err_info = "Illegal parameter: subscribed_topicset's item error, " + err_info;
return false;
}
set<string> tmp_filters;
tmp_sub_map[topic_name] = tmp_filters;
}
is_bound_consume_ = false;
group_name_ = tgt_group_name;
sub_topic_and_filter_map_ = tmp_sub_map;
err_info = "Ok";
return true;
}
bool ConsumerConfig::SetGroupConsumeTarget(
string& err_info, const string& group_name,
const map<string, set<string> >& subscribed_topic_and_filter_map) {
string session_key;
int source_count = 0;
bool is_select_big = false;
map<string, int64_t> part_offset_map;
return setGroupConsumeTarget(err_info, false, group_name, subscribed_topic_and_filter_map,
session_key, source_count, is_select_big, part_offset_map);
}
bool ConsumerConfig::SetGroupConsumeTarget(
string& err_info, const string& group_name,
const map<string, set<string> >& subscribed_topic_and_filter_map, const string& session_key,
uint32_t source_count, bool is_select_big, const map<string, int64_t>& part_offset_map) {
return setGroupConsumeTarget(err_info, true, group_name, subscribed_topic_and_filter_map,
session_key, source_count, is_select_big, part_offset_map);
}
bool ConsumerConfig::setGroupConsumeTarget(
string& err_info, bool is_bound_consume, const string& group_name,
const map<string, set<string> >& subscribed_topic_and_filter_map, const string& session_key,
uint32_t source_count, bool is_select_big, const map<string, int64_t>& part_offset_map) {
// check parameter group_name
string tgt_group_name;
bool is_success = Utils::ValidGroupName(err_info, group_name, tgt_group_name);
if (!is_success) {
return false;
}
// check parameter subscribed_topic_and_filter_map
if (subscribed_topic_and_filter_map.empty()) {
err_info = "Illegal parameter: subscribed_topic_and_filter_map is empty!";
return false;
}
map<string, set<string> > tmp_sub_map;
map<string, set<string> >::const_iterator it_map;
for (it_map = subscribed_topic_and_filter_map.begin();
it_map != subscribed_topic_and_filter_map.end(); ++it_map) {
uint32_t count = 0;
string tmp_filteritem;
set<string> tgt_filters;
// check topic_name info
is_success = Utils::ValidString(err_info, it_map->first, false, true, true,
tb_config::kTopicNameMaxLength);
if (!is_success) {
stringstream ss;
ss << "Check parameter subscribed_topic_and_filter_map error: topic ";
ss << it_map->first;
ss << " ";
ss << err_info;
err_info = ss.str();
return false;
}
string topic_name = Utils::Trim(it_map->first);
// check filter info
set<string> subscribed_filters = it_map->second;
for (set<string>::iterator it = subscribed_filters.begin(); it != subscribed_filters.end();
++it) {
is_success = Utils::ValidFilterItem(err_info, *it, tmp_filteritem);
if (!is_success) {
stringstream ss;
ss << "Check parameter subscribed_topic_and_filter_map error: topic ";
ss << topic_name;
ss << "'s filter item ";
ss << err_info;
err_info = ss.str();
return false;
}
tgt_filters.insert(tmp_filteritem);
count++;
}
if (count > tb_config::kFilterItemMaxCount) {
stringstream ss;
ss << "Check parameter subscribed_topic_and_filter_map error: topic ";
ss << it_map->first;
ss << "'s filter item over max item count : ";
ss << tb_config::kFilterItemMaxCount;
err_info = ss.str();
return false;
}
tmp_sub_map[topic_name] = tgt_filters;
}
// check if bound consume
if (!is_bound_consume) {
is_bound_consume_ = false;
group_name_ = tgt_group_name;
sub_topic_and_filter_map_ = tmp_sub_map;
err_info = "Ok";
return true;
}
// check session_key
string tgt_session_key = Utils::Trim(session_key);
if (tgt_session_key.length() == 0
|| tgt_session_key.length() > tb_config::kSessionKeyMaxLength) {
if (tgt_session_key.length() == 0) {
err_info = "Illegal parameter: session_key is empty!";
} else {
stringstream ss;
ss << "Illegal parameter: session_key's length over max length ";
ss << tb_config::kSessionKeyMaxLength;
err_info = ss.str();
}
return false;
}
// check part_offset_map
string part_key;
map<string, int64_t> tmp_parts_map;
map<string, int64_t>::const_iterator it_part;
for (it_part = part_offset_map.begin(); it_part != part_offset_map.end(); ++it_part) {
vector<string> result;
Utils::Split(it_part->first, result, delimiter::kDelimiterColon);
if (result.size() != 3) {
stringstream ss;
ss << "Illegal parameter: part_offset_map's key ";
ss << it_part->first;
ss << " format error, value must be aaaa:bbbb:cccc !";
err_info = ss.str();
return false;
}
if (tmp_sub_map.find(result[1]) == tmp_sub_map.end()) {
stringstream ss;
ss << "Illegal parameter: ";
ss << it_part->first;
ss << " subscribed topic ";
ss << result[1];
ss << " not included in subscribed_topic_and_filter_map's topic list!";
err_info = ss.str();
return false;
}
if (it_part->first.find_first_of(delimiter::kDelimiterComma) != string::npos) {
stringstream ss;
ss << "Illegal parameter: key ";
ss << it_part->first;
ss << " include ";
ss << delimiter::kDelimiterComma;
ss << " char!";
err_info = ss.str();
return false;
}
if (it_part->second < 0) {
stringstream ss;
ss << "Illegal parameter: ";
ss << it_part->first;
ss << "'s offset must over or equal zero, value is ";
ss << it_part->second;
err_info = ss.str();
return false;
}
Utils::Join(result, delimiter::kDelimiterColon, part_key);
tmp_parts_map[part_key] = it_part->second;
}
// set verified data
is_bound_consume_ = true;
group_name_ = tgt_group_name;
sub_topic_and_filter_map_ = tmp_sub_map;
session_key_ = tgt_session_key;
source_count_ = source_count;
is_select_big_ = is_select_big;
part_offset_map_ = tmp_parts_map;
err_info = "Ok";
return true;
}
const string& ConsumerConfig::GetGroupName() const { return group_name_; }
const map<string, set<string> >& ConsumerConfig::GetSubTopicAndFilterMap() const {
return sub_topic_and_filter_map_;
}
void ConsumerConfig::SetConsumePosition(ConsumePosition consume_from_where) {
consume_position_ = consume_from_where;
}
const ConsumePosition ConsumerConfig::GetConsumePosition() const { return consume_position_; }
const int32_t ConsumerConfig::GetMsgNotFoundWaitPeriodMs() const {
return msg_notfound_wait_period_ms_;
}
void ConsumerConfig::SetMsgNotFoundWaitPeriodMs(int32_t msg_notfound_wait_period_ms) {
msg_notfound_wait_period_ms_ = msg_notfound_wait_period_ms;
}
const uint32_t ConsumerConfig::GetPartCheckSliceMs() const {
return part_check_slice_ms_;
}
void ConsumerConfig::SetPartCheckSliceMs(uint32_t part_check_slice_ms) {
if (part_check_slice_ms >= 0
&& part_check_slice_ms <= 1000) {
part_check_slice_ms_ = part_check_slice_ms;
}
}
const int32_t ConsumerConfig::GetMaxPartCheckPeriodMs() const {
return max_part_check_period_ms_;
}
void ConsumerConfig::SetMaxPartCheckPeriodMs(int32_t max_part_check_period_ms) {
max_part_check_period_ms_ = max_part_check_period_ms;
}
const int32_t ConsumerConfig::GetMaxSubinfoReportIntvl() const {
return max_subinfo_report_intvl_;
}
void ConsumerConfig::SetMaxSubinfoReportIntvl(int32_t max_subinfo_report_intvl) {
max_subinfo_report_intvl_ = max_subinfo_report_intvl;
}
bool ConsumerConfig::IsRollbackIfConfirmTimeout() {
return is_rollback_if_confirm_timout_; }
void ConsumerConfig::setRollbackIfConfirmTimeout(
bool is_rollback_if_confirm_timeout) {
is_rollback_if_confirm_timout_ = is_rollback_if_confirm_timeout;
}
const int ConsumerConfig::GetWaitPeriodIfConfirmWaitRebalanceMs() const {
return reb_confirm_wait_period_ms_;
}
void ConsumerConfig::SetWaitPeriodIfConfirmWaitRebalanceMs(
int32_t reb_confirm_wait_period_ms) {
reb_confirm_wait_period_ms_ = reb_confirm_wait_period_ms;
}
const int32_t ConsumerConfig::GetMaxConfirmWaitPeriodMs() const {
return max_confirm_wait_period_ms_; }
void ConsumerConfig::SetMaxConfirmWaitPeriodMs(
int32_t max_confirm_wait_period_ms) {
max_confirm_wait_period_ms_ = max_confirm_wait_period_ms;
}
const int32_t ConsumerConfig::GetShutdownRebWaitPeriodMs() const {
return shutdown_reb_wait_period_ms_;
}
void ConsumerConfig::SetShutdownRebWaitPeriodMs(
int32_t wait_period_when_shutdown_ms) {
shutdown_reb_wait_period_ms_ = wait_period_when_shutdown_ms;
}
string ConsumerConfig::ToString() {
int32_t i = 0;
stringstream ss;
map<string, int64_t>::iterator it;
map<string, set<string> >::iterator it_map;
// print info
ss << "ConsumerConfig = {";
ss << BaseConfig::ToString();
ss << ", group_name_='";
ss << group_name_;
ss << "', sub_topic_and_filter_map_={";
for (it_map = sub_topic_and_filter_map_.begin();
it_map != sub_topic_and_filter_map_.end(); ++it_map) {
if (i++ > 0) {
ss << ",";
}
ss << "'";
ss << it_map->first;
ss << "'=[";
int32_t j = 0;
set<string> topic_set = it_map->second;
for (set<string>::iterator it = topic_set.begin(); it != topic_set.end(); ++it) {
if (j++ > 0) {
ss << ",";
}
ss << "'";
ss << *it;
ss << "'";
}
ss << "]";
}
ss << "}, is_bound_consume_=";
ss << is_bound_consume_;
ss << ", session_key_='";
ss << session_key_;
ss << "', source_count_=";
ss << source_count_;
ss << ", is_select_big_=";
ss << is_select_big_;
ss << ", part_offset_map_={";
i = 0;
for (it = part_offset_map_.begin(); it != part_offset_map_.end(); ++it) {
if (i++ > 0) {
ss << ",";
}
ss << "'";
ss << it->first;
ss << "'=";
ss << it->second;
}
ss << "}, consume_position_=";
ss << consume_position_;
ss << ", max_subinfo_report_intvl_=";
ss << max_subinfo_report_intvl_;
ss << ", msg_notfound_wait_period_ms_=";
ss << msg_notfound_wait_period_ms_;
ss << ", max_part_check_period_ms_=";
ss << max_part_check_period_ms_;
ss << ", part_check_slice_ms_=";
ss << part_check_slice_ms_;
ss << ", is_rollback_if_confirm_timout_=";
ss << is_rollback_if_confirm_timout_;
ss << ", reb_confirm_wait_period_ms_=";
ss << reb_confirm_wait_period_ms_;
ss << ", max_confirm_wait_period_ms_=";
ss << max_confirm_wait_period_ms_;
ss << ", shutdown_reb_wait_period_ms_=";
ss << shutdown_reb_wait_period_ms_;
ss << "}";
return ss.str();
}
} // namespace tubemq
| 34.933116 | 101 | 0.695293 | [
"vector"
] |
fac17a42a0ac3741d1eb396d59f57003ae79ce12 | 3,185 | cpp | C++ | datastructures/singlylinkedlists/flatten_list.cpp | oishikm12/cpp-collection | 4a454a6ed5b24570c7df0d4f0b692ae98c1ffa97 | [
"MIT"
] | 5 | 2021-05-17T12:32:42.000Z | 2021-12-12T21:09:55.000Z | datastructures/singlylinkedlists/flatten_list.cpp | oishikm12/cpp-collection | 4a454a6ed5b24570c7df0d4f0b692ae98c1ffa97 | [
"MIT"
] | null | null | null | datastructures/singlylinkedlists/flatten_list.cpp | oishikm12/cpp-collection | 4a454a6ed5b24570c7df0d4f0b692ae98c1ffa97 | [
"MIT"
] | 1 | 2021-05-13T20:29:57.000Z | 2021-05-13T20:29:57.000Z | #include <iostream>
#include <vector>
using namespace std;
class Node {
public:
int data;
Node *next, *bottom;
Node(int val = 0, Node *link = NULL, Node *btm = NULL) : data(val), next(link), bottom(btm) {};
~Node() { delete next, delete bottom; }
};
Node* build(Node *, vector<int> &);
void print(Node *);
Node* merge(Node *, Node *);
Node* flattenList(Node *);
int main() {
/**
* In order to flatten a list which consists of left
* & bottom pointers, we can recursively merge left sub lists
* such that all nodes belong to bottom of one
*/
cout << "\nThis problem flattens a 2D linked list\n" << endl;
cout << "Enter size of the List: ";
int n;
cin >> n;
cout << "Enter space seperated sizes of each sublist" << endl;
vector<int> elems(n);
for (int i = 0; i < n; i += 1) cin >> elems[i];
cout << "\nEnter space seperated elements of the list" << endl;
Node *head = NULL;
head = build(head, elems);
cout << "\nThe list before flattening is: " << endl;
print(head);
cout << "\nThe list after flattening is: " << endl;
head = flattenList(head);
print(head);
cout << endl;
delete head;
return 0;
}
Node* build(Node *head, vector<int> &lims) {
head = new Node();
// We need two pointers we have to simultaneously
// traverse bottom and once its done, to right
Node *top = head;
Node *temp = head;
for(int i = 0; i < lims.size(); i += 1) {
while (lims[i]--) {
cin >> head->data;
if (lims[i] != 0) head->bottom = new Node();
head = head->bottom;
}
// Next head in the 2D list
head = top;
if (i != lims.size() - 1) head->next = new Node();
head = head->next;
top = head;
}
return temp;
}
void print(Node *head) {
while (head != NULL) {
Node *temp = head;
// First we print every node in the bottom pointer
while (head != NULL) {
cout << head->data;
if (head->bottom != NULL) cout << " > ";
head = head->bottom;
}
// Then we shift to the right sublist
head = temp->next;
cout << endl;
}
}
Node* merge(Node *a, Node *b) {
// This will be the connecting node to merge
Node *head = new Node(0);
Node *temp = head;
while (a != NULL && b != NULL) {
if (a->data < b->data) {
head->bottom = a;
a = a->bottom;
} else {
head->bottom = b;
b = b->bottom;
}
head = head->bottom;
// We are resetting the next pointer while merge
// to flatten the list
head->next = NULL;
}
head->bottom = a ? a : b;
while(head->bottom) {
// Even after joining we need to reset the next
// pointers if any
head->next = NULL;
head = head->bottom;
}
return temp->bottom;
}
Node* flattenList(Node *head) {
// We recursively merge every head with its next head node
if (!head || !head->next) return head;
return merge(head, flattenList(head->next));
}
| 25.07874 | 103 | 0.529042 | [
"vector"
] |
fac2d6709b29271880b57f90f421b74b881ff24b | 7,311 | cc | C++ | tools/src/create_java_file.cc | haveTryTwo/csutil | 7cb071f6927db4c52832d3074fb69f273968d66e | [
"BSD-2-Clause"
] | 9 | 2015-08-14T08:59:06.000Z | 2018-08-20T13:46:46.000Z | tools/src/create_java_file.cc | haveTryTwo/csutil | 7cb071f6927db4c52832d3074fb69f273968d66e | [
"BSD-2-Clause"
] | null | null | null | tools/src/create_java_file.cc | haveTryTwo/csutil | 7cb071f6927db4c52832d3074fb69f273968d66e | [
"BSD-2-Clause"
] | 1 | 2018-08-20T13:46:29.000Z | 2018-08-20T13:46:29.000Z | // Copyright (c) 2015 The CSUTIL 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 <deque>
#include <vector>
#include <stdio.h>
#include <assert.h>
#include "base/util.h"
#include "base/common.h"
#include "base/file_util.h"
#include "create_java_file.h"
namespace tools
{
const std::string kGradle("gradle");
const std::string kBuildGradle("build.gradle");
const std::string kSettingsGradle("settings.gradle");
const std::string kDistribution("distribution");
const std::string kJacocoGradle("jacoco.gradle");
const std::string kJavaSrcFile("App.java");
const std::string kJavaTestFile("AppTest.java");
base::Code CreateJavaFile(const std::string &project_name, const std::string &package, const std::string &modules)
{/*{{{*/
if (project_name.empty()) return base::kInvalidParam;
std::string pkg;
if (package.empty())
{
pkg = "org.havetrytwo.demo";
}
else
{
pkg = package;
}
base::Code ret = base::kOk;
std::deque<std::string> pkg_2_dirs;
ret = base::Strtok(pkg, '.', &pkg_2_dirs);
if (ret != base::kOk) return ret;
std::deque<std::string> exclude_names;
exclude_names.push_back(kGradle);
exclude_names.push_back(kDistribution);
std::deque<std::string> modules_name;
if (modules.size() == 0)
{
modules_name.push_back("client");
modules_name.push_back("server");
}
else
{
ret = base::Strtok(modules, ',', &modules_name);
if (ret != base::kOk) return ret;
}
std::deque<std::string>::iterator it = modules_name.begin();
for (; it != modules_name.end(); ++it)
{
std::deque<std::string>::iterator exclude_it = exclude_names.begin();
for (; exclude_it != exclude_names.end(); ++exclude_it)
{
if (*exclude_it == *it)
{
fprintf(stderr, "Invalid module name:%s\n", it->c_str());
return base::kInvalidParam;
}
}
}
// 创建根项目
ret = base::CreateDir(project_name);
if (ret != base::kOk) return ret;
// 创建根项目的 build.gradle
char buf[base::kBufLen] = {0};
int r = snprintf(buf, sizeof(buf)/sizeof(buf[0]), kBuildGradleStr.c_str(), pkg.c_str());
if (r < 0) return base::kInvalidParam;
ret = base::CompareAndWriteWholeFile(project_name+"/" + kBuildGradle, buf);
if (ret != base::kOk) return ret;
// 创建根项目的 settings.gradle
memset(buf, 0, sizeof(buf)/sizeof(buf[0]));
int sum = 0;
r = snprintf(buf, sizeof(buf)/sizeof(buf[0]), "include ");
if (r < 0 || r >= sizeof(buf)/sizeof(buf[0])) return base::kInvalidParam;
sum += r;
for (it = modules_name.begin(); it != modules_name.end(); ++it)
{
r = snprintf(buf+sum, sizeof(buf)/sizeof(buf[0])-sum, "'%s', ", it->c_str());
if (r < 0 || r >= sizeof(buf)/sizeof(buf[0])) return base::kInvalidParam;
sum += r;
}
r = snprintf(buf+sum, sizeof(buf)/sizeof(buf[0])-sum, "'%s'\n", kDistribution.c_str());
if (r < 0 || r >= sizeof(buf)/sizeof(buf[0])) return base::kInvalidParam;
ret = base::CompareAndWriteWholeFile(project_name+"/" + kSettingsGradle, buf);
if (ret != base::kOk) return ret;
// 创建jacoco.gradle,用于获取测试覆盖率
ret = base::CreateDir(project_name+"/"+kGradle);
if (ret != base::kOk) return ret;
ret = base::CompareAndWriteWholeFile(project_name+"/"+kGradle+"/"+kJacocoGradle, kJacocoStr);
if (ret != base::kOk) return ret;
// 生成 gradlew,并调整依赖gradle版本为4.5-all
r = system("which gradle");
if (r != 0)
{
fprintf(stderr, "No gradle, please check where it install, ret code:%d\n", r);
return base::kInvalidParam;
}
r = snprintf(buf, sizeof(buf)/sizeof(buf[0]), kGradleWrapper.c_str(), project_name.c_str());
if (r < 0 || r >= sizeof(buf)/sizeof(buf[0])) return base::kInvalidParam;
r = system(buf);
if (r != 0)
{
fprintf(stderr, "gradle wrapper failed, ret code:%d\n", r);
return base::kInvalidParam;
}
// 创建distribution, 设置发布
char buf1[base::kBufLen] = {0};
sum = 0;
for (it = modules_name.begin(); it != modules_name.end(); ++it)
{
r = snprintf(buf1+sum, sizeof(buf1)/sizeof(buf1[0])-sum, kDependsOnStr.c_str(), it->c_str());
if (r < 0 || r >= sizeof(buf1)/sizeof(buf1[0])) return base::kInvalidParam;
sum += r;
}
char buf2[base::kBufLen] = {0};
sum = 0;
for (it = modules_name.begin(); it != modules_name.end(); ++it)
{
r = snprintf(buf2+sum, sizeof(buf2)/sizeof(buf2[0])-sum, kFromStr.c_str(), it->c_str());
if (r < 0 || r >= sizeof(buf2)/sizeof(buf2[0])) return base::kInvalidParam;
sum += r;
}
r = snprintf(buf, sizeof(buf)/sizeof(buf[0]), kDistributionGradleStr.c_str(), buf1, buf2);
if (r < 0 || r >= sizeof(buf)/sizeof(buf[0])) return base::kInvalidParam;
ret = base::CreateDir(project_name+"/"+kDistribution);
if (ret != base::kOk) return ret;
ret = base::CompareAndWriteWholeFile(project_name+"/"+kDistribution+"/"+kBuildGradle, buf);
if (ret != base::kOk) return ret;
// 循环创建项目,包括目录,build.gradle, 源文件(App.java),测试文件(AppTest.java)
for (it = modules_name.begin(); it != modules_name.end(); ++it)
{/*{{{*/
std::deque<std::string> src_dir;
std::deque<std::string> test_dir;
src_dir.push_back(*it);
src_dir.push_back("src");
src_dir.push_back("main");
src_dir.push_back("java");
test_dir.push_back(*it);
test_dir.push_back("src");
test_dir.push_back("test");
test_dir.push_back("java");
std::deque<std::string>::iterator tmp_it;
for (tmp_it = pkg_2_dirs.begin(); tmp_it != pkg_2_dirs.end(); ++tmp_it)
{
src_dir.push_back(*tmp_it);
test_dir.push_back(*tmp_it);
}
std::string tmp_src_dir(project_name);
for (tmp_it = src_dir.begin(); tmp_it != src_dir.end(); ++tmp_it)
{
tmp_src_dir.append("/").append(*tmp_it);
ret = base::CreateDir(tmp_src_dir);
if (ret != base::kOk) return ret;
}
std::string tmp_test_dir(project_name);
for (tmp_it = test_dir.begin(); tmp_it != test_dir.end(); ++tmp_it)
{
tmp_test_dir.append("/").append(*tmp_it);
ret = base::CreateDir(tmp_test_dir);
if (ret != base::kOk) return ret;
}
ret = base::CompareAndWriteWholeFile(project_name+"/"+(*it)+"/"+kBuildGradle, kSubProjectBuildGradleStr);
if (ret != base::kOk) return ret;
r = snprintf(buf, sizeof(buf)/sizeof(buf[0]), kJavaSrcStr.c_str(), pkg.c_str());
if (r < 0 || r >= sizeof(buf)/sizeof(buf[0])) return base::kInvalidParam;
ret = base::CompareAndWriteWholeFile(tmp_src_dir+"/"+kJavaSrcFile, buf);
if (ret != base::kOk) return ret;
r = snprintf(buf, sizeof(buf)/sizeof(buf[0]), kJavaTestStr.c_str(), pkg.c_str());
if (r < 0 || r >= sizeof(buf)/sizeof(buf[0])) return base::kInvalidParam;
ret = base::CompareAndWriteWholeFile(tmp_test_dir+"/"+kJavaTestFile, buf);
if (ret != base::kOk) return ret;
}/*}}}*/
return ret;
}/*}}}*/
}
| 34.814286 | 114 | 0.596498 | [
"vector"
] |
fac5516a029335d0abba5c954ed6d7ae9f56ab9d | 2,937 | cpp | C++ | boboleetcode/Play-Leetcode-master/0684-Redundant-Connection/cpp-0684/main3.cpp | yaominzh/CodeLrn2019 | adc727d92904c5c5d445a2621813dfa99474206d | [
"Apache-2.0"
] | 2 | 2021-03-25T05:26:55.000Z | 2021-04-20T03:33:24.000Z | boboleetcode/Play-Leetcode-master/0684-Redundant-Connection/cpp-0684/main3.cpp | mcuallen/CodeLrn2019 | adc727d92904c5c5d445a2621813dfa99474206d | [
"Apache-2.0"
] | 6 | 2019-12-04T06:08:32.000Z | 2021-05-10T20:22:47.000Z | boboleetcode/Play-Leetcode-master/0684-Redundant-Connection/cpp-0684/main3.cpp | mcuallen/CodeLrn2019 | adc727d92904c5c5d445a2621813dfa99474206d | [
"Apache-2.0"
] | null | null | null | /// Source : https://leetcode.com/problems/redundant-connection/description/
/// Author : liuyubobobo
/// Time : 2017-12-01
#include <iostream>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <cassert>
using namespace std;
/// Using Union-Find, add edges into the UF
/// The first edge make a circle is the result
/// Time Complexity: O(e)
/// Space Complexity: O(e)
class UnionFind{
private:
int* rank;
int* parent; // parent[i]表示第i个元素所指向的父节点
int count; // 数据个数
public:
// 构造函数
UnionFind(int count){
parent = new int[count];
rank = new int[count];
this->count = count;
for( int i = 0 ; i < count ; i ++ ){
parent[i] = i;
rank[i] = 1;
}
}
// 析构函数
~UnionFind(){
delete[] parent;
delete[] rank;
}
// 查找过程, 查找元素p所对应的集合编号
// O(h)复杂度, h为树的高度
int find(int p){
assert( p >= 0 && p < count );
// path compression 1
while( p != parent[p] ){
parent[p] = parent[parent[p]];
p = parent[p];
}
return p;
}
// 查看元素p和元素q是否所属一个集合
// O(h)复杂度, h为树的高度
bool isConnected( int p , int q ){
return find(p) == find(q);
}
// 合并元素p和元素q所属的集合
// O(h)复杂度, h为树的高度
void unionElements(int p, int q){
int pRoot = find(p);
int qRoot = find(q);
if( pRoot == qRoot )
return;
// 根据两个元素所在树的元素个数不同判断合并方向
// 将元素个数少的集合合并到元素个数多的集合上
if( rank[pRoot] < rank[qRoot] ){
parent[pRoot] = qRoot;
}
else if( rank[qRoot] < rank[pRoot]){
parent[qRoot] = pRoot;
}
else{ // rank[pRoot] == rank[qRoot]
parent[pRoot] = qRoot;
rank[qRoot] += 1; // 此时, 我维护rank的值
}
}
};
class Solution {
public:
vector<int> findRedundantConnection(vector<vector<int>>& edges) {
unordered_map<int, int> vIndex;
int index = 0;
for(const vector<int>& edge: edges){
if(vIndex.find(edge[0]) == vIndex.end())
vIndex[edge[0]] = index ++;
if(vIndex.find(edge[1]) == vIndex.end())
vIndex[edge[1]] = index ++;
}
UnionFind uf(vIndex.size());
for(const vector<int>& edge: edges) {
int v = vIndex[edge[0]];
int w = vIndex[edge[1]];
if (uf.isConnected(v, w))
return edge;
else uf.unionElements(v, w);
}
assert(false);
}
};
void printVec(const vector<int>& v){
for(int e: v)
cout << e << " ";
cout << endl;
}
int main() {
vector<vector<int>> vec1 = {{1, 2}, {1, 3}, {2, 3}};
printVec(Solution().findRedundantConnection(vec1));
vector<vector<int>> vec2 = {{1, 2}, {2, 3}, {3, 4}, {1, 4}, {1, 5}};
printVec(Solution().findRedundantConnection(vec2));
return 0;
} | 22.945313 | 76 | 0.511406 | [
"vector"
] |
faca08a840d33ba01f1de56cb5dcce52e4a4c70f | 25,840 | cpp | C++ | private/shell/ext/docpropex/avprop/srv.cpp | King0987654/windows2000 | 01f9c2e62c4289194e33244aade34b7d19e7c9b8 | [
"MIT"
] | 11 | 2017-09-02T11:27:08.000Z | 2022-01-02T15:25:24.000Z | private/shell/ext/docpropex/avprop/srv.cpp | King0987654/windows2000 | 01f9c2e62c4289194e33244aade34b7d19e7c9b8 | [
"MIT"
] | null | null | null | private/shell/ext/docpropex/avprop/srv.cpp | King0987654/windows2000 | 01f9c2e62c4289194e33244aade34b7d19e7c9b8 | [
"MIT"
] | 14 | 2019-01-16T01:01:23.000Z | 2022-02-20T15:54:27.000Z | //-------------------------------------------------------------------------//
// srv.cpp : Implementation of CAVFilePropServer
//-------------------------------------------------------------------------//
#include "pch.h"
#include "srv.h"
#include "propvar.h"
#include "ptsniff.h"
//-------------------------------------------------------------------------//
LPCTSTR szWAVFILE_EXT = TEXT(".wav"),
szAVIFILE_EXT = TEXT(".avi"),
szMIDIFILE_EXT = TEXT(".mid") ;
//-------------------------------------------------------------------------//
// raw property definition block
//
typedef struct tagFOLDER_DEF
{
LPTSTR pszName;
UINT nIdsDisplay;
UINT nIdsQtip;
ULONG dwAccess;
ULONG iOrder;
LONG lParam;
const PFID* ppfid ;
ULONG dwFlags;
} FOLDER_DEF, *PFOLDER_DEF;
//-------------------------------------------------------------------------//
// Avprop folder definitions.
// The ordering of members MUST be kept in synch with that of
// AV_MEDIA_TYPE enum members.
static const FOLDER_DEF folders[] =
{
{ NULL, 0,0,0,0,0,&PFID_NULL,0 },
{ TEXT("waveaudio"), IDS_WAVEAUDIO_FOLDER, IDS_WAVEAUDIO_FOLDER_TIP,
PTIA_READONLY, 0, 0, &PFID_AudioProperties, 0 },
{ TEXT("wideo"), IDS_VIDEO_FOLDER, IDS_VIDEO_FOLDER_TIP,
PTIA_READONLY, 0, 0, &PFID_VideoProperties, 0 },
{ TEXT("midi"), IDS_MIDI_FOLDER, IDS_MIDI_FOLDER_TIP,
PTIA_READONLY, 0, 0, &PFID_MidiProperties, 0 },
} ;
//-------------------------------------------------------------------------//
// raw property definition block
//
typedef struct tagPROPERTY_DEF
{
LPCTSTR pszName ;
UINT nIdsDisplay ;
UINT nIdsTip ;
const FMTID* pfmtid ;
PROPID pid ;
BOOL bShellColumn ;
} PROPERTY_DEF, *PPROPERTY_DEF ;
//-------------------------------------------------------------------------//
// Avprop property definitions.
static const PROPERTY_DEF audiopropdefs[] =
{
{ TEXT("Format"), IDS_PIDASI_FORMAT, IDS_PIDASI_FORMAT_TIP,
&FMTID_AudioSummaryInformation, PIDASI_FORMAT, TRUE },
{ TEXT("TimeLength"), IDS_PIDASI_TIMELENGTH, IDS_PIDASI_TIMELENGTH_TIP,
&FMTID_AudioSummaryInformation, PIDASI_TIMELENGTH, FALSE },
{ TEXT("AvgDataRate"), IDS_PIDASI_AVG_DATA_RATE, IDS_PIDASI_AVG_DATA_RATE_TIP,
&FMTID_AudioSummaryInformation, PIDASI_AVG_DATA_RATE, FALSE },
{ TEXT("SampleRate"), IDS_PIDASI_SAMPLE_RATE, IDS_PIDASI_SAMPLE_RATE_TIP,
&FMTID_AudioSummaryInformation, PIDASI_SAMPLE_RATE, TRUE },
{ TEXT("SampleSize"), IDS_PIDASI_SAMPLE_SIZE, IDS_PIDASI_SAMPLE_SIZE_TIP,
&FMTID_AudioSummaryInformation, PIDASI_SAMPLE_SIZE, TRUE },
{ TEXT("ChannelCount"), IDS_PIDASI_CHANNEL_COUNT, IDS_PIDASI_CHANNEL_COUNT_TIP,
&FMTID_AudioSummaryInformation, PIDASI_CHANNEL_COUNT, TRUE },
} ;
static const PROPERTY_DEF videopropdefs[] =
{
{ TEXT("StreamName"), IDS_PIDVSI_STREAM_NAME, IDS_PIDVSI_STREAM_NAME_TIP,
&FMTID_VideoSummaryInformation, PIDVSI_STREAM_NAME },
{ TEXT("FrameWidth"), IDS_PIDVSI_FRAME_WIDTH, IDS_PIDVSI_FRAME_WIDTH_TIP,
&FMTID_VideoSummaryInformation, PIDVSI_FRAME_WIDTH, FALSE },
{ TEXT("FrameHeight"), IDS_PIDVSI_FRAME_HEIGHT, IDS_PIDVSI_FRAME_HEIGHT_TIP,
&FMTID_VideoSummaryInformation, PIDVSI_FRAME_HEIGHT, FALSE },
{ TEXT("TimeLength"), IDS_PIDVSI_TIMELENGTH, IDS_PIDVSI_TIMELENGTH_TIP,
&FMTID_VideoSummaryInformation, PIDVSI_TIMELENGTH, TRUE },
{ TEXT("FrameCount"), IDS_PIDVSI_FRAME_COUNT, IDS_PIDVSI_FRAME_COUNT_TIP,
&FMTID_VideoSummaryInformation, PIDVSI_FRAME_COUNT, TRUE },
{ TEXT("FrameRate"), IDS_PIDVSI_FRAME_RATE, IDS_PIDVSI_FRAME_RATE_TIP,
&FMTID_VideoSummaryInformation, PIDVSI_FRAME_RATE, TRUE },
{ TEXT("DataRate"), IDS_PIDVSI_DATA_RATE, IDS_PIDVSI_DATA_RATE_TIP,
&FMTID_VideoSummaryInformation, PIDVSI_DATA_RATE, FALSE },
{ TEXT("SampleSize"), IDS_PIDVSI_SAMPLE_SIZE, IDS_PIDVSI_SAMPLE_SIZE_TIP,
&FMTID_VideoSummaryInformation, PIDVSI_SAMPLE_SIZE, TRUE },
{ TEXT("Compression"), IDS_PIDVSI_COMPRESSION, IDS_PIDVSI_COMPRESSION_TIP,
&FMTID_VideoSummaryInformation, PIDVSI_COMPRESSION, TRUE },
} ;
//-------------------------------------------------------------------------//
// fn forwards...
static HRESULT PTPropertyItemFromPropDef( const PROPERTY_DEF* ppd, IN OUT PPROPERTYITEM pItem ) ;
static void CopyPTPropertyItem( OUT PPROPERTYITEM pDest, IN const PPROPERTYITEM pSrc ) ;
static void ClearPTPropertyItem( struct tagPROPERTYITEM* pItem ) ;
//-------------------------------------------------------------------------//
STDMETHODIMP CAVFilePropServer::RegisterFileAssocs()
{
HRESULT hr[3], hrRet ;
hr[0] = RegisterPropServerClassForExtension( szWAVFILE_EXT, CLSID_AVFilePropServer ) ;
hr[1] = RegisterPropServerClassForExtension( szAVIFILE_EXT, CLSID_AVFilePropServer ) ;
hr[2] = RegisterPropServerClassForExtension( szMIDIFILE_EXT, CLSID_AVFilePropServer ) ;
for( int i = 0; i < ARRAYSIZE(hr); i++ )
{
if( FAILED( hr[i] ) )
return hr[i] ;
}
return S_OK ;
}
//-------------------------------------------------------------------------//
// class CAVFilePropServer : IAdvancedPropertyServer.
//-------------------------------------------------------------------------//
//-------------------------------------------------------------------------//
STDMETHODIMP CAVFilePropServer::QueryServerInfo(
IN OUT PROPSERVERINFO *pInfo )
{
return E_NOTIMPL ;
}
//-------------------------------------------------------------------------//
STDMETHODIMP CAVFilePropServer::AcquireAdvanced(
IN const VARIANT *pvarSrc,
OUT LPARAM *plParamSrc )
{
HRESULT hr ;
CAVPropSrc* pSrc ;
// Instantiate a data object to attach to the property source (AV file)
if( FAILED( (hr = CAVPropSrc::CreateInstance( pvarSrc, &pSrc )) ) )
return hr ;
// Accumulate property values in the object.
if( FAILED( (hr = pSrc->Acquire()) ) )
{
delete pSrc ;
return hr ;
}
*plParamSrc = (LPARAM)pSrc ;
return S_OK ;
}
//-------------------------------------------------------------------------//
STDMETHODIMP CAVFilePropServer::EnumFolderItems(
IN LPARAM lParamSrc,
OUT IEnumPROPFOLDERITEM **ppEnum )
{
// Pass the source's data object to the new enumerator
CAVPropSrc* pSrc = (CAVPropSrc*)lParamSrc ;
if( ((*ppEnum) = new CEnumAVFolderItem( pSrc ))==NULL )
return E_OUTOFMEMORY ;
(*ppEnum)->AddRef() ;
return S_OK ;
}
//-------------------------------------------------------------------------//
STDMETHODIMP CAVFilePropServer::EnumPropertyItems(
IN const PROPFOLDERITEM *pFolderItem,
OUT IEnumPROPERTYITEM **ppEnum )
{
// The source's data object comes through PROPFOLDERITEM:lParam.
if( ((*ppEnum) = new CEnumAVPropertyItem( *pFolderItem ))==NULL )
return E_OUTOFMEMORY ;
(*ppEnum)->AddRef() ;
return S_OK ;
}
//-------------------------------------------------------------------------//
STDMETHODIMP CAVFilePropServer::EnumValidValues(
IN const PROPERTYITEM *pItem,
OUT IEnumPROPVARIANT_DISPLAY **ppEnum )
{
return E_NOTIMPL ; // all of our properties are read-only.
}
//-------------------------------------------------------------------------//
STDMETHODIMP CAVFilePropServer::PersistAdvanced(
IN OUT PROPERTYITEM *pItem )
{
return E_NOTIMPL ; // all of our properties are read-only.
}
//-------------------------------------------------------------------------//
STDMETHODIMP CAVFilePropServer::ReleaseAdvanced(
IN LPARAM lParamSrc,
IN ULONG dwFlags )
{
CAVPropSrc* pSrc = (CAVPropSrc*)lParamSrc ;
if ( dwFlags & PTREL_DONE_ENUMERATING )
{
// Throw away any data associated with folder/property
// that enumeration that consumes memory or working set.
}
if( dwFlags & PTREL_CLOSE_SOURCE )
{
// Close the file until further notice.
}
if( dwFlags == PTREL_SOURCE_REMOVED )
{
// Destroy our source data object
delete pSrc ;
}
return S_OK ;
}
//-------------------------------------------------------------------------//
// Enumerator implementation
//-------------------------------------------------------------------------//
// common enumerator IUnknown implementation:
#define IMPLEMENT_ENUM_UNKNOWN( classname, iid ) \
ULONG classname::m_cObj = 0 ; \
STDMETHODIMP classname::QueryInterface( REFIID _iid, void** ppvObj ) { \
if( ppvObj == NULL ) return E_POINTER ; *ppvObj = NULL ; \
if( IsEqualGUID( _iid, IID_IUnknown ) ) *ppvObj = this ; \
else if( IsEqualGUID( _iid, iid ) ) *ppvObj = this ; \
if( *ppvObj ) { AddRef() ; return S_OK ; } \
return E_NOINTERFACE ; } \
STDMETHODIMP_( ULONG ) classname::AddRef() { \
if( InterlockedIncrement( (LONG*)&m_cRef )==1 ) \
_Module.Lock() ; \
return m_cRef ; } \
STDMETHODIMP_( ULONG ) classname::Release() { \
if( InterlockedDecrement( (LONG*)&m_cRef )==0 ) \
{ _Module.Unlock() ; delete this ; return 0 ; } \
return m_cRef ; } \
//-------------------------------------------------------------------------//
// CEnumAVFolderItem
IMPLEMENT_ENUM_UNKNOWN( CEnumAVFolderItem, IID_IEnumPROPFOLDERITEM ) ;
//-------------------------------------------------------------------------//
//-------------------------------------------------------------------------//
STDMETHODIMP CEnumAVFolderItem::Next( ULONG cItems, PROPFOLDERITEM * rgFolderItem, ULONG * pcItemsFetched )
{
if( !( pcItemsFetched && rgFolderItem ) )
return E_POINTER ;
*pcItemsFetched = 0 ;
if( cItems <=0 )
return E_INVALIDARG ;
for( ; m_iPos < ARRAYSIZE(folders) && *pcItemsFetched < cItems; InterlockedIncrement( &m_iPos ) )
{
if( m_pSrc->IsSupportedFolderID( *folders[m_iPos].ppfid ) )
{
USES_CONVERSION ;
rgFolderItem[*pcItemsFetched].cbStruct = sizeof(*rgFolderItem) ;
rgFolderItem[*pcItemsFetched].mask = PTFI_ALL ;
rgFolderItem[*pcItemsFetched].bstrName = SysAllocString( T2W( folders[m_iPos].pszName ) ) ;
rgFolderItem[*pcItemsFetched].bstrDisplayName = BstrFromResource( folders[m_iPos].nIdsDisplay ) ;
rgFolderItem[*pcItemsFetched].bstrQtip = BstrFromResource( folders[m_iPos].nIdsQtip ) ;
rgFolderItem[*pcItemsFetched].dwAccess = folders[m_iPos].dwAccess ;
rgFolderItem[*pcItemsFetched].iOrder = folders[m_iPos].iOrder ;
rgFolderItem[*pcItemsFetched].lParam = (LPARAM)m_pSrc ;
rgFolderItem[*pcItemsFetched].pfid = *folders[m_iPos].ppfid ;
rgFolderItem[*pcItemsFetched].dwFlags = folders[m_iPos].dwFlags ;
InterlockedIncrement( (LONG*)pcItemsFetched ) ;
}
}
return cItems == *pcItemsFetched ? S_OK : S_FALSE ;
}
//-------------------------------------------------------------------------//
// CEnumAVPropertyItem
IMPLEMENT_ENUM_UNKNOWN( CEnumAVPropertyItem, IID_IEnumPROPERTYITEM ) ;
//-------------------------------------------------------------------------//
//-------------------------------------------------------------------------//
STDMETHODIMP CEnumAVPropertyItem::Next(
ULONG cItems,
PROPERTYITEM * rgPropertyItem,
ULONG * pcItemsFetched )
{
HRESULT hr ;
if( !( pcItemsFetched && rgPropertyItem ) )
return E_POINTER ;
*pcItemsFetched = 0 ;
while( *pcItemsFetched < cItems )
{
hr = m_pSrc->GetPropertyItem( m_pfid, m_iPos, &rgPropertyItem[*pcItemsFetched] ) ;
InterlockedIncrement( &m_iPos ) ;
if( S_OK == hr )
(*pcItemsFetched)++ ;
else
break ;
}
return cItems == *pcItemsFetched ? S_OK : S_FALSE ;
}
//-------------------------------------------------------------------------//
// CAVPropSrc - base class for property source data object.
//-------------------------------------------------------------------------//
//-------------------------------------------------------------------------//
STDMETHODIMP CAVPropSrc::CreateInstance(
const VARIANT* pvarSrc,
OUT CAVPropSrc** ppSrc )
{
TCHAR szFile[MAX_PATH] ;
USES_CONVERSION ;
ASSERT( ppSrc ) ;
*ppSrc = NULL ;
if( VT_BSTR != pvarSrc->vt )
return E_NOTIMPL ;
lstrcpyn( szFile, W2T(pvarSrc->bstrVal), ARRAYSIZE(szFile) ) ;
LPCTSTR pszExt = PathFindExtension( szFile ) ;
HRESULT hr ;
if( FAILED( (hr = CreateInstance( pszExt, ppSrc )) ) )
return hr ;
(*ppSrc)->Attach( szFile ) ;
return S_OK ;
}
//-------------------------------------------------------------------------//
STDMETHODIMP CAVPropSrc::CreateInstance( LPCTSTR pszExt, OUT CAVPropSrc** ppSrc )
{
// Instantiate the correct class of data object based on
// the file extension.
if( pszExt )
{
if( 0 == lstrcmpi( pszExt, szWAVFILE_EXT ) )
*ppSrc = new CWaveSrc ;
else if( 0 == lstrcmpi( pszExt, szAVIFILE_EXT ) )
*ppSrc = new CAviSrc ;
else if( 0 == lstrcmpi( pszExt, szMIDIFILE_EXT ) )
*ppSrc = new CMidiSrc ;
else
return E_FAIL ;
}
return ( *ppSrc ) ? S_OK : E_OUTOFMEMORY ;
}
//-------------------------------------------------------------------------//
void CAVPropSrc::Attach( LPCTSTR pszFile )
{
lstrcpyn( _szFile, pszFile, ARRAYSIZE(_szFile) ) ;
}
//-------------------------------------------------------------------------//
// helper: pre-allocates a member array of PROPERTYITEMs
PPROPERTYITEM CAVPropSrc::AllocItems( int nCount )
{
PPROPERTYITEM rgPropItems ;
if( NULL != (rgPropItems = new PROPERTYITEM[nCount]) )
{
FreeItems() ;
ZeroMemory( rgPropItems, sizeof(*rgPropItems) * nCount ) ;
_rgPropItems = rgPropItems ;
_cPropItems = nCount ;
return _rgPropItems ;
}
return NULL ;
}
//-------------------------------------------------------------------------//
// helper: frees member array of PROPERTYITEMs
void CAVPropSrc::FreeItems()
{
if( _rgPropItems )
{
for( int i=0; i<_cPropItems; i++ )
PropVariantClear( &_rgPropItems[i].val ) ;
delete [] _rgPropItems ;
_rgPropItems = NULL ;
_cPropItems = 0 ;
}
}
//-------------------------------------------------------------------------//
// retrieves the specified element of the member PROPERTYITEM array.
STDMETHODIMP CAVPropSrc::GetPropertyItem(
IN REFPFID pfid,
IN LONG iProperty,
OUT PPROPERTYITEM pItem )
{
ASSERT( iProperty >= 0 ) ;
if( iProperty >= _cPropItems )
return S_FALSE ;
CopyPTPropertyItem( pItem, &_rgPropItems[iProperty] ) ;
return S_OK ;
}
STDMETHODIMP CAVPropSrc::GetPropertyValue( LPCSHCOLUMNID pscid, OUT VARIANT* pVal )
{
for( int i=0; i < (int)_cPropItems; i++ )
{
if( pscid->pid == _rgPropItems[i].puid.propid &&
IsEqualGUID( pscid->fmtid, _rgPropItems[i].puid.fmtid ) )
{
return PropVariantToVariant( &_rgPropItems[i].val, pVal ) ;
}
}
return E_UNEXPECTED ;
}
//-------------------------------------------------------------------------//
// CWaveSrc : public CAVPropSrc - wave audio file data object
//-------------------------------------------------------------------------//
//-------------------------------------------------------------------------//
STDMETHODIMP CWaveSrc::Acquire()
{
WAVEDESC wave ;
ZeroMemory( &wave, sizeof(wave) ) ;
HRESULT hr = GetWaveInfo( _szFile, &wave ) ;
if( SUCCEEDED( hr ) )
{
// Allocate an array of PROPERTYITEM blocks
PPROPERTYITEM rgitems = AllocItems( ARRAYSIZE(audiopropdefs) ) ;
if( !rgitems )
return E_OUTOFMEMORY ;
for( int i=0, cnt=0; i< ARRAYSIZE(audiopropdefs); i++ )
{
// Initialize
if( SUCCEEDED( PTPropertyItemFromPropDef( audiopropdefs + i, rgitems + cnt ) ) )
{
rgitems[cnt].iOrder = cnt ;
rgitems[cnt].pfid = PFID_AudioProperties ;
// Stuff values
if( SUCCEEDED( GetWaveProperty( *audiopropdefs[i].pfmtid, audiopropdefs[i].pid,
&wave, &rgitems[cnt].val ) ) )
{
rgitems[cnt].puid.vt = rgitems[cnt].val.vt ;
cnt++ ;
}
else
ClearPTPropertyItem( &rgitems[cnt] ) ; // don't leak these BSTRs.
}
}
_cPropItems = cnt ;
FreeWaveInfo( &wave ) ;
}
return hr ;
}
//-------------------------------------------------------------------------//
// CAviSrc : public CAVPropSrc - AVI file data object
//-------------------------------------------------------------------------//
//-------------------------------------------------------------------------//
STDMETHODIMP CAviSrc::Acquire()
{
AVIDESC avi ;
ZeroMemory( &avi, sizeof(avi) );
HRESULT hr = GetAviInfo( _szFile, &avi ) ;
if( SUCCEEDED( hr ) )
{
// Allocate an array of PROPERTYITEM blocks
PPROPERTYITEM rgitems = AllocItems( ARRAYSIZE(videopropdefs) + ARRAYSIZE(audiopropdefs) ) ;
if( !rgitems )
return E_OUTOFMEMORY ;
int i, cnt = 0 ;
for( i=0; i< ARRAYSIZE(videopropdefs); i++ )
{
// Initialize
if( SUCCEEDED( PTPropertyItemFromPropDef( videopropdefs + i, rgitems + cnt ) ) )
{
rgitems[cnt].iOrder = cnt ;
rgitems[cnt].pfid = PFID_VideoProperties ;
// Stuff values
if( SUCCEEDED( GetAviProperty( *videopropdefs[i].pfmtid, videopropdefs[i].pid,
&avi, &rgitems[cnt].val ) ) )
{
rgitems[cnt].puid.vt = rgitems[cnt].val.vt ;
m_bVideoStream = TRUE ;
cnt++ ;
}
else
ClearPTPropertyItem( rgitems + cnt ) ; // don't leak
}
}
for( i=0; i< ARRAYSIZE(audiopropdefs); i++ )
{
// Initialize
if( SUCCEEDED( PTPropertyItemFromPropDef( audiopropdefs + i, rgitems + cnt ) ) )
{
rgitems[cnt].iOrder = cnt ;
rgitems[cnt].pfid = PFID_AudioProperties ;
// Stuff values
if( SUCCEEDED( GetAviProperty( *audiopropdefs[i].pfmtid, audiopropdefs[i].pid,
&avi, &rgitems[cnt].val ) ) )
{
rgitems[cnt].puid.vt = rgitems[cnt].val.vt ;
m_bAudioStream = TRUE ;
cnt++ ;
}
else
ClearPTPropertyItem( rgitems + cnt ) ; // don't leak
}
}
_cPropItems = cnt ;
FreeAviInfo( &avi ) ;
}
return hr ;
}
//-------------------------------------------------------------------------//
// CMidiSrc : public CAVPropSrc - MIDI file data object
//-------------------------------------------------------------------------//
//-------------------------------------------------------------------------//
STDMETHODIMP CMidiSrc::Acquire()
{
return GetMidiInfo( _szFile, &_midi ) ;
}
//-------------------------------------------------------------------------//
// Utilities
//-------------------------------------------------------------------------//
//-------------------------------------------------------------------------//
BSTR BstrFromResource( UINT nIDS )
{
WCHAR wszBuf[MAX_DESCRIPTOR] ;
*wszBuf = NULL ;
if( !LoadStringW( _Module.GetResourceInstance(), nIDS, wszBuf, ARRAYSIZE(wszBuf) ) )
return NULL ;
return SysAllocString( wszBuf ) ;
}
//-------------------------------------------------------------------------//
HRESULT PTPropertyItemFromPropDef( const PROPERTY_DEF* ppd, IN OUT PPROPERTYITEM pItem )
{
HRESULT hr = S_OK ;
USES_CONVERSION ;
ZeroMemory( pItem, sizeof(*pItem) ) ;
pItem->cbStruct = sizeof(*pItem) ;
pItem->mask = PTPI_ALL ;
pItem->bstrName = SysAllocString( T2W((LPTSTR)ppd->pszName) ) ;
pItem->bstrDisplayName = BstrFromResource( ppd->nIdsDisplay ) ;
pItem->bstrQtip = BstrFromResource( ppd->nIdsTip ) ;
pItem->dwAccess = PTIA_READONLY ;
pItem->iOrder = -1 ;
//pItem->lParam = NULL;
pItem->puid.fmtid = *ppd->pfmtid ;
pItem->puid.propid = ppd->pid ;
//pItem->dwFolderID
//pItem->dwFlags;
//pItem->ctlID;
//pItem->bstrDisplayFmt;
//pItem->val;
return hr ;
}
//-------------------------------------------------------------------------//
void CopyPTPropertyItem( OUT PPROPERTYITEM pDest, IN const PPROPERTYITEM pSrc )
{
ZeroMemory( pDest, sizeof(*pDest) ) ;
*pDest = *pSrc ;
// deep copy...
pDest->bstrName = ( pSrc->bstrName ) ? SysAllocString( pSrc->bstrName ) : NULL ;
pDest->bstrDisplayName = ( pSrc->bstrDisplayName ) ? SysAllocString( pSrc->bstrDisplayName ) : NULL ;
pDest->bstrQtip = ( pSrc->bstrQtip ) ? SysAllocString( pSrc->bstrQtip ) : NULL ;
PropVariantInit( &pDest->val ) ;
PropVariantCopy( &pDest->val, &pSrc->val ) ;
}
#define SAFE_SYSFREESTRING( bstr ) if((bstr)){ SysFreeString((bstr)); (bstr)=NULL; }
//-------------------------------------------------------------------------//
void ClearPTPropertyItem( struct tagPROPERTYITEM* pItem )
{
if( pItem != NULL && sizeof(*pItem) == pItem->cbStruct )
{
SAFE_SYSFREESTRING( pItem->bstrName ) ;
SAFE_SYSFREESTRING( pItem->bstrDisplayName ) ;
SAFE_SYSFREESTRING( pItem->bstrQtip ) ;
PropVariantClear( &pItem->val ) ;
ZeroMemory( pItem, sizeof(*pItem) ) ;
}
}
// {884EA37B-37C0-11d2-BE3F-00A0C9A83DA1}
static const GUID CLSID_AVColumnProvider =
{ 0x884ea37b, 0x37c0, 0x11d2, { 0xbe, 0x3f, 0x0, 0xa0, 0xc9, 0xa8, 0x3d, 0xa1 } };
//-------------------------------------------------------------------------//
STDMETHODIMP CAVColumnProvider::Initialize( LPCSHCOLUMNINIT psci )
{
return *psci->wszFolder ? S_OK : E_FAIL ; // only file-system folders
}
//-------------------------------------------------------------------------//
typedef struct {
const PROPERTY_DEF* prgPropDef ;
int iPropDef ;
} COLUMN_INDEX ;
STDMETHODIMP CAVColumnProvider::GetColumnInfo( DWORD dwIndex, LPSHCOLUMNINFO psci )
{
static COLUMN_INDEX columnIndices[ARRAYSIZE(audiopropdefs) + ARRAYSIZE(videopropdefs)] ;
static int cnt = 0 ;
const PROPERTY_DEF* prgPropDef = NULL ;
int i ;
ZeroMemory(psci, sizeof(*psci));
// Initialize our index
if( 0 == cnt )
{
for( i = 0; i < ARRAYSIZE(audiopropdefs); i++ )
{
if( audiopropdefs[i].bShellColumn )
{
columnIndices[cnt].prgPropDef = audiopropdefs ;
columnIndices[cnt].iPropDef = i ;
cnt++ ;
}
}
for( i = 0; i < ARRAYSIZE(videopropdefs); i++ )
{
if( videopropdefs[i].bShellColumn )
{
columnIndices[cnt].prgPropDef = videopropdefs ;
columnIndices[cnt].iPropDef = i ;
cnt++ ;
}
}
}
if( 0 == cnt || cnt <= (int)dwIndex )
return S_FALSE ;
// Adjust index
prgPropDef = columnIndices[dwIndex].prgPropDef ;
i = columnIndices[dwIndex].iPropDef ;
psci->scid.fmtid = *prgPropDef[i].pfmtid ;
psci->scid.pid = prgPropDef[i].pid ;
psci->vt = VT_BSTR ;
psci->fmt = LVCFMT_LEFT ;
psci->cChars = 30 ;
psci->csFlags = SHCOLSTATE_TYPE_STR;
LoadStringW(_Module.GetResourceInstance(), prgPropDef[i].nIdsDisplay,
psci->wszTitle, ARRAYSIZE(psci->wszTitle) ) ;
return S_OK ;
}
STDMETHODIMP CAVColumnProvider::GetItemData( LPCSHCOLUMNID pscid, LPCSHCOLUMNDATA pscd, LPVARIANT pvarData )
{
USES_CONVERSION ;
HRESULT hr = E_UNEXPECTED ;
AcquireMutex() ;
if( (pscd->dwFlags & SHCDF_UPDATEITEM) || (m_pSrc && lstrcmpi( m_pSrc->Path(), W2CT(pscd->wszFile) ) != 0 ))
Flush() ;
if( NULL == m_pSrc )
{
if( SUCCEEDED( (hr = CAVPropSrc::CreateInstance( W2CT(pscd->pwszExt), &m_pSrc )) ) )
{
m_pSrc->Attach( W2CT(pscd->wszFile) ) ;
if( FAILED( (hr = m_pSrc->Acquire()) ) )
Flush() ;
}
}
if( m_pSrc )
hr = m_pSrc->GetPropertyValue( pscid, pvarData ) ;
ReleaseMutex() ;
return hr ;
}
| 34.361702 | 113 | 0.501935 | [
"object"
] |
faccd181836ed713bf5afc95a1d30d3172c14eb3 | 596 | cpp | C++ | codes/maths/fibonacci/fibonacci(bad space complexity).cpp | arunrajora/algorithms | 3590deefbf94382e10ebd16692118328fc9b538a | [
"MIT"
] | 1 | 2017-08-20T20:35:53.000Z | 2017-08-20T20:35:53.000Z | codes/maths/fibonacci/fibonacci(bad space complexity).cpp | arunrajora/algorithms | 3590deefbf94382e10ebd16692118328fc9b538a | [
"MIT"
] | null | null | null | codes/maths/fibonacci/fibonacci(bad space complexity).cpp | arunrajora/algorithms | 3590deefbf94382e10ebd16692118328fc9b538a | [
"MIT"
] | 1 | 2017-06-10T18:51:56.000Z | 2017-06-10T18:51:56.000Z |
// n-th fibonacci number
#include<iostream>
#include<vector>
using namespace std;
#define ull unsigned long long
#define FIBMAX 100005
int fdp[FIBMAX]={0};
ull fib(int n){
if(n<3){
return fdp[n]=(n>0);
}
if(fdp[n]>0){
return fdp[n];
}
int k=(n%2)?(n+1)/2:n/2;
return fdp[n]=(n%2)?(fib(k)*fib(k)+fib(k-1)*fib(k-1)):fib(k)*(fib(k)+2*fib(k-1));
}
int main(){
cout<<fib(0)<<endl;
cout<<fib(1)<<endl;
cout<<fib(2)<<endl;
cout<<fib(3)<<endl;
cout<<fib(4)<<endl;
cout<<fib(5)<<endl;
cout<<fib(6)<<endl;
cout<<fib(7)<<endl;
cout<<fib(8)<<endl;
cout<<fib(9)<<endl;
return 0;
}
| 15.684211 | 82 | 0.588926 | [
"vector"
] |
fada1d2e2289c8cdec87b2821d6ad714e7640134 | 1,086 | cpp | C++ | test/collection.cpp | SillyMountain/wombat | 8c5735cd501da1991f6a9a3e3a01048fa0aa46be | [
"MIT"
] | null | null | null | test/collection.cpp | SillyMountain/wombat | 8c5735cd501da1991f6a9a3e3a01048fa0aa46be | [
"MIT"
] | null | null | null | test/collection.cpp | SillyMountain/wombat | 8c5735cd501da1991f6a9a3e3a01048fa0aa46be | [
"MIT"
] | null | null | null | #include <cstdio>
#include <vector>
#include <cassert>
#include <algorithm>
#include <ctime>
#include <iostream>
#include <wombat/collections/Array.hpp>
#include <wombat/utils/timer.hpp>
#define N 10000
#define DUMP_TIMING(l) {printf("%30s: %.2lf [s]\n", l, t.elapsed()); t.reset();}
Timer t;
void testWombatArray()
{
Array<int> a;
for(int x = 0; x < N; x++)
{
a.add(x);
}
DUMP_TIMING("wombat.array.insert");
for(int x = 0; x < N; x++)
{
assert(a.contains(x));
}
DUMP_TIMING("wombat.array.contains");
for(int x = 0; x < N; x++)
{
a.remove(0);
}
DUMP_TIMING("wombat.array.remove");
}
void testSTLArray()
{
std::vector<int> v;
for(int x = 0; x < N; x++)
{
v.push_back(x);
}
DUMP_TIMING("STL.array.insert");
for(int x = 0; x < N; x++)
{
assert(std::find(v.begin(), v.end(), x) != v.end());
}
DUMP_TIMING("STL.array.contains");
for(int x = 0; x < N; x++)
{
v.erase(v.begin());
v.swap(v);
}
DUMP_TIMING("STL.array.remove");
}
int main()
{
testWombatArray();
puts("--------------------------------------------");
testSTLArray();
}
| 14.48 | 80 | 0.567219 | [
"vector"
] |
fae55bff8de0e41f84c2d07fad672fd77f220c96 | 60,520 | cpp | C++ | src/vendor/mariadb-10.6.7/storage/columnstore/columnstore/writeengine/bulk/we_bulkload.cpp | zettadb/zettalib | 3d5f96dc9e3e4aa255f4e6105489758944d37cc4 | [
"Apache-2.0"
] | null | null | null | src/vendor/mariadb-10.6.7/storage/columnstore/columnstore/writeengine/bulk/we_bulkload.cpp | zettadb/zettalib | 3d5f96dc9e3e4aa255f4e6105489758944d37cc4 | [
"Apache-2.0"
] | null | null | null | src/vendor/mariadb-10.6.7/storage/columnstore/columnstore/writeengine/bulk/we_bulkload.cpp | zettadb/zettalib | 3d5f96dc9e3e4aa255f4e6105489758944d37cc4 | [
"Apache-2.0"
] | 2 | 2022-02-27T14:00:01.000Z | 2022-03-31T06:24:22.000Z | /* Copyright (C) 2014 InfiniDB, Inc.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; version 2 of
the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
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. */
/*******************************************************************************
* $Id: we_bulkload.cpp 4730 2013-08-08 21:41:13Z chao $
*
*******************************************************************************/
/** @file */
#define WE_BULKLOAD_DLLEXPORT
#include "we_bulkload.h"
#undef WE_BULKLOAD_DLLEXPORT
#include <cmath>
#include <cstdlib>
#include <climits>
#include <glob.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <vector>
#include <sstream>
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/convenience.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <pwd.h>
#include "we_bulkstatus.h"
#include "we_rbmetawriter.h"
#include "we_colopbulk.h"
#include "we_columninfocompressed.h"
#include "we_config.h"
#include "we_dbrootextenttracker.h"
#include "writeengine.h"
#include "sys/time.h"
#include "sys/types.h"
#include "dataconvert.h"
#include "idbcompress.h"
#include "calpontsystemcatalog.h"
#include "we_ddlcommandclient.h"
#include "mcsconfig.h"
using namespace std;
using namespace boost;
using namespace dataconvert;
namespace
{
const std::string IMPORT_PATH_STDIN("STDIN");
const std::string IMPORT_PATH_CWD (".");
const std::string LOG_SUFFIX = ".log"; // Job log file suffix
const std::string ERR_LOG_SUFFIX = ".err"; // Job err log file suffix
}
//extern WriteEngine::BRMWrapper* brmWrapperPtr;
namespace WriteEngine
{
/* static */ boost::ptr_vector<TableInfo> BulkLoad::fTableInfo;
/* static */ boost::mutex* BulkLoad::fDDLMutex = 0;
/* static */ const std::string BulkLoad::DIR_BULK_JOB("job");
/* static */ const std::string BulkLoad::DIR_BULK_TEMP_JOB("tmpjob");
/* static */ const std::string BulkLoad::DIR_BULK_IMPORT("/data/import/");
/* static */ bool BulkLoad::fNoConsoleOutput = false;
//------------------------------------------------------------------------------
// A thread to periodically call dbrm to see if a user is
// shutting down the system or has put the system into write
// suspend mode. DBRM has 2 flags to check in this case, the
// ROLLBACK flag, and the FORCE flag. These flags will be
// reported when we ask for the Shutdown Pending flag (which we
// ignore at this point). Even if the user is putting the system
// into write suspend mode, this call will return the flags we
// are interested in. If ROLLBACK is set, we cancel normally.
// If FORCE is set, we can't rollback.
struct CancellationThread
{
CancellationThread(BulkLoad* pBulkLoad) : fpBulkLoad(pBulkLoad)
{}
BulkLoad* fpBulkLoad;
void operator()()
{
bool bRollback = false;
bool bForce = false;
int iShutdown;
while (fpBulkLoad->getContinue())
{
usleep(1000000); // 1 seconds
// Check to see if someone has ordered a shutdown or suspend with
// rollback or force.
iShutdown = BRMWrapper::getInstance()->isShutdownPending(bRollback,
bForce);
if (iShutdown != ERR_BRM_GET_SHUTDOWN)
{
if (bRollback)
{
if (iShutdown == ERR_BRM_SHUTDOWN)
{
if (!BulkLoad::disableConsoleOutput())
cout << "System stop has been ordered. Rollback"
<< endl;
}
else
{
if (!BulkLoad::disableConsoleOutput())
cout << "Database writes have been suspended. Rollback"
<< endl;
}
BulkStatus::setJobStatus( EXIT_FAILURE );
}
else if (bForce)
{
if (!BulkLoad::disableConsoleOutput())
cout << "Immediate system stop has been ordered. "
<< "No rollback"
<< endl;
}
}
}
}
};
//------------------------------------------------------------------------------
// Constructor
//------------------------------------------------------------------------------
BulkLoad::BulkLoad() :
fColOp(new ColumnOpBulk()),
fColDelim('\0'),
fNoOfBuffers(-1), fBufferSize(-1), fFileVbufSize(-1), fMaxErrors(-1),
fNoOfParseThreads(3), fNoOfReadThreads(1),
fKeepRbMetaFiles(false),
fNullStringMode(false),
fEnclosedByChar('\0'), // not enabled unless user overrides enclosed by char
fEscapeChar('\0'),
fTotalTime(0.0),
fBulkMode(BULK_MODE_LOCAL),
fbTruncationAsError(false),
fImportDataMode(IMPORT_DATA_TEXT),
fbContinue(false),
fDisableTimeOut(false),
fUUID(boost::uuids::nil_generator()()),
fTimeZone("SYSTEM"),
fUsername("mysql") // MCOL-4328 default file owner
{
fTableInfo.clear();
setDebugLevel( DEBUG_0 );
fDDLMutex = new boost::mutex();
memset( &fStartTime, 0, sizeof(timeval) );
memset( &fEndTime, 0, sizeof(timeval) );
}
//------------------------------------------------------------------------------
// Destructor
//------------------------------------------------------------------------------
BulkLoad::~BulkLoad()
{
fTableInfo.clear();
delete fDDLMutex;
}
//------------------------------------------------------------------------------
// DESCRIPTION:
// Set alternate directory path for import data files. If the specified
// path is "STDIN", then the import data will be read from stdin.
// Note that we check for read "and" write access to the import directory
// path so that we can not only read the input files, but also write the
// *.bad and *.err files to that directory.
// PARAMETERS:
// loadDir - import directory path
// errMsg - return error msg if failed return code is returned
// RETURN:
// NO_ERROR if success
// other if fail
//------------------------------------------------------------------------------
int BulkLoad::setAlternateImportDir(const std::string& loadDir,
std::string& errMsg)
{
if (loadDir == IMPORT_PATH_STDIN)
{
fAlternateImportDir = loadDir;
}
else
{
if ( access(loadDir.c_str(), R_OK | W_OK) < 0 )
{
int errnum = errno;
ostringstream oss;
oss << "Error gaining r/w access to import path " << loadDir <<
": " << strerror(errnum);
errMsg = oss.str();
return ERR_FILE_OPEN;
}
if (loadDir == IMPORT_PATH_CWD)
{
fAlternateImportDir = loadDir;
}
else
{
if ( loadDir.c_str()[loadDir.size() - 1 ] == '/' )
fAlternateImportDir = loadDir;
else
fAlternateImportDir = loadDir + "/";
}
}
return NO_ERROR;
}
//------------------------------------------------------------------------------
// DESCRIPTION:
// Load a job information
// PARAMETERS:
// fullName - full filename for job description file
// bUseTempJobFile - are we using a temporary job XML file
// argc - command line arg count
// argv - command line arguments
// bLogInfo2ToConsole - Log info2 msgs to the console
// bValidateColumnList- Validate that all the columns for each table have
// a corresponding <Column> or <DefaultColumn> tag.
// RETURN:
// NO_ERROR if success
// other if fail
//------------------------------------------------------------------------------
int BulkLoad::loadJobInfo(
const string& fullName,
bool bUseTempJobFile,
int argc,
char** argv,
bool bLogInfo2ToConsole,
bool bValidateColumnList )
{
fJobFileName = fullName;
fRootDir = Config::getBulkRoot();
fJobInfo.setTimeZone(fTimeZone);
if ( !exists( fullName.c_str() ) )
{
fLog.logMsg( " file " + fullName + " does not exist",
ERR_FILE_NOT_EXIST, MSGLVL_ERROR );
return ERR_FILE_NOT_EXIST;
}
std::string errMsg;
int rc = fJobInfo.loadJobXmlFile( fullName, bUseTempJobFile,
bValidateColumnList, errMsg );
if ( rc != NO_ERROR )
{
std::ostringstream oss;
oss << "Error loading job file " << fullName << "; " << errMsg;
fLog.logMsg( oss.str(), rc, MSGLVL_ERROR );
return rc;
}
const Job& curJob = fJobInfo.getJob();
string logFile, errlogFile;
logFile = std::string(MCSLOGDIR) + "/cpimport/" + "Job_" +
Convertor::int2Str( curJob.id ) + LOG_SUFFIX;
errlogFile = std::string(MCSLOGDIR) + "/cpimport/" + "Job_" +
Convertor::int2Str( curJob.id ) + ERR_LOG_SUFFIX;
if (disableConsoleOutput())
fLog.setLogFileName(logFile.c_str(), errlogFile.c_str(), false);
else
fLog.setLogFileName(logFile.c_str(), errlogFile.c_str(), (int)bLogInfo2ToConsole);
if (!(disableConsoleOutput()))
{
if (!BulkLoad::disableConsoleOutput())
cout << "Log file for this job: " << logFile << std::endl;
fLog.logMsg( "successfully loaded job file " + fullName, MSGLVL_INFO1 );
}
if (argc > 1)
{
std::ostringstream oss;
oss << "Command line options: ";
for (int k = 1; k < argc; k++)
{
if (!strcmp(argv[k], "\t")) // special case to print a <TAB>
oss << "'\\t'" << " ";
else
oss << argv[k] << " ";
}
fLog.logMsg( oss.str(), MSGLVL_INFO2 );
}
// Validate that each table has 1 or more columns referenced in the xml file
for (unsigned i = 0; i < curJob.jobTableList.size(); i++)
{
if ( curJob.jobTableList[i].colList.size() == 0)
{
rc = ERR_INVALID_PARAM;
fLog.logMsg( "No column definitions in job description file for "
"table " + curJob.jobTableList[i].tblName,
rc, MSGLVL_ERROR );
return rc;
}
}
// Validate that the user's xml file has been regenerated since the
// required tblOid attribute was added to the Table tag for table locking.
for (unsigned i = 0; i < curJob.jobTableList.size(); i++)
{
if (curJob.jobTableList[i].mapOid == 0)
{
rc = ERR_XML_PARSE;
fLog.logMsg( "Outdated job file " + fullName +
"; missing required 'tblOid' table attribute." +
" Please regenerate this xml file.",
rc, MSGLVL_ERROR );
return rc;
}
}
for (unsigned kT = 0; kT < curJob.jobTableList.size(); kT++)
{
for (unsigned kC = 0; kC < curJob.jobTableList[kT].colList.size(); kC++)
{
if (!compress::CompressInterface::isCompressionAvail(
curJob.jobTableList[kT].colList[kC].compressionType))
{
std::ostringstream oss;
oss << "Specified compression type (" <<
curJob.jobTableList[kT].colList[kC].compressionType <<
") for table " << curJob.jobTableList[kT].tblName <<
" and column " <<
curJob.jobTableList[kT].colList[kC].colName <<
" is not available for use.";
rc = ERR_COMP_UNAVAIL_TYPE;
fLog.logMsg( oss.str(), rc, MSGLVL_ERROR );
return rc;
}
}
}
// If binary import, do not allow <IgnoreField> tags in the Job file
if ((fImportDataMode == IMPORT_DATA_BIN_ACCEPT_NULL) ||
(fImportDataMode == IMPORT_DATA_BIN_SAT_NULL))
{
for (unsigned kT = 0; kT < curJob.jobTableList.size(); kT++)
{
if (curJob.jobTableList[kT].fIgnoredFields.size() > 0)
{
std::ostringstream oss;
oss << "<IgnoreField> tag present in Job file for table " <<
curJob.jobTableList[kT].tblName <<
"; this is not allowed for binary imports.";
rc = ERR_BULK_BINARY_IGNORE_FLD;
fLog.logMsg( oss.str(), rc, MSGLVL_ERROR );
return rc;
}
}
}
stopTimer();
std::ostringstream ossXMLTime;
ossXMLTime << "Job file loaded, run time for this step : " <<
getTotalRunTime() << " seconds";
fLog.logMsg( ossXMLTime.str(), MSGLVL_INFO1 );
return NO_ERROR;
}
//------------------------------------------------------------------------------
// DESCRIPTION:
// Spawns and joins the Read and Parsing threads to import the data.
// PARAMETERS:
// none
// RETURN:
// none
//------------------------------------------------------------------------------
void BulkLoad::spawnWorkers()
{
// We're fixin' to launch threads. This lets anybody who cares (i.e.
// checkCancellation) know that read and parse threads are running.
fbContinue = true;
// Spawn a thread to check for user cancellation via calpont console
// But only in mode 3 (local mode)
boost::thread cancelThread;
CancellationThread cancelationThread(this);
if (getBulkLoadMode() == BULK_MODE_LOCAL)
{
cancelThread = boost::thread(cancelationThread);
}
// Spawn read threads
for (int i = 0; i < fNoOfReadThreads; ++i)
{
fReadThreads.create_thread(boost::bind(&BulkLoad::read, this, (int)i));
}
fLog.logMsg("No of Read Threads Spawned = " +
Convertor::int2Str( fNoOfReadThreads ), MSGLVL_INFO1 );
// Spawn parse threads
for (int i = 0; i < fNoOfParseThreads; ++i)
{
fParseThreads.create_thread(boost::bind(&BulkLoad::parse, this, (int)i));
}
fLog.logMsg("No of Parse Threads Spawned = " +
Convertor::int2Str( fNoOfParseThreads ), MSGLVL_INFO1 );
fReadThreads.join_all();
fParseThreads.join_all();
fbContinue = false;
if (getBulkLoadMode() == BULK_MODE_LOCAL)
{
cancelThread.join();
}
}
//------------------------------------------------------------------------------
// DESCRIPTION:
// Pre process job. Determine DBRoot/segment file, HWM etc where we are
// to start adding rows, create ColumnInfo object for each column. Create
// initial segment file if necessary. This could happen in shared-nothing
// where CREATE TABLE only creates the initial segment file on one of the
// PMs. The first time rows are added on the other PMs, an initial segment
// file must be created. (This could also happen "if" we ever decide to
// allow the user to drop all partitions for a DBRoot, including the last
// partition.)
// PreProcessing also includes creating the bulk rollback back up files,
// initializing auto-increment, sanity checking the consistency of the HWM
// across columns, and opening the starting column and dictionary store
// files.
// PARAMETERS:
// job - current job
// tableNo - table no
// tableInfo - TableInfo object corresponding to tableNo table.
// RETURN:
// NO_ERROR if success
// other if fail
//------------------------------------------------------------------------------
int BulkLoad::preProcess( Job& job, int tableNo,
TableInfo* tableInfo )
{
int rc = NO_ERROR, minWidth = 9999; // give a big number
HWM minHWM = 999999; // rp 9/25/07 Bug 473
ColStruct curColStruct;
execplan::CalpontSystemCatalog::ColDataType colDataType;
// Initialize portions of TableInfo object
tableInfo->setBufferSize(fBufferSize);
tableInfo->setFileBufferSize(fFileVbufSize);
tableInfo->setTableId(tableNo);
tableInfo->setColDelimiter(fColDelim);
tableInfo->setJobFileName(fJobFileName);
tableInfo->setJobId(job.id);
tableInfo->setNullStringMode(fNullStringMode);
tableInfo->setEnclosedByChar(fEnclosedByChar);
tableInfo->setEscapeChar(fEscapeChar);
tableInfo->setImportDataMode(fImportDataMode);
tableInfo->setTimeZone(fTimeZone);
tableInfo->setJobUUID(fUUID);
// MCOL-4328 Get username gid and uid if they are set
// We inject uid and gid into TableInfo and All ColumnInfo-s later.
struct passwd* pwd = nullptr;
errno = 0;
if (fUsername.length() && (pwd = getpwnam(fUsername.c_str())) == nullptr)
{
std::ostringstream oss;
oss << "Error getting pwd for " << fUsername
<< " with errno "
<< errno;
fLog.logMsg( oss.str(), MSGLVL_ERROR );
return ERR_FILE_CHOWN;
}
if (pwd)
tableInfo->setUIDGID(pwd->pw_uid, pwd->pw_gid);
if (fMaxErrors != -1)
tableInfo->setMaxErrorRows(fMaxErrors);
else
tableInfo->setMaxErrorRows(job.jobTableList[tableNo].maxErrNum);
// @bug 3929: cpimport.bin error messaging using up too much memory.
// Validate that max allowed error count is within valid range
long long maxErrNum = tableInfo->getMaxErrorRows();
if (maxErrNum > MAX_ALLOW_ERROR_COUNT)
{
ostringstream oss;
oss << "Max allowed error count specified as " << maxErrNum <<
" for table " << job.jobTableList[tableNo].tblName <<
"; this exceeds limit of " << MAX_ALLOW_ERROR_COUNT <<
"; resetting to " << MAX_ALLOW_ERROR_COUNT;
fLog.logMsg( oss.str(), MSGLVL_INFO2 );
maxErrNum = MAX_ALLOW_ERROR_COUNT;
}
tableInfo->setMaxErrorRows(maxErrNum);
//------------------------------------------------------------------------
// First loop thru the columns for the "tableNo" table in jobTableList[].
// Get the HWM information for each column.
//------------------------------------------------------------------------
std::vector<int> colWidths;
std::vector<DBRootExtentInfo> segFileInfo;
std::vector<DBRootExtentTracker*> dbRootExtTrackerVec;
std::vector<BRM::EmDbRootHWMInfo_v> dbRootHWMInfoColVec(
job.jobTableList[tableNo].colList.size() );
DBRootExtentTracker* pRefDBRootExtentTracker = 0;
bool bNoStartExtentOnThisPM = false;
bool bEmptyPM = false;
for ( size_t i = 0; i < job.jobTableList[tableNo].colList.size(); i++ )
{
const JobColumn& curJobCol = job.jobTableList[tableNo].colList[i];
// convert column data type
if ( curJobCol.typeName.length() > 0 &&
fColOp->getColDataType( curJobCol.typeName.c_str(), colDataType ))
{
job.jobTableList[tableNo].colList[i].dataType =
curColStruct.colDataType = colDataType;
}
else
{
ostringstream oss;
oss << "Column type " << curJobCol.typeName << " is not valid ";
fLog.logMsg( oss.str(), ERR_INVALID_PARAM, MSGLVL_ERROR );
return ERR_INVALID_PARAM;
}
curColStruct.colWidth = curJobCol.width;
Convertor::convertColType( &curColStruct );
job.jobTableList[tableNo].colList[i].weType = curColStruct.colType;
// set width to correct column width
job.jobTableList[tableNo].colList[i].width = curColStruct.colWidth;
job.jobTableList[tableNo].colList[i].emptyVal =
getEmptyRowValue(job.jobTableList[tableNo].colList[i].dataType,
job.jobTableList[tableNo].colList[i].width);
// check HWM for column file
rc = BRMWrapper::getInstance()->getDbRootHWMInfo( curJobCol.mapOid,
dbRootHWMInfoColVec[i]);
if (rc != NO_ERROR)
{
WErrorCodes ec;
ostringstream oss;
oss << "Error getting last DBRoot/HWMs for column file " <<
curJobCol.mapOid << "; " << ec.errorString(rc);
fLog.logMsg( oss.str(), rc, MSGLVL_ERROR );
return rc;
}
colWidths.push_back( job.jobTableList[tableNo].colList[i].width );
} // end of 1st for-loop through the list of columns (get starting HWM)
//--------------------------------------------------------------------------
// Second loop thru the columns for the "tableNo" table in jobTableList[].
// Create DBRootExtentTracker, and select starting DBRoot.
// Determine the smallest width column(s), and save that as minHWM.
// We save additional HWM information acquired from BRM, in segFileInfo,
// for later use.
//--------------------------------------------------------------------------
for ( size_t i = 0; i < job.jobTableList[tableNo].colList.size(); i++ )
{
const JobColumn& curJobCol = job.jobTableList[tableNo].colList[i];
// Find DBRoot/segment file where we want to start adding rows
DBRootExtentTracker* pDBRootExtentTracker = new DBRootExtentTracker(
curJobCol.mapOid,
colWidths,
dbRootHWMInfoColVec,
i,
&fLog );
if (i == 0)
pRefDBRootExtentTracker = pDBRootExtentTracker;
dbRootExtTrackerVec.push_back( pDBRootExtentTracker );
// Start adding rows to DBRoot/segment file that is selected
DBRootExtentInfo dbRootExtent;
if (i == 0) // select starting DBRoot/segment for column[0]
{
std::string trkErrMsg;
rc = pDBRootExtentTracker->selectFirstSegFile(dbRootExtent,
bNoStartExtentOnThisPM, bEmptyPM, trkErrMsg);
if (rc != NO_ERROR)
{
fLog.logMsg( trkErrMsg, rc, MSGLVL_ERROR );
return rc;
}
}
else // select starting DBRoot/segment based on column[0] selection
{
// to ensure all columns start with the same DBRoot/segment
pDBRootExtentTracker->assignFirstSegFile(
*pRefDBRootExtentTracker, // reference column[0] tracker
dbRootExtent);
}
if ( job.jobTableList[tableNo].colList[i].width < minWidth )
{
// save the minimum hwm -- rp 9/25/07 Bug 473
minWidth = job.jobTableList[tableNo].colList[i].width;
minHWM = dbRootExtent.fLocalHwm;
}
// Save column segment file info for use in subsequent loop
segFileInfo.push_back( dbRootExtent );
}
//--------------------------------------------------------------------------
// Validate that the starting HWMs for all the columns are in sync
//--------------------------------------------------------------------------
rc = tableInfo->validateColumnHWMs( &job.jobTableList[tableNo],
segFileInfo, "Starting" );
if (rc != NO_ERROR)
{
return rc;
}
//--------------------------------------------------------------------------
// Create bulk rollback meta data file
//--------------------------------------------------------------------------
ostringstream oss11;
oss11 << "Initializing import: " <<
"Table-" << job.jobTableList[tableNo].tblName << "...";
fLog.logMsg( oss11.str(), MSGLVL_INFO2 );
rc = saveBulkRollbackMetaData( job, tableInfo, segFileInfo,
dbRootHWMInfoColVec );
if (rc != NO_ERROR)
{
return rc;
}
//--------------------------------------------------------------------------
// Third loop thru the columns for the "tableNo" table in jobTableList[].
// In this pass through the columns we create the ColumnInfo object,
// open the applicable column and dictionary store files, and seek to
// the block where we will begin adding data.
//--------------------------------------------------------------------------
unsigned int fixedBinaryRecLen = 0;
for ( size_t i = 0; i < job.jobTableList[tableNo].colList.size(); i++ )
{
uint16_t dbRoot = segFileInfo[i].fDbRoot;
uint32_t partition = segFileInfo[i].fPartition;
uint16_t segment = segFileInfo[i].fSegment;
HWM oldHwm = segFileInfo[i].fLocalHwm;
DBRootExtentTracker* pDBRootExtentTracker = 0;
if (dbRootExtTrackerVec.size() > 0)
pDBRootExtentTracker = dbRootExtTrackerVec[i];
// Create a ColumnInfo for the next column, and add to tableInfo
ColumnInfo* info = 0;
if (job.jobTableList[tableNo].colList[i].compressionType)
info = new ColumnInfoCompressed(&fLog, i,
job.jobTableList[tableNo].colList[i],
pDBRootExtentTracker,
tableInfo);
//tableInfo->rbMetaWriter());
else
info = new ColumnInfo(&fLog, i,
job.jobTableList[tableNo].colList[i],
pDBRootExtentTracker,
tableInfo);
if (pwd)
info->setUIDGID(pwd->pw_uid, pwd->pw_gid);
// For auto increment column, we need to get the starting value
if (info->column.autoIncFlag)
{
rc = preProcessAutoInc( job.jobTableList[tableNo].tblName, info );
if (rc != NO_ERROR)
{
return rc;
}
}
// For binary input mode, sum up the columns widths to get fixed rec len
if ((fImportDataMode == IMPORT_DATA_BIN_ACCEPT_NULL) ||
(fImportDataMode == IMPORT_DATA_BIN_SAT_NULL))
{
if (job.jobTableList[tableNo].fFldRefs[i].fFldColType ==
BULK_FLDCOL_COLUMN_FIELD)
{
fixedBinaryRecLen += info->column.definedWidth;
}
}
// Skip minimum blocks before starting import; minwidth columns skip to
// next block. Wider columns skip based on multiple of width. If this
// skipping of blocks requires a new extent, then we extend the column.
HWM hwm = (minHWM + 1) * ( info->column.width / minWidth );
info->relativeColWidthFactor( info->column.width / minWidth );
if ((bEmptyPM) || (bNoStartExtentOnThisPM))
{
// HWM not found in prev loop; can't get LBID. Will create initial
// extent on this PM later in this job, if we have valid rows to add
if (bEmptyPM)
{
// No starting DB file on this PM
ostringstream oss3;
oss3 << "Currently no extents on dbroot" << dbRoot <<
" for column OID " << info->column.mapOid <<
"; will create starting extent";
fLog.logMsg( oss3.str(), MSGLVL_INFO2 );
}
// Skip to subsequent physical partition if current HWM extent
// for this "dbroot" is disabled.
else // bNoStartExtentOnThisPM is true
{
// Starting DB file on this PM is disabled
ostringstream oss3;
oss3 << "Current HWM extent is disabled on dbroot" << dbRoot <<
" for column OID " << info->column.mapOid <<
"; will create starting extent";
fLog.logMsg( oss3.str(), MSGLVL_INFO2 );
}
// Pass blocks to be skipped at start of file "if" we decide to
// employ block skipping for the first extent.
hwm = info->column.width / minWidth;
// We don't have a starting DB file on this PM, or the starting HWM
// extent is disabled. In either case, we will wait and create a
// new DB file to receive any new rows, only after we make sure we
// have rows to insert.
info->setupDelayedFileCreation(
dbRoot, partition, segment, hwm, bEmptyPM );
}
else
{
// Establish starting HWM and LBID for this job.
// Keep in mind we have initial block skipping to account for.
bool bSkippedToNewExtent = false;
BRM::LBID_t lbid;
RETURN_ON_ERROR( preProcessHwmLbid( info,
minWidth, partition, segment,
hwm, lbid, bSkippedToNewExtent ) );
// Setup import to start loading into starting HWM DB file
RETURN_ON_ERROR( info->setupInitialColumnExtent(
dbRoot, partition, segment,
job.jobTableList[tableNo].tblName,
lbid,
oldHwm, hwm,
bSkippedToNewExtent, false) );
}
tableInfo->addColumn(info);
} // end of 2nd for-loop through the list of columns
if ((fImportDataMode == IMPORT_DATA_BIN_ACCEPT_NULL) ||
(fImportDataMode == IMPORT_DATA_BIN_SAT_NULL))
{
ostringstream oss12;
oss12 << "Table " << job.jobTableList[tableNo].tblName << " will be "
"imported in binary mode with fixed record length: " <<
fixedBinaryRecLen << " bytes; ";
if (fImportDataMode == IMPORT_DATA_BIN_ACCEPT_NULL)
oss12 << "NULL values accepted";
else
oss12 << "NULL values saturated";
fLog.logMsg( oss12.str(), MSGLVL_INFO2 );
}
// Initialize BulkLoadBuffers after we have added all the columns
rc = tableInfo->initializeBuffers(fNoOfBuffers,
job.jobTableList[tableNo].fFldRefs,
fixedBinaryRecLen);
if (rc)
return rc;
fTableInfo.push_back(tableInfo);
return NO_ERROR;
}
//------------------------------------------------------------------------------
// DESCRIPTION:
// Saves snapshot of extentmap into a bulk rollback meta data file, for
// use in a bulk rollback, if the current cpimport.bin job should fail.
// PARAMETERS:
// job - current job
// tableInfo - TableInfo object corresponding to tableNo table.
// segFileInfo - Vector of File objects carrying starting DBRoot, partition,
// etc, for the columns belonging to tableNo.
// dbRootHWMInfoColVec - Vector of vectors carrying extent/HWM info for each
// dbroot for each column.
// RETURN:
// NO_ERROR if success
// other if fail
//------------------------------------------------------------------------------
int BulkLoad::saveBulkRollbackMetaData( Job& job,
TableInfo* tableInfo,
const std::vector<DBRootExtentInfo>& segFileInfo,
const std::vector<BRM::EmDbRootHWMInfo_v>& dbRootHWMInfoColVec)
{
return tableInfo->saveBulkRollbackMetaData(
job, segFileInfo, dbRootHWMInfoColVec );
}
//------------------------------------------------------------------------------
// DESCRIPTION:
// Initialize auto-increment column for specified schema and table.
// PARAMETERS:
// fullTableName - Schema and table name separated by a period.
// colInfo - ColumnInfo associated with auto-increment column.
// RETURN:
// NO_ERROR if success
// other if fail
//------------------------------------------------------------------------------
int BulkLoad::preProcessAutoInc( const std::string& fullTableName,
ColumnInfo* colInfo)
{
int rc = colInfo->initAutoInc( fullTableName );
return rc;
}
//------------------------------------------------------------------------------
// DESCRIPTION:
// Determine starting HWM and LBID, after applying block skipping to HWM.
// PARAMETERS:
// info - ColumnInfo of column we are working with
// minWidth - minimum width among all columns for this table
// partition - partition of projected starting HWM
// segment - file segment number of projected starting HWM
// hwm (input/output) - input: projected starting HWM after block skipping
// output: adjusted starting HWM
// lbid output: LBID associated with adjusted HWM
// bSkippedToNewExtent- output:
// true -> normal block skipping use case
// false-> block skipped crossed out of hwm extent
// RETURN:
// NO_ERROR if success
// other if fail
//------------------------------------------------------------------------------
int BulkLoad::preProcessHwmLbid(
const ColumnInfo* info,
int minWidth,
uint32_t partition,
uint16_t segment,
HWM& hwm, // input/output
BRM::LBID_t& lbid, // output
bool& bSkippedToNewExtent) // output
{
int rc = NO_ERROR;
bSkippedToNewExtent = false;
// Get starting LBID for the HWM block; if we can't get the start-
// ing LBID, it means initial block skipping crossed extent boundary
rc = BRMWrapper::getInstance()->getStartLbid(
info->column.mapOid,
partition,
segment,
(int)hwm, lbid);
// If HWM Lbid is missing, take alternative action to see what to do.
// Block skipping has caused us to advance out of the current HWM extent.
if (rc != NO_ERROR)
{
bSkippedToNewExtent = true;
lbid = INVALID_LBID;
int blocksPerExtent =
(BRMWrapper::getInstance()->getExtentRows() *
info->column.width) / BYTE_PER_BLOCK;
// Look for LBID associated with block at end of current extent
uint32_t numBlocks = (((hwm + 1) / blocksPerExtent) * blocksPerExtent);
hwm = numBlocks - 1;
rc = BRMWrapper::getInstance()->getStartLbid(
info->column.mapOid,
partition,
segment,
(int)hwm, lbid);
if (rc != NO_ERROR)
{
WErrorCodes ec;
ostringstream oss;
oss << "Error getting HWM start LBID "
"for previous last extent in column file OID-" <<
info->column.mapOid <<
"; partition-" << partition <<
"; segment-" << segment <<
"; hwm-" << hwm <<
"; " << ec.errorString(rc);
fLog.logMsg( oss.str(), rc, MSGLVL_ERROR );
return rc;
}
}
return rc;
}
//------------------------------------------------------------------------------
// DESCRIPTION:
// NO_ERROR if success
// other if fail
//------------------------------------------------------------------------------
int BulkLoad::processJob( )
{
#ifdef PROFILE
Stats::enableProfiling( fNoOfReadThreads, fNoOfParseThreads );
#endif
int rc = NO_ERROR;
Job curJob;
size_t i;
curJob = fJobInfo.getJob();
// For the following parms, we use the value read from the Job XML file if
// a cmd line override value was not already assigned by cpimport.cpp.
if (fNoOfBuffers == -1)
fNoOfBuffers = curJob.numberOfReadBuffers;
if (fBufferSize == -1)
fBufferSize = curJob.readBufferSize;
if (fFileVbufSize == -1)
fFileVbufSize = curJob.writeBufferSize;
if (fColDelim == '\0')
fColDelim = curJob.fDelimiter;
//std::cout << "bulkload::fEnclosedByChar<" << fEnclosedByChar << '>' <<
//std::endl << "bulkload::fEscapeChar<" << fEscapeChar << '>' <<
//std::endl << "job.fEnclosedByChar<" <<curJob.fEnclosedByChar<< '>' <<
//std::endl << "job.fEscapeChar<" << curJob.fEscapeChar << '>' <<
//std::endl;
if (fEnclosedByChar == '\0')
{
// std::cout << "Using enclosed char from xml file" << std::endl;
fEnclosedByChar = curJob.fEnclosedByChar;
}
if (fEscapeChar == '\0')
{
// std::cout << "Using escape char from xml file" << std::endl;
fEscapeChar = curJob.fEscapeChar;
}
// If EnclosedBy char is given, then we need an escape character.
// We default to '\' if we didn't get one from xml file or cmd line.
if (fEscapeChar == '\0')
{
//std::cout << "Using default escape char" << std::endl;
fEscapeChar = '\\';
}
//std::cout << "bulkload::fEnclosedByChar<" << fEnclosedByChar << '>' <<
//std::endl << "bulkload::fEscapeChar<" << fEscapeChar << '>' << std::endl;
//Bug1315 - check whether DBRoots are RW mounted.
std::vector<std::string> dbRootPathList;
Config::getDBRootPathList( dbRootPathList );
for (unsigned int counter = 0; counter < dbRootPathList.size(); counter++)
{
if ( access( dbRootPathList[counter].c_str(), R_OK | W_OK) < 0 )
{
rc = ERR_FILE_NOT_EXIST;
ostringstream oss;
oss << "Error accessing DBRoot[" << counter << "] " <<
dbRootPathList[counter] << "; " <<
strerror(errno);
fLog.logMsg( oss.str(), rc, MSGLVL_ERROR );
return rc;
}
}
// Init total cumulative run time with time it took to load xml file
double totalRunTime = getTotalRunTime();
fLog.logMsg( "PreProcessing check starts", MSGLVL_INFO1 );
startTimer();
//--------------------------------------------------------------------------
// Validate that only 1 table is specified for import if using STDIN
//--------------------------------------------------------------------------
if ((fAlternateImportDir == IMPORT_PATH_STDIN) &&
(curJob.jobTableList.size() > 1))
{
rc = ERR_INVALID_PARAM;
fLog.logMsg("Only 1 table can be imported per job when using STDIN",
rc, MSGLVL_ERROR );
return rc;
}
//--------------------------------------------------------------------------
// Validate the existence of the import data files
//--------------------------------------------------------------------------
std::vector<TableInfo*> tables;
for ( i = 0; i < curJob.jobTableList.size(); i++ )
{
TableInfo* tableInfo = new TableInfo(&fLog,
fTxnID,
fProcessName,
curJob.jobTableList[i].mapOid,
curJob.jobTableList[i].tblName,
fKeepRbMetaFiles);
if ((fBulkMode == BULK_MODE_REMOTE_SINGLE_SRC) ||
(fBulkMode == BULK_MODE_REMOTE_MULTIPLE_SRC))
tableInfo->setBulkLoadMode( fBulkMode, fBRMRptFileName );
tableInfo->setErrorDir(string(getErrorDir()));
tableInfo->setTruncationAsError(getTruncationAsError());
rc = manageImportDataFileList( curJob, i, tableInfo );
if (rc != NO_ERROR)
{
tableInfo->fBRMReporter.sendErrMsgToFile(tableInfo->fBRMRptFileName);
return rc;
}
tables.push_back( tableInfo );
}
//--------------------------------------------------------------------------
// Before we go any further, we lock all the tables
//--------------------------------------------------------------------------
for ( i = 0; i < curJob.jobTableList.size(); i++ )
{
rc = tables[i]->acquireTableLock( fDisableTimeOut );
if (rc != NO_ERROR)
{
// Try releasing the table locks we already acquired.
// Note that loop is k<i since tables[i] lock failed.
for ( unsigned k = 0; k < i; k++)
{
tables[k]->releaseTableLock( );//ignore return code in this case
}
return rc;
}
// If we have a lock, then init MetaWriter, so that it can delete any
// leftover backup meta data files that collide with the ones we are
// going to create.
rc = tables[i]->initBulkRollbackMetaData( );
if (rc != NO_ERROR)
{
// Try releasing the table locks we already acquired.
// Note that loop is k<i= since tables[i] lock worked
for (unsigned k = 0; k <= i; k++)
{
tables[k]->releaseTableLock( );//ignore return code in this case
}
return rc;
}
}
//--------------------------------------------------------------------------
// Perform necessary preprocessing for each table
//--------------------------------------------------------------------------
for ( i = 0; i < curJob.jobTableList.size(); i++ )
{
// If table already marked as complete then we are skipping the
// table because there were no input files to process.
if ( tables[i]->getStatusTI() == WriteEngine::PARSE_COMPLETE)
continue;
rc = preProcess( curJob, i, tables[i] );
if ( rc != NO_ERROR )
{
std::string errMsg =
"Error in pre-processing the job file for table " +
curJob.jobTableList[i].tblName;
tables[i]->fBRMReporter.addToErrMsgEntry(errMsg);
fLog.logMsg( errMsg, rc, MSGLVL_CRITICAL );
// Okay to release the locks for the tables we did not get to
for ( unsigned k = i + 1; k < tables.size(); k++)
{
tables[k]->releaseTableLock( );//ignore return code in this case
}
// Okay to release the locks for any tables we preprocessed.
// We will not have done anything to change these tables yet,
// so all we need to do is release the locks.
for ( unsigned k = 0; k <= i; k++)
{
tables[k]->deleteMetaDataRollbackFile( );
tables[k]->releaseTableLock( ); //ignore return code
}
// Ignore the return code for now; more important to base rc on the
// success or failure of the previous work
// BUG 4398: distributed cpimport calls takeSnapshot for modes 1 & 2
if ((fBulkMode != BULK_MODE_REMOTE_SINGLE_SRC) &&
(fBulkMode != BULK_MODE_REMOTE_MULTIPLE_SRC))
{
BRMWrapper::getInstance()->takeSnapshot();
}
return rc;
}
}
stopTimer();
fLog.logMsg( "PreProcessing check completed", MSGLVL_INFO1 );
std::ostringstream ossPrepTime;
ossPrepTime << "preProcess completed, run time for this step : " <<
getTotalRunTime() << " seconds";
fLog.logMsg( ossPrepTime.str(), MSGLVL_INFO1 );
totalRunTime += getTotalRunTime();
startTimer();
spawnWorkers();
if (BulkStatus::getJobStatus() == EXIT_FAILURE)
{
rc = ERR_UNKNOWN;
}
// Regardless of JobStatus, we rollback any tables that are left locked
int rollback_rc = rollbackLockedTables( );
if ((rc == NO_ERROR) && (rollback_rc != NO_ERROR))
{
rc = rollback_rc;
}
// Ignore the return code for now; more important to base rc on the
// success or failure of the previous work
// BUG 4398: distributed cpimport now calls takeSnapshot for modes 1 & 2
if ((fBulkMode != BULK_MODE_REMOTE_SINGLE_SRC) &&
(fBulkMode != BULK_MODE_REMOTE_MULTIPLE_SRC))
{
BRMWrapper::getInstance()->takeSnapshot();
}
stopTimer();
totalRunTime += getTotalRunTime();
std::ostringstream ossTotalRunTime;
ossTotalRunTime << "Bulk load completed, total run time : " <<
totalRunTime << " seconds" << std::endl;
fLog.logMsg( ossTotalRunTime.str(), MSGLVL_INFO1 );
#ifdef PROFILE
Stats::printProfilingResults( );
#endif
return rc;
}
//------------------------------------------------------------------------------
// DESCRIPTION:
// Deconstruct the list of 1 or more import files for the specified table,
// and validate the existence of the specified files.
// PARAMETERS:
// job - current job
// tableNo - table no
// tableInfo - TableInfo object corresponding to tableNo table.
// RETURN:
// NO_ERROR if success
// other if fail
//------------------------------------------------------------------------------
int BulkLoad::manageImportDataFileList(Job& job,
int tableNo,
TableInfo* tableInfo)
{
std::vector<std::string> loadFilesList;
bool bUseStdin = false;
// Take loadFileName from command line argument override "if" one exists,
// else we take from the Job xml file
std::string loadFileName;
if (fCmdLineImportFiles.size() > (unsigned)tableNo)
loadFileName = fCmdLineImportFiles[tableNo];
else
loadFileName = job.jobTableList[tableNo].loadFileName;
if (fAlternateImportDir == IMPORT_PATH_STDIN)
{
bUseStdin = true;
fLog.logMsg( "Using STDIN for input data", MSGLVL_INFO2 );
int rc = buildImportDataFileList(std::string(),
loadFileName,
loadFilesList);
if (rc != NO_ERROR)
{
return rc;
}
// BUG 4737 - in Mode 1, all data coming from STDIN, ignore input files
if ((loadFilesList.size() > 1) && (fBulkMode != BULK_MODE_REMOTE_SINGLE_SRC))
{
ostringstream oss;
oss << "Table " << tableInfo->getTableName() <<
" specifies multiple "
"load files; This is not allowed when using STDIN";
fLog.logMsg( oss.str(), ERR_INVALID_PARAM, MSGLVL_ERROR );
tableInfo->fBRMReporter.addToErrMsgEntry(oss.str());
return ERR_INVALID_PARAM;
}
}
else
{
std::string importDir;
if (!fS3Key.empty())
{
loadFilesList.push_back(loadFileName);
}
else
{
if ( fAlternateImportDir == IMPORT_PATH_CWD ) // current working dir
{
char cwdBuf[4096];
importDir = ::getcwd(cwdBuf, sizeof(cwdBuf));
importDir += '/';
}
else if ( fAlternateImportDir.size() > 0 ) // -f path
{
importDir = fAlternateImportDir;
}
else // <BULKROOT>/data/import
{
importDir = fRootDir;
importDir += DIR_BULK_IMPORT;
}
// Break down loadFileName into vector of file names in case load-
// FileName contains a list of files or 1 or more wildcards.
int rc = buildImportDataFileList(importDir,
loadFileName,
loadFilesList);
if (rc != NO_ERROR)
{
return rc;
}
}
// No filenames is considered a fatal error, except for remote mode2.
// For remote mode2 we just mark the table as complete since we will
// have no data to load, but we don't consider this as an error.
if (loadFilesList.size() == 0)
{
ostringstream oss;
oss << "No import files found. " << "default dir: " << importDir <<
" importFileName: " << loadFileName;
if (fBulkMode == BULK_MODE_REMOTE_MULTIPLE_SRC)
{
tableInfo->setLoadFilesInput(bUseStdin, (!fS3Key.empty()), loadFilesList, fS3Host, fS3Key, fS3Secret, fS3Bucket, fS3Region);
tableInfo->markTableComplete( );
fLog.logMsg( oss.str(), MSGLVL_INFO1 );
return NO_ERROR;
}
else
{
fLog.logMsg( oss.str(), ERR_FILE_NOT_EXIST, MSGLVL_ERROR );
return ERR_FILE_NOT_EXIST;
}
}
// Verify that input data files exist.
// We also used to check to make sure the input file is not empty, and
// if it were, we threw an error at this point, but we removed that
// check. With shared-nothing, an empty file is now acceptable.
if (fS3Key.empty())
{
for (unsigned ndx = 0; ndx < loadFilesList.size(); ndx++ )
{
// in addition to being more portable due to the use of boost, this change
// actually fixes an inherent bug with cpimport reading from a named pipe.
// Only the first open call gets any data passed through the pipe so the
// here that used to do an open to test for existence meant cpimport would
// never get data from the pipe.
boost::filesystem::path pathFile(loadFilesList[ndx]);
if ( !boost::filesystem::exists( pathFile ) )
{
ostringstream oss;
oss << "input data file " << loadFilesList[ndx] << " does not exist";
fLog.logMsg( oss.str(), ERR_FILE_NOT_EXIST, MSGLVL_ERROR );
tableInfo->fBRMReporter.addToErrMsgEntry(oss.str());
return ERR_FILE_NOT_EXIST;
}
else
{
ostringstream oss;
oss << "input data file " << loadFilesList[ndx];
fLog.logMsg( oss.str(), MSGLVL_INFO1 );
}
}
}
}
tableInfo->setLoadFilesInput(bUseStdin, (!fS3Key.empty()), loadFilesList, fS3Host, fS3Key, fS3Secret, fS3Bucket, fS3Region);
return NO_ERROR;
}
//------------------------------------------------------------------------------
// DESCRIPTION:
// Break up the filename string (which may contain a list of file names)
// into a vector of strings, with each non-fully-qualified string being
// prefixed by the path specified by "location".
// PARAMETERS:
// location - path prefix
// filename - list of file names
// loadFiles- vector of file names extracted from filename string
// RETURN:
// NO_ERROR if success
//------------------------------------------------------------------------------
int BulkLoad::buildImportDataFileList(
const std::string& location,
const std::string& filename,
std::vector<std::string>& loadFiles)
{
char* filenames = new char[filename.size() + 1];
strcpy(filenames, filename.c_str());
char* str;
char* token;
for (str = filenames; ; str = NULL)
{
#ifdef _MSC_VER
//On Windows, only comma and vertbar can separate input files
token = strtok(str, ",|");
#else
token = strtok(str, ", |");
#endif
if (token == NULL)
break;
// If the token (filename) is fully qualified, then use the filename
// as-is, else prepend the location (path prefix)
boost::filesystem::path p(token);
std::string fullPath;
if (p.has_root_path())
{
fullPath = token;
}
else
{
fullPath = location;
fullPath += token;
}
#ifdef _MSC_VER
loadFiles.push_back(fullPath);
#else
// If running mode2, then support a filename with wildcards
if (fBulkMode == BULK_MODE_REMOTE_MULTIPLE_SRC)
{
bool bExpandFileName = false;
size_t fpos = fullPath.find_first_of( "[*?" );
if (fpos != std::string::npos)
{
bExpandFileName = true;
}
else // expand a directory name
{
struct stat curStat;
if ( (stat(fullPath.c_str(), &curStat) == 0) &&
(S_ISDIR(curStat.st_mode)) )
{
bExpandFileName = true;
fullPath += "/*";
}
}
// If wildcard(s) present use glob() function to expand into a list
if (bExpandFileName)
{
glob_t globBuf;
memset(&globBuf, 0, sizeof(globBuf));
int globFlags = GLOB_ERR | GLOB_MARK;
int rc = glob(fullPath.c_str(), globFlags, 0, &globBuf);
if (rc != 0)
{
if (rc == GLOB_NOMATCH)
{
continue;
}
else
{
ostringstream oss;
oss << "Error expanding filename " << fullPath;
if (rc == GLOB_NOSPACE)
oss << "; out of memory";
else if (rc == GLOB_ABORTED)
oss << "; error reading directory";
else if (rc == GLOB_NOSYS)
oss << "; globbing not implemented";
else
oss << "; rc-" << rc;
fLog.logMsg(oss.str(), ERR_FILE_GLOBBING, MSGLVL_ERROR);
delete [] filenames;
return ERR_FILE_GLOBBING;
}
}
// Include all non-directory files in the import file list
std::string fullPath2;
for (unsigned int k = 0; k < globBuf.gl_pathc; k++)
{
fullPath2 = globBuf.gl_pathv[k];
if ( !fullPath2.empty() )
{
if ( fullPath2[ fullPath2.length() - 1 ] != '/' )
{
loadFiles.push_back( fullPath2 );
}
}
}
} // wild card present
else
{
loadFiles.push_back(fullPath);
}
} // mode2
else
{
loadFiles.push_back(fullPath);
} // not mode2
#endif
} // loop through filename tokens
delete [] filenames;
return NO_ERROR;
}
//------------------------------------------------------------------------------
// DESCRIPTION:
// Clear table locks, and rollback any tables that are
// still locked through session manager.
// PARAMETERS:
// none
// RETURN:
// NO_ERROR if success
// other if fail
//------------------------------------------------------------------------------
int BulkLoad::rollbackLockedTables( )
{
int rc = NO_ERROR;
// See if there are any DB tables that were left in a locked state
bool lockedTableFound = false;
for ( unsigned i = 0; i < fTableInfo.size(); i++ )
{
if (fTableInfo[i].isTableLocked())
{
lockedTableFound = true;
break;
}
}
// If 1 or more tables failed to load, then report the lock
// state of each table we were importing.
if (lockedTableFound)
{
// Report the tables that were successfully loaded
for ( unsigned i = 0; i < fTableInfo.size(); i++ )
{
if (!fTableInfo[i].isTableLocked())
{
ostringstream oss;
oss << "Table " << fTableInfo[i].getTableName() <<
" was successfully loaded. ";
fLog.logMsg( oss.str(), MSGLVL_INFO1 );
}
}
// Report the tables that were not successfully loaded
for ( unsigned i = 0; i < fTableInfo.size(); i++ )
{
if (fTableInfo[i].isTableLocked())
{
if (fTableInfo[i].hasProcessingBegun())
{
ostringstream oss;
oss << "Table " << fTableInfo[i].getTableName() <<
" (OID-" << fTableInfo[i].getTableOID() << ")" <<
" was not successfully loaded. Rolling back.";
fLog.logMsg( oss.str(), MSGLVL_INFO1 );
}
else
{
ostringstream oss;
oss << "Table " << fTableInfo[i].getTableName() <<
" (OID-" << fTableInfo[i].getTableOID() << ")" <<
" did not start loading. No rollback necessary.";
fLog.logMsg( oss.str(), MSGLVL_INFO1 );
}
rc = rollbackLockedTable( fTableInfo[i] );
if (rc != NO_ERROR)
{
break;
}
}
}
}
return rc;
}
//------------------------------------------------------------------------------
// DESCRIPTION:
// Clear table lock, and rollback the specified table that is still locked.
// This function only comes into play for a mode3, since the tablelock and
// bulk rollbacks are managed by the parent (cpipmort file splitter) process
// in the case of mode1 and mode2 bulk loads.
// PARAMETERS:
// tableInfo - the table to be released and rolled back
// RETURN:
// NO_ERROR if success
// other if fail
//------------------------------------------------------------------------------
int BulkLoad::rollbackLockedTable( TableInfo& tableInfo )
{
return tableInfo.rollbackWork( );
}
//------------------------------------------------------------------------------
// DESCRIPTION:
// Update next autoincrement value for specified column OID.
// PARAMETERS:
// columnOid - column OID of interest
// nextAutoIncVal - next autoincrement value to assign to tableOID
// RETURN:
// 0 if success
// other if fail
//------------------------------------------------------------------------------
/* static */
int BulkLoad::updateNextValue(OID columnOid, uint64_t nextAutoIncVal)
{
// The odds of us ever having 2 updateNextValue() calls going on in parallel
// are slim and none. But it's theoretically possible if we had an import
// job for 2 tables; so we put a mutex here just in case the DDLClient code
// won't work well with 2 competing WE_DDLCommandClient objects in the same
// process (ex: if there is any static data in WE_DDLCommandClient).
boost::mutex::scoped_lock lock( *fDDLMutex );
WE_DDLCommandClient ddlCommandClt;
unsigned int rc = ddlCommandClt.UpdateSyscolumnNextval(
columnOid, nextAutoIncVal );
return (int)rc;
}
//------------------------------------------------------------------------------
bool BulkLoad::addErrorMsg2BrmUpdater(const std::string& tablename, const ostringstream& oss)
{
int size = fTableInfo.size();
if (size == 0) return false;
for (int tableId = 0; tableId < size; tableId++)
{
if (fTableInfo[tableId].getTableName() == tablename)
{
fTableInfo[tableId].fBRMReporter.addToErrMsgEntry(oss.str());
return true;
}
}
return false;
}
//------------------------------------------------------------------------------
// DESCRIPTION:
// Set job UUID. Used by Query Telemetry to identify a unique import
// job across PMs
// PARAMETERS:
// jobUUID - the job UUID
// RETURN:
// void
//------------------------------------------------------------------------------
void BulkLoad::setJobUUID(const std::string& jobUUID)
{
fUUID = boost::uuids::string_generator()(jobUUID);
}
void BulkLoad::setDefaultJobUUID()
{
if (fUUID.is_nil())
fUUID = boost::uuids::random_generator()();
}
} //end of namespace
| 36.326531 | 140 | 0.525248 | [
"object",
"vector"
] |
fae99b39e39ec45f5413e674f9ad79d3447126ea | 2,008 | cpp | C++ | bigint.cpp | leodeliyannis/bigint | 6764e4b673e0c86735722bf4f7f3fda49dddfeac | [
"MIT"
] | null | null | null | bigint.cpp | leodeliyannis/bigint | 6764e4b673e0c86735722bf4f7f3fda49dddfeac | [
"MIT"
] | null | null | null | bigint.cpp | leodeliyannis/bigint | 6764e4b673e0c86735722bf4f7f3fda49dddfeac | [
"MIT"
] | null | null | null | /*
* Leonardo Deliyannis Constantin
* Implementação própria de BigInt
*/
#include <stdio.h>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
typedef unsigned long long ull;
struct bigint{
vector<ull> V;
private:
const int BASE = ((int)1e8);
int cmp(const bigint &other) const{
int i;
if(V.size() < other.V.size()) return -1;
if(V.size() > other.V.size()) return 1;
for(i = (int)V.size()-1; i >= 0 && V[i] == other.V[i]; i--);
if(i == -1) return 0;
return (V[i] < other.V[i]) ? -1 : 1;
}
public:
void trimZeroes(){
int i;
for(i = (int)V.size()-1; i >= 0 && V[i] == 0; i--);
V.resize((i == -1) ? 1 : (i + 1));
}
bool fromString(const string &S){
int i, j, pot;
i = (int)S.size() - 1;
if(S.back() == '\n') i--;
if(i == -1)
return false;
V.clear();
while(i >= 0){
pot = 1;
V.push_back(0);
for(j = 1; j <= 8 && i >= 0; j++, i--){
V[V.size()-1] += pot*(S[i] - '0');
pot *= 10;
}
}
trimZeroes();
return true;
}
bigint(){ fromString("0"); }
bigint(const string &S){ fromString(S); }
string toString() const{
int i;
char buf[11];
string ret;
sprintf(buf, "%llu", V.back());
ret.append(buf);
for(i = (int)V.size()-2; i >= 0; i--){
sprintf(buf, "%08llu", V[i]);
ret.append(buf);
}
return ret;
}
bool operator <(const bigint &other) const{ return cmp(other) < 0; }
bool operator ==(const bigint &other) const{ return cmp(other) == 0; }
bool operator >(const bigint &other) const{ return cmp(other) > 0; }
void operator =(const bigint &other){ V = other.V; }
bigint operator +(const bigint &other) const{
int i, t1 = (int)V.size(), t2 = (int)other.V.size();
ull carry = 0, val1, val2;
bigint ret;
ret.V.assign(max(t1, t2), 0);
for(i = 0; i < t1 || i < t2; i++){
val1 = i < t1 ? V[i] : 0;
val2 = i < t2 ? other.V[i] : 0;
ret.V[i] = val1 + val2 + carry;
carry = ret.V[i] / BASE;
ret.V[i] %= BASE;
}
ret.V[i] = carry;
ret.trimZeroes();
return ret;
}
};
| 23.623529 | 71 | 0.548307 | [
"vector"
] |
faef272ac5a2f52ba2b51b123a5ae92fbc3be8f1 | 13,457 | cpp | C++ | tests/unit/sdk/test_pixie_buffer.cpp | xiallc/pixie_sdk | a6cf38b0a0d73a55955f4f906f789ee16eb848d4 | [
"Apache-2.0"
] | 2 | 2021-04-14T13:58:50.000Z | 2021-08-09T19:42:25.000Z | tests/unit/sdk/test_pixie_buffer.cpp | xiallc/pixie_sdk | a6cf38b0a0d73a55955f4f906f789ee16eb848d4 | [
"Apache-2.0"
] | 1 | 2021-08-31T10:32:07.000Z | 2021-09-03T15:03:00.000Z | tests/unit/sdk/test_pixie_buffer.cpp | xiallc/pixie_sdk | a6cf38b0a0d73a55955f4f906f789ee16eb848d4 | [
"Apache-2.0"
] | 1 | 2022-03-25T12:32:52.000Z | 2022-03-25T12:32:52.000Z | /* SPDX-License-Identifier: Apache-2.0 */
/*
* Copyright 2021 XIA LLC, All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/** @file test_pixie_buffer.cpp
* @brief Defines tests for the threaded FIFO buffer readout.
*/
#include <cstring>
#include <doctest/doctest.h>
#include <pixie/buffer.hpp>
TEST_SUITE("xia::buffer") {
TEST_CASE("pool create/destroy") {
SUBCASE("no actions") {
xia::buffer::pool pool;
CHECK(pool.empty());
CHECK(!pool.full());
CHECK(pool.count() == 0);
CHECK(pool.number == 0);
CHECK(pool.size == 0);
pool.create(100, 8 * 1024);
CHECK(!pool.empty());
CHECK(pool.full());
CHECK(pool.count() == 100);
CHECK(pool.number == 100);
CHECK(pool.size == 8 * 1024);
pool.destroy();
CHECK(pool.empty());
CHECK(!pool.full());
CHECK(pool.count() == 0);
CHECK(pool.number == 0);
CHECK(pool.size == 0);
}
SUBCASE("buffer held") {
xia::buffer::pool pool;
pool.create(100, 8 * 1024);
CHECK(!pool.empty());
{
xia::buffer::handle buf = pool.request();
CHECK_THROWS_WITH_AS(pool.destroy(), "pool destroy made while busy",
xia::buffer::error);
}
pool.destroy();
}
}
TEST_CASE("pool create/destroy reuse") {
xia::buffer::pool pool;
SUBCASE("one") {
pool.create(100, 8 * 1024);
CHECK_THROWS_WITH_AS(pool.create(1, 1), "pool is already created", xia::buffer::error);
pool.destroy();
}
SUBCASE("two") {
pool.create(200, 4 * 1024);
pool.destroy();
}
}
TEST_CASE("pool request/release") {
xia::buffer::pool pool;
pool.create(100, 8 * 1024);
SUBCASE("single") {
xia::buffer::handle buf = pool.request();
CHECK(buf->size() == 0);
CHECK((*buf).size() == 0);
CHECK(buf->capacity() == pool.size);
CHECK(pool.count() == pool.number - 1);
}
SUBCASE("all") {
std::vector<xia::buffer::handle> handles;
for (size_t b = 0; b < pool.number; ++b) {
handles.push_back(pool.request());
}
CHECK_THROWS_WITH_AS(pool.request(), "no buffers available", xia::buffer::error);
CHECK(pool.empty());
CHECK(!pool.full());
CHECK(pool.count() == 0);
handles.pop_back();
CHECK(!pool.empty());
CHECK(!pool.full());
CHECK(pool.count() == 1);
handles.erase(handles.begin() + 5);
CHECK(!pool.empty());
CHECK(!pool.full());
CHECK(pool.count() == 2);
handles.clear();
CHECK(!pool.empty());
CHECK(pool.full());
CHECK(pool.count() == pool.number);
}
SUBCASE("variable") {
std::vector<xia::buffer::handle> handles[3];
for (size_t h = 0; h < 3; ++h) {
for (size_t b = 0; b < 10; ++b) {
handles[h].push_back(pool.request());
}
}
CHECK(pool.count() == pool.number - 3 * 10);
handles[1].erase(handles[1].begin() + 5);
handles[1].erase(handles[1].begin() + 6);
handles[0].pop_back();
handles[2].erase(handles[2].begin() + 3);
CHECK(pool.count() == pool.number - 3 * 10 + 4);
handles[0].push_back(pool.request());
CHECK(pool.count() == pool.number - 3 * 10 + 3);
std::vector<xia::buffer::handle> remaining;
while (!pool.empty()) {
remaining.push_back(pool.request());
}
}
pool.destroy();
}
TEST_CASE("queue") {
xia::buffer::pool pool;
pool.create(100, 8 * 1024);
SUBCASE("create/destroy") {
xia::buffer::queue queue;
CHECK(queue.size() == 0);
CHECK(queue.count() == 0);
}
SUBCASE("push and pop") {
xia::buffer::queue queue;
CHECK(queue.size() == 0);
CHECK(queue.count() == 0);
/*
* Empty buffers are not queued but released.
*/
queue.push(pool.request());
CHECK(queue.size() == 0);
CHECK(queue.count() == 0);
CHECK(pool.full());
{
/*
* hold in the block to check the handle's ref counting.
*/
xia::buffer::handle buf = pool.request();
buf->resize(100);
queue.push(buf);
CHECK(queue.size() == 100);
CHECK(queue.count() == 1);
CHECK(pool.count() == pool.number - 1);
}
CHECK(queue.size() == 100);
CHECK(queue.count() == 1);
CHECK(pool.count() == pool.number - 1);
queue.pop();
CHECK(queue.size() == 0);
CHECK(queue.count() == 0);
CHECK(pool.full());
/*
* Hold the buffer in a handle and the queue and then let them
* destruct. The pool destroy will catch any leaks.
*/
xia::buffer::handle buf = pool.request();
buf->resize(100);
queue.push(buf);
}
SUBCASE("size and count") {
xia::buffer::queue queue;
size_t total = 0;
for (size_t b = 0; b < 10; ++b) {
xia::buffer::handle buf = pool.request();
CHECK(buf->size() == 0);
CHECK(buf->capacity() == pool.size);
size_t size = b * 100 + 10;
buf->resize(size);
total += size;
queue.push(buf);
}
CHECK(queue.size() == total);
CHECK(queue.count() == 10);
for (size_t b = 0; b < 5; ++b) {
size_t size = b * 100 + 10;
total -= size;
xia::buffer::handle buf = queue.pop();
CHECK(buf->size() == size);
}
CHECK(queue.size() == total);
CHECK(queue.count() == 5);
}
SUBCASE("compact to one") {
xia::buffer::queue queue;
size_t total = 0;
for (size_t b = 0; b < 10; ++b) {
xia::buffer::handle buf = pool.request();
CHECK(buf->size() == 0);
CHECK(buf->capacity() == pool.size);
size_t size = b * 100 + 10;
buf->resize(size);
total += size;
queue.push(buf);
}
CHECK(queue.count() == 10);
CHECK(queue.size() == total);
queue.compact();
CHECK(queue.count() == 1);
CHECK(queue.size() == total);
}
SUBCASE("compact various sizes") {
xia::buffer::queue queue;
size_t total = 0;
for (size_t b = 0; b < 5; ++b) {
xia::buffer::handle buf = pool.request();
CHECK(buf->size() == 0);
CHECK(buf->capacity() == pool.size);
size_t size = b * 100 + 10;
buf->resize(size);
total += size;
queue.push(buf);
}
for (size_t b = 0; b < 15; ++b) {
xia::buffer::handle buf = pool.request();
CHECK(buf->size() == 0);
CHECK(buf->capacity() == pool.size);
size_t size = buf->capacity() / 4 + b + 1;
buf->resize(size);
total += size;
queue.push(buf);
}
for (size_t b = 0; b < 5; ++b) {
xia::buffer::handle buf = pool.request();
size_t size = buf->capacity() - b * 100;
buf->resize(size);
total += size;
queue.push(buf);
}
CHECK(queue.count() == 25);
CHECK(queue.size() == total);
queue.compact();
CHECK(queue.count() == 9);
CHECK(queue.size() == total);
}
SUBCASE("copy") {
xia::buffer::queue queue;
size_t total = 0;
const xia::buffer::buffer_value inc_by = 0x11111111;
xia::buffer::buffer_value value = 0x11111111;
for (size_t b = 0; b < 5; ++b) {
xia::buffer::handle buf = pool.request();
CHECK(buf->size() == 0);
CHECK(buf->capacity() == pool.size);
size_t size = 100;
buf->resize(size, value);
value += inc_by;
total += size;
queue.push(buf);
}
for (size_t b = 0; b < 5; ++b) {
xia::buffer::handle buf = pool.request();
size_t size = 200;
buf->resize(size, value);
value += inc_by;
total += size;
queue.push(buf);
}
for (size_t b = 0; b < 5; ++b) {
xia::buffer::handle buf = pool.request();
CHECK(buf->size() == 0);
CHECK(buf->capacity() == pool.size);
size_t size = 300;
buf->resize(size, value);
value += inc_by;
total += size;
queue.push(buf);
}
CHECK(queue.count() == 15);
CHECK(queue.size() == total);
xia::buffer::buffer buffer;
queue.copy(buffer);
CHECK(buffer.size() == total);
CHECK(queue.count() == 0);
CHECK(queue.size() == 0);
value = 0x11111111;
size_t v = 0;
bool matched = true;
for (size_t b = 0; b < 5; ++b) {
for (size_t c = 0; c < 100; ++c, ++v) {
if (buffer[v] != value) {
matched = false;
}
}
value += inc_by;
}
CHECK(matched);
matched = true;
for (size_t b = 0; b < 5; ++b) {
for (size_t c = 0; c < 200; ++c, ++v) {
if (buffer[v] != value) {
matched = false;
}
}
value += inc_by;
}
CHECK(matched);
matched = true;
for (size_t b = 0; b < 5; ++b) {
for (size_t c = 0; c < 300; ++c, ++v) {
if (buffer[v] != value) {
matched = false;
}
}
value += inc_by;
}
CHECK(matched);
total = 0;
for (size_t b = 0; b < 10; ++b) {
xia::buffer::handle buf = pool.request();
CHECK(buf->size() == 0);
CHECK(buf->capacity() == pool.size);
size_t size = pool.size;
buf->resize(size, queue.count() + 1);
total += size;
queue.push(buf);
}
for (size_t b = 0; b < 10; ++b) {
xia::buffer::handle buf = pool.request();
CHECK(buf->size() == 0);
CHECK(buf->capacity() == pool.size);
size_t size = pool.size / 4;
buf->resize(size, queue.count() + 1);
total += size;
queue.push(buf);
}
buffer.clear();
xia::buffer::buffer_value_ptr bufp = new xia::buffer::buffer_value[total];
CHECK(bufp != nullptr);
queue.compact();
CHECK_THROWS_WITH_AS(queue.copy(bufp, total + 1), "not enough data in queue",
xia::buffer::error);
queue.copy(bufp, total);
v = 0;
value = 1;
matched = true;
for (size_t b = 0; b < 10; ++b) {
for (size_t c = 0; c < pool.size; ++c, ++v) {
if (bufp[v] != value) {
matched = false;
}
}
++value;
}
CHECK(matched);
matched = true;
for (size_t b = 0; b < 10; ++b) {
for (size_t c = 0; c < pool.size / 4; ++c, ++v) {
if (bufp[v] != value) {
matched = false;
}
}
++value;
}
CHECK(matched);
delete[] bufp;
}
pool.destroy();
}
}
| 36.077748 | 99 | 0.422828 | [
"vector"
] |
4f0ab9b889defc271229852482f327e4d5286549 | 514 | cpp | C++ | Code/src/OE/Engine/Object.cpp | mlomb/OrbitEngine | 41f053626f05782e81c2e48f5c87b04972f9be2c | [
"Apache-2.0"
] | 21 | 2018-06-26T16:37:36.000Z | 2022-01-11T01:19:42.000Z | Code/src/OE/Engine/Object.cpp | mlomb/OrbitEngine | 41f053626f05782e81c2e48f5c87b04972f9be2c | [
"Apache-2.0"
] | null | null | null | Code/src/OE/Engine/Object.cpp | mlomb/OrbitEngine | 41f053626f05782e81c2e48f5c87b04972f9be2c | [
"Apache-2.0"
] | 3 | 2019-10-01T14:10:50.000Z | 2021-11-19T20:30:18.000Z | #include "OE/Engine/Object.hpp"
#include "OE/Scripting/Mono/MonoMapping.hpp"
namespace OrbitEngine { namespace Engine {
/*
Object::Object(MonoType* type) : Object(mono_ptr_class_get(type)) { }
Object::Object(MonoClass* klass) : Object(mono_object_new(mono_domain_get(), klass)) { }
Object::Object(MonoObject* obj) : m_Object(obj)
{
uintptr_t ptr = (uintptr_t)this;
mono_field_set_value(obj, MonoMapping::FIELD_Object_pointer, &ptr);
}
*/
NATIVE_REFLECTION_BEGIN(Object)
NATIVE_REFLECTION_END()
} }
| 27.052632 | 89 | 0.743191 | [
"object"
] |
4f0d1d999dd8f8913585b2fbca11c969556e2123 | 2,862 | cpp | C++ | test/FTExtrudeFont-Test.cpp | fastcall81/ftgl_ue4 | 6f60b179ecfa0c4f1b0397841b8ce21fa965977c | [
"MIT"
] | 45 | 2015-08-26T13:51:55.000Z | 2022-03-04T04:29:32.000Z | test/FTExtrudeFont-Test.cpp | fastcall81/ftgl_ue4 | 6f60b179ecfa0c4f1b0397841b8ce21fa965977c | [
"MIT"
] | 9 | 2015-02-18T20:36:12.000Z | 2020-03-26T18:45:42.000Z | test/FTExtrudeFont-Test.cpp | fastcall81/ftgl_ue4 | 6f60b179ecfa0c4f1b0397841b8ce21fa965977c | [
"MIT"
] | 33 | 2015-02-18T20:27:28.000Z | 2022-03-04T04:28:01.000Z | #include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestCaller.h>
#include <cppunit/TestCase.h>
#include <cppunit/TestSuite.h>
#include <assert.h>
#include "Fontdefs.h"
#include "FTGL/ftgl.h"
#include "FTInternals.h"
extern void buildGLContext();
class FTExtrudeFontTest : public CppUnit::TestCase
{
CPPUNIT_TEST_SUITE(FTExtrudeFontTest);
CPPUNIT_TEST(testConstructor);
// CPPUNIT_TEST(testRender);
CPPUNIT_TEST(testBadDisplayList);
CPPUNIT_TEST(testGoodDisplayList);
CPPUNIT_TEST_SUITE_END();
public:
FTExtrudeFontTest() : CppUnit::TestCase("FTExtrudeFont Test")
{
}
FTExtrudeFontTest(const std::string& name) : CppUnit::TestCase(name) {}
~FTExtrudeFontTest()
{
}
void testConstructor()
{
buildGLContext();
FTExtrudeFont* extrudedFont = new FTExtrudeFont(FONT_FILE);
CPPUNIT_ASSERT_EQUAL(extrudedFont->Error(), 0);
CPPUNIT_ASSERT_EQUAL(GL_NO_ERROR, (int)glGetError());
delete extrudedFont;
}
void testRender()
{
buildGLContext();
FTExtrudeFont* extrudedFont = new FTExtrudeFont(FONT_FILE);
extrudedFont->Render(GOOD_ASCII_TEST_STRING);
CPPUNIT_ASSERT_EQUAL(extrudedFont->Error(), 0x97); // Invalid pixels per em
CPPUNIT_ASSERT_EQUAL(GL_NO_ERROR, (int)glGetError());
extrudedFont->FaceSize(18);
extrudedFont->Render(GOOD_ASCII_TEST_STRING);
CPPUNIT_ASSERT_EQUAL(extrudedFont->Error(), 0);
CPPUNIT_ASSERT_EQUAL(GL_NO_ERROR, (int)glGetError());
delete extrudedFont;
}
void testBadDisplayList()
{
buildGLContext();
FTExtrudeFont* extrudedFont = new FTExtrudeFont(FONT_FILE);
extrudedFont->FaceSize(18);
int glList = glGenLists(1);
glNewList(glList, GL_COMPILE);
extrudedFont->Render(GOOD_ASCII_TEST_STRING);
glEndList();
CPPUNIT_ASSERT_EQUAL((int)glGetError(), GL_INVALID_OPERATION);
delete extrudedFont;
}
void testGoodDisplayList()
{
buildGLContext();
FTExtrudeFont* extrudedFont = new FTExtrudeFont(FONT_FILE);
extrudedFont->FaceSize(18);
extrudedFont->UseDisplayList(false);
int glList = glGenLists(1);
glNewList(glList, GL_COMPILE);
extrudedFont->Render(GOOD_ASCII_TEST_STRING);
glEndList();
CPPUNIT_ASSERT_EQUAL(GL_NO_ERROR, (int)glGetError());
delete extrudedFont;
}
void setUp()
{}
void tearDown()
{}
private:
};
CPPUNIT_TEST_SUITE_REGISTRATION(FTExtrudeFontTest);
| 25.783784 | 89 | 0.609713 | [
"render"
] |
4f0d25f4002cb5cdc7f86e7b0485ff2c7a7f27ed | 2,695 | cpp | C++ | c++/leetcode/0023-Merge_k_Sorted_Lists-H.cpp | levendlee/leetcode | 35e274cb4046f6ec7112cd56babd8fb7d437b844 | [
"Apache-2.0"
] | 1 | 2020-03-02T10:56:22.000Z | 2020-03-02T10:56:22.000Z | c++/leetcode/0023-Merge_k_Sorted_Lists-H.cpp | levendlee/leetcode | 35e274cb4046f6ec7112cd56babd8fb7d437b844 | [
"Apache-2.0"
] | null | null | null | c++/leetcode/0023-Merge_k_Sorted_Lists-H.cpp | levendlee/leetcode | 35e274cb4046f6ec7112cd56babd8fb7d437b844 | [
"Apache-2.0"
] | null | null | null | // 23 Merge k Sorted Lists
// https://leetcode.com/problems/merge-k-sorted-lists
// version: 1; create time: 2019-10-22 20:43:03;
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeHelper(vector<ListNode*>& lists, int start, int end) {
if (start > end) {
return nullptr;
}
if (start == end) {
return lists[start];
}
int mid = start + (end - start) / 2;
auto left = mergeHelper(lists, start, mid);
auto right = mergeHelper(lists, mid+1, end);
ListNode* phead = new ListNode(0);
ListNode* node = phead;
while(left != nullptr || right != nullptr) {
if ((right == nullptr) ||
((left != nullptr) && (right != nullptr) &&
(left->val < right->val))) {
node->next = left;
node = node->next;
left = left->next;
} else {
node->next = right;
node = node->next;
right = right->next;
}
}
return phead->next;
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
return mergeHelper(lists, 0, lists.size() - 1);
}
};
// version: 2; create time: 2020-02-20 21:37:15;
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
// Current solution:
// K list, Avg size N elements
// Time Complexity: O(NKlogK)
// Space Complexity: O(logK)
// Priority queue solution:
// Time Complexity: O(NKlogK)
// Space Complexity: O(K)
ListNode* mergeList(vector<ListNode*>& lists, int lo, int hi) {
if (lo > hi) return nullptr;
if (lo == hi) return lists[lo];
int mid = lo + (hi - lo) / 2;
auto left = mergeList(lists, lo, mid);
auto right = mergeList(lists, mid + 1, hi);
auto pre_head = new ListNode(0);
auto node = pre_head;
while (left || right) {
if (!right || left && (left->val < right->val)) {
node->next = left;
left = left->next;
} else {
node->next = right;
right = right->next;
}
node = node->next;
}
auto head = pre_head->next;
delete pre_head;
return head;
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
return mergeList(lists, 0, lists.size() - 1);
}
};
| 26.95 | 73 | 0.502041 | [
"vector"
] |
4f0d9d8a0cc59fadf1d59fed6aae41e51a8666c8 | 950 | hpp | C++ | source/GeometricObjects/MeshTriangle.hpp | hadryansalles/ray-tracing-from-the-ground-up | 4ca02fca2cdd458767b4ab3df15b6cd20cb1f413 | [
"MIT"
] | 5 | 2021-09-24T12:22:08.000Z | 2022-03-23T06:54:02.000Z | source/GeometricObjects/MeshTriangle.hpp | hadryans/ray-tracing-from-the-ground-up | 4ca02fca2cdd458767b4ab3df15b6cd20cb1f413 | [
"MIT"
] | null | null | null | source/GeometricObjects/MeshTriangle.hpp | hadryans/ray-tracing-from-the-ground-up | 4ca02fca2cdd458767b4ab3df15b6cd20cb1f413 | [
"MIT"
] | 5 | 2021-08-14T22:26:11.000Z | 2022-03-04T09:13:39.000Z | #pragma once
#include "GeometricObject.hpp"
#include "../Utilities/Maths.hpp"
#include "Mesh.hpp"
class MeshTriangle : public GeometricObject {
public:
MeshTriangle(Mesh* mesh_ptr_ = NULL, const int i0 = 0, const int i1 = 0, const int i2 = 0);
MeshTriangle(const MeshTriangle& mesh_triangle);
MeshTriangle& operator=(const MeshTriangle& rhs);
virtual MeshTriangle* clone() const = 0;
virtual ~MeshTriangle();
void set_mesh_ptr(Mesh* mesh_ptr_);
Mesh* get_mesh_ptr() const;
void compute_normal(const bool reverse_normal);
virtual bool hit(const Ray& ray, float& t, ShadeRec& s) const = 0;
virtual Normal get_normal() const;
virtual BBox get_bounding_box() const;
protected:
Mesh* mesh_ptr;
int index0;
int index1;
int index2;
Normal normal;
float interpolate_u(const float beta, const float gamma) const;
float interpolate_v(const float beta, const float gamma) const;
}; | 27.941176 | 95 | 0.706316 | [
"mesh"
] |
4f1944bfdeb2ca95cc434407861bf42f63a8beac | 1,264 | cpp | C++ | src/mode_calc_center.cpp | ToruNiina/Coffee-mill | 343a6b89f7bc4645d596809aac9009db1c5ec0d8 | [
"MIT"
] | 4 | 2017-12-11T07:26:34.000Z | 2021-02-01T07:33:37.000Z | src/mode_calc_center.cpp | ToruNiina/Coffee-mill | 343a6b89f7bc4645d596809aac9009db1c5ec0d8 | [
"MIT"
] | null | null | null | src/mode_calc_center.cpp | ToruNiina/Coffee-mill | 343a6b89f7bc4645d596809aac9009db1c5ec0d8 | [
"MIT"
] | null | null | null | #include "mode_calc_center.hpp"
#include <mill/traj.hpp>
#include <mill/math/Vector.hpp>
#include <mill/util/cmdarg.hpp>
#include <toml/toml.hpp>
namespace mill
{
const char* mode_calc_center_usage() noexcept
{
return "usage: mill calc center [filename]\n"
"calculate the geometric center (it does not consider the weight)";
}
int mode_calc_center(std::deque<std::string_view> args)
{
const auto out = pop_argument<std::string>(args, "output")
.value_or("mill_center.dat");
if(args.empty())
{
log::error("mill calc center: too few arguments.");
log::error(mode_calc_center_usage());
return 1;
}
const auto filename = args.front();
if(filename == "help")
{
log::info(mode_calc_center_usage());
return 0;
}
std::size_t idx = 0;
std::cout << "# frame x y z\n";
for(const auto& frame : reader(filename))
{
Vector<double, 3> center(0.0, 0.0, 0.0);
for(const auto& p : frame)
{
center += p.position();
}
center /= static_cast<double>(frame.size());
std::cout << idx++ << ' ' << center[0] << ' '
<< center[1] << ' ' << center[2] << '\n';
}
return 0;
}
} // mill
| 23.849057 | 78 | 0.564082 | [
"vector"
] |
4f1a5111ea73c2c3d56772ce8514b05c81bf6959 | 6,531 | cpp | C++ | clang/lib/Tooling/Syntax/Pseudo/Grammar.cpp | LaudateCorpus1/llvm-project | ff2e0f0c1112558b3f30d8afec7c9882c33c79e3 | [
"Apache-2.0"
] | null | null | null | clang/lib/Tooling/Syntax/Pseudo/Grammar.cpp | LaudateCorpus1/llvm-project | ff2e0f0c1112558b3f30d8afec7c9882c33c79e3 | [
"Apache-2.0"
] | null | null | null | clang/lib/Tooling/Syntax/Pseudo/Grammar.cpp | LaudateCorpus1/llvm-project | ff2e0f0c1112558b3f30d8afec7c9882c33c79e3 | [
"Apache-2.0"
] | null | null | null | //===--- Grammar.cpp - Grammar for clang pseudo parser ----------*- C++-*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "clang/Tooling/Syntax/Pseudo/Grammar.h"
#include "clang/Basic/TokenKinds.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/FormatVariadic.h"
#include "llvm/Support/raw_ostream.h"
namespace clang {
namespace syntax {
namespace pseudo {
Rule::Rule(SymbolID Target, llvm::ArrayRef<SymbolID> Sequence)
: Target(Target), Size(static_cast<uint8_t>(Sequence.size())) {
assert(Sequence.size() <= Rule::MaxElements);
llvm::copy(Sequence, this->Sequence);
}
Grammar::Grammar(std::unique_ptr<GrammarTable> Table) : T(std::move(Table)) {
// start symbol is named _, binary search it.
auto It = llvm::partition_point(
T->Nonterminals,
[](const GrammarTable::Nonterminal &X) { return X.Name < "_"; });
assert(It != T->Nonterminals.end() && It->Name == "_" &&
"symbol _ must exist in the grammar!");
StartSymbol = It - T->Nonterminals.begin();
}
llvm::ArrayRef<Rule> Grammar::rulesFor(SymbolID SID) const {
assert(isNonterminal(SID));
const auto &R = T->Nonterminals[SID].RuleRange;
assert(R.end <= T->Rules.size());
return llvm::makeArrayRef(&T->Rules[R.start], R.end - R.start);
}
const Rule &Grammar::lookupRule(RuleID RID) const {
assert(RID < T->Rules.size());
return T->Rules[RID];
}
llvm::StringRef Grammar::symbolName(SymbolID SID) const {
if (isToken(SID))
return T->Terminals[symbolToToken(SID)];
return T->Nonterminals[SID].Name;
}
std::string Grammar::dumpRule(RuleID RID) const {
std::string Result;
llvm::raw_string_ostream OS(Result);
const Rule &R = T->Rules[RID];
OS << symbolName(R.Target) << " :=";
for (SymbolID SID : R.seq())
OS << " " << symbolName(SID);
return Result;
}
std::string Grammar::dumpRules(SymbolID SID) const {
assert(isNonterminal(SID));
std::string Result;
const auto &Range = T->Nonterminals[SID].RuleRange;
for (RuleID RID = Range.start; RID < Range.end; ++RID)
Result.append(dumpRule(RID)).push_back('\n');
return Result;
}
std::string Grammar::dump() const {
std::string Result;
llvm::raw_string_ostream OS(Result);
OS << "Nonterminals:\n";
for (SymbolID SID = 0; SID < T->Nonterminals.size(); ++SID)
OS << llvm::formatv(" {0} {1}\n", SID, symbolName(SID));
OS << "Rules:\n";
for (RuleID RID = 0; RID < T->Rules.size(); ++RID)
OS << llvm::formatv(" {0} {1}\n", RID, dumpRule(RID));
return OS.str();
}
std::vector<llvm::DenseSet<SymbolID>> firstSets(const Grammar &G) {
std::vector<llvm::DenseSet<SymbolID>> FirstSets(
G.table().Nonterminals.size());
auto ExpandFirstSet = [&FirstSets](SymbolID Target, SymbolID First) {
assert(isNonterminal(Target));
if (isToken(First))
return FirstSets[Target].insert(First).second;
bool Changed = false;
for (SymbolID SID : FirstSets[First])
Changed |= FirstSets[Target].insert(SID).second;
return Changed;
};
// A rule S := T ... implies elements in FIRST(S):
// - if T is a terminal, FIRST(S) contains T
// - if T is a nonterminal, FIRST(S) contains FIRST(T)
// Since FIRST(T) may not have been fully computed yet, FIRST(S) itself may
// end up being incomplete.
// We iterate until we hit a fixed point.
// (This isn't particularly efficient, but table building isn't on the
// critical path).
bool Changed = true;
while (Changed) {
Changed = false;
for (const auto &R : G.table().Rules)
// We only need to consider the first element because symbols are
// non-nullable.
Changed |= ExpandFirstSet(R.Target, R.seq().front());
}
return FirstSets;
}
std::vector<llvm::DenseSet<SymbolID>> followSets(const Grammar &G) {
auto FirstSets = firstSets(G);
std::vector<llvm::DenseSet<SymbolID>> FollowSets(
G.table().Nonterminals.size());
// Expand the follow set of a non-terminal symbol Y by adding all from the
// given symbol set.
auto ExpandFollowSet = [&FollowSets](SymbolID Y,
const llvm::DenseSet<SymbolID> &ToAdd) {
assert(isNonterminal(Y));
bool Changed = false;
for (SymbolID F : ToAdd)
Changed |= FollowSets[Y].insert(F).second;
return Changed;
};
// Follow sets is computed based on the following 3 rules, the computation
// is completed at a fixed point where there is no more new symbols can be
// added to any of the follow sets.
//
// Rule 1: add endmarker to the FOLLOW(S), where S is the start symbol.
FollowSets[G.startSymbol()].insert(tokenSymbol(tok::eof));
bool Changed = true;
while (Changed) {
Changed = false;
for (const auto &R : G.table().Rules) {
// Rule 2: for a rule X := ... Y Z, we add all symbols from FIRST(Z) to
// FOLLOW(Y).
for (size_t i = 0; i + 1 < R.seq().size(); ++i) {
if (isToken(R.seq()[i]))
continue;
// We only need to consider the next symbol because symbols are
// non-nullable.
SymbolID Next = R.seq()[i + 1];
if (isToken(Next))
// First set for a terminal is itself.
Changed |= ExpandFollowSet(R.seq()[i], {Next});
else
Changed |= ExpandFollowSet(R.seq()[i], FirstSets[Next]);
}
// Rule 3: for a rule X := ... Z, we add all symbols from FOLLOW(X) to
// FOLLOW(Z).
SymbolID Z = R.seq().back();
if (isNonterminal(Z))
Changed |= ExpandFollowSet(Z, FollowSets[R.Target]);
}
}
return FollowSets;
}
static llvm::ArrayRef<std::string> getTerminalNames() {
static const std::vector<std::string> *TerminalNames = []() {
static std::vector<std::string> TerminalNames;
TerminalNames.reserve(NumTerminals);
for (unsigned I = 0; I < NumTerminals; ++I) {
tok::TokenKind K = static_cast<tok::TokenKind>(I);
if (const auto *Punc = tok::getPunctuatorSpelling(K))
TerminalNames.push_back(Punc);
else
TerminalNames.push_back(llvm::StringRef(tok::getTokenName(K)).upper());
}
return &TerminalNames;
}();
return *TerminalNames;
}
GrammarTable::GrammarTable() : Terminals(getTerminalNames()) {}
} // namespace pseudo
} // namespace syntax
} // namespace clang
| 35.112903 | 80 | 0.637728 | [
"vector"
] |
b7b3671c85ef0be6b7f2218171e0bbe66c1a4dc3 | 949 | cpp | C++ | A2/FlirtWithGirls.cpp | MartinAparicioPons/Competitive-Programming | 58151df0ed08a5e4e605abefdd69fef1ecc10fa0 | [
"Apache-2.0"
] | 1 | 2019-09-29T03:58:35.000Z | 2019-09-29T03:58:35.000Z | A2/FlirtWithGirls.cpp | MartinAparicioPons/Competitive-Programming | 58151df0ed08a5e4e605abefdd69fef1ecc10fa0 | [
"Apache-2.0"
] | null | null | null | A2/FlirtWithGirls.cpp | MartinAparicioPons/Competitive-Programming | 58151df0ed08a5e4e605abefdd69fef1ecc10fa0 | [
"Apache-2.0"
] | null | null | null | #include <bits/stdc++.h>
#define scd(x) scanf("%d", &x)
#define scc(x) scanf("%c", &x)
#define scd2(x,y) scanf("%d %d", &x, &y)
#define prd(x) printf("%d\n", x)
#define dprd(x) printf("|| %d\n", x)
#define prd2(x,y) printf("%d %d\n", x,y)
#define dprd2(x,y) printf("||%d | %d\n", x,y)
#define prnl() printf("\n")
#define prc(c) printf("%c\n", c)
#define for0(i,n) for(i = 0; i < n; i++)
#define for1(i,n) for(i = 1; i <= n; i++)
#define _F first
#define _S second
#define _MP make_pair
#define _MT(x, y, z) _MP(x, _MP(y, z))
#define SQ(x) ((x)*(x))
using namespace std;
typedef vector<int> vi;
typedef pair<int, int> ii;
typedef long long ll;
bool isInRadius(int r, int x, int y){
return r*r >= x*x + y*y;
}
int main(){
int T, n, rad, x, y, result;
cin >> T;
while(T--){
cin >> n >> rad;
result = 0;
for(int i = 0; i < n; i++){
cin >> x >> y;
if(isInRadius(rad, x, y)){
result++;
}
}
cout << result << endl;
}
}
| 19.367347 | 45 | 0.546891 | [
"vector"
] |
b7b990973ae2f45d0f60680b3507ec8469f8ad13 | 3,198 | cpp | C++ | DepositService.cpp | NoahTarr/DCash-Wallet-Stripe-API | c9892b8b94460ffc27ba785edd1a4a6ff00d7a62 | [
"BSD-3-Clause"
] | null | null | null | DepositService.cpp | NoahTarr/DCash-Wallet-Stripe-API | c9892b8b94460ffc27ba785edd1a4a6ff00d7a62 | [
"BSD-3-Clause"
] | null | null | null | DepositService.cpp | NoahTarr/DCash-Wallet-Stripe-API | c9892b8b94460ffc27ba785edd1a4a6ff00d7a62 | [
"BSD-3-Clause"
] | null | null | null | #define RAPIDJSON_HAS_STDSTRING 1
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <iostream>
#include <map>
#include <string>
#include <sstream>
#include "DepositService.h"
#include "Database.h"
#include "ClientError.h"
#include "HTTPClientResponse.h"
#include "HttpClient.h"
#include "rapidjson/document.h"
#include "rapidjson/prettywriter.h"
#include "rapidjson/istreamwrapper.h"
#include "rapidjson/stringbuffer.h"
using namespace rapidjson;
using namespace std;
DepositService::DepositService() : HttpService("/deposits") {}
void DepositService::post(HTTPRequest *request, HTTPResponse *response)
{
User *user = getAuthenticatedUser(request);
Deposit *newDeposit;
int amount;
string stripeToken;
try
{
amount = stoi(request->formEncodedBody().get("amount"));
stripeToken = request->formEncodedBody().get("stripe_token");
}
catch (const std::exception &e)
{
//amount or stripe_token not in header
throw ClientError::badRequest();
}
//Stripe API
string stripeChargeId = getStripeChargeId(amount, stripeToken);
//Deposit Succeeded
user->balance += amount;
newDeposit = new Deposit();
newDeposit->to = user;
newDeposit->amount = amount;
newDeposit->stripe_charge_id = stripeChargeId;
m_db->deposits.push_back(newDeposit);
//Build json response object
Document document;
Document::AllocatorType &a = document.GetAllocator();
Value topObj;
topObj.SetObject();
topObj.AddMember("balance", user->balance, a);
Value depositsArray;
depositsArray.SetArray();
for (const auto deposit : m_db->deposits)
{
if (deposit->to->username.compare(user->username))
continue;
Value depositObj;
depositObj.SetObject();
depositObj.AddMember("to", deposit->to->username, a);
depositObj.AddMember("amount", deposit->amount, a);
depositObj.AddMember("stripe_charge_id", deposit->stripe_charge_id, a);
depositsArray.PushBack(depositObj, a);
}
topObj.AddMember("deposits", depositsArray, a);
responseJsonFinalizer(response, &document, &topObj);
}
string DepositService::getStripeChargeId(int amount, string stripeToken)
{
string stripeChargeId;
try
{
HttpClient client("api.stripe.com", 443, true);
client.set_basic_auth(m_db->stripe_secret_key, "");
WwwFormEncodedDict body;
body.set("amount", amount);
body.set("currency", "usd");
body.set("source", stripeToken);
HTTPClientResponse *clientResponse = client.post("/v1/charges", body.encode());
if (!clientResponse->success())
throw ClientError::badRequest();
Document *d = clientResponse->jsonBody();
stripeChargeId = (*d)["id"].GetString();
delete d;
}
catch (const std::exception &e)
{
//Maybe better to throw unknown error here? Just using badRequest() for grading
throw ClientError::badRequest();
}
return stripeChargeId;
}
| 28.553571 | 88 | 0.645403 | [
"object"
] |
b7bb265000672c8cfd769ee7753d0a48b8b9efcc | 4,539 | cc | C++ | tests/si/api.cc | project-arcana/arcana-samples | 7dbe2cab765d4d86c6e96b4ab542cac75608a0b0 | [
"MIT"
] | null | null | null | tests/si/api.cc | project-arcana/arcana-samples | 7dbe2cab765d4d86c6e96b4ab542cac75608a0b0 | [
"MIT"
] | null | null | null | tests/si/api.cc | project-arcana/arcana-samples | 7dbe2cab765d4d86c6e96b4ab542cac75608a0b0 | [
"MIT"
] | 1 | 2020-01-22T18:04:53.000Z | 2020-01-22T18:04:53.000Z | #include <nexus/test.hh>
#include <clean-core/vector.hh>
#include <structured-interface/si.hh>
namespace
{
struct foo
{
int a = 0;
float b = 1;
bool c = true;
};
template <class I>
void introspect(I&& i, foo& v)
{
i(v.a, "a");
i(v.b, "b");
i(v.c, "c");
}
}
TEST("si api", disabled)
{
// see https://docs.microsoft.com/en-us/dotnet/framework/wpf/controls/control-library
// see https://docs.microsoft.com/en-us/dotnet/framework/wpf/controls/controls-by-category
// see https://getbootstrap.com/docs/4.4/components
// see https://bootswatch.com/journal/
float my_float = 1;
int my_int = 1;
bool my_bool = false;
tg::color3 my_color;
tg::pos3 my_pos;
cc::string my_string;
foo my_foo;
cc::vector<float> some_floats = {1, 2, 3, 4};
if (auto w = si::window("Structured Interfaces"))
{
// basics
si::text("hello world");
si::text("int val: {}", my_int);
si::slider("some float", my_float, 0.0f, 1.0f);
si::slider("some int", my_int, -10, 10);
si::input("some int", my_int);
si::input("some color", my_color);
si::input("some string", my_string);
si::input("some foo", my_foo); // uses introspect
if (si::button("reset"))
{
my_float = 1;
my_int = 1;
}
si::checkbox("some checkable bool", my_bool);
si::toggle("some toggleable bool", my_bool);
if (si::radio_button("int = 2", my_int == 2))
my_int = 2;
si::radio_button("int = 3", my_int, 3);
si::radio_button("red", my_color, tg::color3::red);
si::radio_button("blue", my_color, tg::color3::blue);
si::dropdown("floats", my_float, some_floats);
si::listbox("floats", my_float, some_floats);
si::combobox("floats", my_float, some_floats);
// progress
// TODO: progress bar
// TODO: spinner + growing spinner
// buttons
// TODO: icons
// TODO: button groups
// 3D
if (si::gizmo(my_pos))
{
// TODO: update something
}
// grid
if (auto g = si::grid())
{
// TODO: allow per row, per col, individual cells
si::text("in container");
}
if (auto r = si::row()) // single row
{
}
// trees
if (auto t = si::tree_node("level A"))
{
if (auto t = si::tree_node("level A.1"))
{
si::text("A.1");
}
if (auto t = si::tree_node("level A.2"))
{
si::text("A.2");
}
}
// custom lists
#if 0
if (auto l = si::listbox("floats"))
{
si::item();
}
if (auto l = si::listbox("floats"))
{
si::item();
}
if (auto c = si::combobox("floats"))
{
}
#endif
// tooltips & popovers
si::text("hover over me").tooltip("I'm a tooltip!");
si::text("hover over me").tooltip([&] { si::text("complex tooltips possible."); });
{
auto t = si::text("advanced tooltip");
if (auto tt = si::tooltip(si::placement::centered_above()))
{
si::text("manual tooltips");
si::text("just like any element really");
}
}
// TODO: popover
// images
// TODO: si::image
// modals
// dialogs
// TODO: file dialog
// menu
// status bar
// collapsibles
// tabs
if (auto t = si::tabs())
{
if (auto t = si::tab("tab A"))
{
}
if (auto t = si::tab("tab B"))
{
}
}
// canvas
if (auto c = si::canvas({100, 100}))
{
// TODO: draw commands, vector api, something
}
// tables
// TODO: freezing, reordering, hiding, resizing, sorting, style
// layouting
// animation
// plotting
// cached computation
// cards
// carousel
// custom drawing
// docking
// themes and style
// pagination
// events
// TODO: click, hover
// TODO: disabled
// TODO: validation
// TODO: drag'n'drop
// render minimap
// custom controls
// transparency
}
}
| 22.033981 | 94 | 0.470588 | [
"render",
"vector",
"3d"
] |
b7c9a841a3383e6daa747de5657b44416b29726f | 5,466 | cpp | C++ | C++/Algorithms and data structures/lr4/code/binary_tree_heap/treeHandlers.cpp | po4yka/elementary-education-projects | f525a41eef2dee98e2a2ff8a7d063fac747d0d4b | [
"MIT"
] | 1 | 2020-09-01T20:22:30.000Z | 2020-09-01T20:22:30.000Z | C++/Algorithms and data structures/lr4/code/binary_tree_heap/treeHandlers.cpp | po4yka/EducationProjects | f525a41eef2dee98e2a2ff8a7d063fac747d0d4b | [
"MIT"
] | null | null | null | C++/Algorithms and data structures/lr4/code/binary_tree_heap/treeHandlers.cpp | po4yka/EducationProjects | f525a41eef2dee98e2a2ff8a7d063fac747d0d4b | [
"MIT"
] | null | null | null | #include "basicheaders.h"
#include "tree.h"
#include "customvector.h"
namespace lrstruct {
bool Node::stepLoopSwitcher = false;
bool Node::isStepByStepMode = false;
int Node::findDepth(Node* root) {
if(root == nullptr) {
return 0;
}
if(root->_left == nullptr && root->_right == nullptr) {
return 1;
}
else {
int l = findDepth(root->_left);
int r = findDepth(root->_right);
_depth = (1 + ((l > r) ? l : r));
return _depth;
//T O(n) S O(n)
}
}
int Node::findMinNode(Node* root) {
// Base case
if (root == nullptr)
return INT_MAX;
// Return minimum of 3 values:
// 1) Root's data 2) Min in Left Subtree
// 3) Min in right subtree
int res = root->_data.val;
int lres = findMinNode(root->_left);
int rres = findMinNode(root->_right);
if (lres < res)
res = lres;
if (rres < res)
res = rres;
return res;
}
int Node::findMaxNode(Node* root) {
// Base case
if (root == nullptr)
return INT_MIN;
// Return maximum of 3 values:
// 1) Root's data 2) Max in Left Subtree
// 3) Max in right subtree
int res = root->_data.val;
int lres = findMaxNode(root->_left);
int rres = findMaxNode(root->_right);
if (lres > res)
res = lres;
if (rres > res)
res = rres;
return res;
}
int Node::getLargestNumberBsd() {
if (_right == nullptr) {
return _data.val;
}
else {
_right->getLargestNumberBsd();
}
// never happen
return false;
}
int Node::getSmallestNumberBsd() {
if (_left == nullptr) {
return _data.val;
}
else {
_left->getSmallestNumberBsd();
}
// never happen
return false;
}
bool Node::isSymetrical() {
lrstruct::Vector <int> left_side;
lrstruct::Vector <int> right_side;
if(_left == nullptr || _right == nullptr)
return false;
_left->symetricalChecking(left_side);
_right->symetricalChecking(right_side);
if (left_side.size() != right_side.size()) {
return false;
}
for (int i = 0; static_cast<size_t>(i) < left_side.size(); i++) {
if (left_side[i] != right_side[i]) {
return false;
}
}
return true;
}
void Node::symetricalChecking(lrstruct::Vector<int>& vec) {
if (_left != nullptr && _right != nullptr) {
vec.push_back(0);
_left->symetricalChecking(vec);
_right->symetricalChecking(vec);
}
else if (_left != nullptr) {
vec.push_back(-1);
_left->symetricalChecking(vec);
}
else if (_right != nullptr) {
vec.push_back(1);
_right->symetricalChecking(vec);
}
else {
vec.push_back(2);
}
}
int Node::get_next_num(std::string &s, int &i, int& numb) {
qDebug() << "get_next_num() " << "for i = " << i << endl;
int start = i;
while (i != static_cast<int>(s.size()) && \
s[static_cast<unsigned long>(i)] != '(' && s[static_cast<unsigned long>(i)] != ')')
i++;
try {
numb = stoi(s.substr(static_cast<unsigned long>(start), static_cast<unsigned long>(i) - \
static_cast<unsigned long>(start)));
} catch (...) {
qDebug() << "Invalid input string!" << endl;
return 1;
}
return 0;
}
int Node::dfs(std::string &s, int &i, Node*& root) {
qDebug() << "dfs started " << "for i = " << i << endl;
// base case
int size = static_cast<int>(s.size());
if (i >= size || s[static_cast<unsigned long>(i)] == ')') {
// NULL is OK
root = nullptr;
return 0;
}
if(s[static_cast<unsigned long>(i)] == '(') i++;
if(s[static_cast<unsigned long>(i)] == '#') {
root = nullptr;
i++;
return 0;
}
int num;
if(get_next_num(s, i, num))
// something went wrong
return 1;
lrstruct::Data _data;
_data.val = num;
Node* temp_root = new Node(_data);
int check;
Node* left;
check = dfs(s, i, left);
if(check == 1)
return 1;
Node* right;
check = dfs(s, i, right);
if(check == 1)
return 1;
temp_root->_left = left;
temp_root->_right = right;
if (s[static_cast<unsigned long>(i)] == ')') i++;
root = temp_root;
// everything OK
return 0;
}
/**
* @brief Node::convertBracketRepresentationToBinTree
* @param inputStr
* Input string with bracket representation of binary tree
* @return
*/
int Node::convertBracketRepresentationToBinTree(std::string inputStr, Node*& root) {
qDebug() << "convertBracketRepresentationToBinTree()" << endl;
int i = 0;
int check = dfs(inputStr, i, root);
if(check == 1)
return 1;
return 0;
}
}
| 26.15311 | 102 | 0.483535 | [
"vector"
] |
b7ce853b580055c2b2005b2fc9bab2348d1c947c | 827 | cpp | C++ | 19_Special_Operators/2_5_Alloc_Dealloc/GlobalNew.cpp | Gridelen/cpp-prog-lang-ex | 70c40967f0d0ec07eaf2dc0bc6aac052a35f0631 | [
"MIT"
] | 2 | 2020-07-04T17:56:50.000Z | 2021-08-19T18:28:15.000Z | 19_Special_Operators/2_5_Alloc_Dealloc/GlobalNew.cpp | Gridelen/cpp-prog-lang-ex | 70c40967f0d0ec07eaf2dc0bc6aac052a35f0631 | [
"MIT"
] | null | null | null | 19_Special_Operators/2_5_Alloc_Dealloc/GlobalNew.cpp | Gridelen/cpp-prog-lang-ex | 70c40967f0d0ec07eaf2dc0bc6aac052a35f0631 | [
"MIT"
] | 1 | 2019-07-27T08:11:25.000Z | 2019-07-27T08:11:25.000Z | /*
19.2.5 Allocation and Deallocation
*/
#include <memory>
#include <iostream>
#include <vector>
void* operator new(size_t n) // individual object
{
auto p = malloc(n);
std::cout << "new " << n << " @ " << p << "\n";
return p;
}
void* operator new[](size_t n) // array
{
auto p = malloc(n);
std::cout << "new[] " << n << " @ " << p << "\n";
return p;
}
void operator delete(void* p, size_t n) // individual object
{
std::cout << "delete " << n << " @ " << p << "\n";
free(p);
}
void operator delete[](void* p, size_t n) // array
{
std::cout << "delete[] " << n << " @ " << p << "\n";
free(p);
}
void f()
{
std::vector<char> v(5);
v[0] = 1;
std::cout << v.size() << "\n";
}
int main()
{
f();
int* n1 = new int{ 3 };
delete n1;
double* d = new double[3];
delete d; // oops
return 0;
} | 16.54 | 60 | 0.509069 | [
"object",
"vector"
] |
b7cea071a29fb3a899c574c7f6f55ca0571357e1 | 2,271 | cc | C++ | CaloCluster/src/ClusterFinder.cc | resnegfk/Offline | 4ba81dad54486188fa83fea8c085438d104afbbc | [
"Apache-2.0"
] | 9 | 2020-03-28T00:21:41.000Z | 2021-12-09T20:53:26.000Z | CaloCluster/src/ClusterFinder.cc | resnegfk/Offline | 4ba81dad54486188fa83fea8c085438d104afbbc | [
"Apache-2.0"
] | 684 | 2019-08-28T23:37:43.000Z | 2022-03-31T22:47:45.000Z | CaloCluster/src/ClusterFinder.cc | resnegfk/Offline | 4ba81dad54486188fa83fea8c085438d104afbbc | [
"Apache-2.0"
] | 61 | 2019-08-16T23:28:08.000Z | 2021-12-20T08:29:48.000Z | #include "Offline/CaloCluster/inc/ClusterFinder.hh"
#include "Offline/CalorimeterGeom/inc/Calorimeter.hh"
#include "Offline/GeometryService/inc/GeomHandle.hh"
#include "Offline/RecoDataProducts/inc/CaloHit.hh"
#include <iostream>
#include <vector>
#include <algorithm>
namespace mu2e {
ClusterFinder::ClusterFinder(const Calorimeter& cal, const CaloHit* crystalSeed, double deltaTime, double ExpandCut, bool addSecondRing) :
cal_(&cal), crystalSeed_(crystalSeed), seedTime_(crystalSeed->time()), clusterList_(), crystalToVisit_(), isVisited_(cal.nCrystal()),
deltaTime_(deltaTime), ExpandCut_(ExpandCut), addSecondRing_(addSecondRing)
{}
void ClusterFinder::formCluster(std::vector<CaloCrystalList>& idHitVec)
{
std::fill(isVisited_.begin(), isVisited_.end(), false);
clusterList_.clear();
clusterList_.push_front(crystalSeed_);
crystalToVisit_.push(crystalSeed_->crystalID());
CaloCrystalList& liste = idHitVec[crystalSeed_->crystalID()];
liste.erase(std::find(liste.begin(), liste.end(), crystalSeed_));
while (!crystalToVisit_.empty())
{
int visitId = crystalToVisit_.front();
isVisited_[visitId] = true;
std::vector<int> neighborsId = cal_->crystal(visitId).neighbors();
if (addSecondRing_) neighborsId.insert(neighborsId.end(), cal_->nextNeighbors(visitId).begin(), cal_->nextNeighbors(visitId).end());
for (auto& iId : neighborsId)
{
if (isVisited_[iId]) continue;
isVisited_[iId] = true;
CaloCrystalList& list = idHitVec[iId];
auto it=list.begin();
while(it != list.end())
{
CaloHit const* hit = *it;
if (std::abs(hit->time() - seedTime_) < deltaTime_)
{
if (hit->energyDep() > ExpandCut_) crystalToVisit_.push(iId);
clusterList_.push_front(hit);
it = list.erase(it);
}
else ++it;
}
}
crystalToVisit_.pop();
}
// make sure to sort proto0cluster by energy
clusterList_.sort([](const CaloHit* lhs, const CaloHit* rhs) {return lhs->energyDep() > rhs->energyDep();});
}
}
| 30.689189 | 149 | 0.624835 | [
"vector"
] |
b7cf2caf44be87ba4178ba2033273a487364632b | 22,084 | cpp | C++ | lg/solvers/htd-master/src/htd/BucketEliminationTreeDecompositionAlgorithm.cpp | vuphan314/dpo | e24fe63fc3321c0cd6d2179c3300596b91082ab5 | [
"MIT"
] | 14 | 2020-01-31T23:02:39.000Z | 2021-12-26T06:00:13.000Z | lg/solvers/htd-master/src/htd/BucketEliminationTreeDecompositionAlgorithm.cpp | vuphan314/dpo | e24fe63fc3321c0cd6d2179c3300596b91082ab5 | [
"MIT"
] | 3 | 2020-06-27T21:11:46.000Z | 2020-06-27T21:11:47.000Z | lg/solvers/htd-master/src/htd/BucketEliminationTreeDecompositionAlgorithm.cpp | vuphan314/dpo | e24fe63fc3321c0cd6d2179c3300596b91082ab5 | [
"MIT"
] | 2 | 2020-08-08T03:04:30.000Z | 2021-05-21T04:56:02.000Z | /*
* File: BucketEliminationTreeDecompositionAlgorithm.cpp
*
* Author: ABSEHER Michael (abseher@dbai.tuwien.ac.at)
*
* Copyright 2015-2017, Michael Abseher
* E-Mail: <abseher@dbai.tuwien.ac.at>
*
* This file is part of htd.
*
* htd 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.
*
* htd 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 htd. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef HTD_HTD_BUCKETELIMINATIONTREEDECOMPOSITIONALGORITHM_CPP
#define HTD_HTD_BUCKETELIMINATIONTREEDECOMPOSITIONALGORITHM_CPP
#include <htd/Globals.hpp>
#include <htd/Helpers.hpp>
#include <htd/BucketEliminationTreeDecompositionAlgorithm.hpp>
#include <htd/BucketEliminationGraphDecompositionAlgorithm.hpp>
#include <htd/ConnectedComponentAlgorithmFactory.hpp>
#include <htd/GraphDecompositionFactory.hpp>
#include <htd/TreeDecompositionFactory.hpp>
#include <htd/GraphLabeling.hpp>
#include <htd/ILabelingFunction.hpp>
#include <htd/IMutableTreeDecomposition.hpp>
#include <htd/CompressionOperation.hpp>
#include <htd/BreadthFirstGraphTraversal.hpp>
#include <htd/GraphPreprocessorFactory.hpp>
#include <htd/IGraphPreprocessor.hpp>
#include <algorithm>
#include <cstdarg>
#include <memory>
#include <unordered_map>
#include <utility>
#include <vector>
/**
* Private implementation details of class htd::BucketEliminationTreeDecompositionAlgorithm.
*/
struct htd::BucketEliminationTreeDecompositionAlgorithm::Implementation
{
/**
* Constructor for the implementation details structure.
*
* @param[in] manager The management instance to which the current object instance belongs.
*/
Implementation(const htd::LibraryInstance * const manager) : managementInstance_(manager), baseAlgorithm_(new htd::BucketEliminationGraphDecompositionAlgorithm(manager)), labelingFunctions_(), postProcessingOperations_()
{
}
/**
* Copy constructor for the implementation details structure.
*
* @param[in] original The original implementation details structure.
*/
Implementation(const Implementation & original) : managementInstance_(original.managementInstance_), baseAlgorithm_(original.baseAlgorithm_->clone()), labelingFunctions_(), postProcessingOperations_()
{
for (htd::ILabelingFunction * labelingFunction : original.labelingFunctions_)
{
#ifndef HTD_USE_VISUAL_STUDIO_COMPATIBILITY_MODE
labelingFunctions_.push_back(labelingFunction->clone());
#else
labelingFunctions_.push_back(labelingFunction->cloneLabelingFunction());
#endif
}
for (htd::ITreeDecompositionManipulationOperation * postProcessingOperation : original.postProcessingOperations_)
{
#ifndef HTD_USE_VISUAL_STUDIO_COMPATIBILITY_MODE
postProcessingOperations_.push_back(postProcessingOperation->clone());
#else
postProcessingOperations_.push_back(postProcessingOperation->cloneTreeDecompositionManipulationOperation());
#endif
}
}
virtual ~Implementation()
{
delete baseAlgorithm_;
for (auto & labelingFunction : labelingFunctions_)
{
delete labelingFunction;
}
for (auto & postProcessingOperation : postProcessingOperations_)
{
delete postProcessingOperation;
}
}
/**
* The management instance to which the current object instance belongs.
*/
const htd::LibraryInstance * managementInstance_;
/**
* The underlying graph decomposition algorithm based on bucket elimination.
*/
htd::BucketEliminationGraphDecompositionAlgorithm * baseAlgorithm_;
/**
* The labeling functions which are applied after the decomposition was computed.
*/
std::vector<htd::ILabelingFunction *> labelingFunctions_;
/**
* The manipuation operations which are applied after the decomposition was computed.
*/
std::vector<htd::ITreeDecompositionManipulationOperation *> postProcessingOperations_;
/**
* Compute a new mutable tree decompostion of the given graph.
*
* @param[in] graph The graph which shall be decomposed.
* @param[in] preprocessedGraph The input graph in preprocessed format.
* @param[in] maxBagSize The upper bound for the maximum bag size of the decomposition.
* @param[in] maxIterationCount The maximum number of iterations resulting in a higher maximum bag size than maxBagSize after which a null-pointer is returned.
*
* @return A pair consisting of a mutable tree decompostion of the given graph or a null-pointer in case that no decomposition with a appropriate maximum bag size could be found after maxIterationCount iterations and the number of iterations actually needed to find the decomposition at hand.
*/
std::pair<htd::IMutableTreeDecomposition *, std::size_t> computeMutableDecomposition(const htd::IMultiHypergraph & graph, const htd::IPreprocessedGraph & preprocessedGraph, std::size_t maxBagSize, std::size_t maxIterationCount) const;
};
htd::BucketEliminationTreeDecompositionAlgorithm::BucketEliminationTreeDecompositionAlgorithm(const htd::LibraryInstance * const manager) : implementation_(new Implementation(manager))
{
}
htd::BucketEliminationTreeDecompositionAlgorithm::BucketEliminationTreeDecompositionAlgorithm(const htd::LibraryInstance * const manager, const std::vector<htd::IDecompositionManipulationOperation *> & manipulationOperations) : implementation_(new Implementation(manager))
{
setManipulationOperations(manipulationOperations);
}
htd::BucketEliminationTreeDecompositionAlgorithm::BucketEliminationTreeDecompositionAlgorithm(const htd::BucketEliminationTreeDecompositionAlgorithm & original) : implementation_(new Implementation(*(original.implementation_)))
{
}
htd::BucketEliminationTreeDecompositionAlgorithm::~BucketEliminationTreeDecompositionAlgorithm()
{
}
htd::ITreeDecomposition * htd::BucketEliminationTreeDecompositionAlgorithm::computeDecomposition(const htd::IMultiHypergraph & graph) const
{
return computeDecomposition(graph, std::vector<htd::IDecompositionManipulationOperation *>());
}
htd::ITreeDecomposition * htd::BucketEliminationTreeDecompositionAlgorithm::computeDecomposition(const htd::IMultiHypergraph & graph, const std::vector<htd::IDecompositionManipulationOperation *> & manipulationOperations) const
{
return computeDecomposition(graph, manipulationOperations, (std::size_t)-1, 1).first;
}
std::pair<htd::ITreeDecomposition *, std::size_t> htd::BucketEliminationTreeDecompositionAlgorithm::computeDecomposition(const htd::IMultiHypergraph & graph, std::size_t maxBagSize, std::size_t maxIterationCount) const
{
return computeDecomposition(graph, std::vector<htd::IDecompositionManipulationOperation *>(), maxBagSize, maxIterationCount);
}
std::pair<htd::ITreeDecomposition *, std::size_t> htd::BucketEliminationTreeDecompositionAlgorithm::computeDecomposition(const htd::IMultiHypergraph & graph, const std::vector<htd::IDecompositionManipulationOperation *> & manipulationOperations, std::size_t maxBagSize, std::size_t maxIterationCount) const
{
htd::IGraphPreprocessor * preprocessor = implementation_->managementInstance_->graphPreprocessorFactory().createInstance();
htd::IPreprocessedGraph * preprocessedGraph = preprocessor->prepare(graph);
std::pair<htd::ITreeDecomposition *, std::size_t> ret =
computeDecomposition(graph, *preprocessedGraph, manipulationOperations, maxBagSize, maxIterationCount);
delete preprocessedGraph;
delete preprocessor;
return ret;
}
htd::ITreeDecomposition * htd::BucketEliminationTreeDecompositionAlgorithm::computeDecomposition(const htd::IMultiHypergraph & graph, const htd::IPreprocessedGraph & preprocessedGraph) const
{
return computeDecomposition(graph, preprocessedGraph, std::vector<htd::IDecompositionManipulationOperation *>());
}
htd::ITreeDecomposition * htd::BucketEliminationTreeDecompositionAlgorithm::computeDecomposition(const htd::IMultiHypergraph & graph, const htd::IPreprocessedGraph & preprocessedGraph, const std::vector<htd::IDecompositionManipulationOperation *> & manipulationOperations) const
{
return computeDecomposition(graph, preprocessedGraph, manipulationOperations, (std::size_t)-1, 1).first;
}
std::pair<htd::ITreeDecomposition *, std::size_t> htd::BucketEliminationTreeDecompositionAlgorithm::computeDecomposition(const htd::IMultiHypergraph & graph, const htd::IPreprocessedGraph & preprocessedGraph, std::size_t maxBagSize, std::size_t maxIterationCount) const
{
return computeDecomposition(graph, preprocessedGraph, std::vector<htd::IDecompositionManipulationOperation *>(), maxBagSize, maxIterationCount);
}
std::pair<htd::ITreeDecomposition *, std::size_t> htd::BucketEliminationTreeDecompositionAlgorithm::computeDecomposition(const htd::IMultiHypergraph & graph, const htd::IPreprocessedGraph & preprocessedGraph, const std::vector<htd::IDecompositionManipulationOperation *> & manipulationOperations, std::size_t maxBagSize, std::size_t maxIterationCount) const
{
std::pair<htd::IMutableTreeDecomposition *, std::size_t> ret = implementation_->computeMutableDecomposition(graph, preprocessedGraph, maxBagSize, maxIterationCount);
htd::IMutableTreeDecomposition * decomposition = ret.first;
if (decomposition != nullptr)
{
std::vector<htd::ILabelingFunction *> labelingFunctions;
std::vector<htd::ITreeDecompositionManipulationOperation *> postProcessingOperations;
for (htd::IDecompositionManipulationOperation * operation : manipulationOperations)
{
htd::ILabelingFunction * labelingFunction = dynamic_cast<htd::ILabelingFunction *>(operation);
if (labelingFunction != nullptr)
{
labelingFunctions.push_back(labelingFunction);
}
htd::ITreeDecompositionManipulationOperation * manipulationOperation = dynamic_cast<htd::ITreeDecompositionManipulationOperation *>(operation);
if (manipulationOperation != nullptr)
{
postProcessingOperations.push_back(manipulationOperation);
}
}
for (const htd::ITreeDecompositionManipulationOperation * operation : implementation_->postProcessingOperations_)
{
operation->apply(graph, *decomposition);
}
for (htd::ITreeDecompositionManipulationOperation * operation : postProcessingOperations)
{
operation->apply(graph, *decomposition);
}
for (const htd::ILabelingFunction * labelingFunction : implementation_->labelingFunctions_)
{
for (htd::vertex_t vertex : decomposition->vertices())
{
htd::ILabelCollection * labelCollection = decomposition->labelings().exportVertexLabelCollection(vertex);
htd::ILabel * newLabel = labelingFunction->computeLabel(decomposition->bagContent(vertex), *labelCollection);
delete labelCollection;
decomposition->setVertexLabel(labelingFunction->name(), vertex, newLabel);
}
}
for (htd::ILabelingFunction * labelingFunction : labelingFunctions)
{
for (htd::vertex_t vertex : decomposition->vertices())
{
htd::ILabelCollection * labelCollection = decomposition->labelings().exportVertexLabelCollection(vertex);
htd::ILabel * newLabel = labelingFunction->computeLabel(decomposition->bagContent(vertex), *labelCollection);
delete labelCollection;
decomposition->setVertexLabel(labelingFunction->name(), vertex, newLabel);
}
}
}
for (htd::IDecompositionManipulationOperation * operation : manipulationOperations)
{
delete operation;
}
return ret;
}
htd::ITreeDecomposition * htd::BucketEliminationTreeDecompositionAlgorithm::computeDecomposition(const htd::IMultiHypergraph & graph, int manipulationOperationCount, ...) const
{
va_list arguments;
va_start(arguments, manipulationOperationCount);
std::vector<htd::IDecompositionManipulationOperation *> manipulationOperations;
for (int manipulationOperationIndex = 0; manipulationOperationIndex < manipulationOperationCount; manipulationOperationIndex++)
{
manipulationOperations.push_back(va_arg(arguments, htd::IDecompositionManipulationOperation *));
}
va_end(arguments);
return computeDecomposition(graph, manipulationOperations);
}
htd::ITreeDecomposition * htd::BucketEliminationTreeDecompositionAlgorithm::computeDecomposition(const htd::IMultiHypergraph & graph, const htd::IPreprocessedGraph & preprocessedGraph, int manipulationOperationCount, ...) const
{
va_list arguments;
va_start(arguments, manipulationOperationCount);
std::vector<htd::IDecompositionManipulationOperation *> manipulationOperations;
for (int manipulationOperationIndex = 0; manipulationOperationIndex < manipulationOperationCount; manipulationOperationIndex++)
{
manipulationOperations.push_back(va_arg(arguments, htd::IDecompositionManipulationOperation *));
}
va_end(arguments);
return computeDecomposition(graph, preprocessedGraph, manipulationOperations);
}
void htd::BucketEliminationTreeDecompositionAlgorithm::setOrderingAlgorithm(htd::IOrderingAlgorithm * algorithm)
{
implementation_->baseAlgorithm_->setOrderingAlgorithm(algorithm);
}
void htd::BucketEliminationTreeDecompositionAlgorithm::setManipulationOperations(const std::vector<htd::IDecompositionManipulationOperation *> & manipulationOperations)
{
for (auto & labelingFunction : implementation_->labelingFunctions_)
{
delete labelingFunction;
}
for (auto & postProcessingOperation : implementation_->postProcessingOperations_)
{
delete postProcessingOperation;
}
implementation_->labelingFunctions_.clear();
implementation_->postProcessingOperations_.clear();
addManipulationOperations(manipulationOperations);
}
void htd::BucketEliminationTreeDecompositionAlgorithm::addManipulationOperation(htd::IDecompositionManipulationOperation * manipulationOperation)
{
bool assigned = false;
htd::ILabelingFunction * labelingFunction = dynamic_cast<htd::ILabelingFunction *>(manipulationOperation);
if (labelingFunction != nullptr)
{
implementation_->labelingFunctions_.emplace_back(labelingFunction);
assigned = true;
}
htd::ITreeDecompositionManipulationOperation * newManipulationOperation = dynamic_cast<htd::ITreeDecompositionManipulationOperation *>(manipulationOperation);
if (newManipulationOperation != nullptr)
{
implementation_->postProcessingOperations_.emplace_back(newManipulationOperation);
assigned = true;
}
if (!assigned)
{
delete manipulationOperation;
}
}
void htd::BucketEliminationTreeDecompositionAlgorithm::addManipulationOperations(const std::vector<htd::IDecompositionManipulationOperation *> & manipulationOperations)
{
for (htd::IDecompositionManipulationOperation * operation : manipulationOperations)
{
addManipulationOperation(operation);
}
}
bool htd::BucketEliminationTreeDecompositionAlgorithm::isSafelyInterruptible(void) const
{
return false;
}
const htd::LibraryInstance * htd::BucketEliminationTreeDecompositionAlgorithm::managementInstance(void) const HTD_NOEXCEPT
{
return implementation_->managementInstance_;
}
void htd::BucketEliminationTreeDecompositionAlgorithm::setManagementInstance(const htd::LibraryInstance * const manager)
{
HTD_ASSERT(manager != nullptr)
implementation_->managementInstance_ = manager;
}
bool htd::BucketEliminationTreeDecompositionAlgorithm::isCompressionEnabled(void) const
{
return implementation_->baseAlgorithm_->isCompressionEnabled();
}
void htd::BucketEliminationTreeDecompositionAlgorithm::setCompressionEnabled(bool compressionEnabled)
{
implementation_->baseAlgorithm_->setCompressionEnabled(compressionEnabled);
}
bool htd::BucketEliminationTreeDecompositionAlgorithm::isComputeInducedEdgesEnabled(void) const
{
return implementation_->baseAlgorithm_->isComputeInducedEdgesEnabled();
}
void htd::BucketEliminationTreeDecompositionAlgorithm::setComputeInducedEdgesEnabled(bool computeInducedEdgesEnabled)
{
implementation_->baseAlgorithm_->setComputeInducedEdgesEnabled(computeInducedEdgesEnabled);
}
htd::BucketEliminationTreeDecompositionAlgorithm * htd::BucketEliminationTreeDecompositionAlgorithm::clone(void) const
{
return new htd::BucketEliminationTreeDecompositionAlgorithm(*this);
}
std::pair<htd::IMutableTreeDecomposition *, std::size_t> htd::BucketEliminationTreeDecompositionAlgorithm::Implementation::computeMutableDecomposition(const htd::IMultiHypergraph & graph, const htd::IPreprocessedGraph & preprocessedGraph, std::size_t maxBagSize, std::size_t maxIterationCount) const
{
htd::IMutableTreeDecomposition * ret = managementInstance_->treeDecompositionFactory().createInstance();
std::size_t iterations = 1;
if (graph.vertexCount() > 0)
{
std::pair<htd::IGraphDecomposition *, std::size_t> graphDecomposition = baseAlgorithm_->computeDecomposition(graph, preprocessedGraph, maxBagSize, maxIterationCount);
if (graphDecomposition.first != nullptr)
{
htd::IMutableGraphDecomposition & mutableGraphDecomposition = managementInstance_->graphDecompositionFactory().accessMutableInstance(*(graphDecomposition.first));
if (!managementInstance_->isTerminated())
{
if (mutableGraphDecomposition.edgeCount() + 1 != mutableGraphDecomposition.vertexCount() || mutableGraphDecomposition.isolatedVertexCount() > 0)
{
htd::IConnectedComponentAlgorithm * connectedComponentAlgorithm = managementInstance_->connectedComponentAlgorithmFactory().createInstance();
HTD_ASSERT(connectedComponentAlgorithm != nullptr)
std::vector<std::vector<htd::vertex_t>> components;
connectedComponentAlgorithm->determineComponents(*(graphDecomposition.first), components);
delete connectedComponentAlgorithm;
std::size_t componentCount = components.size();
if (componentCount > 1)
{
for (htd::index_t index = 0; index < componentCount - 1; ++index)
{
const std::vector<htd::vertex_t> & component1 = components[index];
const std::vector<htd::vertex_t> & component2 = components[index + 1];
/* Coverity complains about std::rand() being not safe for security related operations. We are happy with a pseudo-random number here. */
// coverity[dont_call]
htd::vertex_t vertex1 = component1[std::rand() % component1.size()];
/* Coverity complains about std::rand() being not safe for security related operations. We are happy with a pseudo-random number here. */
// coverity[dont_call]
htd::vertex_t vertex2 = component2[std::rand() % component2.size()];
mutableGraphDecomposition.addEdge(vertex1, vertex2);
}
}
}
htd::vertex_t node = htd::Vertex::UNKNOWN;
std::unordered_map<htd::vertex_t, htd::vertex_t> vertexMapping;
htd::BreadthFirstGraphTraversal graphTraversal(managementInstance_);
/* Coverity complains about std::rand() being not safe for security related operations. We are happy with a pseudo-random number here. */
// coverity[dont_call]
graphTraversal.traverse(*(graphDecomposition.first), graphDecomposition.first->vertexAtPosition(std::rand() % graphDecomposition.first->vertexCount()), [&](htd::vertex_t vertex, htd::vertex_t predecessor, std::size_t distanceFromStartingVertex)
{
HTD_UNUSED(distanceFromStartingVertex)
if (predecessor == htd::Vertex::UNKNOWN)
{
node = ret->insertRoot(std::move(mutableGraphDecomposition.mutableBagContent(vertex)),
std::move(mutableGraphDecomposition.mutableInducedHyperedges(vertex)));
}
else
{
node = ret->addChild(vertexMapping.at(predecessor),
std::move(mutableGraphDecomposition.mutableBagContent(vertex)),
std::move(mutableGraphDecomposition.mutableInducedHyperedges(vertex)));
}
vertexMapping.emplace(vertex, node);
});
}
else
{
delete ret;
ret = nullptr;
}
delete graphDecomposition.first;
}
else
{
delete ret;
ret = nullptr;
}
iterations = graphDecomposition.second;
}
else
{
ret->insertRoot();
}
return std::make_pair(ret, iterations);
}
#endif /* HTD_HTD_BUCKETELIMINATIONTREEDECOMPOSITIONALGORITHM_CPP */
| 42.225621 | 357 | 0.72111 | [
"object",
"vector"
] |
b7d1b758baaf1fd501d765a421bb44ed352a1352 | 1,848 | cpp | C++ | engine/src/Font.cpp | irishpatrick/sdl-game | 23ff8330fe2aaa765119df40d62e50570f606f07 | [
"MIT-0",
"MIT"
] | null | null | null | engine/src/Font.cpp | irishpatrick/sdl-game | 23ff8330fe2aaa765119df40d62e50570f606f07 | [
"MIT-0",
"MIT"
] | null | null | null | engine/src/Font.cpp | irishpatrick/sdl-game | 23ff8330fe2aaa765119df40d62e50570f606f07 | [
"MIT-0",
"MIT"
] | null | null | null | #include "Font.hpp"
const std::string& chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 ";
namespace engine
{
Font::Font()
{
}
Font::~Font()
{
}
void Font::init(const std::string& fn, int size)
{
font = TTF_OpenFont(fn.c_str(), size);
if (font == nullptr)
{
return;
}
SDL_Color color = {255,255,255,255};
for (unsigned int i = 0; i < chars.size(); i++)
{
char c = chars.at(i);
GlyphMetrics* gm = (GlyphMetrics*)malloc(sizeof(GlyphMetrics));
metrics.push_back(gm);
TTF_GlyphMetrics(font, c, &gm->minx, &gm->maxx, &gm->miny, &gm->maxy, &gm->advance);
glyphCache.push_back(TTF_RenderGlyph_Solid(font, c, color));
}
}
SDL_Surface* Font::getChar(char c)
{
return glyphCache[static_cast<int>(chars.find(c))];
}
void Font::renderString(SDL_Surface* out, const std::string& str, int x0, int y0)
{
int x = x0;
int y = y0;
for (auto& c : str)
{
//std::cout << "render " << c << std::endl;
size_t index = chars.find(c);
GlyphMetrics* gm = metrics[static_cast<int>(index)];
SDL_Surface* surf = glyphCache[static_cast<int>(index)];
SDL_Rect rect;
//SDL_Rect srcRect;
rect.x = x;// +gm->minx;
rect.y = y + TTF_FontDescent(font);
//rect.y = y + gm->maxy;
// set rect w
//rect.w = (gm->maxx - gm->minx);
// set rect h
//rect.h = (gm->maxy - gm->miny);
//std::cout << "rect: {" << rect.x << "," << rect.y << "}" << std::endl;
// blit to surface
SDL_BlitSurface(surf, nullptr, out, &rect);
// increment xs
x += gm->advance;
}
}
int Font::getLineSkip()
{
return TTF_FontLineSkip(font);
}
int Font::getCharWidth(const std::string& c)
{
GlyphMetrics* gm = metrics[static_cast<int>(chars.find(c))];
return gm->advance;
}
}
| 22.536585 | 94 | 0.584957 | [
"render"
] |
b7d646014fb8407ea3056b9c5c49d7a2bf66948c | 16,057 | cpp | C++ | modules/pygauss/src/array_like_numpy.cpp | shapelets/shapelets-compute | 1dffe62d4eab9b1115b95bda5aaa7a3392024d72 | [
"MIT",
"BSD-3-Clause"
] | 14 | 2021-05-28T09:43:28.000Z | 2022-03-31T01:44:55.000Z | modules/pygauss/src/array_like_numpy.cpp | shapelets/shapelets-compute | 1dffe62d4eab9b1115b95bda5aaa7a3392024d72 | [
"MIT",
"BSD-3-Clause"
] | 14 | 2021-05-31T11:48:12.000Z | 2022-03-06T20:30:34.000Z | modules/pygauss/src/array_like_numpy.cpp | shapelets/shapelets-compute | 1dffe62d4eab9b1115b95bda5aaa7a3392024d72 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | /* Copyright (c) 2021 Grumpy Cat Software S.L.
*
* This Source Code is licensed under the MIT 2.0 license.
* the terms can be found in LICENSE.md at the root of
* this project, or at http://mozilla.org/MPL/2.0/.
*/
#include <arrayfire.h>
#include <spdlog/spdlog.h>
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <optional>
#include <pygauss.h>
namespace spd = spdlog;
namespace py = pybind11;
using dtype_converter = py::detail::type_caster<af::dtype>;
using half_float::half;
namespace pygauss::arraylike {
py::buffer_info numpy_buffer_protocol(const af::array &self) {
// Ensure all the computations have completed.
af::eval(self);
// get the type
auto fmt = dtype_converter::cast(self.type());
// get the scalar size
ssize_t scalarSize = fmt.itemsize();
// get the number of dimensions
auto dimCount = self.numdims();
// get the shape
auto shape = self.dims();
// convert shape
std::vector<ssize_t> dimensions(dimCount);
for (size_t i = 0; i < dimCount; i++) {
dimensions[i] = shape[i];
}
// create strides
std::vector<ssize_t> strides(dimCount, scalarSize);
for (size_t i = 1; i < dimCount; ++i)
strides[i] = strides[i - 1] * shape[i - 1];
af_backend arr_backend = AF_BACKEND_DEFAULT;
af_get_backend_id(&arr_backend, self.get());
auto isDirect = arr_backend == AF_BACKEND_CPU;
void *data = nullptr;
switch (self.type()) {
case af::dtype::b8:
case af::dtype::u8:
data = isDirect ? self.device<unsigned char>() : self.host<unsigned char>();
break;
case af::dtype::s16:
data = isDirect ? self.device<short>() : self.host<short>();
break;
case af::dtype::u16:
data = isDirect ? self.device<unsigned short>() : self.host<unsigned short>();
break;
case af::dtype::f16:
data = isDirect ? self.device<af::half>() : self.host<af::half>();
break;
case af::dtype::f32:
data = isDirect ? self.device<float>() : self.host<float>();
break;
case af::dtype::s32:
data = isDirect ? self.device<int>() : self.host<int>();
break;
case af::dtype::u32:
data = isDirect ? self.device<unsigned int>() : self.host<unsigned int>();
break;
case af::dtype::u64:
data = isDirect ? self.device<unsigned long long>() : self.host<unsigned long long>();
break;
case af::dtype::s64:
data = isDirect ? self.device<long long>() : self.host<long long>();
break;
case af::dtype::f64:
data = isDirect ? self.device<double>() : self.host<double>();
break;
case af::dtype::c32:
data = isDirect ? self.device<af::cfloat>() : self.host<af::cfloat>();
break;
case af::dtype::c64:
data = isDirect ? self.device<af::cdouble>() : self.host<af::cdouble>();
break;
}
auto capsule = isDirect ?
py::capsule(&self, [](void *f) {
spd::debug("Unlocking array");
static_cast<af::array *>(f)->unlock();
}) :
py::capsule(data, [](void *f) {
spd::debug("Freeing host pointer");
af::freeHost(f);
});
spd::debug("Returning a {}writable of type [{}-{}] {}",
isDirect ? "" : "non ",
fmt.kind(),
fmt.itemsize(),
shape);
return py::array(fmt, dimensions, strides, data, capsule).request(isDirect);
}
namespace detail {
bool numpy_is_array(const py::object &value) {
// Can be understood as an array?
auto arr = py::array::ensure(value);
if (!arr) return false;
// Got dimensions?
auto has_dimensions = arr.ndim() > 0 && arr.size() > 1;
if (!has_dimensions) return false;
// supported array fire type?
auto type = dtype_converter::load(arr.dtype().cast<py::handle>());
return type.has_value();
}
bool numpy_is_scalar(const py::object &value) {
// Can be understood and converted...
auto arr = py::array::ensure(value);
if (!arr) return false;
// Should not have dimensions
auto has_dimensions = arr.ndim() > 0 && arr.size() > 1;
if (has_dimensions) return false;
// is supported by an arrayfire type?
auto type = dtype_converter::load(arr.dtype().cast<py::handle>());
return type.has_value();
}
inline af::dtype choose_type(af::dtype _64, af::dtype _32) {
return af::isDoubleAvailable(af::getDevice()) ? _64 : _32;
}
af::array numpy_scalar_to_array(const py::object &value, const af::dim4 &shape, const af::dtype& ref_type) {
auto arr = py::array::ensure(value);
if (!arr) throw std::invalid_argument("Value not a valid numpy object");
auto has_dimensions = arr.ndim() > 0 && arr.size() > 1;
if (has_dimensions) throw std::invalid_argument("Value is not a numpy scalar");
auto type = dtype_converter::load(arr.dtype().cast<py::handle>());
if (!type.has_value()) throw std::invalid_argument("Unsupported value type.");
auto actual_type = harmonize_types(type.value(), ref_type);
af_array handle = nullptr;
af_err err;
switch (type.value()) {
case af::dtype::c32: {
auto ptr = arr.unchecked<std::complex<float>>()(0);
auto real = static_cast<double>(ptr.real());
auto imag = static_cast<double>(ptr.imag());
err = af_constant_complex(&handle, real, imag, shape.ndims(), shape.get(), actual_type);
break;
}
case af::dtype::c64: {
auto ptr = arr.unchecked<std::complex<double>>()(0);
err = af_constant_complex(&handle, ptr.real(), ptr.imag(), shape.ndims(), shape.get(), actual_type);
break;
}
case af::dtype::s16: {
auto data = arr.unchecked<int16_t>()(0);
auto casted = static_cast<double>(data);
err = af_constant(&handle, casted, shape.ndims(), shape.get(), actual_type);
break;
}
case af::dtype::s32: {
auto data = arr.unchecked<int32_t>()(0);
auto casted = static_cast<double>(data);
err = af_constant(&handle, casted, shape.ndims(), shape.get(), actual_type);
break;
}
case af::dtype::s64: {
auto data = arr.unchecked<int64_t>()(0);
auto casted = static_cast<double>(data);
err = af_constant(&handle, casted, shape.ndims(), shape.get(), actual_type);
break;
}
case af::dtype::f16: {
auto data = arr.unchecked<half>()(0);
auto casted = static_cast<double>(data);
err = af_constant(&handle, casted, shape.ndims(), shape.get(), actual_type);
break;
}
case af::dtype::f32: {
auto data = arr.unchecked<float>()(0);
auto casted = static_cast<double>(data);
err = af_constant(&handle, casted, shape.ndims(), shape.get(), actual_type);
break;
}
case af::dtype::f64: {
auto data = arr.unchecked<double>()(0);
err = af_constant(&handle, data, shape.ndims(), shape.get(), actual_type);
break;
}
case af::dtype::u8: {
auto data = arr.unchecked<uint8_t>()(0);
auto casted = static_cast<double>(data);
err = af_constant(&handle, casted, shape.ndims(), shape.get(), actual_type);
break;
}
case af::dtype::u16: {
auto data = arr.unchecked<uint16_t>()(0);
auto casted = static_cast<double>(data);
err = af_constant(&handle, casted, shape.ndims(), shape.get(), actual_type);
break;
}
case af::dtype::u32: {
auto data = arr.unchecked<uint32_t>()(0);
auto casted = static_cast<double>(data);
err = af_constant(&handle, casted, shape.ndims(), shape.get(), actual_type);
break;
}
case af::dtype::u64: {
auto data = arr.unchecked<uint64_t>()(0);
auto casted = static_cast<double>(data);
err = af_constant(&handle, casted, shape.ndims(), shape.get(),actual_type);
break;
}
case af::dtype::b8: {
auto data = arr.unchecked<uint8_t>()(0);
auto casted = data == 1 ? 1.0 : 0.0;
err = af_constant(&handle, casted, shape.ndims(), shape.get(), actual_type);
break;
}
}
// Throw if the operation failed to convert
throw_on_error(err);
// otherwise, return the new array.
return af::array(handle);
}
af::array numpy_array_to_array(const py::object &value) {
auto np_arr = py::array::ensure(value);
if (!np_arr) throw std::invalid_argument("Value not a valid numpy object");
af::dim4 dims(1, 1, 1, 1);
auto i = 0;
auto ndim = np_arr.ndim();
auto implied_shape = np_arr.shape();
while (i < ndim) {
dims[i] = implied_shape[i];
i += 1;
}
spd::debug("Dims are {}", dims);
auto arr_type = py::cast<af::dtype>(np_arr.dtype());
spd::debug("ArrType is {}", arr_type);
auto isDblAvailable = af::isDoubleAvailable(af::getDevice());
auto isHalfAvailable = af::isHalfAvailable(af::getDevice());
if (arr_type == af::dtype::f64 && !isDblAvailable)
arr_type = af::dtype::f32;
if (arr_type == af::dtype::c64 && !isDblAvailable)
arr_type = af::dtype::c32;
if (arr_type == af::dtype::f16 && !isHalfAvailable)
arr_type = af::dtype::f32;
spd::debug("Final arrType is {}", arr_type);
/*
* TODO
*
* At the moment the code below doesn't check for:
* a) if the data is a vector, it is not necessary to request a f_style
* b) the data taken from host memory, which implies always a copy; for cpu and cuda
* devices, we may be able to just put the data in the devices memory.
*/
af::array result;
switch (arr_type) {
case af::dtype::f32: {
auto arr = py::array_t<float, py::array::f_style | py::array::forcecast>::ensure(np_arr);
auto req = arr.request();
return af::array(dims, static_cast<float *>(req.ptr));
}
case af::dtype::c32: {
auto arr = py::array_t<std::complex<float>, py::array::f_style | py::array::forcecast>::ensure(
np_arr);
auto req = arr.request();
return af::array(dims, static_cast<af::cfloat *>(req.ptr));
}
case af::dtype::f64: {
auto arr = py::array_t<double, py::array::f_style | py::array::forcecast>::ensure(np_arr);
auto req = arr.request();
return af::array(dims, static_cast<double *>(req.ptr));
}
case af::dtype::c64: {
auto arr = py::array_t<std::complex<double>, py::array::f_style | py::array::forcecast>::ensure(
np_arr);
auto req = arr.request();
return af::array(dims, static_cast<af::cdouble *>(req.ptr));
}
case af::dtype::b8: {
auto arr = py::array_t<uint8_t, py::array::f_style | py::array::forcecast>::ensure(np_arr);
auto req = arr.request();
// missing symbols if bool is used as type param
return af::array(dims, static_cast<unsigned char *>(req.ptr)).as(af::dtype::b8);
}
case af::dtype::s32: {
auto arr = py::array_t<int32_t, py::array::f_style | py::array::forcecast>::ensure(np_arr);
auto req = arr.request();
return af::array(dims, static_cast<int *>(req.ptr));
}
case af::dtype::u32: {
auto arr = py::array_t<uint32_t, py::array::f_style | py::array::forcecast>::ensure(np_arr);
auto req = arr.request();
return af::array(dims, static_cast<unsigned int *>(req.ptr));
}
case af::dtype::u8: {
auto arr = py::array_t<uint8_t, py::array::f_style | py::array::forcecast>::ensure(np_arr);
auto req = arr.request();
return af::array(dims, static_cast<unsigned char *>(req.ptr));
}
case af::dtype::s64: {
auto arr = py::array_t<int64_t, py::array::f_style | py::array::forcecast>::ensure(np_arr);
auto req = arr.request();
return af::array(dims, static_cast<long long *>(req.ptr));
}
case af::dtype::u64: {
auto arr = py::array_t<uint64_t, py::array::f_style | py::array::forcecast>::ensure(np_arr);
auto req = arr.request();
return af::array(dims, static_cast<unsigned long long *>(req.ptr));
}
case af::dtype::s16: {
auto arr = py::array_t<int16_t, py::array::f_style | py::array::forcecast>::ensure(np_arr);
auto req = arr.request();
return af::array(dims, static_cast<short *>(req.ptr));
}
case af::dtype::u16: {
auto arr = py::array_t<uint16_t, py::array::f_style | py::array::forcecast>::ensure(np_arr);
auto req = arr.request();
return af::array(dims, static_cast<unsigned short *>(req.ptr));
}
case af::dtype::f16: {
auto arr = py::array_t<half, py::array::f_style | py::array::forcecast>::ensure(np_arr);
auto req = arr.request();
// note we are using af::half
return af::array(dims, static_cast<af::half *>(req.ptr));
}
default: {
std::ostringstream msg;
msg << "Unknown data type [" << arr_type << "]";
throw std::runtime_error(msg.str());
}
}
}
}
}
| 42.818667 | 120 | 0.482531 | [
"object",
"shape",
"vector"
] |
b7dbac5bd16ec97d3c31e1f478712704944ebe8a | 43,923 | hpp | C++ | include/GlobalNamespace/IGameplayRpcManager.hpp | sc2ad/BeatSaber-Quest-Codegen | ba8acaae541cfe1161e05fbc3bf87f4bc46bc4ab | [
"Unlicense"
] | 23 | 2020-08-07T04:09:00.000Z | 2022-03-31T22:10:29.000Z | include/GlobalNamespace/IGameplayRpcManager.hpp | sc2ad/BeatSaber-Quest-Codegen | ba8acaae541cfe1161e05fbc3bf87f4bc46bc4ab | [
"Unlicense"
] | 6 | 2021-09-29T23:47:31.000Z | 2022-03-30T20:49:23.000Z | include/GlobalNamespace/IGameplayRpcManager.hpp | sc2ad/BeatSaber-Quest-Codegen | ba8acaae541cfe1161e05fbc3bf87f4bc46bc4ab | [
"Unlicense"
] | 17 | 2020-08-20T19:36:52.000Z | 2022-03-30T18:28:24.000Z | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: System.IDisposable
#include "System/IDisposable.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Action`3<T1, T2, T3>
template<typename T1, typename T2, typename T3>
class Action_3;
// Forward declaring type: Action`2<T1, T2>
template<typename T1, typename T2>
class Action_2;
// Forward declaring type: Action`1<T>
template<typename T>
class Action_1;
// Forward declaring type: Action`4<T1, T2, T3, T4>
template<typename T1, typename T2, typename T3, typename T4>
class Action_4;
}
// Forward declaring namespace: GlobalNamespace
namespace GlobalNamespace {
// Forward declaring type: PlayerSpecificSettingsAtStartNetSerializable
class PlayerSpecificSettingsAtStartNetSerializable;
// Forward declaring type: PlayerSpecificSettingsNetSerializable
class PlayerSpecificSettingsNetSerializable;
// Forward declaring type: MultiplayerLevelCompletionResults
class MultiplayerLevelCompletionResults;
// Forward declaring type: NoteCutInfoNetSerializable
class NoteCutInfoNetSerializable;
// Forward declaring type: NoteMissInfoNetSerializable
class NoteMissInfoNetSerializable;
}
// Completed forward declares
// Begin il2cpp-utils forward declares
struct Il2CppString;
// Completed il2cpp-utils forward declares
// Type namespace:
namespace GlobalNamespace {
// Forward declaring type: IGameplayRpcManager
class IGameplayRpcManager;
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(GlobalNamespace::IGameplayRpcManager);
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::IGameplayRpcManager*, "", "IGameplayRpcManager");
// Type namespace:
namespace GlobalNamespace {
// Size: 0x10
#pragma pack(push, 1)
// Autogenerated type: IGameplayRpcManager
// [TokenAttribute] Offset: FFFFFFFF
class IGameplayRpcManager/*, public System::IDisposable*/ {
public:
// Creating interface conversion operator: operator System::IDisposable
operator System::IDisposable() noexcept {
return *reinterpret_cast<System::IDisposable*>(this);
}
// public System.Boolean get_enabled()
// Offset: 0xFFFFFFFF
bool get_enabled();
// public System.Void set_enabled(System.Boolean value)
// Offset: 0xFFFFFFFF
void set_enabled(bool value);
// public System.Void add_setGameplaySceneSyncFinishedEvent(System.Action`3<System.String,PlayerSpecificSettingsAtStartNetSerializable,System.String> value)
// Offset: 0xFFFFFFFF
void add_setGameplaySceneSyncFinishedEvent(System::Action_3<::Il2CppString*, GlobalNamespace::PlayerSpecificSettingsAtStartNetSerializable*, ::Il2CppString*>* value);
// public System.Void remove_setGameplaySceneSyncFinishedEvent(System.Action`3<System.String,PlayerSpecificSettingsAtStartNetSerializable,System.String> value)
// Offset: 0xFFFFFFFF
void remove_setGameplaySceneSyncFinishedEvent(System::Action_3<::Il2CppString*, GlobalNamespace::PlayerSpecificSettingsAtStartNetSerializable*, ::Il2CppString*>* value);
// public System.Void add_setGameplaySceneReadyEvent(System.Action`2<System.String,PlayerSpecificSettingsNetSerializable> value)
// Offset: 0xFFFFFFFF
void add_setGameplaySceneReadyEvent(System::Action_2<::Il2CppString*, GlobalNamespace::PlayerSpecificSettingsNetSerializable*>* value);
// public System.Void remove_setGameplaySceneReadyEvent(System.Action`2<System.String,PlayerSpecificSettingsNetSerializable> value)
// Offset: 0xFFFFFFFF
void remove_setGameplaySceneReadyEvent(System::Action_2<::Il2CppString*, GlobalNamespace::PlayerSpecificSettingsNetSerializable*>* value);
// public System.Void add_getGameplaySceneReadyEvent(System.Action`1<System.String> value)
// Offset: 0xFFFFFFFF
void add_getGameplaySceneReadyEvent(System::Action_1<::Il2CppString*>* value);
// public System.Void remove_getGameplaySceneReadyEvent(System.Action`1<System.String> value)
// Offset: 0xFFFFFFFF
void remove_getGameplaySceneReadyEvent(System::Action_1<::Il2CppString*>* value);
// public System.Void add_setPlayerDidConnectLateEvent(System.Action`4<System.String,System.String,PlayerSpecificSettingsAtStartNetSerializable,System.String> value)
// Offset: 0xFFFFFFFF
void add_setPlayerDidConnectLateEvent(System::Action_4<::Il2CppString*, ::Il2CppString*, GlobalNamespace::PlayerSpecificSettingsAtStartNetSerializable*, ::Il2CppString*>* value);
// public System.Void remove_setPlayerDidConnectLateEvent(System.Action`4<System.String,System.String,PlayerSpecificSettingsAtStartNetSerializable,System.String> value)
// Offset: 0xFFFFFFFF
void remove_setPlayerDidConnectLateEvent(System::Action_4<::Il2CppString*, ::Il2CppString*, GlobalNamespace::PlayerSpecificSettingsAtStartNetSerializable*, ::Il2CppString*>* value);
// public System.Void add_setGameplaySongReadyEvent(System.Action`1<System.String> value)
// Offset: 0xFFFFFFFF
void add_setGameplaySongReadyEvent(System::Action_1<::Il2CppString*>* value);
// public System.Void remove_setGameplaySongReadyEvent(System.Action`1<System.String> value)
// Offset: 0xFFFFFFFF
void remove_setGameplaySongReadyEvent(System::Action_1<::Il2CppString*>* value);
// public System.Void add_getGameplaySongReadyEvent(System.Action`1<System.String> value)
// Offset: 0xFFFFFFFF
void add_getGameplaySongReadyEvent(System::Action_1<::Il2CppString*>* value);
// public System.Void remove_getGameplaySongReadyEvent(System.Action`1<System.String> value)
// Offset: 0xFFFFFFFF
void remove_getGameplaySongReadyEvent(System::Action_1<::Il2CppString*>* value);
// public System.Void add_setSongStartTimeEvent(System.Action`2<System.String,System.Single> value)
// Offset: 0xFFFFFFFF
void add_setSongStartTimeEvent(System::Action_2<::Il2CppString*, float>* value);
// public System.Void remove_setSongStartTimeEvent(System.Action`2<System.String,System.Single> value)
// Offset: 0xFFFFFFFF
void remove_setSongStartTimeEvent(System::Action_2<::Il2CppString*, float>* value);
// public System.Void add_requestReturnToMenuEvent(System.Action`1<System.String> value)
// Offset: 0xFFFFFFFF
void add_requestReturnToMenuEvent(System::Action_1<::Il2CppString*>* value);
// public System.Void remove_requestReturnToMenuEvent(System.Action`1<System.String> value)
// Offset: 0xFFFFFFFF
void remove_requestReturnToMenuEvent(System::Action_1<::Il2CppString*>* value);
// public System.Void add_returnToMenuEvent(System.Action`1<System.String> value)
// Offset: 0xFFFFFFFF
void add_returnToMenuEvent(System::Action_1<::Il2CppString*>* value);
// public System.Void remove_returnToMenuEvent(System.Action`1<System.String> value)
// Offset: 0xFFFFFFFF
void remove_returnToMenuEvent(System::Action_1<::Il2CppString*>* value);
// public System.Void add_levelFinishedEvent(System.Action`2<System.String,MultiplayerLevelCompletionResults> value)
// Offset: 0xFFFFFFFF
void add_levelFinishedEvent(System::Action_2<::Il2CppString*, GlobalNamespace::MultiplayerLevelCompletionResults*>* value);
// public System.Void remove_levelFinishedEvent(System.Action`2<System.String,MultiplayerLevelCompletionResults> value)
// Offset: 0xFFFFFFFF
void remove_levelFinishedEvent(System::Action_2<::Il2CppString*, GlobalNamespace::MultiplayerLevelCompletionResults*>* value);
// public System.Void add_noteWasCutEvent(System.Action`4<System.String,System.Single,System.Single,NoteCutInfoNetSerializable> value)
// Offset: 0xFFFFFFFF
void add_noteWasCutEvent(System::Action_4<::Il2CppString*, float, float, GlobalNamespace::NoteCutInfoNetSerializable*>* value);
// public System.Void remove_noteWasCutEvent(System.Action`4<System.String,System.Single,System.Single,NoteCutInfoNetSerializable> value)
// Offset: 0xFFFFFFFF
void remove_noteWasCutEvent(System::Action_4<::Il2CppString*, float, float, GlobalNamespace::NoteCutInfoNetSerializable*>* value);
// public System.Void add_noteWasMissedEvent(System.Action`4<System.String,System.Single,System.Single,NoteMissInfoNetSerializable> value)
// Offset: 0xFFFFFFFF
void add_noteWasMissedEvent(System::Action_4<::Il2CppString*, float, float, GlobalNamespace::NoteMissInfoNetSerializable*>* value);
// public System.Void remove_noteWasMissedEvent(System.Action`4<System.String,System.Single,System.Single,NoteMissInfoNetSerializable> value)
// Offset: 0xFFFFFFFF
void remove_noteWasMissedEvent(System::Action_4<::Il2CppString*, float, float, GlobalNamespace::NoteMissInfoNetSerializable*>* value);
// public System.Void NoteMissed(System.Single songTime, NoteMissInfoNetSerializable noteMissInfoNetSerializable)
// Offset: 0xFFFFFFFF
void NoteMissed(float songTime, GlobalNamespace::NoteMissInfoNetSerializable* noteMissInfoNetSerializable);
// public System.Void NoteCut(System.Single songTime, NoteCutInfoNetSerializable noteCutInfoNetSerializable)
// Offset: 0xFFFFFFFF
void NoteCut(float songTime, GlobalNamespace::NoteCutInfoNetSerializable* noteCutInfoNetSerializable);
// public System.Void SetGameplaySceneSyncFinished(PlayerSpecificSettingsAtStartNetSerializable playersAtGameStartNetSerializable, System.String sessionGameId)
// Offset: 0xFFFFFFFF
void SetGameplaySceneSyncFinished(GlobalNamespace::PlayerSpecificSettingsAtStartNetSerializable* playersAtGameStartNetSerializable, ::Il2CppString* sessionGameId);
// public System.Void SetGameplaySceneReady(PlayerSpecificSettingsNetSerializable playerSpecificSettings)
// Offset: 0xFFFFFFFF
void SetGameplaySceneReady(GlobalNamespace::PlayerSpecificSettingsNetSerializable* playerSpecificSettings);
// public System.Void GetGameplaySceneReady()
// Offset: 0xFFFFFFFF
void GetGameplaySceneReady();
// public System.Void SetPlayerDidConnectLate(System.String userId, PlayerSpecificSettingsAtStartNetSerializable playersAtGameStartNetSerializable, System.String sessionGameId)
// Offset: 0xFFFFFFFF
void SetPlayerDidConnectLate(::Il2CppString* userId, GlobalNamespace::PlayerSpecificSettingsAtStartNetSerializable* playersAtGameStartNetSerializable, ::Il2CppString* sessionGameId);
// public System.Void SetSongStartTime(System.Single startTime)
// Offset: 0xFFFFFFFF
void SetSongStartTime(float startTime);
// public System.Void SetGameplaySongReady()
// Offset: 0xFFFFFFFF
void SetGameplaySongReady();
// public System.Void GetGameplaySongReady()
// Offset: 0xFFFFFFFF
void GetGameplaySongReady();
// public System.Void RequestReturnToMenu()
// Offset: 0xFFFFFFFF
void RequestReturnToMenu();
// public System.Void ReturnToMenu()
// Offset: 0xFFFFFFFF
void ReturnToMenu();
// public System.Void LevelFinished(MultiplayerLevelCompletionResults results)
// Offset: 0xFFFFFFFF
void LevelFinished(GlobalNamespace::MultiplayerLevelCompletionResults* results);
}; // IGameplayRpcManager
#pragma pack(pop)
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: GlobalNamespace::IGameplayRpcManager::get_enabled
// Il2CppName: get_enabled
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::IGameplayRpcManager::*)()>(&GlobalNamespace::IGameplayRpcManager::get_enabled)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::IGameplayRpcManager*), "get_enabled", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::IGameplayRpcManager::set_enabled
// Il2CppName: set_enabled
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::IGameplayRpcManager::*)(bool)>(&GlobalNamespace::IGameplayRpcManager::set_enabled)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::IGameplayRpcManager*), "set_enabled", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::IGameplayRpcManager::add_setGameplaySceneSyncFinishedEvent
// Il2CppName: add_setGameplaySceneSyncFinishedEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::IGameplayRpcManager::*)(System::Action_3<::Il2CppString*, GlobalNamespace::PlayerSpecificSettingsAtStartNetSerializable*, ::Il2CppString*>*)>(&GlobalNamespace::IGameplayRpcManager::add_setGameplaySceneSyncFinishedEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`3"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "String"), ::il2cpp_utils::GetClassFromName("", "PlayerSpecificSettingsAtStartNetSerializable"), ::il2cpp_utils::GetClassFromName("System", "String")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::IGameplayRpcManager*), "add_setGameplaySceneSyncFinishedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::IGameplayRpcManager::remove_setGameplaySceneSyncFinishedEvent
// Il2CppName: remove_setGameplaySceneSyncFinishedEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::IGameplayRpcManager::*)(System::Action_3<::Il2CppString*, GlobalNamespace::PlayerSpecificSettingsAtStartNetSerializable*, ::Il2CppString*>*)>(&GlobalNamespace::IGameplayRpcManager::remove_setGameplaySceneSyncFinishedEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`3"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "String"), ::il2cpp_utils::GetClassFromName("", "PlayerSpecificSettingsAtStartNetSerializable"), ::il2cpp_utils::GetClassFromName("System", "String")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::IGameplayRpcManager*), "remove_setGameplaySceneSyncFinishedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::IGameplayRpcManager::add_setGameplaySceneReadyEvent
// Il2CppName: add_setGameplaySceneReadyEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::IGameplayRpcManager::*)(System::Action_2<::Il2CppString*, GlobalNamespace::PlayerSpecificSettingsNetSerializable*>*)>(&GlobalNamespace::IGameplayRpcManager::add_setGameplaySceneReadyEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`2"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "String"), ::il2cpp_utils::GetClassFromName("", "PlayerSpecificSettingsNetSerializable")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::IGameplayRpcManager*), "add_setGameplaySceneReadyEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::IGameplayRpcManager::remove_setGameplaySceneReadyEvent
// Il2CppName: remove_setGameplaySceneReadyEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::IGameplayRpcManager::*)(System::Action_2<::Il2CppString*, GlobalNamespace::PlayerSpecificSettingsNetSerializable*>*)>(&GlobalNamespace::IGameplayRpcManager::remove_setGameplaySceneReadyEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`2"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "String"), ::il2cpp_utils::GetClassFromName("", "PlayerSpecificSettingsNetSerializable")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::IGameplayRpcManager*), "remove_setGameplaySceneReadyEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::IGameplayRpcManager::add_getGameplaySceneReadyEvent
// Il2CppName: add_getGameplaySceneReadyEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::IGameplayRpcManager::*)(System::Action_1<::Il2CppString*>*)>(&GlobalNamespace::IGameplayRpcManager::add_getGameplaySceneReadyEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "String")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::IGameplayRpcManager*), "add_getGameplaySceneReadyEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::IGameplayRpcManager::remove_getGameplaySceneReadyEvent
// Il2CppName: remove_getGameplaySceneReadyEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::IGameplayRpcManager::*)(System::Action_1<::Il2CppString*>*)>(&GlobalNamespace::IGameplayRpcManager::remove_getGameplaySceneReadyEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "String")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::IGameplayRpcManager*), "remove_getGameplaySceneReadyEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::IGameplayRpcManager::add_setPlayerDidConnectLateEvent
// Il2CppName: add_setPlayerDidConnectLateEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::IGameplayRpcManager::*)(System::Action_4<::Il2CppString*, ::Il2CppString*, GlobalNamespace::PlayerSpecificSettingsAtStartNetSerializable*, ::Il2CppString*>*)>(&GlobalNamespace::IGameplayRpcManager::add_setPlayerDidConnectLateEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`4"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "String"), ::il2cpp_utils::GetClassFromName("System", "String"), ::il2cpp_utils::GetClassFromName("", "PlayerSpecificSettingsAtStartNetSerializable"), ::il2cpp_utils::GetClassFromName("System", "String")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::IGameplayRpcManager*), "add_setPlayerDidConnectLateEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::IGameplayRpcManager::remove_setPlayerDidConnectLateEvent
// Il2CppName: remove_setPlayerDidConnectLateEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::IGameplayRpcManager::*)(System::Action_4<::Il2CppString*, ::Il2CppString*, GlobalNamespace::PlayerSpecificSettingsAtStartNetSerializable*, ::Il2CppString*>*)>(&GlobalNamespace::IGameplayRpcManager::remove_setPlayerDidConnectLateEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`4"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "String"), ::il2cpp_utils::GetClassFromName("System", "String"), ::il2cpp_utils::GetClassFromName("", "PlayerSpecificSettingsAtStartNetSerializable"), ::il2cpp_utils::GetClassFromName("System", "String")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::IGameplayRpcManager*), "remove_setPlayerDidConnectLateEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::IGameplayRpcManager::add_setGameplaySongReadyEvent
// Il2CppName: add_setGameplaySongReadyEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::IGameplayRpcManager::*)(System::Action_1<::Il2CppString*>*)>(&GlobalNamespace::IGameplayRpcManager::add_setGameplaySongReadyEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "String")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::IGameplayRpcManager*), "add_setGameplaySongReadyEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::IGameplayRpcManager::remove_setGameplaySongReadyEvent
// Il2CppName: remove_setGameplaySongReadyEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::IGameplayRpcManager::*)(System::Action_1<::Il2CppString*>*)>(&GlobalNamespace::IGameplayRpcManager::remove_setGameplaySongReadyEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "String")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::IGameplayRpcManager*), "remove_setGameplaySongReadyEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::IGameplayRpcManager::add_getGameplaySongReadyEvent
// Il2CppName: add_getGameplaySongReadyEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::IGameplayRpcManager::*)(System::Action_1<::Il2CppString*>*)>(&GlobalNamespace::IGameplayRpcManager::add_getGameplaySongReadyEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "String")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::IGameplayRpcManager*), "add_getGameplaySongReadyEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::IGameplayRpcManager::remove_getGameplaySongReadyEvent
// Il2CppName: remove_getGameplaySongReadyEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::IGameplayRpcManager::*)(System::Action_1<::Il2CppString*>*)>(&GlobalNamespace::IGameplayRpcManager::remove_getGameplaySongReadyEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "String")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::IGameplayRpcManager*), "remove_getGameplaySongReadyEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::IGameplayRpcManager::add_setSongStartTimeEvent
// Il2CppName: add_setSongStartTimeEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::IGameplayRpcManager::*)(System::Action_2<::Il2CppString*, float>*)>(&GlobalNamespace::IGameplayRpcManager::add_setSongStartTimeEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`2"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "String"), ::il2cpp_utils::GetClassFromName("System", "Single")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::IGameplayRpcManager*), "add_setSongStartTimeEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::IGameplayRpcManager::remove_setSongStartTimeEvent
// Il2CppName: remove_setSongStartTimeEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::IGameplayRpcManager::*)(System::Action_2<::Il2CppString*, float>*)>(&GlobalNamespace::IGameplayRpcManager::remove_setSongStartTimeEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`2"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "String"), ::il2cpp_utils::GetClassFromName("System", "Single")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::IGameplayRpcManager*), "remove_setSongStartTimeEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::IGameplayRpcManager::add_requestReturnToMenuEvent
// Il2CppName: add_requestReturnToMenuEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::IGameplayRpcManager::*)(System::Action_1<::Il2CppString*>*)>(&GlobalNamespace::IGameplayRpcManager::add_requestReturnToMenuEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "String")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::IGameplayRpcManager*), "add_requestReturnToMenuEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::IGameplayRpcManager::remove_requestReturnToMenuEvent
// Il2CppName: remove_requestReturnToMenuEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::IGameplayRpcManager::*)(System::Action_1<::Il2CppString*>*)>(&GlobalNamespace::IGameplayRpcManager::remove_requestReturnToMenuEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "String")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::IGameplayRpcManager*), "remove_requestReturnToMenuEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::IGameplayRpcManager::add_returnToMenuEvent
// Il2CppName: add_returnToMenuEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::IGameplayRpcManager::*)(System::Action_1<::Il2CppString*>*)>(&GlobalNamespace::IGameplayRpcManager::add_returnToMenuEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "String")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::IGameplayRpcManager*), "add_returnToMenuEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::IGameplayRpcManager::remove_returnToMenuEvent
// Il2CppName: remove_returnToMenuEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::IGameplayRpcManager::*)(System::Action_1<::Il2CppString*>*)>(&GlobalNamespace::IGameplayRpcManager::remove_returnToMenuEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "String")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::IGameplayRpcManager*), "remove_returnToMenuEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::IGameplayRpcManager::add_levelFinishedEvent
// Il2CppName: add_levelFinishedEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::IGameplayRpcManager::*)(System::Action_2<::Il2CppString*, GlobalNamespace::MultiplayerLevelCompletionResults*>*)>(&GlobalNamespace::IGameplayRpcManager::add_levelFinishedEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`2"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "String"), ::il2cpp_utils::GetClassFromName("", "MultiplayerLevelCompletionResults")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::IGameplayRpcManager*), "add_levelFinishedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::IGameplayRpcManager::remove_levelFinishedEvent
// Il2CppName: remove_levelFinishedEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::IGameplayRpcManager::*)(System::Action_2<::Il2CppString*, GlobalNamespace::MultiplayerLevelCompletionResults*>*)>(&GlobalNamespace::IGameplayRpcManager::remove_levelFinishedEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`2"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "String"), ::il2cpp_utils::GetClassFromName("", "MultiplayerLevelCompletionResults")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::IGameplayRpcManager*), "remove_levelFinishedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::IGameplayRpcManager::add_noteWasCutEvent
// Il2CppName: add_noteWasCutEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::IGameplayRpcManager::*)(System::Action_4<::Il2CppString*, float, float, GlobalNamespace::NoteCutInfoNetSerializable*>*)>(&GlobalNamespace::IGameplayRpcManager::add_noteWasCutEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`4"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "String"), ::il2cpp_utils::GetClassFromName("System", "Single"), ::il2cpp_utils::GetClassFromName("System", "Single"), ::il2cpp_utils::GetClassFromName("", "NoteCutInfoNetSerializable")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::IGameplayRpcManager*), "add_noteWasCutEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::IGameplayRpcManager::remove_noteWasCutEvent
// Il2CppName: remove_noteWasCutEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::IGameplayRpcManager::*)(System::Action_4<::Il2CppString*, float, float, GlobalNamespace::NoteCutInfoNetSerializable*>*)>(&GlobalNamespace::IGameplayRpcManager::remove_noteWasCutEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`4"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "String"), ::il2cpp_utils::GetClassFromName("System", "Single"), ::il2cpp_utils::GetClassFromName("System", "Single"), ::il2cpp_utils::GetClassFromName("", "NoteCutInfoNetSerializable")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::IGameplayRpcManager*), "remove_noteWasCutEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::IGameplayRpcManager::add_noteWasMissedEvent
// Il2CppName: add_noteWasMissedEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::IGameplayRpcManager::*)(System::Action_4<::Il2CppString*, float, float, GlobalNamespace::NoteMissInfoNetSerializable*>*)>(&GlobalNamespace::IGameplayRpcManager::add_noteWasMissedEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`4"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "String"), ::il2cpp_utils::GetClassFromName("System", "Single"), ::il2cpp_utils::GetClassFromName("System", "Single"), ::il2cpp_utils::GetClassFromName("", "NoteMissInfoNetSerializable")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::IGameplayRpcManager*), "add_noteWasMissedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::IGameplayRpcManager::remove_noteWasMissedEvent
// Il2CppName: remove_noteWasMissedEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::IGameplayRpcManager::*)(System::Action_4<::Il2CppString*, float, float, GlobalNamespace::NoteMissInfoNetSerializable*>*)>(&GlobalNamespace::IGameplayRpcManager::remove_noteWasMissedEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`4"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "String"), ::il2cpp_utils::GetClassFromName("System", "Single"), ::il2cpp_utils::GetClassFromName("System", "Single"), ::il2cpp_utils::GetClassFromName("", "NoteMissInfoNetSerializable")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::IGameplayRpcManager*), "remove_noteWasMissedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::IGameplayRpcManager::NoteMissed
// Il2CppName: NoteMissed
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::IGameplayRpcManager::*)(float, GlobalNamespace::NoteMissInfoNetSerializable*)>(&GlobalNamespace::IGameplayRpcManager::NoteMissed)> {
static const MethodInfo* get() {
static auto* songTime = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
static auto* noteMissInfoNetSerializable = &::il2cpp_utils::GetClassFromName("", "NoteMissInfoNetSerializable")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::IGameplayRpcManager*), "NoteMissed", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{songTime, noteMissInfoNetSerializable});
}
};
// Writing MetadataGetter for method: GlobalNamespace::IGameplayRpcManager::NoteCut
// Il2CppName: NoteCut
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::IGameplayRpcManager::*)(float, GlobalNamespace::NoteCutInfoNetSerializable*)>(&GlobalNamespace::IGameplayRpcManager::NoteCut)> {
static const MethodInfo* get() {
static auto* songTime = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
static auto* noteCutInfoNetSerializable = &::il2cpp_utils::GetClassFromName("", "NoteCutInfoNetSerializable")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::IGameplayRpcManager*), "NoteCut", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{songTime, noteCutInfoNetSerializable});
}
};
// Writing MetadataGetter for method: GlobalNamespace::IGameplayRpcManager::SetGameplaySceneSyncFinished
// Il2CppName: SetGameplaySceneSyncFinished
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::IGameplayRpcManager::*)(GlobalNamespace::PlayerSpecificSettingsAtStartNetSerializable*, ::Il2CppString*)>(&GlobalNamespace::IGameplayRpcManager::SetGameplaySceneSyncFinished)> {
static const MethodInfo* get() {
static auto* playersAtGameStartNetSerializable = &::il2cpp_utils::GetClassFromName("", "PlayerSpecificSettingsAtStartNetSerializable")->byval_arg;
static auto* sessionGameId = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::IGameplayRpcManager*), "SetGameplaySceneSyncFinished", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{playersAtGameStartNetSerializable, sessionGameId});
}
};
// Writing MetadataGetter for method: GlobalNamespace::IGameplayRpcManager::SetGameplaySceneReady
// Il2CppName: SetGameplaySceneReady
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::IGameplayRpcManager::*)(GlobalNamespace::PlayerSpecificSettingsNetSerializable*)>(&GlobalNamespace::IGameplayRpcManager::SetGameplaySceneReady)> {
static const MethodInfo* get() {
static auto* playerSpecificSettings = &::il2cpp_utils::GetClassFromName("", "PlayerSpecificSettingsNetSerializable")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::IGameplayRpcManager*), "SetGameplaySceneReady", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{playerSpecificSettings});
}
};
// Writing MetadataGetter for method: GlobalNamespace::IGameplayRpcManager::GetGameplaySceneReady
// Il2CppName: GetGameplaySceneReady
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::IGameplayRpcManager::*)()>(&GlobalNamespace::IGameplayRpcManager::GetGameplaySceneReady)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::IGameplayRpcManager*), "GetGameplaySceneReady", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::IGameplayRpcManager::SetPlayerDidConnectLate
// Il2CppName: SetPlayerDidConnectLate
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::IGameplayRpcManager::*)(::Il2CppString*, GlobalNamespace::PlayerSpecificSettingsAtStartNetSerializable*, ::Il2CppString*)>(&GlobalNamespace::IGameplayRpcManager::SetPlayerDidConnectLate)> {
static const MethodInfo* get() {
static auto* userId = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
static auto* playersAtGameStartNetSerializable = &::il2cpp_utils::GetClassFromName("", "PlayerSpecificSettingsAtStartNetSerializable")->byval_arg;
static auto* sessionGameId = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::IGameplayRpcManager*), "SetPlayerDidConnectLate", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{userId, playersAtGameStartNetSerializable, sessionGameId});
}
};
// Writing MetadataGetter for method: GlobalNamespace::IGameplayRpcManager::SetSongStartTime
// Il2CppName: SetSongStartTime
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::IGameplayRpcManager::*)(float)>(&GlobalNamespace::IGameplayRpcManager::SetSongStartTime)> {
static const MethodInfo* get() {
static auto* startTime = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::IGameplayRpcManager*), "SetSongStartTime", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{startTime});
}
};
// Writing MetadataGetter for method: GlobalNamespace::IGameplayRpcManager::SetGameplaySongReady
// Il2CppName: SetGameplaySongReady
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::IGameplayRpcManager::*)()>(&GlobalNamespace::IGameplayRpcManager::SetGameplaySongReady)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::IGameplayRpcManager*), "SetGameplaySongReady", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::IGameplayRpcManager::GetGameplaySongReady
// Il2CppName: GetGameplaySongReady
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::IGameplayRpcManager::*)()>(&GlobalNamespace::IGameplayRpcManager::GetGameplaySongReady)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::IGameplayRpcManager*), "GetGameplaySongReady", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::IGameplayRpcManager::RequestReturnToMenu
// Il2CppName: RequestReturnToMenu
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::IGameplayRpcManager::*)()>(&GlobalNamespace::IGameplayRpcManager::RequestReturnToMenu)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::IGameplayRpcManager*), "RequestReturnToMenu", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::IGameplayRpcManager::ReturnToMenu
// Il2CppName: ReturnToMenu
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::IGameplayRpcManager::*)()>(&GlobalNamespace::IGameplayRpcManager::ReturnToMenu)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::IGameplayRpcManager*), "ReturnToMenu", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::IGameplayRpcManager::LevelFinished
// Il2CppName: LevelFinished
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::IGameplayRpcManager::*)(GlobalNamespace::MultiplayerLevelCompletionResults*)>(&GlobalNamespace::IGameplayRpcManager::LevelFinished)> {
static const MethodInfo* get() {
static auto* results = &::il2cpp_utils::GetClassFromName("", "MultiplayerLevelCompletionResults")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::IGameplayRpcManager*), "LevelFinished", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{results});
}
};
| 84.143678 | 405 | 0.778043 | [
"vector"
] |
b7e3dedde6b81cf7cc3f85c0c65541e7ce6f1224 | 7,338 | cpp | C++ | mordor/streams/fd.cpp | NoevilMe/mordor | d1963c0a8ee15524462ad5d01cb859e9d7706c1e | [
"BSD-3-Clause"
] | 200 | 2015-01-11T22:31:21.000Z | 2022-03-23T08:48:53.000Z | mordor/streams/fd.cpp | NoevilMe/mordor | d1963c0a8ee15524462ad5d01cb859e9d7706c1e | [
"BSD-3-Clause"
] | 3 | 2018-11-27T15:16:46.000Z | 2022-01-14T15:40:31.000Z | mordor/streams/fd.cpp | NoevilMe/mordor | d1963c0a8ee15524462ad5d01cb859e9d7706c1e | [
"BSD-3-Clause"
] | 31 | 2015-02-12T04:22:43.000Z | 2021-12-24T09:27:33.000Z | // Copyright (c) 2009 - Mozy, Inc.
#include "mordor/pch.h"
#include "fd.h"
#include <algorithm>
#include <limits>
#include <sys/fcntl.h>
#include <sys/stat.h>
#include <sys/uio.h>
#include "buffer.h"
#include "mordor/assert.h"
#include "mordor/iomanager.h"
namespace Mordor {
static Logger::ptr g_log = Log::lookup("mordor:streams:fd");
FDStream::FDStream()
: m_ioManager(NULL),
m_scheduler(NULL),
m_fd(-1),
m_own(false)
{}
void
FDStream::init(int fd, IOManager *ioManager, Scheduler *scheduler, bool own)
{
MORDOR_ASSERT(fd >= 0);
m_ioManager = ioManager;
m_scheduler = scheduler;
m_fd = fd;
m_own = own;
if (m_ioManager) {
if (fcntl(m_fd, F_SETFL, O_NONBLOCK)) {
error_t error = lastError();
if (own) {
::close(m_fd);
m_fd = -1;
}
MORDOR_THROW_EXCEPTION_FROM_ERROR_API(error, "fcntl");
}
}
}
FDStream::~FDStream()
{
if (m_own && m_fd >= 0) {
SchedulerSwitcher switcher(m_scheduler);
int rc = ::close(m_fd);
MORDOR_LOG_LEVEL(g_log, rc ? Log::ERROR : Log::VERBOSE) << this
<< " close(" << m_fd << "): " << rc << " (" << lastError() << ")";
}
}
void
FDStream::close(CloseType type)
{
MORDOR_ASSERT(type == BOTH);
if (m_fd > 0 && m_own) {
SchedulerSwitcher switcher(m_scheduler);
int rc = ::close(m_fd);
error_t error = lastError();
MORDOR_LOG_LEVEL(g_log, rc ? Log::ERROR : Log::VERBOSE) << this
<< " close(" << m_fd << "): " << rc << " (" << error << ")";
if (rc)
MORDOR_THROW_EXCEPTION_FROM_ERROR_API(error, "close");
m_fd = -1;
}
}
size_t
FDStream::read(Buffer &buffer, size_t length)
{
SchedulerSwitcher switcher(m_ioManager ? NULL : m_scheduler);
MORDOR_ASSERT(m_fd >= 0);
if (length > 0xfffffffe)
length = 0xfffffffe;
std::vector<iovec> iovs = buffer.writeBuffers(length);
int rc = readv(m_fd, &iovs[0], iovs.size());
while (rc < 0 && errno == EAGAIN && m_ioManager) {
MORDOR_LOG_TRACE(g_log) << this << " readv(" << m_fd << ", " << length
<< "): " << rc << " (EAGAIN)";
m_ioManager->registerEvent(m_fd, IOManager::READ);
Scheduler::yieldTo();
rc = readv(m_fd, &iovs[0], iovs.size());
}
error_t error = lastError();
MORDOR_LOG_LEVEL(g_log, rc < 0 ? Log::ERROR : Log::DEBUG) << this
<< " readv(" << m_fd << ", " << length << "): " << rc << " (" << error
<< ")";
if (rc < 0)
MORDOR_THROW_EXCEPTION_FROM_ERROR_API(error, "readv");
buffer.produce(rc);
return rc;
}
size_t
FDStream::read(void *buffer, size_t length)
{
SchedulerSwitcher switcher(m_ioManager ? NULL : m_scheduler);
MORDOR_ASSERT(m_fd >= 0);
if (length > 0xfffffffe)
length = 0xfffffffe;
int rc = ::read(m_fd, buffer, length);
while (rc < 0 && errno == EAGAIN && m_ioManager) {
MORDOR_LOG_TRACE(g_log) << this << " read(" << m_fd << ", " << length
<< "): " << rc << " (EAGAIN)";
m_ioManager->registerEvent(m_fd, IOManager::READ);
Scheduler::yieldTo();
rc = ::read(m_fd, buffer, length);
}
error_t error = lastError();
MORDOR_LOG_LEVEL(g_log, rc < 0 ? Log::ERROR : Log::DEBUG) << this
<< " read(" << m_fd << ", " << length << "): " << rc << " (" << error
<< ")";
if (rc < 0)
MORDOR_THROW_EXCEPTION_FROM_ERROR_API(error, "read");
return rc;
}
size_t
FDStream::write(const Buffer &buffer, size_t length)
{
SchedulerSwitcher switcher(m_ioManager ? NULL : m_scheduler);
MORDOR_ASSERT(m_fd >= 0);
length = std::min(length, (size_t)std::numeric_limits<ssize_t>::max());
const std::vector<iovec> iovs = buffer.readBuffers(length);
ssize_t rc = 0;
const int count = std::min(iovs.size(), (size_t)IOV_MAX);
while ((rc = writev(m_fd, &iovs[0], count)) < 0 &&
errno == EAGAIN && m_ioManager) {
MORDOR_LOG_TRACE(g_log) << this << " writev(" << m_fd << ", " << length
<< "): " << rc << " (EAGAIN)";
m_ioManager->registerEvent(m_fd, IOManager::WRITE);
Scheduler::yieldTo();
}
error_t error = lastError();
MORDOR_LOG_LEVEL(g_log, rc < 0 ? Log::ERROR : Log::DEBUG) << this
<< " writev(" << m_fd << ", " << length << "): " << rc << " (" << error
<< ")";
if (rc == 0)
MORDOR_THROW_EXCEPTION(std::runtime_error("Zero length write"));
if (rc < 0)
MORDOR_THROW_EXCEPTION_FROM_ERROR_API(error, "writev");
return rc;
}
size_t
FDStream::write(const void *buffer, size_t length)
{
SchedulerSwitcher switcher(m_ioManager ? NULL : m_scheduler);
MORDOR_ASSERT(m_fd >= 0);
if (length > 0xfffffffe)
length = 0xfffffffe;
int rc = ::write(m_fd, buffer, length);
while (rc < 0 && errno == EAGAIN && m_ioManager) {
MORDOR_LOG_TRACE(g_log) << this << " write(" << m_fd << ", " << length
<< "): " << rc << " (EAGAIN)";
m_ioManager->registerEvent(m_fd, IOManager::WRITE);
Scheduler::yieldTo();
rc = ::write(m_fd, buffer, length);
}
error_t error = lastError();
MORDOR_LOG_LEVEL(g_log, rc < 0 ? Log::ERROR : Log::DEBUG) << this
<< " write(" << m_fd << ", " << length << "): " << rc << " (" << error
<< ")";
if (rc == 0)
MORDOR_THROW_EXCEPTION(std::runtime_error("Zero length write"));
if (rc < 0)
MORDOR_THROW_EXCEPTION_FROM_ERROR_API(error, "write");
return rc;
}
long long
FDStream::seek(long long offset, Anchor anchor)
{
SchedulerSwitcher switcher(m_scheduler);
MORDOR_ASSERT(m_fd >= 0);
long long pos = lseek(m_fd, offset, (int)anchor);
error_t error = lastError();
MORDOR_LOG_LEVEL(g_log, pos < 0 ? Log::ERROR : Log::VERBOSE) << this
<< " lseek(" << m_fd << ", " << offset << ", " << anchor << "): "
<< pos << " (" << error << ")";
if (pos < 0)
MORDOR_THROW_EXCEPTION_FROM_ERROR_API(error, "lseek");
return pos;
}
long long
FDStream::size()
{
SchedulerSwitcher switcher(m_scheduler);
MORDOR_ASSERT(m_fd >= 0);
struct stat statbuf;
int rc = fstat(m_fd, &statbuf);
error_t error = lastError();
MORDOR_LOG_LEVEL(g_log, rc ? Log::ERROR : Log::VERBOSE) << this
<< " fstat(" << m_fd << "): " << rc << " (" << error << ")";
if (rc)
MORDOR_THROW_EXCEPTION_FROM_ERROR_API(error, "fstat");
return statbuf.st_size;
}
void
FDStream::truncate(long long size)
{
SchedulerSwitcher switcher(m_scheduler);
MORDOR_ASSERT(m_fd >= 0);
int rc = ftruncate(m_fd, size);
error_t error = lastError();
MORDOR_LOG_LEVEL(g_log, rc ? Log::ERROR : Log::VERBOSE) << this
<< " ftruncate(" << m_fd << ", " << size << "): " << rc
<< " (" << error << ")";
if (rc)
MORDOR_THROW_EXCEPTION_FROM_ERROR_API(error, "ftruncate");
}
void
FDStream::flush(bool flushParent)
{
SchedulerSwitcher switcher(m_scheduler);
MORDOR_ASSERT(m_fd >= 0);
int rc = fsync(m_fd);
error_t error = lastError();
MORDOR_LOG_LEVEL(g_log, rc ? Log::ERROR : Log::VERBOSE) << this
<< " fsync(" << m_fd << "): " << rc << " (" << error << ")";
if (rc)
MORDOR_THROW_EXCEPTION_FROM_ERROR_API(error, "fsync");
}
}
| 31.09322 | 79 | 0.568411 | [
"vector"
] |
b7ee3b356cb2680dd85bd2e9c97353529d91e623 | 22,333 | cc | C++ | chrome/browser/ui/webui/policy_tool_ui_handler.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | chrome/browser/ui/webui/policy_tool_ui_handler.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | chrome/browser/ui/webui/policy_tool_ui_handler.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/policy_tool_ui_handler.h"
#include "base/files/file_enumerator.h"
#include "base/files/file_util.h"
#include "base/json/json_reader.h"
#include "base/json/json_writer.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task_scheduler/post_task.h"
#include "build/build_config.h"
#include "chrome/browser/download/download_prefs.h"
#include "chrome/browser/policy/schema_registry_service.h"
#include "chrome/browser/policy/schema_registry_service_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/chrome_select_file_policy.h"
#include "components/policy/core/common/plist_writer.h"
#include "components/strings/grit/components_strings.h"
#include "content/public/browser/web_contents.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/shell_dialogs/select_file_policy.h"
namespace {
const base::FilePath::CharType kPolicyToolSessionsDir[] =
FILE_PATH_LITERAL("Policy sessions");
const base::FilePath::CharType kPolicyToolDefaultSessionName[] =
FILE_PATH_LITERAL("policy");
const base::FilePath::CharType kPolicyToolSessionExtension[] =
FILE_PATH_LITERAL("json");
const base::FilePath::CharType kPolicyToolLinuxExtension[] =
FILE_PATH_LITERAL("json");
const base::FilePath::CharType kPolicyToolMacExtension[] =
FILE_PATH_LITERAL("plist");
// Returns the current list of all sessions sorted by last access time in
// decreasing order.
base::ListValue GetSessionsList(const base::FilePath& sessions_dir) {
base::FilePath::StringType sessions_pattern =
FILE_PATH_LITERAL("*.") +
base::FilePath::StringType(kPolicyToolSessionExtension);
base::FileEnumerator enumerator(sessions_dir, /*recursive=*/false,
base::FileEnumerator::FILES,
sessions_pattern);
// A vector of session names and their last access times.
using Session = std::pair<base::Time, base::FilePath::StringType>;
std::vector<Session> sessions;
for (base::FilePath name = enumerator.Next(); !name.empty();
name = enumerator.Next()) {
base::File::Info info;
base::GetFileInfo(name, &info);
sessions.push_back(
{info.last_accessed, name.BaseName().RemoveExtension().value()});
}
// Sort the sessions by the the time of last access in decreasing order.
std::sort(sessions.begin(), sessions.end(), std::greater<Session>());
// Convert sessions to the list containing only names.
base::ListValue session_names;
for (const Session& session : sessions)
session_names.GetList().push_back(base::Value(session.second));
return session_names;
}
// Tries to parse the value if it is necessary. If parsing was necessary, but
// not successful, returns nullptr.
std::unique_ptr<base::Value> ParseSinglePolicyType(
const policy::Schema& policy_schema,
const std::string& policy_name,
base::Value* policy_value) {
if (!policy_schema.valid())
return nullptr;
if (policy_value->type() == base::Value::Type::STRING &&
policy_schema.type() != base::Value::Type::STRING) {
return base::JSONReader::Read(policy_value->GetString());
}
return base::Value::ToUniquePtrValue(policy_value->Clone());
}
// Checks if the value matches the actual policy type.
bool CheckSinglePolicyType(const policy::Schema& policy_schema,
const std::string& policy_name,
base::Value* policy_value) {
// If the schema is invalid, this means that the policy is unknown, and so
// considered valid.
if (!policy_schema.valid())
return true;
std::string error_path, error;
return policy_schema.Validate(*policy_value, policy::SCHEMA_STRICT,
&error_path, &error);
}
// Parses and checks policy types for a single source (e.g. chrome policies
// or policies for one extension). For each policy, if parsing was successful
// and the parsed value matches its expected schema, replaces the policy value
// with the parsed value. Also, sets the 'valid' field to indicate whether the
// value is valid for its policy.
void ParseSourcePolicyTypes(const policy::Schema* source_schema,
base::Value* policies) {
for (const auto& policy : policies->DictItems()) {
const std::string policy_name = policy.first;
policy::Schema policy_schema = source_schema->GetKnownProperty(policy_name);
std::unique_ptr<base::Value> parsed_value = ParseSinglePolicyType(
policy_schema, policy_name, policy.second.FindKey("value"));
if (parsed_value &&
CheckSinglePolicyType(policy_schema, policy_name, parsed_value.get())) {
policy.second.SetKey("value", std::move(*parsed_value));
policy.second.SetKey("valid", base::Value(true));
} else {
policy.second.SetKey("valid", base::Value(false));
}
}
}
} // namespace
PolicyToolUIHandler::PolicyToolUIHandler() : callback_weak_ptr_factory_(this) {}
PolicyToolUIHandler::~PolicyToolUIHandler() {}
void PolicyToolUIHandler::RegisterMessages() {
// Set directory for storing sessions.
sessions_dir_ =
Profile::FromWebUI(web_ui())->GetPath().Append(kPolicyToolSessionsDir);
web_ui()->RegisterMessageCallback(
"initialized",
base::BindRepeating(&PolicyToolUIHandler::HandleInitializedAdmin,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(
"loadSession",
base::BindRepeating(&PolicyToolUIHandler::HandleLoadSession,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(
"renameSession",
base::BindRepeating(&PolicyToolUIHandler::HandleRenameSession,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(
"updateSession",
base::BindRepeating(&PolicyToolUIHandler::HandleUpdateSession,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(
"resetSession",
base::BindRepeating(&PolicyToolUIHandler::HandleResetSession,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(
"deleteSession",
base::BindRepeating(&PolicyToolUIHandler::HandleDeleteSession,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(
"exportLinux",
base::BindRepeating(&PolicyToolUIHandler::HandleExportLinux,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(
"exportMac", base::BindRepeating(&PolicyToolUIHandler::HandleExportMac,
base::Unretained(this)));
}
void PolicyToolUIHandler::OnJavascriptDisallowed() {
callback_weak_ptr_factory_.InvalidateWeakPtrs();
}
base::FilePath PolicyToolUIHandler::GetSessionPath(
const base::FilePath::StringType& name) const {
return sessions_dir_.Append(name).AddExtension(kPolicyToolSessionExtension);
}
void PolicyToolUIHandler::SetDefaultSessionName() {
base::ListValue sessions = GetSessionsList(sessions_dir_);
if (sessions.empty()) {
// If there are no sessions, fallback to the default session name.
session_name_ = kPolicyToolDefaultSessionName;
} else {
session_name_ =
base::FilePath::FromUTF8Unsafe(sessions.GetList()[0].GetString())
.value();
}
}
std::string PolicyToolUIHandler::ReadOrCreateFileCallback() {
// Create sessions directory, if it doesn't exist yet.
// If unable to create a directory, just silently return a dictionary
// indicating that saving was unsuccessful.
// TODO(urusant): add a possibility to disable saving to disk in similar
// cases.
if (!base::CreateDirectory(sessions_dir_))
is_saving_enabled_ = false;
// Initialize session name if it is not initialized yet.
if (session_name_.empty())
SetDefaultSessionName();
const base::FilePath session_path = GetSessionPath(session_name_);
// Check if the file for the current session already exists. If not, create it
// and put an empty dictionary in it.
base::File session_file(session_path, base::File::Flags::FLAG_CREATE |
base::File::Flags::FLAG_WRITE);
// If unable to open the file, just return an empty dictionary.
if (session_file.created()) {
session_file.WriteAtCurrentPos("{}", 2);
return "{}";
}
session_file.Close();
// Check that the file exists by now. If it doesn't, it means that at least
// one of the filesystem operations wasn't successful. In this case, return
// a dictionary indicating that saving was unsuccessful. Potentially this can
// also be the place to disable saving to disk.
if (!PathExists(session_path))
is_saving_enabled_ = false;
// Read file contents.
std::string contents;
base::ReadFileToString(session_path, &contents);
// Touch the file to remember the last session.
base::File::Info info;
base::GetFileInfo(session_path, &info);
base::TouchFile(session_path, base::Time::Now(), info.last_modified);
return contents;
}
void PolicyToolUIHandler::OnSessionContentReceived(
const std::string& contents) {
// If the saving is disabled, send a message about that to the UI.
if (!is_saving_enabled_) {
CallJavascriptFunction("policy.Page.disableSaving");
return;
}
std::unique_ptr<base::DictionaryValue> value =
base::DictionaryValue::From(base::JSONReader::Read(contents));
// If contents is not a properly formed JSON string, disable editing in the
// UI to prevent the user from accidentally overriding it.
if (!value) {
CallJavascriptFunction("policy.Page.setPolicyValues",
base::DictionaryValue());
CallJavascriptFunction("policy.Page.disableEditing");
} else {
ParsePolicyTypes(value.get());
CallJavascriptFunction("policy.Page.setPolicyValues", *value);
CallJavascriptFunction("policy.Page.setSessionTitle",
base::Value(session_name_));
base::PostTaskWithTraitsAndReplyWithResult(
FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE},
base::BindOnce(&GetSessionsList, sessions_dir_),
base::BindOnce(&PolicyToolUIHandler::OnSessionsListReceived,
callback_weak_ptr_factory_.GetWeakPtr()));
}
}
void PolicyToolUIHandler::OnSessionsListReceived(base::ListValue list) {
CallJavascriptFunction("policy.Page.setSessionsList", list);
}
void PolicyToolUIHandler::ImportFile() {
base::PostTaskWithTraitsAndReplyWithResult(
FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE},
base::BindOnce(&PolicyToolUIHandler::ReadOrCreateFileCallback,
base::Unretained(this)),
base::BindOnce(&PolicyToolUIHandler::OnSessionContentReceived,
callback_weak_ptr_factory_.GetWeakPtr()));
}
void PolicyToolUIHandler::HandleInitializedAdmin(const base::ListValue* args) {
DCHECK_EQ(0U, args->GetSize());
AllowJavascript();
is_saving_enabled_ = true;
SendPolicyNames();
ImportFile();
}
bool PolicyToolUIHandler::IsValidSessionName(
const base::FilePath::StringType& name) const {
// Check if the session name is valid, which means that it doesn't use
// filesystem navigation (e.g. ../ or nested folder).
// Sanity check to avoid that GetSessionPath(|name|) crashed.
if (base::FilePath(name).IsAbsolute())
return false;
base::FilePath session_path = GetSessionPath(name);
return !session_path.empty() && session_path.DirName() == sessions_dir_ &&
session_path.BaseName().RemoveExtension() == base::FilePath(name) &&
!session_path.EndsWithSeparator();
}
void PolicyToolUIHandler::HandleLoadSession(const base::ListValue* args) {
DCHECK_EQ(1U, args->GetSize());
base::FilePath::StringType new_session_name =
base::FilePath::FromUTF8Unsafe(args->GetList()[0].GetString()).value();
if (!IsValidSessionName(new_session_name)) {
CallJavascriptFunction("policy.Page.showInvalidSessionNameError");
return;
}
session_name_ = new_session_name;
ImportFile();
}
// static
PolicyToolUIHandler::SessionErrors PolicyToolUIHandler::DoRenameSession(
const base::FilePath& old_session_path,
const base::FilePath& new_session_path) {
// Check if a session files with the new name exist. If |old_session_path|
// doesn't exist, it means that is not a valid session. If |new_session_path|
// exists, it means that we can't do the rename because that will cause a file
// overwrite.
if (!PathExists(old_session_path))
return SessionErrors::kSessionNameNotExist;
if (PathExists(new_session_path))
return SessionErrors::kSessionNameExist;
if (!base::Move(old_session_path, new_session_path))
return SessionErrors::kRenamedSessionError;
return SessionErrors::kNone;
}
void PolicyToolUIHandler::OnSessionRenamed(
PolicyToolUIHandler::SessionErrors result) {
if (result == SessionErrors::kNone) {
base::PostTaskWithTraitsAndReplyWithResult(
FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE},
base::BindOnce(&GetSessionsList, sessions_dir_),
base::BindOnce(&PolicyToolUIHandler::OnSessionsListReceived,
callback_weak_ptr_factory_.GetWeakPtr()));
CallJavascriptFunction("policy.Page.closeRenameSessionDialog");
return;
}
int error_message_id;
if (result == SessionErrors::kSessionNameNotExist) {
error_message_id = IDS_POLICY_TOOL_SESSION_NOT_EXIST;
} else if (result == SessionErrors::kSessionNameExist) {
error_message_id = IDS_POLICY_TOOL_SESSION_EXIST;
} else {
error_message_id = IDS_POLICY_TOOL_RENAME_FAILED;
}
CallJavascriptFunction(
"policy.Page.showRenameSessionError",
base::Value(l10n_util::GetStringUTF16(error_message_id)));
}
void PolicyToolUIHandler::HandleRenameSession(const base::ListValue* args) {
DCHECK_EQ(2U, args->GetSize());
base::FilePath::StringType old_session_name, new_session_name;
old_session_name =
base::FilePath::FromUTF8Unsafe(args->GetList()[0].GetString()).value();
new_session_name =
base::FilePath::FromUTF8Unsafe(args->GetList()[1].GetString()).value();
if (!IsValidSessionName(new_session_name) ||
!IsValidSessionName(old_session_name)) {
CallJavascriptFunction("policy.Page.showRenameSessionError",
base::Value(l10n_util::GetStringUTF16(
IDS_POLICY_TOOL_INVALID_SESSION_NAME)));
return;
}
// This is important in case the user renames the current active session.
// If we don't clear the current session name, after the rename, a new file
// will be created with the old name and with an empty dictionary in it.
session_name_.clear();
base::PostTaskWithTraitsAndReplyWithResult(
FROM_HERE,
{base::MayBlock(), base::TaskPriority::USER_BLOCKING,
base::TaskShutdownBehavior::BLOCK_SHUTDOWN},
base::BindOnce(&PolicyToolUIHandler::DoRenameSession,
GetSessionPath(old_session_name),
GetSessionPath(new_session_name)),
base::BindOnce(&PolicyToolUIHandler::OnSessionRenamed,
callback_weak_ptr_factory_.GetWeakPtr()));
}
bool PolicyToolUIHandler::DoUpdateSession(const std::string& contents) {
// Sanity check that contents is not too big. Otherwise, passing it to
// WriteFile will be int overflow.
if (contents.size() > static_cast<size_t>(std::numeric_limits<int>::max()))
return false;
int bytes_written = base::WriteFile(GetSessionPath(session_name_),
contents.c_str(), contents.size());
return bytes_written == static_cast<int>(contents.size());
}
void PolicyToolUIHandler::OnSessionUpdated(bool is_successful) {
if (!is_successful) {
is_saving_enabled_ = false;
CallJavascriptFunction("policy.Page.disableSaving");
}
}
void PolicyToolUIHandler::HandleUpdateSession(const base::ListValue* args) {
DCHECK(is_saving_enabled_);
DCHECK_EQ(1U, args->GetSize());
const base::DictionaryValue* policy_values = nullptr;
args->GetDictionary(0, &policy_values);
DCHECK(policy_values);
std::string converted_values;
base::JSONWriter::Write(*policy_values, &converted_values);
base::PostTaskWithTraitsAndReplyWithResult(
FROM_HERE, {base::MayBlock(), base::TaskPriority::BACKGROUND},
base::BindOnce(&PolicyToolUIHandler::DoUpdateSession,
base::Unretained(this), converted_values),
base::BindOnce(&PolicyToolUIHandler::OnSessionUpdated,
callback_weak_ptr_factory_.GetWeakPtr()));
OnSessionContentReceived(converted_values);
}
void PolicyToolUIHandler::HandleResetSession(const base::ListValue* args) {
DCHECK_EQ(0U, args->GetSize());
base::PostTaskWithTraitsAndReplyWithResult(
FROM_HERE, {base::MayBlock(), base::TaskPriority::BACKGROUND},
base::BindOnce(&PolicyToolUIHandler::DoUpdateSession,
base::Unretained(this), "{}"),
base::BindOnce(&PolicyToolUIHandler::OnSessionUpdated,
callback_weak_ptr_factory_.GetWeakPtr()));
}
void PolicyToolUIHandler::OnSessionDeleted(bool is_successful) {
if (is_successful) {
ImportFile();
}
}
void PolicyToolUIHandler::HandleDeleteSession(const base::ListValue* args) {
DCHECK_EQ(1U, args->GetSize());
base::FilePath::StringType name =
base::FilePath::FromUTF8Unsafe(args->GetList()[0].GetString()).value();
if (!IsValidSessionName(name)) {
return;
}
// Clear the current session name to ensure that we force a reload of the
// active session. This is important in case the user has deleted the current
// active session, in which case a new one is selected.
session_name_.clear();
base::PostTaskWithTraitsAndReplyWithResult(
FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE},
base::BindOnce(&base::DeleteFile, GetSessionPath(name),
/*recursive=*/false),
base::BindOnce(&PolicyToolUIHandler::OnSessionDeleted,
callback_weak_ptr_factory_.GetWeakPtr()));
}
void PolicyToolUIHandler::HandleExportLinux(const base::ListValue* args) {
DCHECK_EQ(1U, args->GetSize());
base::JSONWriter::Write(args->GetList()[0], &session_dict_for_exporting_);
ExportSessionToFile(kPolicyToolLinuxExtension);
}
void PolicyToolUIHandler::HandleExportMac(const base::ListValue* args) {
DCHECK_EQ(1U, args->GetSize());
policy::PlistWrite(args->GetList()[0], &session_dict_for_exporting_);
ExportSessionToFile(kPolicyToolMacExtension);
}
void DoWriteSessionPolicyToFile(const base::FilePath& path,
const std::string& data) {
// TODO(rodmartin): Handle when WriteFile fail.
base::WriteFile(path, data.c_str(), data.size());
}
void PolicyToolUIHandler::WriteSessionPolicyToFile(
const base::FilePath& path) const {
const std::string data = session_dict_for_exporting_;
base::PostTaskWithTraits(
FROM_HERE,
{base::MayBlock(), base::TaskPriority::BACKGROUND,
base::TaskShutdownBehavior::BLOCK_SHUTDOWN},
base::BindOnce(&DoWriteSessionPolicyToFile, path, data));
}
void PolicyToolUIHandler::FileSelected(const base::FilePath& path,
int index,
void* params) {
DCHECK(export_policies_select_file_dialog_);
WriteSessionPolicyToFile(path);
session_dict_for_exporting_.clear();
export_policies_select_file_dialog_ = nullptr;
}
void PolicyToolUIHandler::FileSelectionCanceled(void* params) {
DCHECK(export_policies_select_file_dialog_);
session_dict_for_exporting_.clear();
export_policies_select_file_dialog_ = nullptr;
}
void PolicyToolUIHandler::ExportSessionToFile(
const base::FilePath::StringType& file_extension) {
// If the "select file" dialog window is already opened, we don't want to open
// it again.
if (export_policies_select_file_dialog_)
return;
content::WebContents* webcontents = web_ui()->GetWebContents();
// Building initial path based on download preferences.
base::FilePath initial_dir =
DownloadPrefs::FromBrowserContext(webcontents->GetBrowserContext())
->DownloadPath();
base::FilePath initial_path =
initial_dir.Append(kPolicyToolDefaultSessionName)
.AddExtension(file_extension);
// TODO(rodmartin): Put an error message when the user is not allowed
// to open select file dialogs.
export_policies_select_file_dialog_ = ui::SelectFileDialog::Create(
this, std::make_unique<ChromeSelectFilePolicy>(webcontents));
ui::SelectFileDialog::FileTypeInfo file_type_info;
file_type_info.extensions = {{file_extension}};
gfx::NativeWindow owning_window = webcontents->GetTopLevelNativeWindow();
export_policies_select_file_dialog_->SelectFile(
ui::SelectFileDialog::SELECT_SAVEAS_FILE, /*title=*/base::string16(),
initial_path, &file_type_info, /*file_type_index=*/0,
/*default_extension=*/base::FilePath::StringType(), owning_window,
/*params=*/nullptr);
}
void PolicyToolUIHandler::ParsePolicyTypes(
base::DictionaryValue* policies_dict) {
// TODO(rodmartin): Is there a better way to get the
// types for each policy?.
Profile* profile = Profile::FromWebUI(web_ui());
policy::SchemaRegistry* registry =
policy::SchemaRegistryServiceFactory::GetForContext(
profile->GetOriginalProfile())
->registry();
scoped_refptr<policy::SchemaMap> schema_map = registry->schema_map();
for (const auto& policies_dict : policies_dict->DictItems()) {
policy::PolicyNamespace policy_domain;
if (policies_dict.first == "chromePolicies") {
policy_domain = policy::PolicyNamespace(policy::POLICY_DOMAIN_CHROME, "");
} else if (policies_dict.first == "extensionPolicies") {
policy_domain =
policy::PolicyNamespace(policy::POLICY_DOMAIN_EXTENSIONS, "");
} else {
// The domains should be only chromePolicies and extensionPolicies.
NOTREACHED();
continue;
}
const policy::Schema* schema = schema_map->GetSchema(policy_domain);
ParseSourcePolicyTypes(schema, &policies_dict.second);
}
}
| 40.385172 | 80 | 0.711951 | [
"vector"
] |
b7f0e9ca9895f8795e1d4c8ab4fa3d912eb735d5 | 1,729 | cpp | C++ | grooking_patterns_cpp/dp_probs/longest_common_subsequence.cpp | Amarnathpg123/grokking_coding_patterns | c615482ef2819d90cba832944943a6b5713d11f3 | [
"MIT"
] | 1 | 2021-09-19T16:41:58.000Z | 2021-09-19T16:41:58.000Z | grooking_patterns_cpp/dp_probs/longest_common_subsequence.cpp | Amarnathpg123/grokking_coding_patterns | c615482ef2819d90cba832944943a6b5713d11f3 | [
"MIT"
] | null | null | null | grooking_patterns_cpp/dp_probs/longest_common_subsequence.cpp | Amarnathpg123/grokking_coding_patterns | c615482ef2819d90cba832944943a6b5713d11f3 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
long lcs_rec(string &s, string &t, vector<vector<long>> &L, size_t i, size_t j){
if(i == 0 or j == 0)
return L[i][j] = 0;
if(s[i-1] == t[j-1]){
if(L[i-1][j-1] == -1) L[i-1][j-1] = lcs_rec(s, t, L, i-1, j-1);
return 1+L[i-1][j-1];
}
else{
if(L[i][j-1] == -1) L[i][j-1] = lcs_rec(s, t, L, i, j-1);
if(L[i-1][j] == -1) L[i-1][j] = lcs_rec(s, t, L, i-1, j);
return max(L[i][j-1], L[i-1][j]);
}
}
void printLCS(string &s) {
if(s.length() < 2) return;
string t(s.rbegin(), s.rend());
int n = s.length();
vector<vector<int>> dp(n+1, vector<int> (n+1, 0));
for(int i = 1; i <= n; ++i) {
for(int j = 1; j <= n; ++j) {
if(s[i-1] == t[j-1]) dp[i][j] = 1+dp[i-1][j-1];
else dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
}
}
int i = n, j = n;
vector<int> left, right;
string res;
while(i > 0 and j > 0) {
if(dp[i][j] == 1+dp[i-1][j-1]) {
res += s[i-1]; //only i is giving currect string not j
left.push_back(i);
i--; j--;
}
else if(dp[i][j] == dp[i-1][j]) i--;
else j--;
}
reverse(res.begin(), res.end());
cout << res << endl;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
string s, t;
cout << "Enter the strings for lcs: " << endl; cin >> s;
printLCS(s); // from one string to find longest palindrome
// cin >> t;
// vector<vector<long>> L(s.length()+1, vector<long> (t.length()+1, -1));
// printf("Longest common subsequence length: %ld\n", lcs_rec(s, t, L, s.length(), t.length()));
return 0;
} | 27.444444 | 100 | 0.459803 | [
"vector"
] |
b7f303e519f8a6da567182251df757342391c8fe | 23,017 | cc | C++ | chrome/browser/chromeos/proxy_config_service_impl_unittest.cc | SlimKatLegacy/android_external_chromium | bc611cda58cc18d0dbaa8a7aee05eb3c0742e573 | [
"BSD-3-Clause"
] | 2 | 2017-02-20T14:25:04.000Z | 2019-12-13T13:58:28.000Z | chrome/browser/chromeos/proxy_config_service_impl_unittest.cc | SlimKatLegacy/android_external_chromium | bc611cda58cc18d0dbaa8a7aee05eb3c0742e573 | [
"BSD-3-Clause"
] | 2 | 2017-07-25T09:37:22.000Z | 2017-08-04T07:18:56.000Z | chrome/browser/chromeos/proxy_config_service_impl_unittest.cc | SlimKatLegacy/android_external_chromium | bc611cda58cc18d0dbaa8a7aee05eb3c0742e573 | [
"BSD-3-Clause"
] | 2 | 2020-01-12T00:55:53.000Z | 2020-11-04T06:36:41.000Z | // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/proxy_config_service_impl.h"
#include <map>
#include <string>
#include <vector>
#include "base/format_macros.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "base/stringprintf.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "content/browser/browser_thread.h"
#include "content/common/json_value_serializer.h"
#include "net/proxy/proxy_config_service_common_unittest.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/platform_test.h"
namespace chromeos {
namespace {
struct Input { // Fields of chromeos::ProxyConfigServiceImpl::ProxyConfig.
ProxyConfigServiceImpl::ProxyConfig::Mode mode;
const char* pac_url;
const char* single_uri;
const char* http_uri;
const char* https_uri;
const char* ftp_uri;
const char* socks_uri;
const char* bypass_rules;
};
// Builds an identifier for each test in an array.
#define TEST_DESC(desc) base::StringPrintf("at line %d <%s>", __LINE__, desc)
// Shortcuts to declare enums within chromeos's ProxyConfig.
#define MK_MODE(mode) ProxyConfigServiceImpl::ProxyConfig::MODE_##mode
#define MK_SRC(src) ProxyConfigServiceImpl::ProxyConfig::SOURCE_##src
#define MK_SCHM(scheme) net::ProxyServer::SCHEME_##scheme
// Inspired from net/proxy/proxy_config_service_linux_unittest.cc.
const struct {
// Short description to identify the test
std::string description;
bool is_valid;
bool test_read_write_access;
Input input;
// Expected outputs from fields of net::ProxyConfig (via IO).
bool auto_detect;
GURL pac_url;
net::ProxyRulesExpectation proxy_rules;
} tests[] = {
{
TEST_DESC("No proxying"),
true, // is_valid
true, // test_read_write_access
{ // Input.
MK_MODE(DIRECT), // mode
},
// Expected result.
false, // auto_detect
GURL(), // pac_url
net::ProxyRulesExpectation::Empty(), // proxy_rules
},
{
TEST_DESC("Auto detect"),
true, // is_valid
true, // test_read_write_access
{ // Input.
MK_MODE(AUTO_DETECT), // mode
},
// Expected result.
true, // auto_detect
GURL(), // pac_url
net::ProxyRulesExpectation::Empty(), // proxy_rules
},
{
TEST_DESC("Valid PAC URL"),
true, // is_valid
true, // test_read_write_access
{ // Input.
MK_MODE(PAC_SCRIPT), // mode
"http://wpad/wpad.dat", // pac_url
},
// Expected result.
false, // auto_detect
GURL("http://wpad/wpad.dat"), // pac_url
net::ProxyRulesExpectation::Empty(), // proxy_rules
},
{
TEST_DESC("Invalid PAC URL"),
false, // is_valid
false, // test_read_write_access
{ // Input.
MK_MODE(PAC_SCRIPT), // mode
"wpad.dat", // pac_url
},
// Expected result.
false, // auto_detect
GURL(), // pac_url
net::ProxyRulesExpectation::Empty(), // proxy_rules
},
{
TEST_DESC("Single-host in proxy list"),
true, // is_valid
true, // test_read_write_access
{ // Input.
MK_MODE(SINGLE_PROXY), // mode
NULL, // pac_url
"www.google.com", // single_uri
},
// Expected result.
false, // auto_detect
GURL(), // pac_url
net::ProxyRulesExpectation::Single( // proxy_rules
"www.google.com:80", // single proxy
""), // bypass rules
},
{
TEST_DESC("Single-host, different port"),
true, // is_valid
false, // test_read_write_access
{ // Input.
MK_MODE(SINGLE_PROXY), // mode
NULL, // pac_url
"www.google.com:99", // single_uri
},
// Expected result.
false, // auto_detect
GURL(), // pac_url
net::ProxyRulesExpectation::Single( // proxy_rules
"www.google.com:99", // single
""), // bypass rules
},
{
TEST_DESC("Tolerate a scheme"),
true, // is_valid
false, // test_read_write_access
{ // Input.
MK_MODE(SINGLE_PROXY), // mode
NULL, // pac_url
"http://www.google.com:99", // single_uri
},
// Expected result.
false, // auto_detect
GURL(), // pac_url
net::ProxyRulesExpectation::Single( // proxy_rules
"www.google.com:99", // single proxy
""), // bypass rules
},
{
TEST_DESC("Per-scheme proxy rules"),
true, // is_valid
true, // test_read_write_access
{ // Input.
MK_MODE(PROXY_PER_SCHEME), // mode
NULL, // pac_url
NULL, // single_uri
"www.google.com:80", // http_uri
"www.foo.com:110", // https_uri
"ftp.foo.com:121", // ftp_uri
"socks.com:888", // socks_uri
},
// Expected result.
false, // auto_detect
GURL(), // pac_url
net::ProxyRulesExpectation::PerSchemeWithSocks( // proxy_rules
"www.google.com:80", // http
"https://www.foo.com:110", // https
"ftp.foo.com:121", // ftp
"socks5://socks.com:888", // fallback proxy
""), // bypass rules
},
{
TEST_DESC("Bypass rules"),
true, // is_valid
true, // test_read_write_access
{ // Input.
MK_MODE(SINGLE_PROXY), // mode
NULL, // pac_url
"www.google.com", // single_uri
NULL, NULL, NULL, NULL, // per-proto
".google.com, foo.com:99, 1.2.3.4:22, 127.0.0.1/8", // bypass_rules
},
// Expected result.
false, // auto_detect
GURL(), // pac_url
net::ProxyRulesExpectation::Single( // proxy_rules
"www.google.com:80", // single proxy
"*.google.com,*foo.com:99,1.2.3.4:22,127.0.0.1/8"), // bypass_rules
},
}; // tests
} // namespace
class ProxyConfigServiceImplTest : public PlatformTest {
protected:
ProxyConfigServiceImplTest()
: ui_thread_(BrowserThread::UI, &message_loop_),
io_thread_(BrowserThread::IO, &message_loop_) {
}
virtual ~ProxyConfigServiceImplTest() {
config_service_ = NULL;
MessageLoop::current()->RunAllPending();
}
void CreateConfigService(
const ProxyConfigServiceImpl::ProxyConfig& init_config) {
// Instantiate proxy config service with |init_config|.
config_service_ = new ProxyConfigServiceImpl(init_config);
}
void SetAutomaticProxy(
ProxyConfigServiceImpl::ProxyConfig::Mode mode,
ProxyConfigServiceImpl::ProxyConfig::Source source,
const char* pac_url,
ProxyConfigServiceImpl::ProxyConfig* config,
ProxyConfigServiceImpl::ProxyConfig::AutomaticProxy* automatic_proxy) {
config->mode = mode;
automatic_proxy->source = source;
if (pac_url)
automatic_proxy->pac_url = GURL(pac_url);
}
void SetManualProxy(
ProxyConfigServiceImpl::ProxyConfig::Mode mode,
ProxyConfigServiceImpl::ProxyConfig::Source source,
const char* server_uri,
net::ProxyServer::Scheme scheme,
ProxyConfigServiceImpl::ProxyConfig* config,
ProxyConfigServiceImpl::ProxyConfig::ManualProxy* manual_proxy) {
if (!server_uri)
return;
config->mode = mode;
manual_proxy->source = source;
manual_proxy->server = net::ProxyServer::FromURI(server_uri, scheme);
}
void InitConfigWithTestInput(
const Input& input, ProxyConfigServiceImpl::ProxyConfig::Source source,
ProxyConfigServiceImpl::ProxyConfig* init_config) {
switch (input.mode) {
case MK_MODE(DIRECT):
case MK_MODE(AUTO_DETECT):
case MK_MODE(PAC_SCRIPT):
SetAutomaticProxy(input.mode, source, input.pac_url, init_config,
&init_config->automatic_proxy);
return;
case MK_MODE(SINGLE_PROXY):
SetManualProxy(input.mode, source, input.single_uri, MK_SCHM(HTTP),
init_config, &init_config->single_proxy);
break;
case MK_MODE(PROXY_PER_SCHEME):
SetManualProxy(input.mode, source, input.http_uri, MK_SCHM(HTTP),
init_config, &init_config->http_proxy);
SetManualProxy(input.mode, source, input.https_uri, MK_SCHM(HTTPS),
init_config, &init_config->https_proxy);
SetManualProxy(input.mode, source, input.ftp_uri, MK_SCHM(HTTP),
init_config, &init_config->ftp_proxy);
SetManualProxy(input.mode, source, input.socks_uri, MK_SCHM(SOCKS5),
init_config, &init_config->socks_proxy);
break;
}
if (input.bypass_rules) {
init_config->bypass_rules.ParseFromStringUsingSuffixMatching(
input.bypass_rules);
}
}
void TestReadWriteAccessForMode(const Input& input,
ProxyConfigServiceImpl::ProxyConfig::Source source) {
// Init config from |source|.
ProxyConfigServiceImpl::ProxyConfig init_config;
InitConfigWithTestInput(input, source, &init_config);
CreateConfigService(init_config);
ProxyConfigServiceImpl::ProxyConfig config;
config_service()->UIGetProxyConfig(&config);
// For owner, write access to config should be equal CanBeWrittenByOwner().
// For non-owner, config is never writeable.
bool expected_writeable_by_owner = CanBeWrittenByOwner(source);
if (config.mode == MK_MODE(PROXY_PER_SCHEME)) {
if (input.http_uri) {
EXPECT_EQ(expected_writeable_by_owner,
config.CanBeWrittenByUser(true, "http"));
EXPECT_FALSE(config.CanBeWrittenByUser(false, "http"));
}
if (input.https_uri) {
EXPECT_EQ(expected_writeable_by_owner,
config.CanBeWrittenByUser(true, "http"));
EXPECT_FALSE(config.CanBeWrittenByUser(false, "https"));
}
if (input.ftp_uri) {
EXPECT_EQ(expected_writeable_by_owner,
config.CanBeWrittenByUser(true, "http"));
EXPECT_FALSE(config.CanBeWrittenByUser(false, "ftp"));
}
if (input.socks_uri) {
EXPECT_EQ(expected_writeable_by_owner,
config.CanBeWrittenByUser(true, "http"));
EXPECT_FALSE(config.CanBeWrittenByUser(false, "socks"));
}
} else {
EXPECT_EQ(expected_writeable_by_owner,
config.CanBeWrittenByUser(true, std::string()));
EXPECT_FALSE(config.CanBeWrittenByUser(false, std::string()));
}
}
void TestReadWriteAccessForScheme(
ProxyConfigServiceImpl::ProxyConfig::Source source,
const char* server_uri,
const std::string& scheme) {
// Init with manual |scheme| proxy.
ProxyConfigServiceImpl::ProxyConfig init_config;
ProxyConfigServiceImpl::ProxyConfig::ManualProxy* proxy =
init_config.MapSchemeToProxy(scheme);
net::ProxyServer::Scheme net_scheme = MK_SCHM(HTTP);
if (scheme == "http" || scheme == "ftp")
net_scheme = MK_SCHM(HTTP);
else if (scheme == "https")
net_scheme = MK_SCHM(HTTPS);
else if (scheme == "socks")
net_scheme = MK_SCHM(SOCKS4);
SetManualProxy(MK_MODE(PROXY_PER_SCHEME), source, server_uri, net_scheme,
&init_config, proxy);
CreateConfigService(init_config);
ProxyConfigServiceImpl::ProxyConfig config;
config_service()->UIGetProxyConfig(&config);
// For owner, write access to config should be equal CanBeWrittenByOwner().
// For non-owner, config is never writeable.
bool expected_writeable_by_owner = CanBeWrittenByOwner(source);
EXPECT_EQ(expected_writeable_by_owner,
config.CanBeWrittenByUser(true, scheme));
EXPECT_FALSE(config.CanBeWrittenByUser(false, scheme));
const char* all_schemes[] = {
"http", "https", "ftp", "socks",
};
// Rest of protos should be writeable by owner, but not writeable by
// non-owner.
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(all_schemes); ++i) {
if (scheme == all_schemes[i])
continue;
EXPECT_TRUE(config.CanBeWrittenByUser(true, all_schemes[i]));
EXPECT_FALSE(config.CanBeWrittenByUser(false, all_schemes[i]));
}
}
// Synchronously gets the latest proxy config.
bool SyncGetLatestProxyConfig(net::ProxyConfig* config) {
// Let message loop process all messages.
MessageLoop::current()->RunAllPending();
// Calls IOGetProxyConfig (which is called from
// ProxyConfigService::GetLatestProxyConfig), running on faked IO thread.
return config_service_->IOGetProxyConfig(config);
}
ProxyConfigServiceImpl* config_service() const {
return config_service_;
}
private:
bool CanBeWrittenByOwner(
ProxyConfigServiceImpl::ProxyConfig::Source source) const {
return source == MK_SRC(POLICY) ? false : true;
}
ScopedStubCrosEnabler stub_cros_enabler_;
MessageLoop message_loop_;
BrowserThread ui_thread_;
BrowserThread io_thread_;
scoped_refptr<ProxyConfigServiceImpl> config_service_;
};
TEST_F(ProxyConfigServiceImplTest, ChromeosProxyConfigToNetProxyConfig) {
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
SCOPED_TRACE(StringPrintf("Test[%" PRIuS "] %s", i,
tests[i].description.c_str()));
ProxyConfigServiceImpl::ProxyConfig init_config;
InitConfigWithTestInput(tests[i].input, MK_SRC(OWNER), &init_config);
CreateConfigService(init_config);
net::ProxyConfig config;
SyncGetLatestProxyConfig(&config);
EXPECT_EQ(tests[i].auto_detect, config.auto_detect());
EXPECT_EQ(tests[i].pac_url, config.pac_url());
EXPECT_TRUE(tests[i].proxy_rules.Matches(config.proxy_rules()));
}
}
TEST_F(ProxyConfigServiceImplTest, ModifyFromUI) {
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
SCOPED_TRACE(StringPrintf("Test[%" PRIuS "] %s", i,
tests[i].description.c_str()));
// Init with direct.
ProxyConfigServiceImpl::ProxyConfig init_config;
SetAutomaticProxy(MK_MODE(DIRECT), MK_SRC(OWNER), NULL, &init_config,
&init_config.automatic_proxy);
CreateConfigService(init_config);
// Set config to tests[i].input via UI.
net::ProxyBypassRules bypass_rules;
const Input& input = tests[i].input;
switch (input.mode) {
case MK_MODE(DIRECT) :
config_service()->UISetProxyConfigToDirect();
break;
case MK_MODE(AUTO_DETECT) :
config_service()->UISetProxyConfigToAutoDetect();
break;
case MK_MODE(PAC_SCRIPT) :
config_service()->UISetProxyConfigToPACScript(GURL(input.pac_url));
break;
case MK_MODE(SINGLE_PROXY) :
config_service()->UISetProxyConfigToSingleProxy(
net::ProxyServer::FromURI(input.single_uri, MK_SCHM(HTTP)));
if (input.bypass_rules) {
bypass_rules.ParseFromStringUsingSuffixMatching(input.bypass_rules);
config_service()->UISetProxyConfigBypassRules(bypass_rules);
}
break;
case MK_MODE(PROXY_PER_SCHEME) :
if (input.http_uri) {
config_service()->UISetProxyConfigToProxyPerScheme("http",
net::ProxyServer::FromURI(input.http_uri, MK_SCHM(HTTP)));
}
if (input.https_uri) {
config_service()->UISetProxyConfigToProxyPerScheme("https",
net::ProxyServer::FromURI(input.https_uri, MK_SCHM(HTTPS)));
}
if (input.ftp_uri) {
config_service()->UISetProxyConfigToProxyPerScheme("ftp",
net::ProxyServer::FromURI(input.ftp_uri, MK_SCHM(HTTP)));
}
if (input.socks_uri) {
config_service()->UISetProxyConfigToProxyPerScheme("socks",
net::ProxyServer::FromURI(input.socks_uri, MK_SCHM(SOCKS5)));
}
if (input.bypass_rules) {
bypass_rules.ParseFromStringUsingSuffixMatching(input.bypass_rules);
config_service()->UISetProxyConfigBypassRules(bypass_rules);
}
break;
}
// Retrieve config from IO thread.
net::ProxyConfig io_config;
SyncGetLatestProxyConfig(&io_config);
EXPECT_EQ(tests[i].auto_detect, io_config.auto_detect());
EXPECT_EQ(tests[i].pac_url, io_config.pac_url());
EXPECT_TRUE(tests[i].proxy_rules.Matches(io_config.proxy_rules()));
// Retrieve config from UI thread.
ProxyConfigServiceImpl::ProxyConfig ui_config;
config_service()->UIGetProxyConfig(&ui_config);
EXPECT_EQ(input.mode, ui_config.mode);
if (tests[i].is_valid) {
if (input.pac_url)
EXPECT_EQ(GURL(input.pac_url), ui_config.automatic_proxy.pac_url);
const net::ProxyRulesExpectation& proxy_rules = tests[i].proxy_rules;
if (input.single_uri)
EXPECT_EQ(proxy_rules.single_proxy,
ui_config.single_proxy.server.ToURI());
if (input.http_uri)
EXPECT_EQ(proxy_rules.proxy_for_http,
ui_config.http_proxy.server.ToURI());
if (input.https_uri)
EXPECT_EQ(proxy_rules.proxy_for_https,
ui_config.https_proxy.server.ToURI());
if (input.ftp_uri)
EXPECT_EQ(proxy_rules.proxy_for_ftp,
ui_config.ftp_proxy.server.ToURI());
if (input.socks_uri) {
EXPECT_EQ(proxy_rules.fallback_proxy,
ui_config.socks_proxy.server.ToURI());
}
if (input.bypass_rules)
EXPECT_TRUE(bypass_rules.Equals(ui_config.bypass_rules));
}
}
}
TEST_F(ProxyConfigServiceImplTest, ProxyChangedObserver) {
// This is used to observe for OnProxyConfigChanged notification.
class ProxyChangedObserver : public net::ProxyConfigService::Observer {
public:
explicit ProxyChangedObserver(
const scoped_refptr<ProxyConfigServiceImpl>& config_service)
: config_service_(config_service) {
config_service_->AddObserver(this);
}
virtual ~ProxyChangedObserver() {
config_service_->RemoveObserver(this);
}
net::ProxyConfigService::ConfigAvailability availability() const {
return availability_;
}
const net::ProxyConfig& config() const {
return config_;
}
private:
virtual void OnProxyConfigChanged(
const net::ProxyConfig& config,
net::ProxyConfigService::ConfigAvailability availability) {
config_ = config;
availability_ = availability;
}
scoped_refptr<ProxyConfigServiceImpl> config_service_;
net::ProxyConfigService::ConfigAvailability availability_;
net::ProxyConfig config_;
};
// Init with direct.
ProxyConfigServiceImpl::ProxyConfig init_config;
SetAutomaticProxy(MK_MODE(DIRECT), MK_SRC(OWNER), NULL, &init_config,
&init_config.automatic_proxy);
CreateConfigService(init_config);
ProxyChangedObserver observer(config_service());
// Set to pac script from UI.
EXPECT_TRUE(config_service()->UISetProxyConfigToPACScript(
GURL("http://wpad.dat")));
// Retrieve config from IO thread.
net::ProxyConfig io_config;
SyncGetLatestProxyConfig(&io_config);
// Observer should have gotten the same new proxy config.
EXPECT_EQ(net::ProxyConfigService::CONFIG_VALID, observer.availability());
EXPECT_TRUE(io_config.Equals(observer.config()));
}
TEST_F(ProxyConfigServiceImplTest, SerializeAndDeserialize) {
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
if (!tests[i].is_valid)
continue;
SCOPED_TRACE(StringPrintf("Test[%" PRIuS "] %s", i,
tests[i].description.c_str()));
ProxyConfigServiceImpl::ProxyConfig source_config;
InitConfigWithTestInput(tests[i].input, MK_SRC(OWNER), &source_config);
// Serialize source_config into std::string.
std::string serialized_value;
EXPECT_TRUE(source_config.Serialize(&serialized_value));
// Deserialize std:string into target_config.
ProxyConfigServiceImpl::ProxyConfig target_config;
EXPECT_TRUE(target_config.Deserialize(serialized_value));
// Compare the configs after serialization and deserialization.
net::ProxyConfig net_src_cfg;
net::ProxyConfig net_tgt_cfg;
source_config.ToNetProxyConfig(&net_src_cfg);
target_config.ToNetProxyConfig(&net_tgt_cfg);
#if !defined(NDEBUG)
if (!net_src_cfg.Equals(net_tgt_cfg)) {
std::string src_output, tgt_output;
JSONStringValueSerializer src_serializer(&src_output);
src_serializer.Serialize(*net_src_cfg.ToValue());
JSONStringValueSerializer tgt_serializer(&tgt_output);
tgt_serializer.Serialize(*net_tgt_cfg.ToValue());
VLOG(1) << "source:\n" << src_output
<< "\ntarget:\n" << tgt_output;
}
#endif // !defined(NDEBUG)
EXPECT_TRUE(net_src_cfg.Equals(net_tgt_cfg));
}
}
TEST_F(ProxyConfigServiceImplTest, ReadWriteAccessForPolicySource) {
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
if (!tests[i].test_read_write_access)
continue;
SCOPED_TRACE(StringPrintf("Test[%" PRIuS "] %s", i,
tests[i].description.c_str()));
TestReadWriteAccessForMode(tests[i].input, MK_SRC(POLICY));
}
}
TEST_F(ProxyConfigServiceImplTest, ReadWriteAccessForOwnerSource) {
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
if (!tests[i].test_read_write_access)
continue;
SCOPED_TRACE(StringPrintf("Test[%" PRIuS "] %s", i,
tests[i].description.c_str()));
TestReadWriteAccessForMode(tests[i].input, MK_SRC(OWNER));
}
}
TEST_F(ProxyConfigServiceImplTest, ReadWriteAccessForMixedSchemes) {
const char* http_uri = "www.google.com:80";
const char* https_uri = "www.foo.com:110";
const char* ftp_uri = "ftp.foo.com:121";
const char* socks_uri = "socks.com:888";
// Init with policy source.
TestReadWriteAccessForScheme(MK_SRC(POLICY), http_uri, "http");
TestReadWriteAccessForScheme(MK_SRC(POLICY), https_uri, "https");
TestReadWriteAccessForScheme(MK_SRC(POLICY), ftp_uri, "ftp");
TestReadWriteAccessForScheme(MK_SRC(POLICY), socks_uri, "socks");
// Init with owner source.
TestReadWriteAccessForScheme(MK_SRC(OWNER), http_uri, "http");
TestReadWriteAccessForScheme(MK_SRC(OWNER), https_uri, "https");
TestReadWriteAccessForScheme(MK_SRC(OWNER), ftp_uri, "ftp");
TestReadWriteAccessForScheme(MK_SRC(OWNER), socks_uri, "socks");
}
} // namespace chromeos
| 34.56006 | 79 | 0.644089 | [
"vector"
] |
b7f8874cbf622a20d0ce46c90341c4426cfe498d | 856 | cpp | C++ | reduction.cpp | SCOREC/omegah_examples | 7c1f15b0a3ceaf1dc8c1f8bc897b58cf75243688 | [
"BSD-3-Clause"
] | 1 | 2020-02-10T05:19:20.000Z | 2020-02-10T05:19:20.000Z | reduction.cpp | joshia5/omegah_examples | 34648e520d629f6ac35021be24c4813801b4ee79 | [
"BSD-3-Clause"
] | 5 | 2020-11-10T18:49:40.000Z | 2021-03-10T03:47:27.000Z | reduction.cpp | SCOREC/omegah_examples | 7c1f15b0a3ceaf1dc8c1f8bc897b58cf75243688 | [
"BSD-3-Clause"
] | 1 | 2019-12-09T01:22:36.000Z | 2019-12-09T01:22:36.000Z | #include <Omega_h_file.hpp>
#include <Omega_h_library.hpp>
#include <Omega_h_mesh.hpp>
#include <Omega_h_array_ops.hpp>
#include <Omega_h_for.hpp>
using namespace Omega_h;
int main(int argc, char** argv) {
auto lib = Library(&argc, &argv);
if(argc!=2) {
fprintf(stderr, "Usage: %s <input mesh>\n", argv[0]);
return 0;
}
const auto inmesh = argv[1];
Mesh mesh(&lib);
binary::read(inmesh, lib.world(), &mesh);
const auto rank = lib.world()->rank();
const auto comm = lib.world();
LO max_input = 45;
Write<LO> for_max(mesh.nfaces(), 0, "for_max");
if (!rank) {
auto set_max_val = OMEGA_H_LAMBDA(LO i) {
if(!i) for_max[i] = max_input;
};
parallel_for(1, set_max_val, "set_max_val");
}
Read<LO> for_max_r(for_max);
auto max_val = get_max(comm, for_max_r);
assert (max_val == max_input);
return 0;
}
| 24.457143 | 57 | 0.648364 | [
"mesh"
] |
b7faa26a6bb636d84fac147cf4733da7cda4ed53 | 16,681 | cc | C++ | rc_roi_manager_gui/src/interactive_roi_selection.cc | dragandbot/rc_visard_ros | 9eeace69677867646b211812c2745ee7e26e39b6 | [
"BSD-3-Clause"
] | null | null | null | rc_roi_manager_gui/src/interactive_roi_selection.cc | dragandbot/rc_visard_ros | 9eeace69677867646b211812c2745ee7e26e39b6 | [
"BSD-3-Clause"
] | null | null | null | rc_roi_manager_gui/src/interactive_roi_selection.cc | dragandbot/rc_visard_ros | 9eeace69677867646b211812c2745ee7e26e39b6 | [
"BSD-3-Clause"
] | 1 | 2019-09-17T09:56:14.000Z | 2019-09-17T09:56:14.000Z | /*
* Copyright (c) 2019 Roboception GmbH
*
* Author: Carlos Xavier Garcia Briones
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "interactive_roi_selection.h"
#include <rc_pick_client/SetRegionOfInterest.h>
#include <rc_pick_client/GetRegionsOfInterest.h>
namespace rc_roi_manager_gui
{
InteractiveRoiSelection::InteractiveRoiSelection()
{
nh_ = std::make_shared<ros::NodeHandle>();
server_.reset(new interactive_markers::InteractiveMarkerServer("rc_roi_manager_gui", "", true));
ros::Duration(0.1).sleep();
}
InteractiveRoiSelection::~InteractiveRoiSelection()
{
ROS_INFO("Disconnecting the interactive region of interest server..");
server_.reset();
}
void
InteractiveRoiSelection::computeVectorRotation(const tf::Vector3 &v, const tf::Quaternion &q, tf::Vector3 &rot_v)
{
tf::Vector3 u(q.x(), q.y(), q.z());
double w = q.w();
rot_v = 2.0f * u.dot(v) * u + (w * w - u.dot(u)) * v + 2.0f * w * u.cross(v);
}
void
InteractiveRoiSelection::processRoiPoseFeedback(
const visualization_msgs::InteractiveMarkerFeedbackConstPtr &feedback)
{
ROS_DEBUG_STREAM(feedback->marker_name << " is now at "
<< feedback->pose.position.x << ", " << feedback->pose.position.y
<< ", " << feedback->pose.position.z);
visualization_msgs::InteractiveMarker corner_int_marker;
server_->get("corner_0", corner_int_marker);
geometry_msgs::Pose corner_pose;
if (corner_int_marker.pose.orientation.w == 0) corner_int_marker.pose.orientation.w = 1;
// Find out if a rotation has taken place
double orientation_change = (feedback->pose.orientation.x + feedback->pose.orientation.y +
feedback->pose.orientation.z + feedback->pose.orientation.w) -
(corner_int_marker.pose.orientation.x + corner_int_marker.pose.orientation.y +
corner_int_marker.pose.orientation.z + corner_int_marker.pose.orientation.w);
if (orientation_change < 0) orientation_change *= -1;
bool center_has_rotated = (orientation_change > 0.001);
corner_pose.orientation = feedback->pose.orientation;
// Calculate new corner position due to rotation
if (center_has_rotated)
{
tf::Quaternion q_center, q_corner;
tf::quaternionMsgToTF(corner_int_marker.pose.orientation, q_corner);
tf::quaternionMsgToTF(feedback->pose.orientation, q_center);
// Compute rotation quaternion
tf::Quaternion rot_quaternion = q_center * q_corner.inverse();
// Move corner back to its relative position
tf::Vector3 transf_position;
tf::Vector3 translation_corner_to_center(corner_int_marker.pose.position.x - feedback->pose.position.x,
corner_int_marker.pose.position.y - feedback->pose.position.y,
corner_int_marker.pose.position.z - feedback->pose.position.z);
computeVectorRotation(translation_corner_to_center, rot_quaternion, transf_position);
corner_pose.position.x = transf_position.x() + feedback->pose.position.x;
corner_pose.position.y = transf_position.y() + feedback->pose.position.y;
corner_pose.position.z = transf_position.z() + feedback->pose.position.z;
ROS_DEBUG_STREAM(
"center quaternion: " << q_center.x() << "," << q_center.y() << "," << q_center.z() << "," << q_center.w());
ROS_DEBUG_STREAM(
"corner quaternion: " << q_corner.x() << "," << q_corner.y() << "," << q_corner.z() << "," << q_corner.w());
ROS_DEBUG_STREAM(
"rotation quaternion: " << rot_quaternion.x() << "," << rot_quaternion.y() << "," << rot_quaternion.z()
<< "," << rot_quaternion.w());
}
else
{
// Corner position has to be updated
corner_pose.position.x = corner_int_marker.pose.position.x + feedback->pose.position.x - center_position_.x();
corner_pose.position.y = corner_int_marker.pose.position.y + feedback->pose.position.y - center_position_.y();
corner_pose.position.z = corner_int_marker.pose.position.z + feedback->pose.position.z - center_position_.z();
}
server_->setPose("corner_0", corner_pose);
server_->applyChanges();
// Saving the present center position to compute the future displacement of the center
tf::quaternionMsgToTF(corner_pose.orientation, center_orientation_);
tf::pointMsgToTF(feedback->pose.position, center_position_);
ROS_DEBUG_STREAM("corner_0" << " is now at "
<< corner_pose.position.x << ", " << corner_pose.position.y
<< ", " << corner_pose.position.z);
}
void InteractiveRoiSelection::processSphereSizeFeedback(
const visualization_msgs::InteractiveMarkerFeedbackConstPtr &feedback)
{
tf::Vector3 position;
tf::pointMsgToTF(feedback->pose.position, position);
float radius = (position - center_position_).length();
dimensions_ = tf::Vector3(radius, radius, radius);
updateCenterMarker();
}
void InteractiveRoiSelection::updateCenterMarker()
{
server_->erase("center");
makeInteractiveMarker("center", "Pose", center_position_, true, dimensions_, center_orientation_);
server_->applyChanges();
}
void
InteractiveRoiSelection::processRoiSizeFeedback(
const visualization_msgs::InteractiveMarkerFeedbackConstPtr &feedback)
{
ROS_DEBUG_STREAM(feedback->marker_name << " is now at "
<< feedback->pose.position.x << ", " << feedback->pose.position.y
<< ", " << feedback->pose.position.z);
tf::Vector3 present_dimensions(feedback->pose.position.x - center_position_.x(),
feedback->pose.position.y - center_position_.y(),
feedback->pose.position.z - center_position_.z());
// Compute rotated dimensions of the box
computeVectorRotation(present_dimensions, center_orientation_.inverse(), dimensions_);
dimensions_ = dimensions_.absolute();
updateCenterMarker();
}
// Generate marker box
visualization_msgs::Marker
InteractiveRoiSelection::makeMarker(tf::Vector3 box_dimensions, bool is_center)
{
visualization_msgs::Marker marker;
marker.type = interactive_roi_.primitive.type;
if (is_center)
{
float center_scale = 2;
marker.scale.x = center_scale * box_dimensions.x();
marker.scale.y = center_scale * box_dimensions.y();
marker.scale.z = center_scale * box_dimensions.z();
marker.color.r = 150 / 255.0;
marker.color.g = 104 / 2;
marker.color.b = 251 / 255.0;
marker.color.a = 0.3;
}
else
{
marker.scale.x = box_dimensions.x();
marker.scale.y = box_dimensions.y();
marker.scale.z = box_dimensions.z();
marker.color.r = 255 / 255.0;
marker.color.g = 204 / 2;
marker.color.b = 0 / 255.0;
marker.color.a = 1.0;
}
return marker;
}
void InteractiveRoiSelection::makeSphereControls(visualization_msgs::InteractiveMarker &interactive_marker, bool
is_center)
{
// Add controls for axis rotation and positioning
if (is_center)
{
visualization_msgs::InteractiveMarkerControl control;
control.orientation_mode = visualization_msgs::InteractiveMarkerControl::FIXED;
control.orientation.w = 1;
control.orientation.x = 1;
control.orientation.y = 0;
control.orientation.z = 0;
control.name = "move_x";
control.interaction_mode = visualization_msgs::InteractiveMarkerControl::MOVE_AXIS;
interactive_marker.controls.push_back(control);
control.name = "move_y";
control.orientation.w = 1;
control.orientation.x = 0;
control.orientation.y = 1;
control.orientation.z = 0;
control.interaction_mode = visualization_msgs::InteractiveMarkerControl::MOVE_AXIS;
interactive_marker.controls.push_back(control);
control.name = "move_z";
control.orientation.w = 1;
control.orientation.x = 0;
control.orientation.y = 0;
control.orientation.z = 1;
control.interaction_mode = visualization_msgs::InteractiveMarkerControl::MOVE_AXIS;
interactive_marker.controls.push_back(control);
}
else
{
// Rotate corner marker orientation 45 degrees on the y-Axis.
visualization_msgs::InteractiveMarkerControl control;
control.orientation_mode = visualization_msgs::InteractiveMarkerControl::FIXED;
control.orientation.w = 0.923879468105164;
control.orientation.x = 0;
control.orientation.y = 0.382683587855188;
control.orientation.z = 0;
control.name = "move_x";
control.interaction_mode = visualization_msgs::InteractiveMarkerControl::MOVE_AXIS;
interactive_marker.controls.push_back(control);
}
}
// Generate interactive markers
void InteractiveRoiSelection::makeBoxControls(visualization_msgs::InteractiveMarker &interactive_marker,
bool is_center)
{
// Add controls for axis rotation and positioning
visualization_msgs::InteractiveMarkerControl control;
control.orientation_mode = visualization_msgs::InteractiveMarkerControl::INHERIT;
control.orientation.w = 1;
control.orientation.x = 1;
control.orientation.y = 0;
control.orientation.z = 0;
control.name = "move_x";
control.interaction_mode = visualization_msgs::InteractiveMarkerControl::MOVE_AXIS;
interactive_marker.controls.push_back(control);
if (is_center)
{
control.name = "rotate_x";
control.interaction_mode = visualization_msgs::InteractiveMarkerControl::ROTATE_AXIS;
interactive_marker.controls.push_back(control);
}
control.name = "move_y";
control.orientation.w = 1;
control.orientation.x = 0;
control.orientation.y = 1;
control.orientation.z = 0;
control.interaction_mode = visualization_msgs::InteractiveMarkerControl::MOVE_AXIS;
interactive_marker.controls.push_back(control);
if (is_center)
{
control.name = "rotate_y";
control.interaction_mode = visualization_msgs::InteractiveMarkerControl::ROTATE_AXIS;
interactive_marker.controls.push_back(control);
}
control.name = "move_z";
control.orientation.w = 1;
control.orientation.x = 0;
control.orientation.y = 0;
control.orientation.z = 1;
control.interaction_mode = visualization_msgs::InteractiveMarkerControl::MOVE_AXIS;
interactive_marker.controls.push_back(control);
if (is_center)
{
control.name = "rotate_z";
control.interaction_mode = visualization_msgs::InteractiveMarkerControl::ROTATE_AXIS;
interactive_marker.controls.push_back(control);
}
}
// Generate interactive markers
void InteractiveRoiSelection::makeInteractiveMarker(std::string int_marker_name, std::string int_marker_description,
const tf::Vector3 &position, bool is_center,
tf::Vector3 box_dimensions, tf::Quaternion box_orientation)
{
visualization_msgs::InteractiveMarker int_marker;
int_marker.header.frame_id = interactive_roi_.pose.header.frame_id;
tf::pointTFToMsg(position, int_marker.pose.position);
tf::quaternionTFToMsg(box_orientation, int_marker.pose.orientation);
int_marker.scale = 1.7 * box_dimensions[box_dimensions.maxAxis()];
int_marker.name = int_marker_name;
int_marker.description = int_marker_description;
// insert a marker
visualization_msgs::InteractiveMarkerControl control;
control.always_visible = is_center;
control.markers.push_back(makeMarker(box_dimensions, is_center));
control.interaction_mode = visualization_msgs::InteractiveMarkerControl::NONE;
int_marker.controls.push_back(control);
int_marker.controls.back();
if (interactive_roi_.primitive.type == shape_msgs::SolidPrimitive::Type::BOX)
{
makeBoxControls(int_marker, is_center);
server_->insert(int_marker);
if (is_center)
{
server_->setCallback(int_marker.name,
boost::bind(&InteractiveRoiSelection::processRoiPoseFeedback, this, _1));
}
else
{
server_->setCallback(int_marker.name,
boost::bind(&InteractiveRoiSelection::processRoiSizeFeedback, this, _1));
}
}
else if (interactive_roi_.primitive.type == shape_msgs::SolidPrimitive::Type::SPHERE)
{
makeSphereControls(int_marker, is_center);
server_->insert(int_marker);
if (is_center)
{
server_->setCallback(int_marker.name,
boost::bind(&InteractiveRoiSelection::processRoiPoseFeedback, this, _1));
}
else
{
server_->setCallback(int_marker.name,
boost::bind(&InteractiveRoiSelection::processSphereSizeFeedback, this, _1));
}
}
else
{
ROS_FATAL("The provided shape is currently not supported.");
}
}
bool InteractiveRoiSelection::setInteractiveRoi(const rc_pick_client::RegionOfInterest &roi)
{
interactive_roi_ = roi;
tf::quaternionMsgToTF(interactive_roi_.pose.pose.orientation, center_orientation_);
tf::pointMsgToTF(interactive_roi_.pose.pose.position, center_position_);
tf::Vector3 corner_position_rot;
if (interactive_roi_.primitive.type == shape_msgs::SolidPrimitive::Type::BOX)
{
dimensions_ = tf::Vector3(interactive_roi_.primitive.dimensions[0] / 2,
interactive_roi_.primitive.dimensions[1] / 2,
interactive_roi_.primitive.dimensions[2] / 2);
// Rotate corner marker position with the roi orientation.
computeVectorRotation(dimensions_, center_orientation_, corner_position_rot);
}
else if (interactive_roi_.primitive.type == shape_msgs::SolidPrimitive::Type::SPHERE)
{
dimensions_ = tf::Vector3(interactive_roi_.primitive.dimensions[0], interactive_roi_.primitive.dimensions[0],
interactive_roi_.primitive.dimensions[0]);
// Rotate corner marker position 45 degrees on the y-Axis.
corner_position_rot = tf::Vector3(dimensions_.x(), 0, 0);
computeVectorRotation(corner_position_rot, tf::Quaternion(0, 0.382683587855188, 0, 0.923879468105164),
corner_position_rot);
}
else
{
ROS_ERROR_STREAM("An unsupported primitive was used.");
return false;
}
makeInteractiveMarker("center", "Pose", center_position_, true,
dimensions_, center_orientation_);
makeInteractiveMarker("corner_0", "Size",
center_position_ + corner_position_rot, false,
tf::Vector3(0.02, 0.02, 0.02), center_orientation_);
server_->applyChanges();
return true;
}
bool InteractiveRoiSelection::getInteractiveRoi(rc_pick_client::RegionOfInterest &roi)
{
if (interactive_roi_.primitive.type == shape_msgs::SolidPrimitive::Type::BOX)
{
dimensions_ = dimensions_ * 2;
}
tf::pointTFToMsg(center_position_, interactive_roi_.pose.pose.position);
tf::quaternionTFToMsg(center_orientation_, interactive_roi_.pose.pose.orientation);
interactive_roi_.primitive.dimensions[0] = dimensions_.x();
interactive_roi_.primitive.dimensions[1] = dimensions_.y();
interactive_roi_.primitive.dimensions[2] = dimensions_.z();
roi = interactive_roi_;
server_->clear();
server_->applyChanges();
return true;
}
} //rc_roi_manager_gui
| 39.249412 | 120 | 0.704094 | [
"shape"
] |
b7fc14b48fe5a834e49f71e4bc72d0cdeaf44365 | 2,856 | cpp | C++ | test/test_3.cpp | active911/fastcache | a845449b54bee4555ed957ccfe373c34333389cb | [
"Apache-2.0"
] | 9 | 2016-03-16T06:18:02.000Z | 2021-02-07T20:59:19.000Z | test/test_3.cpp | iamrameshkumar/fastcache | a845449b54bee4555ed957ccfe373c34333389cb | [
"Apache-2.0"
] | null | null | null | test/test_3.cpp | iamrameshkumar/fastcache | a845449b54bee4555ed957ccfe373c34333389cb | [
"Apache-2.0"
] | 6 | 2016-08-29T23:55:09.000Z | 2020-10-11T18:43:03.000Z |
// Test3
// Speed check
// Do 9000 reads and writes, fast
// This is also a test of using ints for keys
// Run with 30 threads
#define THREAD_COUNT 30
#define OBJECT_COUNT 1000
#define FASTCACHE_TEST_SMALL
// Clock source
#define CLOCKSRC CLOCK_MONOTONIC_RAW
#include <iostream>
#include <string>
#include <boost/shared_ptr.hpp>
#include <boost/thread.hpp>
#include <boost/detail/atomic_count.hpp>
#include "../Fastcache.h"
#include "TestClass.h"
#include <time.h>
#include <cassert>
using namespace std;
using namespace active911;
using boost::shared_ptr;
using boost::thread;
// Counter for thread runloop
boost::detail::atomic_count run(1);
// The cache
Fastcache<unsigned int, TestClass>cache;
// Timer
struct timespec start;
struct timespec end;
void load_cache(int thread_number) {
// Create a cache object
for(int n=0; n<OBJECT_COUNT; n++){
int key=(thread_number*1000000)+n;
shared_ptr<TestClass>obj=shared_ptr<TestClass>(new TestClass());
cache.set(key, obj);
}
}
void read_cache(int thread_number) {
// Read
for(int n=0; n<OBJECT_COUNT; n++){
int key=(thread_number*1000000)+n;
shared_ptr<TestClass>obj=cache.get(key);
// assert(obj->name.compare(s.str())==0);
}
}
int main(int argc, char **argv) {
// Setup cout
cout.precision(5);
// Start load test
cout << "Testing with " << THREAD_COUNT << " simultaneous threads" << endl;
cout << "Object size is " << sizeof(TestClass) << " bytes" << endl;
cout << "Loading up cache..." << flush;
clock_gettime(CLOCKSRC, &start);
// Start threads
vector<shared_ptr<boost::thread> > threads;
for(int n=0; n<THREAD_COUNT; n++){
threads.push_back(shared_ptr<boost::thread>(new boost::thread(&load_cache,n)));
}
// Join the threads
--run;
for(int n=0; n<THREAD_COUNT; n++){
threads[n]->join();
}
// End the load test
clock_gettime(CLOCKSRC, &end);
double start_time=(double)start.tv_sec+((double)start.tv_nsec/1000000000.0);
double end_time=(double)end.tv_sec+((double)end.tv_nsec/1000000000.0);
double elapsed_time=end_time-start_time;
cout << ( THREAD_COUNT * OBJECT_COUNT ) << " objects stored in " << elapsed_time << " sec" << endl;
threads.clear();
// Start read test
cout << "Reading cache..." << flush;
clock_gettime(CLOCKSRC, &start);
// Start threads
for(int n=0; n<THREAD_COUNT; n++){
threads.push_back(shared_ptr<boost::thread>(new boost::thread(&read_cache,n)));
}
// Join the threads
--run;
for(int n=0; n<THREAD_COUNT; n++){
threads[n]->join();
}
// End the load test
clock_gettime(CLOCKSRC, &end);
start_time=(double)start.tv_sec+((double)start.tv_nsec/1000000000.0);
end_time=(double)end.tv_sec+((double)end.tv_nsec/1000000000.0);
elapsed_time=end_time-start_time;
cout << ( THREAD_COUNT * OBJECT_COUNT ) << " objects read in " << elapsed_time << " sec" << endl;
return 0;
}
| 19.696552 | 100 | 0.690826 | [
"object",
"vector"
] |
b7fcdeb14dde3f1861dbeb1c5dc63fd5a690d801 | 59,764 | cpp | C++ | c++/src/connect/ncbi_pipe.cpp | OpenHero/gblastn | a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8 | [
"MIT"
] | 31 | 2016-12-09T04:56:59.000Z | 2021-12-31T17:19:10.000Z | c++/src/connect/ncbi_pipe.cpp | OpenHero/gblastn | a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8 | [
"MIT"
] | 6 | 2017-03-10T17:25:13.000Z | 2021-09-22T15:49:49.000Z | c++/src/connect/ncbi_pipe.cpp | OpenHero/gblastn | a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8 | [
"MIT"
] | 20 | 2015-01-04T02:15:17.000Z | 2021-12-03T02:31:43.000Z | /* $Id: ncbi_pipe.cpp 363410 2012-05-16 17:03:41Z lavr $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Authors: Anton Lavrentiev, Mike DiCuccio, Vladimir Ivanov
*
* File Description:
* Inter-process pipe with a spawned process.
*
*/
#include <ncbi_pch.hpp>
/* Cancel __wur (warn unused result) ill effects in GCC */
#ifdef _FORTIFY_SOURCE
# undef _FORTIFY_SOURCE
#endif /*_FORTIFY_SOURCE*/
#define _FORTIFY_SOURCE 0
#include <connect/error_codes.hpp>
#include <connect/ncbi_pipe.hpp>
#include <connect/ncbi_util.h>
#include <corelib/ncbi_system.hpp>
#include <corelib/stream_utils.hpp>
#ifdef NCBI_OS_MSWIN
# include <windows.h>
# include <corelib/ncbiexec.hpp>
#elif defined NCBI_OS_UNIX
# include <errno.h>
# include <fcntl.h>
# include <signal.h>
# include <unistd.h>
# include <sys/time.h>
# include <sys/types.h>
# include <sys/wait.h>
#else
# error "Class CPipe is supported only on Windows and Unix"
#endif
#define NCBI_USE_ERRCODE_X Connect_Pipe
#define IS_SET(flags, mask) (((flags) & (mask)) == (mask))
BEGIN_NCBI_SCOPE
// Predefined timeout (in milliseconds)
const unsigned long kWaitPrecision = 100;
//////////////////////////////////////////////////////////////////////////////
//
// Auxiliary functions
//
static STimeout* s_SetTimeout(const STimeout* from, STimeout* to)
{
if ( !from ) {
return const_cast<STimeout*>(kInfiniteTimeout);
}
to->sec = from->usec / 1000000 + from->sec;
to->usec = from->usec % 1000000;
return to;
}
static EIO_Status s_Close(const CProcess& process, CPipe::TCreateFlags flags,
const STimeout* timeout, int* exitcode)
{
CProcess::CExitInfo exitinfo;
int x_exitcode = process.Wait(NcbiTimeoutToMs(timeout), &exitinfo);
EIO_Status status;
if (x_exitcode < 0) {
if ( !exitinfo.IsPresent() ) {
status = eIO_Unknown;
} else if ( !exitinfo.IsAlive() ) {
status = eIO_Unknown;
#ifdef NCBI_OS_UNIX
if ( exitinfo.IsSignaled() ) {
x_exitcode = -(exitinfo.GetSignal() + 1000);
}
#endif //NCBI_OS_UNIX
} else {
status = eIO_Timeout;
if ( !IS_SET(flags, CPipe::fKeepOnClose) ) {
if ( IS_SET(flags, CPipe::fKillOnClose) ) {
unsigned long x_timeout;
if (!timeout || (timeout->sec | timeout->usec)) {
x_timeout = CProcess::kDefaultKillTimeout;
} else {
x_timeout = 0/*fast but unsafe*/;
}
bool killed;
if ( IS_SET(flags, CPipe::fNewGroup) ) {
killed = process.KillGroup(x_timeout);
} else {
killed = process.Kill (x_timeout);
}
status = killed ? eIO_Success : eIO_Unknown;
} else {
status = eIO_Success;
}
}
}
} else {
_ASSERT(exitinfo.IsPresent());
_ASSERT(exitinfo.IsExited());
_ASSERT(exitinfo.GetExitCode() == x_exitcode);
status = eIO_Success;
}
if ( exitcode ) {
*exitcode = x_exitcode;
}
return status;
}
//////////////////////////////////////////////////////////////////////////////
//
// Class CPipeHandle handles forwarded requests from CPipe.
// This class is reimplemented in a platform-specific fashion where needed.
//
#if defined(NCBI_OS_MSWIN)
#define PIPE_THROW(err, errtxt) \
{ \
DWORD _err = err; \
string _errstr(errtxt); \
throw s_WinError(_err, _errstr); \
}
static string s_WinError(DWORD error, string& message)
{
TXChar* errstr = NULL;
DWORD rv = ::FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_MAX_WIDTH_MASK |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, error,
MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT),
(TXChar*) &errstr, 0, NULL);
if (!rv && errstr) {
::LocalFree(errstr);
errstr = NULL;
}
int dynamic = 0/*false*/;
const char* result = ::NcbiMessagePlusError(&dynamic,
message.c_str(),
(int) error,
_T_CSTRING(errstr));
if (errstr) {
::LocalFree(errstr);
}
string retval;
if (result) {
retval = result;
if (dynamic) {
free((void*) result);
}
} else {
retval.swap(message);
}
return retval;
}
//////////////////////////////////////////////////////////////////////////////
//
// CPipeHandle -- MS Windows version
//
class CPipeHandle
{
public:
CPipeHandle(void);
~CPipeHandle();
EIO_Status Open(const string& cmd, const vector<string>& args,
CPipe::TCreateFlags create_flags,
const string& current_dir,
const char* const env[]);
void OpenSelf(void);
EIO_Status Close(int* exitcode, const STimeout* timeout);
EIO_Status CloseHandle (CPipe::EChildIOHandle handle);
EIO_Status Read(void* buf, size_t count, size_t* n_read,
const CPipe::EChildIOHandle from_handle,
const STimeout* timeout) const;
EIO_Status Write(const void* buf, size_t count, size_t* written,
const STimeout* timeout) const;
CPipe::TChildPollMask Poll(CPipe::TChildPollMask mask,
const STimeout* timeout) const;
TProcessHandle GetProcessHandle(void) const { return m_ProcHandle; }
private:
// Clear object state.
void x_Clear(void);
// Get child's I/O handle.
HANDLE x_GetHandle(CPipe::EChildIOHandle from_handle) const;
// Trigger blocking mode on specified I/O handle.
void x_SetNonBlockingMode(HANDLE fd) const;
// Wait on the file descriptors I/O.
CPipe::TChildPollMask x_Poll(CPipe::TChildPollMask mask,
const STimeout* timeout) const;
private:
// I/O handles for child process.
HANDLE m_ChildStdIn;
HANDLE m_ChildStdOut;
HANDLE m_ChildStdErr;
// Child process descriptor.
HANDLE m_ProcHandle;
// Pipe flags
CPipe::TCreateFlags m_Flags;
// Flag that indicates whether the m_ChildStd* and m_ProcHandle
// member variables contain the relevant handles of the
// current process, in which case they won't be closed.
bool m_SelfHandles;
};
CPipeHandle::CPipeHandle(void)
: m_ProcHandle(INVALID_HANDLE_VALUE),
m_ChildStdIn(INVALID_HANDLE_VALUE),
m_ChildStdOut(INVALID_HANDLE_VALUE),
m_ChildStdErr(INVALID_HANDLE_VALUE),
m_Flags(0),
m_SelfHandles(false)
{
return;
}
CPipeHandle::~CPipeHandle()
{
static const STimeout kZeroTimeout = {0, 0};
Close(0, &kZeroTimeout);
x_Clear();
}
EIO_Status CPipeHandle::Open(const string& cmd,
const vector<string>& args,
CPipe::TCreateFlags create_flags,
const string& current_dir,
const char* const env[])
{
DEFINE_STATIC_FAST_MUTEX(s_Mutex);
CFastMutexGuard guard_mutex(s_Mutex);
x_Clear();
m_Flags = create_flags;
EIO_Status status = eIO_Unknown;
HANDLE child_stdin = INVALID_HANDLE_VALUE;
HANDLE child_stdout = INVALID_HANDLE_VALUE;
HANDLE child_stderr = INVALID_HANDLE_VALUE;
try {
// Prepare command line to run
string cmd_line(cmd);
ITERATE (vector<string>, iter, args) {
// Add argument to command line.
// Escape it with quotes if necessary.
if ( !cmd_line.empty() ) {
cmd_line += ' ';
}
cmd_line += CExec::QuoteArg(*iter);
}
// Convert environment array to block form
AutoPtr< TXChar, ArrayDeleter<TXChar> > env_block;
if ( env ) {
// Count block size
// It should have one zero byte at least.
size_t size = 1;
int count = 0;
while ( env[count] ) {
size += strlen(env[count++]) + 1/*'\0'*/;
}
// Allocate memory
TXChar* block = new TXChar[size];
env_block.reset(block);
// Copy environment strings
for (int i = 0; i < count; i++) {
#if defined(NCBI_OS_MSWIN) && defined(_UNICODE)
TXString tmp = _T_XSTRING(env[i]);
size_t n = tmp.size() + 1;
memcpy(block, tmp.c_str(), n);
#else
size_t n = strlen(env[i]) + 1;
memcpy(block, env[i], n);
#endif // NCBI_OS_MSWIN && _UNICODE
block += n;
}
*block = _TX('\0');
}
HANDLE stdout_handle = ::GetStdHandle(STD_OUTPUT_HANDLE);
if (stdout_handle == NULL) {
stdout_handle = INVALID_HANDLE_VALUE;
}
HANDLE stderr_handle = ::GetStdHandle(STD_ERROR_HANDLE);
if (stderr_handle == NULL) {
stderr_handle = INVALID_HANDLE_VALUE;
}
// Flush std.output buffers before remap
NcbiCout.flush();
::fflush(stdout);
if (stdout_handle != INVALID_HANDLE_VALUE) {
::FlushFileBuffers(stdout_handle);
}
NcbiCerr.flush();
::fflush(stderr);
if (stderr_handle != INVALID_HANDLE_VALUE) {
::FlushFileBuffers(stderr_handle);
}
// Set base security attributes
SECURITY_ATTRIBUTES attr;
attr.nLength = sizeof(attr);
attr.bInheritHandle = TRUE;
attr.lpSecurityDescriptor = NULL;
// Create pipe for child's stdin
_ASSERT(CPipe::fStdIn_Close);
if ( !IS_SET(create_flags, CPipe::fStdIn_Close) ) {
if ( !::CreatePipe(&child_stdin, &m_ChildStdIn, &attr, 0) ) {
PIPE_THROW(::GetLastError(), "CreatePipe(stdin) failed");
}
::SetHandleInformation(m_ChildStdIn, HANDLE_FLAG_INHERIT, 0);
x_SetNonBlockingMode(m_ChildStdIn);
}
// Create pipe for child's stdout
_ASSERT(CPipe::fStdOut_Close);
if ( !IS_SET(create_flags, CPipe::fStdOut_Close) ) {
if ( !::CreatePipe(&m_ChildStdOut, &child_stdout, &attr, 0)) {
PIPE_THROW(::GetLastError(), "CreatePipe(stdout) failed");
}
::SetHandleInformation(m_ChildStdOut, HANDLE_FLAG_INHERIT, 0);
x_SetNonBlockingMode(m_ChildStdOut);
}
// Create pipe for child's stderr
_ASSERT(CPipe::fStdErr_Open);
if ( IS_SET(create_flags, CPipe::fStdErr_Open) ) {
if ( !::CreatePipe(&m_ChildStdErr, &child_stderr, &attr, 0)) {
PIPE_THROW(::GetLastError(), "CreatePipe(stderr) failed");
}
::SetHandleInformation(m_ChildStdErr, HANDLE_FLAG_INHERIT, 0);
x_SetNonBlockingMode(m_ChildStdErr);
} else if ( IS_SET(create_flags, CPipe::fStdErr_Share) ) {
if (stderr_handle != INVALID_HANDLE_VALUE) {
HANDLE current_process = ::GetCurrentProcess();
if ( !::DuplicateHandle(current_process, stderr_handle,
current_process, &child_stderr,
0, TRUE, DUPLICATE_SAME_ACCESS)) {
PIPE_THROW(::GetLastError(),
"DuplicateHandle(stderr) failed");
}
}
} else if ( IS_SET(create_flags, CPipe::fStdErr_StdOut) ) {
child_stderr = child_stdout;
}
// Create child process
STARTUPINFO sinfo;
PROCESS_INFORMATION pinfo;
::ZeroMemory(&pinfo, sizeof(pinfo));
::ZeroMemory(&sinfo, sizeof(sinfo));
sinfo.cb = sizeof(sinfo);
sinfo.hStdError = child_stderr;
sinfo.hStdOutput = child_stdout;
sinfo.hStdInput = child_stdin;
sinfo.dwFlags |= STARTF_USESTDHANDLES;
if ( !::CreateProcess(NULL,
(LPTSTR)(_T_XCSTRING(cmd_line)),
NULL, NULL, TRUE, 0,
env_block.get(), current_dir.empty()
? 0 : _T_XCSTRING(current_dir),
&sinfo, &pinfo) ) {
status = eIO_Closed;
PIPE_THROW(::GetLastError(),
"CreateProcess(\"" + cmd_line + "\") failed");
}
::CloseHandle(pinfo.hThread);
m_ProcHandle = pinfo.hProcess;
_ASSERT(m_ProcHandle != INVALID_HANDLE_VALUE);
status = eIO_Success;
}
catch (string& what) {
static const STimeout kZeroZimeout = {0, 0};
Close(0, &kZeroZimeout);
ERR_POST_X(1, what);
x_Clear();
}
if (child_stdin != INVALID_HANDLE_VALUE) {
::CloseHandle(child_stdin);
}
if (child_stdout != INVALID_HANDLE_VALUE) {
::CloseHandle(child_stdout);
}
if (child_stderr != INVALID_HANDLE_VALUE
&& child_stderr != child_stdout) {
::CloseHandle(child_stderr);
}
return status;
}
void CPipeHandle::OpenSelf(void)
{
x_Clear();
NcbiCout.flush();
::fflush(stdout);
if ( !::FlushFileBuffers(m_ChildStdIn) ) {
PIPE_THROW(::GetLastError(), "FlushFileBuffers(stdout) failed");
}
if ((m_ChildStdIn = ::GetStdHandle(STD_OUTPUT_HANDLE))
== INVALID_HANDLE_VALUE) {
PIPE_THROW(::GetLastError(), "GetStdHandle(stdout) failed");
}
if ((m_ChildStdOut = ::GetStdHandle(STD_INPUT_HANDLE))
== INVALID_HANDLE_VALUE) {
PIPE_THROW(::GetLastError(), "GetStdHandle(stdin) failed");
}
m_ProcHandle = ::GetCurrentProcess();
m_SelfHandles = true;
}
void CPipeHandle::x_Clear(void)
{
m_ProcHandle = INVALID_HANDLE_VALUE;
if (m_SelfHandles) {
m_ChildStdIn = INVALID_HANDLE_VALUE;
m_ChildStdOut = INVALID_HANDLE_VALUE;
m_SelfHandles = false;
} else {
CloseHandle(CPipe::eStdIn);
CloseHandle(CPipe::eStdOut);
CloseHandle(CPipe::eStdErr);
}
}
EIO_Status CPipeHandle::Close(int* exitcode, const STimeout* timeout)
{
EIO_Status status;
if (!m_SelfHandles) {
CloseHandle(CPipe::eStdIn);
CloseHandle(CPipe::eStdOut);
CloseHandle(CPipe::eStdErr);
if (m_ProcHandle == INVALID_HANDLE_VALUE) {
if ( exitcode ) {
*exitcode = -1;
}
status = eIO_Closed;
} else {
status = s_Close(CProcess(m_ProcHandle, CProcess::eHandle),
m_Flags, timeout, exitcode);
}
} else {
if ( exitcode ) {
*exitcode = 0;
}
status = eIO_Success;
}
if (status != eIO_Timeout) {
x_Clear();
}
return status;
}
EIO_Status CPipeHandle::CloseHandle(CPipe::EChildIOHandle handle)
{
switch (handle) {
case CPipe::eStdIn:
if (m_ChildStdIn == INVALID_HANDLE_VALUE) {
return eIO_Closed;
}
::CloseHandle(m_ChildStdIn);
m_ChildStdIn = INVALID_HANDLE_VALUE;
break;
case CPipe::eStdOut:
if (m_ChildStdOut == INVALID_HANDLE_VALUE) {
return eIO_Closed;
}
::CloseHandle(m_ChildStdOut);
m_ChildStdOut = INVALID_HANDLE_VALUE;
break;
case CPipe::eStdErr:
if (m_ChildStdErr == INVALID_HANDLE_VALUE) {
return eIO_Closed;
}
::CloseHandle(m_ChildStdErr);
m_ChildStdErr = INVALID_HANDLE_VALUE;
break;
default:
return eIO_InvalidArg;
}
return eIO_Success;
}
EIO_Status CPipeHandle::Read(void* buf, size_t count, size_t* read,
const CPipe::EChildIOHandle from_handle,
const STimeout* timeout) const
{
EIO_Status status = eIO_Unknown;
try {
if (m_ProcHandle == INVALID_HANDLE_VALUE) {
status = eIO_Closed;
throw string("Pipe closed");
}
HANDLE fd = x_GetHandle(from_handle);
if (fd == INVALID_HANDLE_VALUE) {
status = eIO_Closed;
throw string("Pipe I/O handle closed");
}
if ( !count ) {
return eIO_Success;
}
DWORD x_timeout = timeout ? NcbiTimeoutToMs(timeout) : INFINITE;
DWORD bytes_avail = 0;
// Wait for data from the pipe with timeout.
// Using a loop and periodically try PeekNamedPipe is inefficient,
// but Windows doesn't have asynchronous mechanism to read
// from a pipe.
// NOTE: WaitForSingleObject() doesn't work with anonymous pipes.
// See CPipe::Poll() for more details.
for (;;) {
if ( !::PeekNamedPipe(fd, NULL, 0, NULL, &bytes_avail, NULL) ) {
// Has peer closed connection?
DWORD error = ::GetLastError();
if (error != ERROR_BROKEN_PIPE) {
PIPE_THROW(error, "PeekNamedPipe() failed");
}
return eIO_Closed;
}
if ( bytes_avail ) {
break;
}
unsigned long x_sleep = kWaitPrecision;
if (x_timeout != INFINITE) {
if (x_sleep > x_timeout) {
x_sleep = x_timeout;
}
if ( !x_sleep ) {
return eIO_Timeout;
}
x_timeout -= x_sleep;
}
SleepMilliSec(x_sleep);
}
_ASSERT(bytes_avail);
// We must read only "count" bytes of data regardless of
// the amount available to read
if (bytes_avail > count) {
bytes_avail = (DWORD) count;
}
if ( !::ReadFile(fd, buf, bytes_avail, &bytes_avail, NULL) ) {
PIPE_THROW(::GetLastError(), "Failed to read data from pipe");
}
if ( read ) {
*read = (size_t) bytes_avail;
}
return eIO_Success;
}
catch (string& what) {
ERR_POST_X(2, what);
}
return status;
}
EIO_Status CPipeHandle::Write(const void* buf, size_t count,
size_t* n_written, const STimeout* timeout) const
{
EIO_Status status = eIO_Unknown;
try {
if (m_ProcHandle == INVALID_HANDLE_VALUE) {
status = eIO_Closed;
throw string("Pipe closed");
}
if (m_ChildStdIn == INVALID_HANDLE_VALUE) {
status = eIO_Closed;
throw string("Pipe I/O handle closed");
}
if ( !count ) {
return eIO_Success;
}
DWORD x_timeout = timeout ? NcbiTimeoutToMs(timeout) : INFINITE;
DWORD to_write = (count > numeric_limits<DWORD>::max()
? numeric_limits<DWORD>::max()
: (DWORD) count);
DWORD bytes_written = 0;
// Try to write data into the pipe within specified time.
for (;;) {
BOOL ok = ::WriteFile(m_ChildStdIn, (char*) buf, to_write,
&bytes_written, NULL);
if ( bytes_written ) {
break;
}
if ( !ok ) {
PIPE_THROW(::GetLastError(), "Failed to write data to pipe");
}
DWORD x_sleep = kWaitPrecision;
if (x_timeout != INFINITE) {
if ( x_timeout ) {
if (x_sleep > x_timeout) {
x_sleep = x_timeout;
}
x_timeout -= x_sleep;
} else {
return eIO_Timeout;
}
}
SleepMilliSec(x_sleep);
}
if ( n_written ) {
*n_written = bytes_written;
}
return eIO_Success;
}
catch (string& what) {
ERR_POST_X(3, what);
}
return status;
}
CPipe::TChildPollMask CPipeHandle::Poll(CPipe::TChildPollMask mask,
const STimeout* timeout) const
{
CPipe::TChildPollMask poll = 0;
try {
if (m_ProcHandle == INVALID_HANDLE_VALUE) {
throw string("Pipe closed");
}
if (m_ChildStdIn == INVALID_HANDLE_VALUE &&
m_ChildStdOut == INVALID_HANDLE_VALUE &&
m_ChildStdErr == INVALID_HANDLE_VALUE) {
throw string("All pipe I/O handles closed");
}
poll = x_Poll(mask, timeout);
}
catch (string& what) {
ERR_POST_X(4, what);
}
return poll;
}
HANDLE CPipeHandle::x_GetHandle(CPipe::EChildIOHandle from_handle) const
{
switch (from_handle) {
case CPipe::eStdIn:
return m_ChildStdIn;
case CPipe::eStdOut:
return m_ChildStdOut;
case CPipe::eStdErr:
return m_ChildStdErr;
default:
break;
}
return INVALID_HANDLE_VALUE;
}
void CPipeHandle::x_SetNonBlockingMode(HANDLE fd) const
{
// NB: Pipe is in byte-mode.
// NOTE: We cannot get a state of a pipe handle opened for writing.
// We cannot set a state of a pipe handle opened for reading.
DWORD state = PIPE_READMODE_BYTE | PIPE_NOWAIT;
if ( !::SetNamedPipeHandleState(fd, &state, NULL, NULL) ) {
PIPE_THROW(::GetLastError(), "x_SetNonBlockingMode() failed");
}
}
CPipe::TChildPollMask CPipeHandle::x_Poll(CPipe::TChildPollMask mask,
const STimeout* timeout) const
{
CPipe::TChildPollMask poll = 0;
DWORD x_timeout = timeout ? NcbiTimeoutToMs(timeout) : INFINITE;
// Wait for data from the pipe with timeout.
// Using a loop and periodically try PeekNamedPipe is inefficient,
// but Windows doesn't have asynchronous mechanism to read from a pipe.
// NOTE: WaitForSingleObject() doesn't work with anonymous pipes.
for (;;) {
if ( (mask & CPipe::fStdOut)
&& m_ChildStdOut != INVALID_HANDLE_VALUE ) {
DWORD bytes_avail = 0;
if ( !::PeekNamedPipe(m_ChildStdOut, NULL, 0, NULL,
&bytes_avail, NULL) ) {
DWORD error = ::GetLastError();
// Has peer closed connection?
if (error != ERROR_BROKEN_PIPE) {
PIPE_THROW(error, "PeekNamedPipe(stdout) failed");
}
poll |= CPipe::fStdOut;
} else if ( bytes_avail ) {
poll |= CPipe::fStdOut;
}
}
if ( (mask & CPipe::fStdErr)
&& m_ChildStdErr != INVALID_HANDLE_VALUE ) {
DWORD bytes_avail = 0;
if ( !::PeekNamedPipe(m_ChildStdErr, NULL, 0, NULL,
&bytes_avail, NULL) ) {
DWORD error = ::GetLastError();
// Has peer closed connection?
if (error != ERROR_BROKEN_PIPE) {
PIPE_THROW(error, "PeekNamedPipe(stderr) failed");
}
poll |= CPipe::fStdErr;
} else if ( bytes_avail ) {
poll |= CPipe::fStdErr;
}
}
if ( poll ) {
break;
}
unsigned long x_sleep = kWaitPrecision;
if (x_timeout != INFINITE) {
if (x_sleep > x_timeout) {
x_sleep = x_timeout;
}
if ( !x_sleep ) {
break;
}
x_timeout -= x_sleep;
}
SleepMilliSec(x_sleep);
}
// We cannot poll child's stdin, so just copy corresponding flag
// from source to result mask before return
poll |= mask & CPipe::fStdIn ;
return poll;
}
#elif defined(NCBI_OS_UNIX)
#define PIPE_THROW(err, errtxt) \
{ \
int _err = err; \
string _errstr(errtxt); \
throw s_UnixError(_err, _errstr); \
}
static string s_UnixError(int error, string& message)
{
const char* errstr = error ? strerror(error) : 0;
if (!errstr) {
errstr = "";
}
int dynamic = 0/*false*/;
const char* result = ::NcbiMessagePlusError(&dynamic, message.c_str(),
(int) error, errstr);
string retval;
if (result) {
retval = result;
if (dynamic) {
free((void*) result);
}
} else {
retval.swap(message);
}
return retval;
}
//////////////////////////////////////////////////////////////////////////////
//
// CPipeHandle -- Unix version
//
class CPipeHandle
{
public:
CPipeHandle(void);
~CPipeHandle();
EIO_Status Open(const string& cmd,
const vector<string>& args,
CPipe::TCreateFlags create_flags,
const string& current_dir,
const char* const env[]);
void OpenSelf(void);
EIO_Status Close(int* exitcode, const STimeout* timeout);
EIO_Status CloseHandle(CPipe::EChildIOHandle handle);
EIO_Status Read(void* buf, size_t count, size_t* read,
const CPipe::EChildIOHandle from_handle,
const STimeout* timeout) const;
EIO_Status Write(const void* buf, size_t count, size_t* written,
const STimeout* timeout) const;
CPipe::TChildPollMask Poll(CPipe::TChildPollMask mask,
const STimeout* timeout) const;
TProcessHandle GetProcessHandle(void) const { return m_Pid; }
private:
// Clear object state.
void x_Clear(void);
// Get child's I/O handle.
int x_GetHandle(CPipe::EChildIOHandle from_handle) const;
// Trigger blocking mode on specified I/O handle.
bool x_SetNonBlockingMode(int fd) const;
// Wait on the file descriptors I/O.
CPipe::TChildPollMask x_Poll(CPipe::TChildPollMask mask,
const STimeout* timeout) const;
private:
// I/O handles for child process.
int m_ChildStdIn;
int m_ChildStdOut;
int m_ChildStdErr;
// Child process pid.
TPid m_Pid;
// Pipe flags
CPipe::TCreateFlags m_Flags;
// Flag that indicates whether the m_ChildStd* and m_Pid
// member variables contain the relevant handles of the
// current process, in which case they won't be closed.
bool m_SelfHandles;
};
CPipeHandle::CPipeHandle(void)
: m_ChildStdIn(-1), m_ChildStdOut(-1), m_ChildStdErr(-1),
m_Pid((pid_t)(-1)), m_Flags(0),
m_SelfHandles(false)
{
}
CPipeHandle::~CPipeHandle()
{
static const STimeout kZeroTimeout = {0, 0};
Close(0, &kZeroTimeout);
x_Clear();
}
// Auxiliary function for exit from forked process with reporting errno
// on errors to specified file descriptor
static void s_Exit(int status, int fd)
{
int errcode = errno;
(void) ::write(fd, &errcode, sizeof(errcode));
::close(fd);
::_exit(status);
}
// Emulate inexistent function execvpe().
// On success, execve() does not return, on error -1 is returned,
// and errno is set appropriately.
static int s_ExecShell(const char *file,
char *const argv[], char *const envp[])
{
static const char kShell[] = "/bin/sh";
// Count number of arguments
int i;
for (i = 0; argv[i]; i++);
i++; // copy last zero element also
// Construct an argument list for the shell.
// Not all compilers support next construction:
// const char* args[i + 1];
const char **args = new const char*[i + 1];
AutoPtr<const char*, ArrayDeleter<const char*> > args_ptr(args);
args[0] = kShell;
args[1] = file;
for (; i > 1; i--) {
args[i] = argv[i - 1];
}
// Execute the shell
return ::execve(kShell, (char**) args, envp);
}
static int s_ExecVPE(const char *file, char *const argv[], char *const envp[])
{
// CAUTION (security): current directory is in the path on purpose,
// to be in-sync with default behavior of MS-Win.
static const char* kPathDefault = ":/bin:/usr/bin";
// If file name is not specified
if (!file || *file == '\0') {
errno = ENOENT;
return -1;
}
// If the file name contains path
if ( strchr(file, '/') ) {
::execve(file, argv, envp);
if (errno == ENOEXEC) {
return s_ExecShell(file, argv, envp);
}
return -1;
}
// Get PATH environment variable
const char *path = getenv("PATH");
if ( !path ) {
path = kPathDefault;
}
size_t file_len = strlen(file) + 1 /* '\0' */;
size_t buf_len = strlen(path) + file_len + 1 /* '/' */;
char* buf = new char[buf_len];
if ( !buf ) {
errno = ENOMEM;
return -1;
}
AutoPtr<char, ArrayDeleter<char> > buf_ptr(buf);
bool eacces_err = false;
const char* next = path;
while (*next) {
next = strchr(path,':');
if ( !next ) {
// Last part of the PATH environment variable
next = path + strlen(path);
}
size_t len = next - path;
if ( len ) {
// Copy directory name into the buffer
memmove(buf, path, next - path);
} else {
// Two colons side by side -- current directory
buf[0]='.';
len = 1;
}
// Add slash and file name
if (buf[len-1] != '/') {
buf[len++] = '/';
}
memcpy(buf + len, file, file_len);
path = next + 1;
// Try to execute file with generated name
::execve(buf, argv, envp);
if (errno == ENOEXEC) {
return s_ExecShell(buf, argv, envp);
}
switch (errno) {
case EACCES:
// Permission denied. Memorize this thing and try next path.
eacces_err = true;
case ENOENT:
case ENOTDIR:
// Try next path directory
break;
default:
// We found an executable file, but could not execute it
return -1;
}
}
if ( eacces_err ) {
errno = EACCES;
}
return -1;
}
static int x_SafeFD(int fd, int safe)
{
if (fd == safe || fd > STDERR_FILENO)
return fd;
int temp = ::fcntl(fd, F_DUPFD, STDERR_FILENO + 1);
::close(fd);
return temp;
}
static bool x_SafePipe(int pipe[2], int n, int safe)
{
bool retval = true;
if ((pipe[0] = x_SafeFD(pipe[0], n == 0 ? safe : -1)) == -1) {
::close(pipe[1]);
retval = false;
} else if ((pipe[1] = x_SafeFD(pipe[1], n == 1 ? safe : -1)) == -1) {
::close(pipe[0]);
retval = false;
}
return retval;
}
EIO_Status CPipeHandle::Open(const string& cmd,
const vector<string>& args,
CPipe::TCreateFlags create_flags,
const string& current_dir,
const char* const env[])
{
DEFINE_STATIC_FAST_MUTEX(s_Mutex);
CFastMutexGuard guard_mutex(s_Mutex);
x_Clear();
m_Flags = create_flags;
// Child process I/O handles
int pipe_in[2], pipe_out[2], pipe_err[2];
pipe_in[0] = -1;
pipe_out[1] = -1;
pipe_err[1] = -1;
int status_pipe[2] = {-1, -1};
try {
// Flush std.output
NcbiCout.flush();
::fflush(stdout);
NcbiCerr.flush();
::fflush(stderr);
// Create pipe for child's stdin
_ASSERT(CPipe::fStdIn_Close);
if ( !IS_SET(create_flags, CPipe::fStdIn_Close) ) {
if (::pipe(pipe_in) < 0
|| !x_SafePipe(pipe_in, 0, STDIN_FILENO)) {
pipe_in[0] = -1;
PIPE_THROW(errno, "Failed to create pipe for stdin");
}
m_ChildStdIn = pipe_in[1];
x_SetNonBlockingMode(m_ChildStdIn);
}
// Create pipe for child's stdout
_ASSERT(CPipe::fStdOut_Close);
if ( !IS_SET(create_flags, CPipe::fStdOut_Close) ) {
if (::pipe(pipe_out) < 0
|| !x_SafePipe(pipe_out, 1, STDOUT_FILENO)) {
pipe_out[1] = -1;
PIPE_THROW(errno, "Failed to create pipe for stdout");
}
m_ChildStdOut = pipe_out[0];
x_SetNonBlockingMode(m_ChildStdOut);
}
// Create pipe for child's stderr
_ASSERT(CPipe::fStdErr_Open);
if ( IS_SET(create_flags, CPipe::fStdErr_Open) ) {
if (::pipe(pipe_err) < 0
|| !x_SafePipe(pipe_err, 1, STDERR_FILENO)) {
pipe_err[1] = -1;
PIPE_THROW(errno, "Failed to create pipe for stderr");
}
m_ChildStdErr = pipe_err[0];
x_SetNonBlockingMode(m_ChildStdErr);
}
// Create temporary pipe to get status of execution
// of the child process
if (::pipe(status_pipe) < 0
|| !x_SafePipe(status_pipe, -1, -1)) {
PIPE_THROW(errno, "Failed to create status pipe");
}
::fcntl(status_pipe[1], F_SETFD,
::fcntl(status_pipe[1], F_GETFD, 0) | FD_CLOEXEC);
// Fork child process
switch (m_Pid = ::fork()) {
case (pid_t)(-1):
PIPE_THROW(errno, "Failed fork()");
/*NOTREACHED*/
break;
case 0:
// *** CHILD PROCESS CONTINUES HERE ***
// Create new process group if needed
if ( IS_SET(create_flags, CPipe::fNewGroup) ) {
::setpgid(0, 0);
}
// Close unused pipe handle
::close(status_pipe[0]);
// Bind child's standard I/O file handles to pipes
if ( !IS_SET(create_flags, CPipe::fStdIn_Close) ) {
if (pipe_in[0] != STDIN_FILENO) {
if (::dup2(pipe_in[0], STDIN_FILENO) < 0) {
s_Exit(-1, status_pipe[1]);
}
::close(pipe_in[0]);
}
::close(pipe_in[1]);
} else {
(void) ::freopen("/dev/null", "r", stdin);
}
if ( !IS_SET(create_flags, CPipe::fStdOut_Close) ) {
if (pipe_out[1] != STDOUT_FILENO) {
if (::dup2(pipe_out[1], STDOUT_FILENO) < 0) {
s_Exit(-1, status_pipe[1]);
}
::close(pipe_out[1]);
}
::close(pipe_out[0]);
} else {
(void) ::freopen("/dev/null", "w", stdout);
}
if ( IS_SET(create_flags, CPipe::fStdErr_Open) ) {
if (pipe_err[1] != STDERR_FILENO) {
if (::dup2(pipe_err[1], STDERR_FILENO) < 0) {
s_Exit(-1, status_pipe[1]);
}
::close(pipe_err[1]);
}
::close(pipe_err[0]);
} else if ( IS_SET(create_flags, CPipe::fStdErr_Share) ) {
/*nothing to do*/;
} else if ( IS_SET(create_flags, CPipe::fStdErr_StdOut) ) {
_ASSERT(STDOUT_FILENO != STDERR_FILENO);
if (::dup2(STDOUT_FILENO, STDERR_FILENO) < 0) {
s_Exit(-1, status_pipe[1]);
}
} else {
(void) ::freopen("/dev/null", "a", stderr);
}
// Restore SIGPIPE signal processing
if ( IS_SET(create_flags, CPipe::fSigPipe_Restore) ) {
::signal(SIGPIPE, SIG_DFL);
}
// Prepare program arguments
size_t cnt = args.size();
size_t i = 0;
const char** x_args = new const char*[cnt + 2];
typedef ArrayDeleter<const char*> TArgsDeleter;
AutoPtr<const char*, TArgsDeleter> p_args = x_args;
ITERATE (vector<string>, arg, args) {
x_args[++i] = arg->c_str();
}
x_args[0] = cmd.c_str();
x_args[cnt + 1] = 0;
// Change current working directory if specified
if ( !current_dir.empty() ) {
(void) ::chdir(current_dir.c_str());
}
// Execute the program
int status;
if ( env ) {
// Emulate inexistent execvpe()
status = s_ExecVPE(cmd.c_str(),
const_cast<char**>(x_args),
const_cast<char**>(env));
} else {
status = ::execvp(cmd.c_str(), const_cast<char**>(x_args));
}
s_Exit(status, status_pipe[1]);
// *** CHILD PROCESS DOES NOT CONTINUE BEYOND THIS LINE ***
}
// Close unused pipe handles
if ( !IS_SET(create_flags, CPipe::fStdIn_Close) ) {
::close(pipe_in[0]);
pipe_in[0] = -1;
}
if ( !IS_SET(create_flags, CPipe::fStdOut_Close) ) {
::close(pipe_out[1]);
pipe_out[1] = -1;
}
if ( IS_SET(create_flags, CPipe::fStdErr_Open) ) {
::close(pipe_err[1]);
pipe_err[1] = -1;
}
::close(status_pipe[1]);
status_pipe[1] = -1;
// Check status pipe:
// if it has some data, this is an errno from the child process;
// if there is an EOF, then the child exec()'d successfully.
// Retry if either blocked or interrupted
// Try to read errno from forked process
ssize_t n;
int errcode;
while ((n = ::read(status_pipe[0], &errcode, sizeof(errcode))) < 0) {
if (errno != EINTR)
break;
}
::close(status_pipe[0]);
status_pipe[0] = -1;
if (n > 0) {
// Child could not run -- reap it and exit with error
::waitpid(m_Pid, NULL, 0);
string errmsg("Failed to execute \"" + cmd + '"');
if ((size_t) n >= sizeof(errcode) && errcode) {
PIPE_THROW(errcode, errmsg);
}
throw errmsg;
}
return eIO_Success;
}
catch (string& what) {
// Close all opened file descriptors
if ( pipe_in[0] != -1 ) {
::close(pipe_in[0]);
}
if ( pipe_out[1] != -1 ) {
::close(pipe_out[1]);
}
if ( pipe_err[1] != -1 ) {
::close(pipe_err[1]);
}
if ( status_pipe[0] != -1 ) {
::close(status_pipe[0]);
}
if ( status_pipe[1] != -1 ) {
::close(status_pipe[1]);
}
static const STimeout kZeroZimeout = {0, 0};
Close(0, &kZeroZimeout);
ERR_POST_X(1, what);
x_Clear();
}
return eIO_Unknown;
}
void CPipeHandle::OpenSelf(void)
{
x_Clear();
NcbiCout.flush();
::fflush(stdout);
m_ChildStdIn = fileno(stdout); // NB: a macro on BSD
m_ChildStdOut = fileno(stdin);
m_Pid = ::getpid();
m_SelfHandles = true;
}
void CPipeHandle::x_Clear(void)
{
m_Pid = -1;
if (m_SelfHandles) {
m_ChildStdIn = -1;
m_ChildStdOut = -1;
m_SelfHandles = false;
} else {
CloseHandle(CPipe::eStdIn);
CloseHandle(CPipe::eStdOut);
CloseHandle(CPipe::eStdErr);
}
}
EIO_Status CPipeHandle::Close(int* exitcode, const STimeout* timeout)
{
EIO_Status status;
if (!m_SelfHandles) {
CloseHandle(CPipe::eStdIn);
CloseHandle(CPipe::eStdOut);
CloseHandle(CPipe::eStdErr);
if (m_Pid == (pid_t)(-1)) {
if ( exitcode ) {
*exitcode = -1;
}
status = eIO_Closed;
} else {
status = s_Close(CProcess(m_Pid, CProcess::ePid),
m_Flags, timeout, exitcode);
}
} else {
if ( exitcode ) {
*exitcode = 0;
}
status = eIO_Success;
}
if (status != eIO_Timeout) {
x_Clear();
}
return status;
}
EIO_Status CPipeHandle::CloseHandle(CPipe::EChildIOHandle handle)
{
switch ( handle ) {
case CPipe::eStdIn:
if (m_ChildStdIn == -1) {
return eIO_Closed;
}
::close(m_ChildStdIn);
m_ChildStdIn = -1;
break;
case CPipe::eStdOut:
if (m_ChildStdOut == -1) {
return eIO_Closed;
}
::close(m_ChildStdOut);
m_ChildStdOut = -1;
break;
case CPipe::eStdErr:
if (m_ChildStdErr == -1) {
return eIO_Closed;
}
::close(m_ChildStdErr);
m_ChildStdErr = -1;
break;
default:
return eIO_InvalidArg;
}
return eIO_Success;
}
EIO_Status CPipeHandle::Read(void* buf, size_t count, size_t* n_read,
const CPipe::EChildIOHandle from_handle,
const STimeout* timeout) const
{
EIO_Status status = eIO_Unknown;
try {
if (m_Pid == (pid_t)(-1)) {
status = eIO_Closed;
throw string("Pipe closed");
}
int fd = x_GetHandle(from_handle);
if (fd == -1) {
status = eIO_Closed;
throw string("Pipe I/O handle closed");
}
if ( !count ) {
return eIO_Success;
}
// Retry if either blocked or interrupted
for (;;) {
// Try to read
ssize_t bytes_read = ::read(fd, buf, count);
if (bytes_read >= 0) {
if ( n_read ) {
*n_read = (size_t) bytes_read;
}
status = bytes_read ? eIO_Success : eIO_Closed;
break;
}
// Blocked -- wait for data to come; exit if timeout/error
if (errno == EAGAIN || errno == EWOULDBLOCK) {
if ( (timeout && !(timeout->sec | timeout->usec ))
|| !x_Poll(from_handle, timeout) ) {
status = eIO_Timeout;
break;
}
continue;
}
// Interrupted read -- restart
if (errno != EINTR) {
PIPE_THROW(errno, "Failed to read data from pipe");
}
}
}
catch (string& what) {
ERR_POST_X(2, what);
}
return status;
}
EIO_Status CPipeHandle::Write(const void* buf, size_t count,
size_t* n_written, const STimeout* timeout) const
{
EIO_Status status = eIO_Unknown;
try {
if (m_Pid == (pid_t)(-1)) {
status = eIO_Closed;
throw string("Pipe closed");
}
if (m_ChildStdIn == -1) {
status = eIO_Closed;
throw string("Pipe I/O handle closed");
}
if ( !count ) {
return eIO_Success;
}
// Retry if either blocked or interrupted
for (;;) {
// Try to write
ssize_t bytes_written = ::write(m_ChildStdIn, buf, count);
if (bytes_written >= 0) {
if ( n_written ) {
*n_written = (size_t) bytes_written;
}
status = eIO_Success;
break;
}
// Peer has closed its end
if (errno == EPIPE) {
return eIO_Closed;
}
// Blocked -- wait for write readiness; exit if timeout/error
if (errno == EAGAIN || errno == EWOULDBLOCK) {
if ( (timeout && !(timeout->sec | timeout->usec))
|| !x_Poll(CPipe::fStdIn, timeout) ) {
status = eIO_Timeout;
break;
}
continue;
}
// Interrupted write -- restart
if (errno != EINTR) {
PIPE_THROW(errno, "Failed to write data into pipe");
}
}
}
catch (string& what) {
ERR_POST_X(3, what);
}
return status;
}
CPipe::TChildPollMask CPipeHandle::Poll(CPipe::TChildPollMask mask,
const STimeout* timeout) const
{
CPipe::TChildPollMask poll = 0;
try {
if (m_Pid == (pid_t)(-1)) {
throw string("Pipe closed");
}
if (m_ChildStdIn == -1 &&
m_ChildStdOut == -1 &&
m_ChildStdErr == -1) {
throw string("All pipe I/O handles closed");
}
poll = x_Poll(mask, timeout);
}
catch (string& what) {
ERR_POST_X(4, what);
}
return poll;
}
int CPipeHandle::x_GetHandle(CPipe::EChildIOHandle from_handle) const
{
switch (from_handle) {
case CPipe::eStdIn:
return m_ChildStdIn;
case CPipe::eStdOut:
return m_ChildStdOut;
case CPipe::eStdErr:
return m_ChildStdErr;
default:
break;
}
return -1;
}
bool CPipeHandle::x_SetNonBlockingMode(int fd) const
{
return ::fcntl(fd, F_SETFL, ::fcntl(fd, F_GETFL, 0) | O_NONBLOCK) != -1;
}
CPipe::TChildPollMask CPipeHandle::x_Poll(CPipe::TChildPollMask mask,
const STimeout* timeout) const
{
CPipe::TChildPollMask poll = 0;
for (;;) { // Auto-resume if interrupted by a signal
struct timeval* tmp;
struct timeval tmo;
if ( timeout ) {
// NB: Timeout has already been normalized
tmo.tv_sec = timeout->sec;
tmo.tv_usec = timeout->usec;
tmp = &tmo;
} else {
tmp = 0;
}
fd_set rfds;
fd_set wfds;
fd_set efds;
int max = -1;
bool rd = false;
bool wr = false;
FD_ZERO(&efds);
if ( (mask & CPipe::fStdIn) && m_ChildStdIn != -1 ) {
wr = true;
FD_ZERO(&wfds);
FD_SET(m_ChildStdIn, &wfds);
FD_SET(m_ChildStdIn, &efds);
if (max < m_ChildStdIn) {
max = m_ChildStdIn;
}
}
if ( (mask & CPipe::fStdOut) && m_ChildStdOut != -1 ) {
if (!rd) {
rd = true;
FD_ZERO(&rfds);
}
FD_SET(m_ChildStdOut, &rfds);
FD_SET(m_ChildStdOut, &efds);
if (max < m_ChildStdOut) {
max = m_ChildStdOut;
}
}
if ( (mask & CPipe::fStdErr) && m_ChildStdErr != -1 ) {
if (!rd) {
rd = true;
FD_ZERO(&rfds);
}
FD_SET(m_ChildStdErr, &rfds);
FD_SET(m_ChildStdErr, &efds);
if (max < m_ChildStdErr) {
max = m_ChildStdErr;
}
}
_ASSERT(rd || wr);
int n = ::select(max + 1, rd ? &rfds : 0, wr ? &wfds : 0, &efds, tmp);
if (n == 0) {
// timeout
break;
}
if (n > 0) {
if ( wr
&& ( FD_ISSET(m_ChildStdIn, &wfds) ||
FD_ISSET(m_ChildStdIn, &efds) ) ) {
poll |= CPipe::fStdIn;
}
if ( (mask & CPipe::fStdOut) && m_ChildStdOut != -1
&& ( FD_ISSET(m_ChildStdOut, &rfds) ||
FD_ISSET(m_ChildStdOut, &efds) ) ) {
poll |= CPipe::fStdOut;
}
if ( (mask & CPipe::fStdErr) && m_ChildStdErr != -1
&& ( FD_ISSET(m_ChildStdErr, &rfds) ||
FD_ISSET(m_ChildStdErr, &efds) ) ) {
poll |= CPipe::fStdErr;
}
break;
}
if ((n = errno) != EINTR) {
PIPE_THROW(n, "Failed select() on pipe");
}
// continue
}
return poll;
}
#endif /* NCBI_OS_UNIX | NCBI_OS_MSWIN */
//////////////////////////////////////////////////////////////////////////////
//
// CPipe
//
CPipe::CPipe(void)
: m_PipeHandle(new CPipeHandle), m_ReadHandle(eStdOut),
m_ReadStatus(eIO_Closed), m_WriteStatus(eIO_Closed),
m_ReadTimeout(0), m_WriteTimeout(0), m_CloseTimeout(0)
{
}
CPipe::CPipe(const string& cmd,
const vector<string>& args,
TCreateFlags create_flags,
const string& current_dir,
const char* const env[])
: m_PipeHandle(new CPipeHandle), m_ReadHandle(eStdOut),
m_ReadStatus(eIO_Closed), m_WriteStatus(eIO_Closed),
m_ReadTimeout(0), m_WriteTimeout(0), m_CloseTimeout(0)
{
EIO_Status status = Open(cmd, args, create_flags, current_dir, env);
if (status != eIO_Success) {
NCBI_THROW(CPipeException, eOpen, "CPipe::Open() failed");
}
}
CPipe::~CPipe()
{
Close();
if ( m_PipeHandle ) {
delete m_PipeHandle;
}
}
EIO_Status CPipe::Open(const string& cmd, const vector<string>& args,
TCreateFlags create_flags,
const string& current_dir,
const char* const env[])
{
if ( !m_PipeHandle ) {
return eIO_Unknown;
}
EIO_Status status = m_PipeHandle->Open(cmd, args, create_flags,
current_dir, env);
if (status == eIO_Success) {
m_ReadStatus = eIO_Success;
m_WriteStatus = eIO_Success;
}
return status;
}
void CPipe::OpenSelf(void)
{
if (m_PipeHandle) {
m_PipeHandle->OpenSelf();
m_ReadStatus = eIO_Success;
m_WriteStatus = eIO_Success;
}
}
EIO_Status CPipe::Close(int* exitcode)
{
if ( !m_PipeHandle ) {
return eIO_Unknown;
}
m_ReadStatus = eIO_Closed;
m_WriteStatus = eIO_Closed;
return m_PipeHandle->Close(exitcode, m_CloseTimeout);
}
EIO_Status CPipe::CloseHandle(EChildIOHandle handle)
{
if ( !m_PipeHandle ) {
return eIO_Unknown;
}
return m_PipeHandle->CloseHandle(handle);
}
EIO_Status CPipe::SetReadHandle(EChildIOHandle from_handle)
{
if (from_handle == eStdIn) {
return eIO_InvalidArg;
}
m_ReadHandle = from_handle == eDefault ? eStdOut : from_handle;
return eIO_Success;
}
EIO_Status CPipe::Read(void* buf, size_t count, size_t* read,
EChildIOHandle from_handle)
{
if ( read ) {
*read = 0;
}
if (from_handle == eStdIn) {
return eIO_InvalidArg;
}
if (from_handle == eDefault) {
from_handle = m_ReadHandle;
}
_ASSERT(m_ReadHandle == eStdOut || m_ReadHandle == eStdErr);
if (count && !buf) {
return eIO_InvalidArg;
}
if ( !m_PipeHandle ) {
return eIO_Unknown;
}
m_ReadStatus = m_PipeHandle->Read(buf, count, read, from_handle,
m_ReadTimeout);
return m_ReadStatus;
}
EIO_Status CPipe::Write(const void* buf, size_t count, size_t* written)
{
if ( written ) {
*written = 0;
}
if (count && !buf) {
return eIO_InvalidArg;
}
if ( !m_PipeHandle ) {
return eIO_Unknown;
}
m_WriteStatus = m_PipeHandle->Write(buf, count, written,
m_WriteTimeout);
return m_WriteStatus;
}
CPipe::TChildPollMask CPipe::Poll(TChildPollMask mask,
const STimeout* timeout)
{
if (!mask || !m_PipeHandle) {
return 0;
}
TChildPollMask x_mask = mask;
if ( mask & fDefault ) {
_ASSERT(m_ReadHandle == eStdOut || m_ReadHandle == eStdErr);
x_mask |= m_ReadHandle;
}
TChildPollMask poll = m_PipeHandle->Poll(x_mask, timeout);
if ( mask & fDefault ) {
if ( poll & m_ReadHandle ) {
poll |= fDefault;
}
poll &= mask;
}
// Result may not be a bigger set
_ASSERT(!(poll ^ (poll & mask)));
return poll;
}
EIO_Status CPipe::Status(EIO_Event direction) const
{
switch ( direction ) {
case eIO_Read:
return m_PipeHandle ? m_ReadStatus : eIO_Closed;
case eIO_Write:
return m_PipeHandle ? m_WriteStatus : eIO_Closed;
default:
break;
}
return eIO_InvalidArg;
}
EIO_Status CPipe::SetTimeout(EIO_Event event, const STimeout* timeout)
{
if (timeout == kDefaultTimeout) {
return eIO_Success;
}
switch ( event ) {
case eIO_Close:
m_CloseTimeout = s_SetTimeout(timeout, &m_CloseTimeoutValue);
break;
case eIO_Read:
m_ReadTimeout = s_SetTimeout(timeout, &m_ReadTimeoutValue);
break;
case eIO_Write:
m_WriteTimeout = s_SetTimeout(timeout, &m_WriteTimeoutValue);
break;
case eIO_ReadWrite:
m_ReadTimeout = s_SetTimeout(timeout, &m_ReadTimeoutValue);
m_WriteTimeout = s_SetTimeout(timeout, &m_WriteTimeoutValue);
break;
default:
return eIO_InvalidArg;
}
return eIO_Success;
}
const STimeout* CPipe::GetTimeout(EIO_Event event) const
{
switch ( event ) {
case eIO_Close:
return m_CloseTimeout;
case eIO_Read:
return m_ReadTimeout;
case eIO_Write:
return m_WriteTimeout;
default:
break;
}
return kDefaultTimeout;
}
TProcessHandle CPipe::GetProcessHandle(void) const
{
return m_PipeHandle ? m_PipeHandle->GetProcessHandle() : 0;
}
CPipe::IProcessWatcher::~IProcessWatcher()
{
}
/* static */
CPipe::EFinish CPipe::ExecWait(const string& cmd,
const vector<string>& args,
CNcbiIstream& in,
CNcbiOstream& out,
CNcbiOstream& err,
int& exit_code,
const string& current_dir,
const char* const env[],
CPipe::IProcessWatcher* watcher,
const STimeout* kill_timeout)
{
STimeout ktm;
if (kill_timeout) {
ktm = *kill_timeout;
} else {
NcbiMsToTimeout(&ktm, CProcess::kDefaultKillTimeout);
}
CPipe pipe;
EIO_Status st = pipe.Open(cmd, args,
fStdErr_Open | fSigPipe_Restore
| fNewGroup | fKillOnClose,
current_dir, env);
if (st != eIO_Success) {
NCBI_THROW(CPipeException, eOpen, "Cannot execute \"" + cmd + "\"");
}
TProcessHandle pid = pipe.GetProcessHandle();
if (watcher && watcher->OnStart(pid) != IProcessWatcher::eContinue) {
pipe.SetTimeout(eIO_Close, &ktm);
pipe.Close(&exit_code);
return eCanceled;
}
EFinish finish = eDone;
bool out_done = false;
bool err_done = false;
bool in_done = false;
const size_t buf_size = 4096;
char buf[buf_size];
size_t bytes_in_inbuf = 0;
size_t total_bytes_written = 0;
char inbuf[buf_size];
TChildPollMask mask = fStdIn | fStdOut | fStdErr;
try {
STimeout wait_time = {1, 0};
while (!out_done || !err_done) {
EIO_Status rstatus;
size_t bytes_read;
TChildPollMask rmask = pipe.Poll(mask, &wait_time);
if (rmask & fStdIn && !in_done) {
if (in.good() && bytes_in_inbuf == 0) {
bytes_in_inbuf =
(size_t)CStreamUtils::Readsome(in, inbuf, buf_size);
total_bytes_written = 0;
}
size_t bytes_written;
if (bytes_in_inbuf > 0) {
rstatus =
pipe.Write(inbuf + total_bytes_written,
bytes_in_inbuf, &bytes_written);
if (rstatus != eIO_Success) {
ERR_POST_X(5, "Cannot send all data to child process");
in_done = true;
}
total_bytes_written += bytes_written;
bytes_in_inbuf -= bytes_written;
}
if ((!in.good() && bytes_in_inbuf == 0) || in_done) {
pipe.CloseHandle(eStdIn);
mask &= ~fStdIn;
}
}
if (rmask & fStdOut) {
// read stdout
if (!out_done) {
rstatus = pipe.Read(buf, buf_size, &bytes_read);
out.write(buf, bytes_read);
if (rstatus != eIO_Success) {
out_done = true;
mask &= ~fStdOut;
}
}
}
if ((rmask & fStdErr) && !err_done) {
rstatus = pipe.Read(buf, buf_size, &bytes_read, eStdErr);
err.write(buf, bytes_read);
if (rstatus != eIO_Success) {
err_done = true;
mask &= ~fStdErr;
}
}
if (!CProcess(pid).IsAlive())
break;
if (watcher && watcher->Watch(pid) != IProcessWatcher::eContinue) {
pipe.SetTimeout(eIO_Close, &ktm);
finish = eCanceled;
break;
}
}
} catch (...) {
pipe.SetTimeout(eIO_Close, &ktm);
pipe.Close(&exit_code);
throw;
}
pipe.Close(&exit_code);
return finish;
}
const char* CPipeException::GetErrCodeString(void) const
{
switch (GetErrCode()) {
case eInit: return "eInit";
case eOpen: return "eOpen";
case eSetBuf: return "eSetBuf";
default: return CException::GetErrCodeString();
}
}
END_NCBI_SCOPE
| 29.852148 | 79 | 0.51859 | [
"object",
"vector"
] |
b7fd8cb7e7fb85e7e30e5f1d21d7963ee5486805 | 7,876 | cpp | C++ | dbms/src/TestUtils/tests/gtest_function_test_utils.cpp | solotzg/tiflash | 66f45c76692e941bc845c01349ea89de0f2cc210 | [
"Apache-2.0"
] | 85 | 2022-03-25T09:03:16.000Z | 2022-03-25T09:45:03.000Z | dbms/src/TestUtils/tests/gtest_function_test_utils.cpp | solotzg/tiflash | 66f45c76692e941bc845c01349ea89de0f2cc210 | [
"Apache-2.0"
] | 7 | 2022-03-25T08:59:10.000Z | 2022-03-25T09:40:13.000Z | dbms/src/TestUtils/tests/gtest_function_test_utils.cpp | solotzg/tiflash | 66f45c76692e941bc845c01349ea89de0f2cc210 | [
"Apache-2.0"
] | 11 | 2022-03-25T09:15:36.000Z | 2022-03-25T09:45:07.000Z | // Copyright 2022 PingCAP, 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.
#include <TestUtils/FunctionTestUtils.h>
namespace DB
{
namespace tests
{
class TestFunctionTestUtils : public ::testing::Test
{
};
TEST_F(TestFunctionTestUtils, ParseDecimal)
try
{
using DecimalField64 = DecimalField<Decimal64>;
ASSERT_EQ(parseDecimal<Nullable<Decimal64>>(std::nullopt, 3, 0), std::nullopt);
ASSERT_EQ(parseDecimal<Nullable<Decimal64>>("123", 3, 0), DecimalField64(123, 0));
ASSERT_EQ(parseDecimal<Nullable<Decimal64>>("123.4", 3, 0), DecimalField64(123, 0));
ASSERT_EQ(parseDecimal<Nullable<Decimal64>>("123.5", 3, 0), DecimalField64(124, 0));
ASSERT_EQ(parseDecimal<Nullable<Decimal64>>("123.4", 5, 2), DecimalField64(12340, 2));
constexpr auto parse = parseDecimal<Decimal64>;
ASSERT_EQ(parse("123.123", 6, 3), DecimalField64(123123, 3));
ASSERT_THROW(parse("123.123", 3, 3), TiFlashTestException);
ASSERT_EQ(parse("123.123", 6, 0), DecimalField64(123, 0));
ASSERT_NO_THROW(parse("123.123", 10, 3));
ASSERT_THROW(parse(" 123.123", 6, 3), TiFlashTestException);
ASSERT_NO_THROW(parse("123.123", 60, 3));
ASSERT_THROW(parse("123123123123123123.123", 60, 3), TiFlashTestException);
ASSERT_THROW(parse("+.123", 3, 3), TiFlashTestException);
ASSERT_EQ(parse("+0.123", 3, 3), DecimalField64(123, 3));
ASSERT_EQ(parse("-0.123", 4, 3), DecimalField64(-123, 3));
ASSERT_EQ(parse("", 1, 0), DecimalField64(0, 0));
ASSERT_THROW(parse(".", 1, 0), TiFlashTestException);
ASSERT_EQ(parse("0", 1, 0), DecimalField64(0, 0));
ASSERT_EQ(parse("00", 2, 0), DecimalField64(0, 0));
ASSERT_EQ(parse("0.", 1, 0), DecimalField64(0, 0));
ASSERT_EQ(parse("0.0", 2, 1), DecimalField64(0, 1));
ASSERT_EQ(parse("000000.000000", 12, 6), DecimalField64(0, 6));
ASSERT_THROW(parse("0..", 1, 0), TiFlashTestException);
ASSERT_THROW(parse("abc", 3, 0), TiFlashTestException);
ASSERT_THROW(parse("+-0", 3, 0), TiFlashTestException);
ASSERT_THROW(parse("-+0", 3, 0), TiFlashTestException);
}
CATCH
TEST_F(TestFunctionTestUtils, CreateDecimalColumn)
try
{
using DecimalField64 = DecimalField<Decimal64>;
auto args = std::make_tuple(4, 2);
auto field = DecimalField64(4200, 2);
auto null = Null();
{
std::vector<DecimalField64> vec = {field};
auto column = createColumn<Decimal64>(args, vec).column;
ASSERT_NE(column, nullptr);
ASSERT_EQ(column->size(), 1);
ASSERT_EQ((*column)[0], field);
}
{
std::vector<std::optional<DecimalField64>> vec = {field, std::nullopt};
auto column = createColumn<Nullable<Decimal64>>(args, vec).column;
ASSERT_NE(column, nullptr);
ASSERT_EQ(column->size(), 2);
ASSERT_EQ((*column)[0], field);
ASSERT_EQ((*column)[1], null);
}
{
std::vector<std::optional<DecimalField64>> vec = {std::nullopt, field};
auto column = createColumn<Nullable<Decimal64>>(args, vec).column;
ASSERT_NE(column, nullptr);
ASSERT_EQ(column->size(), 2);
ASSERT_EQ((*column)[0], null);
ASSERT_EQ((*column)[1], field);
}
{
auto column = createColumn<Decimal64>(args, {field}).column;
ASSERT_NE(column, nullptr);
ASSERT_EQ(column->size(), 1);
ASSERT_EQ((*column)[0], field);
}
{
auto column = createColumn<Nullable<Decimal64>>(args, {field, {}}).column;
ASSERT_NE(column, nullptr);
ASSERT_EQ(column->size(), 2);
ASSERT_EQ((*column)[0], field);
ASSERT_EQ((*column)[1], null);
}
{
auto column = createColumn<Nullable<Decimal64>>(args, {{}, field}).column;
ASSERT_NE(column, nullptr);
ASSERT_EQ(column->size(), 2);
ASSERT_EQ((*column)[0], null);
ASSERT_EQ((*column)[1], field);
}
{
std::vector<String> vec = {"42.00"};
auto column = createColumn<Decimal64>(args, vec).column;
ASSERT_NE(column, nullptr);
ASSERT_EQ(column->size(), 1);
ASSERT_EQ((*column)[0], field);
}
{
std::vector<std::optional<String>> vec = {"42.00", {}};
auto column = createColumn<Nullable<Decimal64>>(args, vec).column;
ASSERT_NE(column, nullptr);
ASSERT_EQ(column->size(), 2);
ASSERT_EQ((*column)[0], field);
ASSERT_EQ((*column)[1], null);
}
{
std::vector<std::optional<String>> vec = {{}, "42.00"};
auto column = createColumn<Nullable<Decimal64>>(args, vec).column;
ASSERT_NE(column, nullptr);
ASSERT_EQ(column->size(), 2);
ASSERT_EQ((*column)[0], null);
ASSERT_EQ((*column)[1], field);
}
{
auto column = createColumn<Nullable<Decimal64>>(args, {"42.00"}).column;
ASSERT_NE(column, nullptr);
ASSERT_EQ(column->size(), 1);
ASSERT_EQ((*column)[0], field);
}
{
auto column = createColumn<Nullable<Decimal64>>(args, {"42.00", {}}).column;
ASSERT_NE(column, nullptr);
ASSERT_EQ(column->size(), 2);
ASSERT_EQ((*column)[0], field);
ASSERT_EQ((*column)[1], null);
}
{
auto column = createColumn<Nullable<Decimal64>>(args, {{}, "42.00"}).column;
ASSERT_NE(column, nullptr);
ASSERT_EQ(column->size(), 2);
ASSERT_EQ((*column)[0], null);
ASSERT_EQ((*column)[1], field);
}
// passing an initializer list of "{}" is ambiguous.
// > createColumn<Nullable<Decimal64>>(args, {{}})
// > createColumn<Nullable<Decimal64>>(args, {{}, {}})
//
// workaround: use `std::nullopt` instead.
{
auto column = createColumn<Nullable<Decimal64>>(args, {std::nullopt}).column;
ASSERT_NE(column, nullptr);
ASSERT_EQ(column->size(), 1);
ASSERT_EQ((*column)[0], null);
}
{
auto column = createColumn<Nullable<Decimal64>>(args, {std::nullopt, std::nullopt}).column;
ASSERT_NE(column, nullptr);
ASSERT_EQ(column->size(), 2);
ASSERT_EQ((*column)[0], null);
ASSERT_EQ((*column)[1], null);
}
{
auto column = createConstColumn<Decimal64>(args, 233, field).column;
ASSERT_NE(column, nullptr);
ASSERT_EQ(column->size(), 233);
ASSERT_EQ((*column)[0], field);
}
{
auto column = createConstColumn<Decimal64>(args, 233, "42.00").column;
ASSERT_NE(column, nullptr);
ASSERT_EQ(column->size(), 233);
ASSERT_EQ((*column)[0], field);
}
{
auto column = createConstColumn<Nullable<Decimal64>>(args, 233, field).column;
ASSERT_NE(column, nullptr);
ASSERT_EQ(column->size(), 233);
ASSERT_EQ((*column)[0], field);
}
{
auto column = createConstColumn<Nullable<Decimal64>>(args, 233, "42.00").column;
ASSERT_NE(column, nullptr);
ASSERT_EQ(column->size(), 233);
ASSERT_EQ((*column)[0], field);
}
{
// the following call is ambiguous:
// > createConstColumn<Nullable<Decimal64>>(args, 233, {})
auto column = createConstColumn<Nullable<Decimal64>>(args, 233, std::nullopt).column;
ASSERT_NE(column, nullptr);
ASSERT_EQ(column->size(), 233);
ASSERT_EQ((*column)[0], null);
}
}
CATCH
} // namespace tests
} // namespace DB
| 33.948276 | 99 | 0.61224 | [
"vector"
] |
4d001f24515335f140c3933604767544cfae736d | 12,717 | cpp | C++ | src/behavior_planner.cpp | grygoryant/CarND-Path-Planning-Project | fccb5a228e444bd24e6083d0011b23a3cf60d658 | [
"MIT"
] | null | null | null | src/behavior_planner.cpp | grygoryant/CarND-Path-Planning-Project | fccb5a228e444bd24e6083d0011b23a3cf60d658 | [
"MIT"
] | null | null | null | src/behavior_planner.cpp | grygoryant/CarND-Path-Planning-Project | fccb5a228e444bd24e6083d0011b23a3cf60d658 | [
"MIT"
] | null | null | null | //
// Created by grigorii on 9/8/19.
//
#include "behavior_planner.h"
#include <algorithm>
#include <iostream>
#include "helpers.h"
#include "spline.h"
std::string to_string(action a)
{
switch(a)
{
case(action::KL): return "action::KL";
case(action::LCL): return "action::LCL";
case(action::LCR): return "action::LCR";
case(action::PLCL): return "action::PLCL";
case(action::PLCR): return "action::PLCR";
default: return "unknown action";
}
}
trajectory_t behavior_planner::get_trajectory(const sensor_fusion_data_t &sf_data,
const vehicle &curr_state,
const trajectory_t &prev_path,
const std::pair<double, double> &prev_path_end_frenet)
{
const auto& next_states = action_adjacency.find(m_curr_action);
if(next_states != std::end(action_adjacency))
{
std::vector<double> costs;
std::vector<trajectory_t> final_trajectories;
std::vector<action> final_states;
for(const auto& state : next_states->second)
{
auto [dst_lane, trajectory] = generate_trajectory(state, sf_data,
prev_path, curr_state, prev_path_end_frenet);
if (!std::get<0>(trajectory).empty())
{
auto cost = calculate_cost(sf_data,
curr_state,
trajectory, dst_lane);
costs.push_back(cost);
final_trajectories.emplace_back(trajectory);
final_states.emplace_back(state);
}
}
auto best_cost = std::min_element(begin(costs), end(costs));
int best_idx = std::distance(begin(costs), best_cost);
auto best_action = final_states[best_idx];
if(best_action != m_curr_action)
{
std::cout << "State transition: " << to_string(m_curr_action) <<
" -> " << to_string(best_action) << std::endl;
m_curr_action = best_action;
}
return final_trajectories[best_idx];
}
return {{}, {}};
}
std::tuple<int, trajectory_t> behavior_planner::generate_trajectory(action dst_action,
const sensor_fusion_data_t &sf_data,
const trajectory_t &prev_path,
const vehicle &curr_state,
const std::pair<double, double> &prev_path_end_frenet)
{
switch(dst_action)
{
case action::KL:
return kl_trajectory(sf_data, prev_path, curr_state, prev_path_end_frenet);
case action::LCL:
case action::LCR:
return lc_trajectory(dst_action, sf_data, prev_path, curr_state, prev_path_end_frenet);
case action::PLCL:
case action::PLCR:
return plc_trajectory(dst_action, sf_data, prev_path, curr_state, prev_path_end_frenet);
default: break;
}
return {};
}
behavior_planner::behavior_planner(const std::vector<double> &map_wp_x,
const std::vector<double> &map_wp_y,
const std::vector<double> &map_wp_s) :
m_map_waypoints_x(map_wp_x),
m_map_waypoints_y(map_wp_y),
m_map_waypoints_s(map_wp_s)
{
}
std::tuple<int, trajectory_t> behavior_planner::kl_trajectory(const sensor_fusion_data_t &sf_data,
const trajectory_t &prev_path,
const vehicle &curr_state,
const std::pair<double, double> &prev_path_end_frenet)
{
const auto& [previous_path_x, previous_path_y] = prev_path;
double car_x = curr_state.x();
double car_y = curr_state.y();
double car_s = curr_state.s();
double car_d = curr_state.d();
double car_yaw = curr_state.yaw();
double car_speed = curr_state.speed();
auto end_path_s = prev_path_end_frenet.first;
auto prev_size = previous_path_x.size();
if(prev_size > 0)
{
car_s = end_path_s;
}
bool too_close = false;
double target_vel = 0;
auto curr_lane = curr_state.get_cur_lane();
for(int i = 0; i < sf_data.size(); i++)
{
float d = sf_data[i][6];
if(d < (2 + 4 * curr_lane + 2) && d > (2 + 4 * curr_lane - 2))
{
double vx = sf_data[i][3];
double vy = sf_data[i][4];
double check_speed = sqrt(vx * vx + vy * vy);
double check_car_s = sf_data[i][5];
check_car_s += static_cast<double>(prev_size) * 0.02 * check_speed;
if((check_car_s > car_s) && (check_car_s - car_s) < 25)
{
too_close = true;
target_vel = check_speed;
break;
}
}
}
if(too_close && m_ref_vel > target_vel)
{
m_ref_vel -= 0.224;
}
else if((too_close && m_ref_vel <= target_vel) ||
m_ref_vel < 49.5)
{
m_ref_vel += 0.224;
}
return {curr_lane, get_trajectory_points(curr_lane, previous_path_x,
previous_path_y, curr_state, m_ref_vel) };
}
std::tuple<int, trajectory_t>
behavior_planner::plc_trajectory(action dst_action,
const sensor_fusion_data_t &sf_data,
const trajectory_t &prev_path,
const vehicle &curr_state,
const std::pair<double, double> &prev_path_end_frenet)
{
return {};
}
std::tuple<int, trajectory_t>
behavior_planner::lc_trajectory(action dst_action,
const sensor_fusion_data_t &sf_data,
const trajectory_t &prev_path,
const vehicle &curr_state,
const std::pair<double, double> &prev_path_end_frenet)
{
const auto& dir = lane_direction.find(dst_action);
if(dir != std::end(lane_direction))
{
int new_lane = curr_state.get_cur_lane() + dir->second;
const auto& [previous_path_x, previous_path_y] = prev_path;
return { new_lane, get_trajectory_points(new_lane, previous_path_x,
previous_path_y, curr_state, m_ref_vel) };
}
return {};
}
trajectory_t behavior_planner::get_trajectory_points(int target_lane,
const std::vector<double> &prev_path_x,
const std::vector<double> &prev_path_y,
const vehicle &curr_state,
double ref_vel)
{
auto ref_x = curr_state.x();
auto ref_y = curr_state.y();
auto ref_yaw = deg2rad(curr_state.yaw());
std::vector<double> pts_x;
std::vector<double> pts_y;
if(prev_path_x.size() < 2)
{
auto prev_car_x = curr_state.x() - cos(curr_state.yaw());
auto prev_car_y = curr_state.y() - sin(curr_state.yaw());
pts_x.emplace_back(prev_car_x);
pts_x.emplace_back(curr_state.x());
pts_y.emplace_back(prev_car_y);
pts_y.emplace_back(curr_state.y());
}
else
{
ref_x = prev_path_x[prev_path_x.size() - 1];
ref_y = prev_path_y[prev_path_x.size() - 1];
double ref_x_prev = prev_path_x[prev_path_x.size() - 2];
double ref_y_prev = prev_path_y[prev_path_x.size() - 2];
ref_yaw = atan2(ref_y - ref_y_prev, ref_x - ref_x_prev);
pts_x.emplace_back(ref_x_prev);
pts_x.emplace_back(ref_x);
pts_y.emplace_back(ref_y_prev);
pts_y.emplace_back(ref_y);
}
auto next_wp0 = getXY(curr_state.s() + 50, (2 + 4 * target_lane), m_map_waypoints_s,
m_map_waypoints_x, m_map_waypoints_y);
auto next_wp1 = getXY(curr_state.s() + 60, (2 + 4 * target_lane), m_map_waypoints_s,
m_map_waypoints_x, m_map_waypoints_y);
auto next_wp2 = getXY(curr_state.s() + 90, (2 + 4 * target_lane), m_map_waypoints_s,
m_map_waypoints_x, m_map_waypoints_y);
pts_x.emplace_back(next_wp0[0]);
pts_x.emplace_back(next_wp1[0]);
pts_x.emplace_back(next_wp2[0]);
pts_y.emplace_back(next_wp0[1]);
pts_y.emplace_back(next_wp1[1]);
pts_y.emplace_back(next_wp2[1]);
for(int i = 0; i < pts_x.size(); i++)
{
auto shift_x = pts_x[i] - ref_x;
auto shift_y = pts_y[i] - ref_y;
pts_x[i] = (shift_x * cos(0 - ref_yaw) - shift_y * sin(0 - ref_yaw));
pts_y[i] = (shift_x * sin(0 - ref_yaw) + shift_y * cos(0 - ref_yaw));
}
tk::spline spline;
spline.set_points(pts_x, pts_y);
std::vector<double> next_x_vals;
std::vector<double> next_y_vals;
for(int i = 0; i < prev_path_x.size(); i++)
{
next_x_vals.emplace_back(prev_path_x[i]);
next_y_vals.emplace_back(prev_path_y[i]);
}
double target_x = 30.0;
double target_y = spline(target_x);
double target_dist = sqrt(target_x * target_x + target_y * target_y);
double x_add_on = 0;
for(int i = 1; i <= 50 - prev_path_x.size(); i++)
{
double N = (target_dist / (0.02 * ref_vel / 2.24));
double x_point = x_add_on + target_x / N;
double y_point = spline(x_point);
x_add_on = x_point;
auto x_ref = x_point;
auto y_ref = y_point;
x_point = (x_ref * cos(ref_yaw) - y_ref * sin(ref_yaw));
y_point = (x_ref * sin(ref_yaw) + y_ref * cos(ref_yaw));
x_point += ref_x;
y_point += ref_y;
next_x_vals.emplace_back(x_point);
next_y_vals.emplace_back(y_point);
}
return {next_x_vals, next_y_vals};
}
double lane_speed(const sensor_fusion_data_t &sf_data,
const vehicle& curr_state, int lane)
{
for(const auto& v : sf_data)
{
double check_car_s = v[5];
if((check_car_s > curr_state.s()) && (check_car_s - curr_state.s()) < 30)
{
double vx = v[3];
double vy = v[4];
double speed = sqrt(vx * vx + vy * vy);
vehicle veh(v[1], v[2], v[5], v[6], 0, speed);
if (veh.get_cur_lane() == lane)
{
return veh.speed();
}
}
}
// Found no vehicle in the lane
return -1.0;
}
double inefficiency_cost(double target_speed,
const sensor_fusion_data_t &sf_data,
const vehicle &curr_state,
int curr_lane, int dst_lane) {
double proposed_speed_intended = lane_speed(sf_data, curr_state, curr_lane);
if (proposed_speed_intended < 0) {
proposed_speed_intended = target_speed;
}
double proposed_speed_final = lane_speed(sf_data, curr_state, dst_lane);
if (proposed_speed_final < 0) {
proposed_speed_final = target_speed;
}
auto cost = (2.0*target_speed - proposed_speed_intended
- proposed_speed_final)/target_speed;
return cost;
}
double lane_cost(int dst_lane)
{
if(dst_lane < 0 || dst_lane > 2)
return 1;
return 0;
}
double collision_cost(const sensor_fusion_data_t &sf_data,
const vehicle &curr_state,
int curr_lane, int dst_lane)
{
for(const auto& v : sf_data)
{
double check_car_s = v[5];
if(check_car_s - curr_state.s() < 40)
{
vehicle veh(v[1], v[2], v[5], v[6], 0, 0);
if(veh.get_cur_lane() == dst_lane)
{
return 1;
}
}
}
return 0;
}
double lane_emptyness_cost(const sensor_fusion_data_t &sf_data,
const vehicle &curr_state,
int dst_lane)
{
for(const auto& v : sf_data)
{
double check_car_s = v[5];
if((check_car_s > curr_state.s()) && (check_car_s - curr_state.s()) < 30)
{
vehicle veh(v[1], v[2], v[5], v[6], 0, 0);
if (veh.get_cur_lane() == dst_lane)
{
return 1;
}
}
}
return 0;
}
double behavior_planner::calculate_cost(const sensor_fusion_data_t &sf_data,
const vehicle &curr_state,
const trajectory_t &trajectory,
int dst_lane)
{
if(std::get<0>(trajectory).empty())
{
return std::numeric_limits<double>::max();
}
auto cost = inefficiency_cost(49.5, sf_data, curr_state,
curr_state.get_cur_lane(), dst_lane) + 9999999 * lane_cost(dst_lane) +
9999 * collision_cost(sf_data, curr_state, curr_state.get_cur_lane(), dst_lane) +
5 * lane_emptyness_cost(sf_data, curr_state, dst_lane);
return cost;
}
| 32.032746 | 122 | 0.57026 | [
"vector"
] |
4d0415c0c1e38e912bf85960600318bc93154bb5 | 4,233 | cpp | C++ | src/Earworm/YoutubeSearch.cpp | sppp/Earworm | e8529563722b575fde0aa7a7329a01945a177f9c | [
"MIT"
] | null | null | null | src/Earworm/YoutubeSearch.cpp | sppp/Earworm | e8529563722b575fde0aa7a7329a01945a177f9c | [
"MIT"
] | null | null | null | src/Earworm/YoutubeSearch.cpp | sppp/Earworm | e8529563722b575fde0aa7a7329a01945a177f9c | [
"MIT"
] | null | null | null | #include "Earworm.h"
#include <plugin/tidy/tidy.h>
extern "C" {
int Tidy(const char* file, const char* html);
}
void BasicHeaders(HttpRequest& h)
{
h.ClearHeaders();
h.KeepAlive(1);
h.UserAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko");
h.Header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
h.Header("Accept-Language", "en-US,en;q=0.5");
h.Header("Accept-Encoding", "gzip, deflate");
h.Header("DNT", "1");
}
const XmlNode& TryOpenLocation(String pos, const XmlNode& root, int& errorcode) {
Vector<String> p = Split(pos, " ");
const XmlNode* xn = &root;
for(int i = 0; i < p.GetCount(); i++) {
int j = StrInt(p[i]);
if (j >= xn->GetCount()) {
errorcode = 1;
LOG("ERROR!!! xml TryOpenLocation fails! Maybe major change in web page");
return root;
}
xn = &(*xn)[j];
}
return *xn;
}
String XmlTreeString(const XmlNode& node, int indent=0, String prev_addr="") {
String out;
for(int i = 0; i < indent; i++) {
out.Cat(' ');
}
out << String(node.GetTag()) << " : " << String(node.GetText()) << " : " << prev_addr << " : ";
for(int i = 0; i < node.GetAttrCount(); i++) {
out += node.AttrId(i) + "=" + node.Attr(i) + ", ";
}
out += "\n";
for(int i = 0; i < node.GetCount(); i++) {
out += XmlTreeString(node[i], indent+1, prev_addr + " " + IntStr(i));
}
return out;
}
YouTubeSearch::YouTubeSearch() {
check_avail = false;
max_avail_checks = -1;
}
void YouTubeSearch::Search(String string) {
list.Clear();
HttpRequest h;
HttpRequest::Trace();
//h.Proxy("192.168.0.169:3128");
//h.SSLProxy("192.168.0.169:3128");
BasicHeaders(h);
String url = "https://www.youtube.com/results?search_query=" + UrlEncode(string);
h.SSL();
h.Url(url);
h.KeepAlive(false);
String c = h.Execute();
String filehtm = ConfigFile("yt_search_result.htm");
String file = ConfigFile("yt_search_result.xml");
FileOut out(filehtm);
out << c;
out.Close();
Tidy(file, filehtm);
FileIn in(file);
String xml = in.Get(in.GetSize());
in.Close();
//LOG(xml);
XmlNode xn;
try {
XmlParser p(xml);
p.Relaxed();
xn = ParseXML(p);
}
catch (XmlError e) {
LOG(e);
}
LOG(XmlTreeString(xn));
int errorcode = 0;
const XmlNode& list = TryOpenLocation("0 1 1 4 0 4 0 0 0 0 0 1 1 0 1 0", xn, errorcode);
if (!errorcode) {
int count = list.GetCount();
int check_count = 0;
for(int i = 0; i < count; i++) {
const XmlNode& sub = TryOpenLocation(IntStr(i) + " 0 0 1 0 0", list, errorcode);
String href = sub.Attr("href");
String title = sub.Attr("title");
String url = "https://www.youtube.com" + href;
if (href.GetCount() == 0)
continue;
if (check_avail && check_count != max_avail_checks) {
check_count++;
if (!IsVideoAvailable(url))
continue;
}
SearchResult& sr = this->list.Add();
sr.SetTitle(title);
sr.SetAddress(url);
LOG(i << ": " << title << ": " << href);
}
}
LOG("end");
//0 1 1 4 0 4 0 0 0 0 0 1 1 1 1 0 0 0 0 1 0 0
//0 1 1 4 0 4 0 0 0 0 0 1 1 1 1 0 1 0 0 1 0 0
//const XmlNode& x = xn[0][1][0][0][2][1][8][0][0][0][1][0][1];
}
bool YouTubeSearch::IsVideoAvailable(String url) {
HttpRequest h;
HttpRequest::Trace();
//h.Proxy("192.168.0.169:3128");
//h.SSLProxy("192.168.0.169:3128");
BasicHeaders(h);
h.SSL();
h.Url(url);
h.KeepAlive(false);
String c = h.Execute();
String filehtm = ConfigFile("yt_avail_check.htm");
String file = ConfigFile("yt_avail_check.xml");
FileOut out(filehtm);
out << c;
out.Close();
Tidy(file, filehtm);
FileIn in(file);
String xml = in.Get(in.GetSize());
in.Close();
//LOG(xml);
XmlNode xn;
try {
XmlParser p(xml);
p.Relaxed();
xn = ParseXML(p);
}
catch (XmlError e) {
LOG(e);
}
LOG(XmlTreeString(xn));
int errorcode = 0;
const XmlNode& avail_node = TryOpenLocation("0 1 1 4 0 3 1 0 1 0", xn, errorcode);
if (!errorcode) {
if (avail_node.Attr("id") == "unavailable-message")
return false;
}
return true;
}
| 21.378788 | 97 | 0.573588 | [
"vector"
] |
4d04521a1d85e24a25a46555a9106478135895ad | 264 | cpp | C++ | Leetcode Problems/268.MissingNumber.cpp | rishusingh022/My-Journey-of-Data-Structures-and-Algorithms | 28a70fdf10366fc97ddb9f6a69852b3478b564e6 | [
"MIT"
] | 1 | 2021-01-13T07:20:57.000Z | 2021-01-13T07:20:57.000Z | Leetcode Problems/268.MissingNumber.cpp | rishusingh022/My-Journey-of-Data-Structures-and-Algorithms | 28a70fdf10366fc97ddb9f6a69852b3478b564e6 | [
"MIT"
] | 1 | 2021-10-01T18:26:34.000Z | 2021-10-01T18:26:34.000Z | Leetcode Problems/268.MissingNumber.cpp | rishusingh022/My-Journey-of-Data-Structures-and-Algorithms | 28a70fdf10366fc97ddb9f6a69852b3478b564e6 | [
"MIT"
] | 7 | 2021-10-01T16:07:29.000Z | 2021-10-04T13:23:48.000Z | class Solution {
public:
int missingNumber(vector<int>& nums) {
int i = 0;
sort(nums.begin(), nums.end());
for(; i < nums.size(); ++i)
{
if(nums[i] != i)
return i;
}
return i;
}
}; | 20.307692 | 42 | 0.409091 | [
"vector"
] |
4d0829977453a5fe5f2158cc872f4f22cb578b7c | 2,234 | cpp | C++ | src/cascadia/TerminalSettingsEditor/Actions.cpp | hessedoneen/terminal | aa54de1d648f45920996aeba1edecc67237c6642 | [
"MIT"
] | 3 | 2019-08-04T13:44:57.000Z | 2021-09-25T20:13:28.000Z | src/cascadia/TerminalSettingsEditor/Actions.cpp | hessedoneen/terminal | aa54de1d648f45920996aeba1edecc67237c6642 | [
"MIT"
] | null | null | null | src/cascadia/TerminalSettingsEditor/Actions.cpp | hessedoneen/terminal | aa54de1d648f45920996aeba1edecc67237c6642 | [
"MIT"
] | 1 | 2021-04-15T17:13:29.000Z | 2021-04-15T17:13:29.000Z | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
#include "pch.h"
#include "Actions.h"
#include "Actions.g.cpp"
#include "ActionsPageNavigationState.g.cpp"
#include "EnumEntry.h"
using namespace winrt::Windows::Foundation;
using namespace winrt::Windows::System;
using namespace winrt::Windows::UI::Core;
using namespace winrt::Windows::UI::Xaml::Navigation;
using namespace winrt::Microsoft::Terminal::Settings::Model;
namespace winrt::Microsoft::Terminal::Settings::Editor::implementation
{
Actions::Actions()
{
InitializeComponent();
_filteredActions = winrt::single_threaded_observable_vector<winrt::Microsoft::Terminal::Settings::Model::Command>();
}
void Actions::OnNavigatedTo(const NavigationEventArgs& e)
{
_State = e.Parameter().as<Editor::ActionsPageNavigationState>();
for (const auto& [k, command] : _State.Settings().GlobalSettings().Commands())
{
// Filter out nested commands, and commands that aren't bound to a
// key. This page is currently just for displaying the actions that
// _are_ bound to keys.
if (command.HasNestedCommands() || command.KeyChordText().empty())
{
continue;
}
_filteredActions.Append(command);
}
}
Collections::IObservableVector<Command> Actions::FilteredActions()
{
return _filteredActions;
}
void Actions::_OpenSettingsClick(const IInspectable& /*sender*/,
const Windows::UI::Xaml::RoutedEventArgs& /*eventArgs*/)
{
const CoreWindow window = CoreWindow::GetForCurrentThread();
const auto rAltState = window.GetKeyState(VirtualKey::RightMenu);
const auto lAltState = window.GetKeyState(VirtualKey::LeftMenu);
const bool altPressed = WI_IsFlagSet(lAltState, CoreVirtualKeyStates::Down) ||
WI_IsFlagSet(rAltState, CoreVirtualKeyStates::Down);
const auto target = altPressed ? SettingsTarget::DefaultsFile : SettingsTarget::SettingsFile;
_State.RequestOpenJson(target);
}
}
| 36.032258 | 125 | 0.643688 | [
"model"
] |
4d223f324b0cb97776e1736751ebc24620a78a88 | 3,602 | cc | C++ | EnergyDeposition/src/Analysis.cc | murffer/DetectorSim | 1ba114c405eff42c0a52b6dc394cbecfc2d2bab0 | [
"Apache-2.0"
] | 5 | 2018-01-13T22:42:24.000Z | 2021-03-19T07:38:47.000Z | EnergyDeposition/src/Analysis.cc | murffer/DetectorSim | 1ba114c405eff42c0a52b6dc394cbecfc2d2bab0 | [
"Apache-2.0"
] | 1 | 2017-05-03T19:01:12.000Z | 2017-05-03T19:01:12.000Z | EnergyDeposition/src/Analysis.cc | murffer/DetectorSim | 1ba114c405eff42c0a52b6dc394cbecfc2d2bab0 | [
"Apache-2.0"
] | 3 | 2015-10-10T15:12:22.000Z | 2021-10-18T00:53:35.000Z | #include "Analysis.hh"
#include "G4UnitsTable.hh"
#include "globals.hh"
#include "G4RunManager.hh"
#include "G4LogicalVolumeStore.hh"
#include "G4LogicalVolume.hh"
#include "G4Tubs.hh"
#include "G4Material.hh"
#include "G4HCofThisEvent.hh"
#include "G4Event.hh"
#include "G4ThreeVector.hh"
#include "HistoManager.hh"
Analysis* Analysis::singleton = 0;
/**
* Analysis
*
* Creates an Analysis object
*/
Analysis::Analysis(){
}
/**
* Initilize the analysis manager
*
* Creates a new HistoManager
*/
void Analysis::Initilize(){
fHistoManager = new HistoManager();
}
/**
* Cleaning up the analysis manager
*
* Deleting the HistoManager
*/
void Analysis::CleanUp(){
delete fHistoManager;
}
Analysis::~Analysis(){
}
/**
* PrepareNewRun
*
* @brief - called before each run.
* There is no need to update the geometry because the geometry
* is fixed during a run.
*/
void Analysis::PrepareNewRun(const G4Run* ){
G4AnalysisManager* analysisManager = G4AnalysisManager::Instance();
if ( analysisManager->IsActive() ) {
analysisManager->OpenFile();
}
}
/**
* PrepareNewEvent
*
* @brief - Called before each event
* The energy deposition per slice is initialzed per event
*/
void Analysis::PrepareNewEvent(const G4Event* ){
// Initialize energy deposition to zero
eDepEvent = 0.0;
}
/**
* EndOfEvent
*
* @param G4Event* event
*/
void Analysis::EndOfEvent(const G4Event* event){
G4VHitsCollection *hc;
G4double zPos = 0.0;
bool isFirst = true;
CaloHit *hit;
G4AnalysisManager* analysisManager = G4AnalysisManager::Instance();
// Iterating through the hit collection to accumulate the energy deposition
G4int numHitColl = event->GetHCofThisEvent()->GetNumberOfCollections();
for(G4int hitItter = 0; hitItter < numHitColl; hitItter++){
// Itterating through the hit collection
hc = event->GetHCofThisEvent()->GetHC(hitItter);
for(G4int i = 0; i < hc->GetSize(); i++){
hit = (CaloHit*) hc->GetHit(i);
if (hit->GetTrackID() == 2 && hit->GetParentID() == 1 && isFirst){
// First interaction of the particle
isFirst = false;
zPos = GetCalorimeterThickness(); // Subtracting the thickness
zPos -= hit->GetPosition().z();
}
// Adding the energy deposition (in MeV)
eDepEvent += hit->GetEdep();
}
}
// Adding to the run accumulation only events with deposit energy
if (eDepEvent > 0.0){
analysisManager->FillH1(1,eDepEvent);
analysisManager->FillH2(1,eDepEvent/MeV,zPos/mm);
}
}
/**
* EndOfRun
*
* Called at the end of a run, which summerizes the run
*/
void Analysis::EndOfRun(const G4Run* ){
G4AnalysisManager* analysisManager = G4AnalysisManager::Instance();
//save histograms
if ( analysisManager->IsActive() ) {
analysisManager->Write();
analysisManager->CloseFile();
}
}
/**
* GetCalorimeterThickness
* @return the thickness of the calorimeter
*/
G4double Analysis::GetCalorimeterThickness(){
G4double caloThickness = 0;
G4LogicalVolume* detLV
= G4LogicalVolumeStore::GetInstance()->GetVolume("Absorber");
G4LogicalVolume* gapLV
= G4LogicalVolumeStore::GetInstance()->GetVolume("Gap");
G4Tubs* detTubs = 0;
G4Tubs* gapTubs = 0;
if ( detLV && gapLV) {
detTubs = dynamic_cast< G4Tubs*>(detLV->GetSolid());
gapTubs = dynamic_cast< G4Tubs*>(gapLV->GetSolid());
}
if ( detTubs && gapTubs) {
caloThickness = detTubs->GetZHalfLength()*2;
caloThickness += gapTubs->GetZHalfLength()*1;
}
else {
G4cerr << "Calorimeter Thickness not found." << G4endl;
}
return caloThickness;
}
| 24.174497 | 78 | 0.682121 | [
"geometry",
"object"
] |
4d2673b638114853d595889cceed66ef77f8301b | 3,516 | hpp | C++ | trie/aggregate-stats-policy.hpp | seanbraley/ndn-split-caching | 58d8c69c0316ed209661fb3f5a99c424847e2e37 | [
"MIT"
] | 3 | 2018-05-23T08:54:28.000Z | 2021-04-28T12:57:13.000Z | trie/aggregate-stats-policy.hpp | seanbraley/ndn-split-caching | 58d8c69c0316ed209661fb3f5a99c424847e2e37 | [
"MIT"
] | null | null | null | trie/aggregate-stats-policy.hpp | seanbraley/ndn-split-caching | 58d8c69c0316ed209661fb3f5a99c424847e2e37 | [
"MIT"
] | 1 | 2020-09-25T05:13:36.000Z | 2020-09-25T05:13:36.000Z | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2011-2015 Regents of the University of California.
*
* This file is part of ndnSIM. See AUTHORS for complete list of ndnSIM authors and
* contributors.
*
* ndnSIM is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* ndnSIM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* ndnSIM, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
**/
#ifndef AGGREGATE_STATS_POLICY_H_
#define AGGREGATE_STATS_POLICY_H_
#include <boost/intrusive/options.hpp>
#include <boost/intrusive/list.hpp>
namespace ns3 {
namespace ndn {
namespace ndnSIM {
/// @cond include_hidden
/**
* @brief Traits for policy that just keeps track of number of elements
* It's doing a rather expensive job, but just in case it needs to be extended later
*/
struct aggregate_stats_policy_traits {
/// @brief Name that can be used to identify the policy (for NS-3 object model and logging)
static std::string
GetName()
{
return "AggregateStats";
}
struct policy_hook_type {
};
template<class Container>
struct container_hook {
struct type {
};
};
template<class Base, class Container, class Hook>
struct policy {
// typedef typename boost::intrusive::list< Container, Hook > policy_container;
// could be just typedef
class type {
public:
typedef Container parent_trie;
type(Base& base)
: base_(base)
, m_updates(0)
, m_inserts(0)
, m_lookups(0)
, m_erases(0)
{
}
inline void
update(typename parent_trie::iterator item)
{
m_updates++;
// do nothing
}
inline bool
insert(typename parent_trie::iterator item)
{
m_inserts++;
return true;
}
inline void
lookup(typename parent_trie::iterator item)
{
m_lookups++;
}
inline void
erase(typename parent_trie::iterator item)
{
m_erases++;
}
inline void set_max_size(uint32_t)
{
}
inline uint32_t
get_max_size() const
{
return 0;
}
inline void
clear()
{
// is called only at the end of simulation
}
inline void
ResetStats()
{
m_updates = 0;
m_inserts = 0;
m_lookups = 0;
m_erases = 0;
}
inline uint64_t
GetUpdates() const
{
return m_updates;
}
inline uint64_t
GetInserts() const
{
return m_inserts;
}
inline uint64_t
GetLookups() const
{
return m_lookups;
}
inline uint64_t
GetErases() const
{
return m_erases;
}
private:
type()
: base_(*((Base*)0)){};
private:
Base& base_;
uint64_t m_updates;
uint64_t m_inserts;
uint64_t m_lookups;
uint64_t m_erases;
};
};
};
} // ndnSIM
} // ndn
} // ns3
/// @endcond
#endif // AGGREGATE_STATS_POLICY_H_
| 21.053892 | 93 | 0.610068 | [
"object",
"model"
] |
4d2ca813cf60a6a6e1d622ca592fb9f223c70c48 | 10,671 | cxx | C++ | shipgen/HNLPythia8Generator.cxx | Plamenna/proba | 517d7e437865c372e538f77d2242c188740f35d9 | [
"BSD-4-Clause"
] | null | null | null | shipgen/HNLPythia8Generator.cxx | Plamenna/proba | 517d7e437865c372e538f77d2242c188740f35d9 | [
"BSD-4-Clause"
] | null | null | null | shipgen/HNLPythia8Generator.cxx | Plamenna/proba | 517d7e437865c372e538f77d2242c188740f35d9 | [
"BSD-4-Clause"
] | null | null | null | #include <math.h>
#include "TROOT.h"
#include "TMath.h"
#include "FairPrimaryGenerator.h"
#include "TDatabasePDG.h" // for TDatabasePDG
#include "HNLPythia8Generator.h"
#include "Pythia8/Pythia.h"
const Double_t cm = 10.; // pythia units are mm
const Double_t c_light = 2.99792458e+10; // speed of light in cm/sec (c_light = 2.99792458e+8 * m/s)
const Bool_t debug = false;
using namespace Pythia8;
// ----- Default constructor -------------------------------------------
HNLPythia8Generator::HNLPythia8Generator()
{
fId = 2212; // proton
fMom = 400; // proton
fHNL = 9900015; // HNL pdg code
fLmin = 5000.*cm; // mm minimum decay position z ROOT units !
fLmax = 12000.*cm; // mm maximum decay position z
fextFile = "";
fInputFile = NULL;
fnRetries = 0;
fPythia = new Pythia8::Pythia();
}
// -------------------------------------------------------------------------
// ----- Default constructor -------------------------------------------
Bool_t HNLPythia8Generator::Init()
{
if ( debug ){List(9900015);}
fLogger = FairLogger::GetLogger();
if (fUseRandom1) fRandomEngine = new PyTr1Rng();
if (fUseRandom3) fRandomEngine = new PyTr3Rng();
fPythia->setRndmEnginePtr(fRandomEngine);
fn = 0;
if (fextFile != ""){
if (0 == strncmp("/eos",fextFile,4) ) {
char stupidCpp[100];
strcpy(stupidCpp,"root://eoslhcb/");
strcat(stupidCpp,fextFile);
fLogger->Info(MESSAGE_ORIGIN,"Open external file with charm or beauty hadrons on eos: %s",stupidCpp);
fInputFile = TFile::Open(stupidCpp);
if (!fInputFile) {
fLogger->Fatal(MESSAGE_ORIGIN, "Error opening input file. You may have forgotten to provide a krb5 token. Try kinit username@lxplus.cern.ch");
return kFALSE; }
}else{
fLogger->Info(MESSAGE_ORIGIN,"Open external file with charm or beauty hadrons: %s",fextFile);
fInputFile = new TFile(fextFile);
if (!fInputFile) {
fLogger->Fatal(MESSAGE_ORIGIN, "Error opening input file");
return kFALSE; }
}
if (fInputFile->IsZombie()) {
fLogger->Fatal(MESSAGE_ORIGIN, "File is corrupted");
return kFALSE; }
fTree = (TTree *)fInputFile->Get("pythia6");
fNevents = fTree->GetEntries();
fn = firstEvent;
fTree->SetBranchAddress("id",&hid); // particle id
fTree->SetBranchAddress("px",&hpx); // momentum
fTree->SetBranchAddress("py",&hpy);
fTree->SetBranchAddress("pz",&hpz);
fTree->SetBranchAddress("E",&hE);
fTree->SetBranchAddress("M",&hM);
fTree->SetBranchAddress("mid",&mid); // mother
fTree->SetBranchAddress("mpx",&mpx); // momentum
fTree->SetBranchAddress("mpy",&mpy);
fTree->SetBranchAddress("mpz",&mpz);
fTree->SetBranchAddress("mE",&mE);
}else{
if ( debug ){cout<<"Beam Momentum "<<fMom<<endl;}
fPythia->settings.mode("Beams:idA", fId);
fPythia->settings.mode("Beams:idB", 2212);
fPythia->settings.mode("Beams:frameType", 2);
fPythia->settings.parm("Beams:eA",fMom);
fPythia->settings.parm("Beams:eB",0.);
}
TDatabasePDG* pdgBase = TDatabasePDG::Instance();
Double_t root_ctau = pdgBase->GetParticle(fHNL)->Lifetime();
if ( debug ){cout<<"tau root "<<root_ctau<< "[s] ctau root = " << root_ctau*3e10 << "[cm]"<<endl;}
fctau = fPythia->particleData.tau0(fHNL); //* 3.3333e-12
if ( debug ){cout<<"ctau pythia "<<fctau<<"[mm]"<<endl;}
if ( debug ){List(9900015);}
fPythia->init();
return kTRUE;
}
// -------------------------------------------------------------------------
// ----- Destructor ----------------------------------------------------
HNLPythia8Generator::~HNLPythia8Generator()
{
}
// -------------------------------------------------------------------------
// ----- Passing the event ---------------------------------------------
Bool_t HNLPythia8Generator::ReadEvent(FairPrimaryGenerator* cpg)
{
Double_t tp,td,tS,zp,xp,yp,zd,xd,yd,zS,xS,yS,pz,px,py,e,w;
Double_t tm,zm,xm,ym,pmz,pmx,pmy,em;
Int_t im;
// take HNL decay of Pythia, move it to the SHiP decay region
// recalculate decay time
// weight event with exp(-t_ship/tau_HNL) / exp(-t_pythia/tau_HNL)
int iHNL = 0; // index of the chosen HNL (the 1st one), also ensures that at least 1 HNL is produced
std::vector<int> dec_chain; // pythia indices of the particles to be stored on the stack
std::vector<int> hnls; // pythia indices of HNL particles
do {
if (fextFile != ""){
// take charm or beauty hadron from external file
if (fn==fNevents) {fLogger->Warning(MESSAGE_ORIGIN, "End of input file. Rewind.");}
fTree->GetEntry(fn%fNevents);
fPythia->event.reset();
fPythia->event.append( (Int_t)hid[0], 1, 0, 0, hpx[0], hpy[0], hpz[0], hE[0], hM[0], 0., 9. );
}
fn++;
if (fn%100==0) {
fLogger->Info(MESSAGE_ORIGIN,"pythia event-nr %i",fn);
}
fPythia->next();
for(int i=0; i<fPythia->event.size(); i++){
// find first HNL
if (abs(fPythia->event[i].id())==fHNL){
hnls.push_back( i );
}
}
iHNL = hnls.size();
if ( iHNL == 0 ){
//fLogger->Info(MESSAGE_ORIGIN,"Event without HNL. Retry.");
//fPythia->event.list();
fnRetries+=1; // can happen if phasespace does not allow charm hadron to decay to HNL
}else{
int r = int( gRandom->Uniform(0,iHNL) );
// cout << " ----> debug 2 " << r << endl;
int i = hnls[r];
// production vertex
zp =fPythia->event[i].zProd();
xp =fPythia->event[i].xProd();
yp =fPythia->event[i].yProd();
tp =fPythia->event[i].tProd();
// momentum
pz =fPythia->event[i].pz();
px =fPythia->event[i].px();
py =fPythia->event[i].py();
e =fPythia->event[i].e();
// old decay vertex
Int_t ida =fPythia->event[i].daughter1();
zd =fPythia->event[ida].zProd();
xd =fPythia->event[ida].xProd();
yd =fPythia->event[ida].yProd();
td =fPythia->event[ida].tProd();
// new decay vertex
Double_t LS = gRandom->Uniform(fLmin,fLmax); // mm, G4 and Pythia8 units
Double_t p = TMath::Sqrt(px*px+py*py+pz*pz);
Double_t lam = LS/p;
xS = xp + lam * px;
yS = yp + lam * py;
zS = zp + lam * pz;
Double_t gam = e/TMath::Sqrt(e*e-p*p);
Double_t beta = p/e;
tS = tp + LS/beta; // units ? [mm/c] + [mm/beta] (beta is dimensionless speed, and c=1 here)
// if one would use [s], then tS = tp/(cm*c_light) + (LS/cm)/(beta*c_light) = tS/(cm*c_light) i.e. units look consisent
w = TMath::Exp(-LS/(beta*gam*fctau))*( (fLmax-fLmin)/(beta*gam*fctau) );
im = (Int_t)fPythia->event[i].mother1();
zm =fPythia->event[im].zProd();
xm =fPythia->event[im].xProd();
ym =fPythia->event[im].yProd();
pmz =fPythia->event[im].pz();
pmx =fPythia->event[im].px();
pmy =fPythia->event[im].py();
em =fPythia->event[im].e();
tm =fPythia->event[im].tProd();
if (fextFile != ""){
// take grand mother particle from input file, to know if primary or secondary production
cpg->AddTrack((Int_t)mid[0],mpx[0],mpy[0],mpz[0],xm/cm,ym/cm,zm/cm,-1,false,mE[0],0.,1.);
cpg->AddTrack((Int_t)fPythia->event[im].id(),pmx,pmy,pmz,xm/cm,ym/cm,zm/cm,0,false,em,tm/cm/c_light,w); // convert pythia's (x,y,z[mm], t[mm/c]) to ([cm], [s])
cpg->AddTrack(fHNL, px, py, pz, xp/cm,yp/cm,zp/cm, 1,false,e,tp/cm/c_light,w);
}else{
cpg->AddTrack((Int_t)fPythia->event[im].id(),pmx,pmy,pmz,xm/cm,ym/cm,zm/cm,-1,false,em,tm/cm/c_light,w); // convert pythia's (x,y,z[mm], t[mm/c]) to ([cm], [s])
cpg->AddTrack(fHNL, px, py, pz, xp/cm,yp/cm,zp/cm, 0,false,e,tp/cm/c_light,w);
}
// bookkeep the indices of stored particles
dec_chain.push_back( im );
dec_chain.push_back( i );
//cout << endl << " insert mother pdg=" <<fPythia->event[im].id() << " pmz = " << pmz << " [GeV], zm = " << zm << " [mm] tm = " << tm << " [mm/c]" << endl;
//cout << " ----> insert HNL =" << fHNL << " pz = " << pz << " [GeV] zp = " << zp << " [mm] tp = " << tp << " [mm/c]" << endl;
iHNL = i;
}
} while ( iHNL == 0 ); // ----------- avoid rare empty events w/o any HNL's produced
// fill a container with pythia indices of the HNL decay chain
for(int k=0; k<fPythia->event.size(); k++){
// if daughter of HNL, copy
im =fPythia->event[k].mother1();
while (im>0){
if ( im == iHNL ){break;} // pick the decay products of only 1 chosen HNL
// if ( abs(fPythia->event[im].id())==fHNL && im == iHNL ){break;}
else {im =fPythia->event[im].mother1();}
}
if (im < 1) {continue;}
dec_chain.push_back( k );
}
// go over daughters and store them on the stack, starting from 2 to account for HNL and its mother
for(std::vector<int>::iterator it = dec_chain.begin() + 2; it != dec_chain.end(); ++it){
// pythia index of the paricle to store
int k = *it;
// find mother position on the output stack: impy -> im
int impy =fPythia->event[k].mother1();
std::vector<int>::iterator itm = std::find( dec_chain.begin(), dec_chain.end(), impy);
im =-1; // safety
if ( itm != dec_chain.end() )
im = itm - dec_chain.begin(); // convert iterator into sequence number
Bool_t wanttracking=false;
if(fPythia->event[k].isFinal()){ wanttracking=true;}
pz =fPythia->event[k].pz();
px =fPythia->event[k].px();
py =fPythia->event[k].py();
e =fPythia->event[k].e();
if (fextFile != ""){im+=1;};
cpg->AddTrack((Int_t)fPythia->event[k].id(),px,py,pz,xS/cm,yS/cm,zS/cm,im,wanttracking,e,tp/cm/c_light,w);
// cout <<k<< " insert pdg =" <<fPythia->event[k].id() << " pz = " << pz << " [GeV] zS = " << zS << " [mm] tp = " << tp << "[mm/c]" << endl;
}
return kTRUE;
}
// -------------------------------------------------------------------------
void HNLPythia8Generator::SetParameters(char* par)
{
// Set Parameters
fPythia->readString(par);
if ( debug ){cout<<"fPythia->readString(\""<<par<<"\")"<<endl;}
}
// -------------------------------------------------------------------------
ClassImp(HNLPythia8Generator)
| 44.095041 | 166 | 0.539781 | [
"vector"
] |
4d2f8eec661c3b6833bad1476c036bdf857c1413 | 2,678 | cpp | C++ | backup/2/interviewbit/c++/regular-expression-match.cpp | yangyanzhan/code-camp | 4272564e916fc230a4a488f92ae32c07d355dee0 | [
"Apache-2.0"
] | 21 | 2019-11-16T19:08:35.000Z | 2021-11-12T12:26:01.000Z | backup/2/interviewbit/c++/regular-expression-match.cpp | yangyanzhan/code-camp | 4272564e916fc230a4a488f92ae32c07d355dee0 | [
"Apache-2.0"
] | 1 | 2022-02-04T16:02:53.000Z | 2022-02-04T16:02:53.000Z | backup/2/interviewbit/c++/regular-expression-match.cpp | yangyanzhan/code-camp | 4272564e916fc230a4a488f92ae32c07d355dee0 | [
"Apache-2.0"
] | 4 | 2020-05-15T19:39:41.000Z | 2021-10-30T06:40:31.000Z | // Hi, I'm Yanzhan. For more algothmic problems, visit my Youtube Channel (Yanzhan Yang's Youtube Channel) : https://www.youtube.com/channel/UCDkz-__gl3frqLexukpG0DA?view_as=subscriber or my Twitter Account (Yanzhan Yang's Twitter) : https://twitter.com/YangYanzhan or my GitHub HomePage (Yanzhan Yang's GitHub HomePage) : https://yanzhan.site .
// For this specific algothmic problem, visit my Youtube Video : .
// It's fascinating to solve algothmic problems, follow Yanzhan to learn more!
// Blog URL for this problem: https://yanzhan.site/interviewbit/regular-expression-match.html .
int match(string s, int i, string p, int j) {
if (i >= s.size() && j >= p.size()) {
return 1;
}
if (i == s.size() && j < p.size()) {
for (int t = j; t < p.size(); t++) {
if (p[t] != '*') {
return 0;
}
}
return 1;
}
if (s[i] == p[j] || p[j] == '?') {
return match(s, i + 1, p, j + 1);
}
if (p[j] == '*') {
return max(match(s, i + 1, p, j), match(s, i, p, j + 1));
}
}
int Solution::isMatch(const string s, const string p) {
// Do not write main() function.
// Do not read input, instead use the arguments to the function.
// Do not print the output, instead return values as specified
// Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details
int pat = p.size();
int str = s.size();
int i = 0, j = 0;
int iIndex = -1, jIndex = -1;
while (i < str) {
if (s[i] == p[j] || (j < pat && p[j] == '?')) {
i++;
j++;
} else if (p[j] == '*' && j < pat) {
jIndex = j;
iIndex = i;
j++;
} else if (jIndex != -1) {
j = jIndex + 1;
i = iIndex + 1;
iIndex++;
} else {
return 0;
}
}
while (j < pat && p[j] == '*') {
j++;
}
if (j == pat) {
return 1;
}
return 0;
// return match(s, 0, p, 0);
// vector<vector<int> > temp(str+1, vector<int>(pat+1, 0));
// temp[0][0] = 1;
// for(int i = 1; i < temp[0].size(); i++){
// if(p[i-1] == '*'){
// temp[0][i] = temp[0][i-1];
// }
// }
// for(int i = 1; i < temp.size(); i++){
// for(int j = 1; j < temp[i].size(); j++){
// if(p[j-1] == s[i-1] || p[j-1] == '?'){
// temp[i][j] = temp[i-1][j-1];
// }
// else if(p[j-1] == '*'){
// temp[i][j] = max(temp[i-1][j], temp[i][j-1]);
// }
// }
// }
// return temp[str][pat];
}
| 28.489362 | 345 | 0.458178 | [
"vector"
] |
2ec460b129653f4fefb40618c37b63698f957b37 | 35,175 | cxx | C++ | com/netfx/src/framework/xsp/isapi/perfcounterserver.cxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | com/netfx/src/framework/xsp/isapi/perfcounterserver.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | com/netfx/src/framework/xsp/isapi/perfcounterserver.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /**
* PerfCounterServer.cxx
*
* Copyright (c) 1998-2002, Microsoft Corporation
*
*/
#include "precomp.h"
#include "ProcessTableManager.h"
#include "dbg.h"
#include "util.h"
#include "platform_apis.h"
#include "nisapi.h"
#include "aspnetver.h"
#include "hashtable.h"
#include "SmartFileHandle.h"
#include "completion.h"
#include "names.h"
#include "ary.h"
#include "PerfCounters.h"
/* Performance counters in ASP.NET
Here's a short description on the implementation details of performance counters for ASP.NET.
The main class for dealing with performance counters is the CPerfCounterServer class. This class was
designed to be a singleton per process and does all the management of counter data for different
app domains, as well as the communication layer with the perf counter dll. Communication with
the perf dll is done via named pipes, with their names randomly generated and stored in a key
in the registry ACL'd so that worker processes can R/W from it, but everyone else can only Read.
Named pipes are also connected with static security of Anonymous, to prevent any malicious users
from impersonating the process.
ASP.NET contains 2 sets of performance counters: global and app. Internally they are stored
in a CPerfData structure, which contains a DWORD array of values and the name of the application.
A NULL application name signifies it contains the global data. An array of CPerfData is
used to hold on to the data for all app domains.
There is also a set of methods exposed that are basically entry points for managed code to open, close
and set the various perf counters.
*/
/////////////////////////////////////////////////////////////////////////////
// Class definitions
#define PIPE_PREFIX_L L"\\\\.\\pipe\\"
#define PIPE_PREFIX_LENGTH 9
// Declare the array of CPerfData*
DECLARE_CPtrAry(CPerfDataAry, CPerfData*);
// Declare the array of WCHAR*
DECLARE_CPtrAry(CWCHARAry, WCHAR*);
class CPerfPipeOverlapped : public OVERLAPPED_COMPLETION
{
public:
DECLARE_MEMCLEAR_NEW_DELETE();
CPerfPipeOverlapped();
~CPerfPipeOverlapped();
BOOL fWriteOprn; // WriteFile or ReadFile?
DWORD dwPipeNum;
DWORD dwBytes;
DWORD dwBufferSize;
BYTE* lpNextData;
BYTE* lpBuffer;
CSmartFileHandle pipeHandle;
CPerfVersion versionBuffer;
BOOL fClientConnected;
private:
NO_COPY(CPerfPipeOverlapped);
};
class CPerfCounterServer : public ICompletion
{
public:
static CPerfCounterServer* GetSingleton();
static CPerfData * g_GlobalCounterData;
static HRESULT StaticInitialize();
HRESULT OpenInstanceCounter(CPerfData ** hInstanceData, WCHAR * szAppName);
HRESULT CloseInstanceCounter(CPerfData * pInstanceData);
// ICompletion interface
STDMETHOD (QueryInterface ) (REFIID , void ** );
STDMETHOD (ProcessCompletion) (HRESULT , int, LPOVERLAPPED );
STDMETHOD_ (ULONG, AddRef ) ();
STDMETHOD_ (ULONG, Release ) ();
private:
DECLARE_MEMCLEAR_NEW_DELETE();
// Private constructor and destructor -- there can only be a singleton of this class
CPerfCounterServer();
~CPerfCounterServer();
NO_COPY(CPerfCounterServer);
// Private methods
HRESULT Initialize();
HRESULT StartRead(HANDLE hPipe, CPerfPipeOverlapped * pOverlapped);
HRESULT StartOverlapped(HANDLE hPipe, CPerfPipeOverlapped * pOverlapped);
HRESULT InitPerfPipe();
HRESULT StartNewPipeInstance(BOOL firstOne);
void ClosePipe(CPerfPipeOverlapped * pOverlapped);
HRESULT CleanupNames();
HRESULT CreateSids(PSID *BuiltInAdministrators, PSID *ServiceUsers, PSID *AuthenticatedUsers);
HRESULT CreateSd(PSECURITY_DESCRIPTOR * descriptor);
HRESULT SendPerfData(HANDLE hPipe, CPerfPipeOverlapped * lpOverlapped);
// Static
static CPerfCounterServer * s_Singleton;
const static int MaxPipeInstances = 32;
const static int MaxPipeNameLength = PERF_PIPE_NAME_MAX_BUFFER;
const static int MaxDirInfoBufferSize = 4000;
// Instance vars
CReadWriteSpinLock _perfLock;
CPerfDataAry _perfDataAry;
CPerfVersion * _currentVersion;
// Pipe maintenance vars
BOOL _inited;
LONG _lPendingReadWriteCount;
CPerfPipeOverlapped * _pipeServerData[MaxPipeInstances];
LONG _pipesConnected;
LONG _pipeIndex; // This is the highest pipe INDEX created (add 1 for count!)
WCHAR * _pipeName;
};
/////////////////////////////////////////////////////////////////////////////
// Static
//
CPerfCounterServer * CPerfCounterServer::s_Singleton;
CPerfData * CPerfCounterServer::g_GlobalCounterData;
/////////////////////////////////////////////////////////////////////////////
// Singleton retriever for CPerfCounterServer class
//
inline CPerfCounterServer* CPerfCounterServer::GetSingleton()
{
return s_Singleton;
}
/////////////////////////////////////////////////////////////////////////////
// CTor
//
CPerfCounterServer::CPerfCounterServer():_perfLock("CPerfCounterServer")
{
_pipeIndex = -1;
}
/////////////////////////////////////////////////////////////////////////////
// DTor
//
CPerfCounterServer::~CPerfCounterServer()
{
}
/////////////////////////////////////////////////////////////////////////////
// CTor
//
CPerfPipeOverlapped::CPerfPipeOverlapped()
{
}
/////////////////////////////////////////////////////////////////////////////
// DTor
//
CPerfPipeOverlapped::~CPerfPipeOverlapped()
{
DELETE_BYTES(lpBuffer);
}
/////////////////////////////////////////////////////////////////////////////
// Inits the CPerfCounterServer class
//
HRESULT CPerfCounterServer::StaticInitialize()
{
HRESULT hr = S_OK;
CPerfCounterServer * counterServer = NULL;
if (CPerfCounterServer::s_Singleton == NULL) {
counterServer = new CPerfCounterServer;
ON_OOM_EXIT(counterServer);
hr = counterServer->Initialize();
ON_ERROR_EXIT();
CPerfCounterServer::s_Singleton = counterServer;
counterServer = NULL;
}
Cleanup:
delete counterServer;
return hr;
}
HRESULT CPerfCounterServer::Initialize()
{
HRESULT hr = S_OK;
_currentVersion = CPerfVersion::GetCurrentVersion();
ON_OOM_EXIT(_currentVersion);
g_GlobalCounterData = new CPerfData;
ON_OOM_EXIT(g_GlobalCounterData);
_perfDataAry.Append(g_GlobalCounterData);
hr = InitPerfPipe();
ON_ERROR_EXIT();
_inited = TRUE;
Cleanup:
return hr;
}
/////////////////////////////////////////////////////////////////////////////
// Given an app name, returns the CPerfData struct for it.
// It'll retrieve an existing one if there, else will return a new one
//
HRESULT CPerfCounterServer::OpenInstanceCounter(CPerfData ** hInstanceData, WCHAR * wcsAppName)
{
HRESULT hr = S_OK;
size_t length;
CPerfData * data;
if (!_inited)
EXIT_WITH_HRESULT(E_UNEXPECTED);
hr = StringCchLengthW(wcsAppName, CPerfData::MaxNameLength, &length);
ON_ERROR_EXIT();
_perfLock.AcquireWriterLock();
__try {
data = (CPerfData *) NEW_CLEAR_BYTES(sizeof(CPerfData) + (length * sizeof(WCHAR)));
ON_OOM_EXIT(data);
hr = StringCchCopyW(data->name, length + 1, wcsAppName);
ON_ERROR_EXIT();
data->nameLength = (int) length;
_perfDataAry.Append(data);
*hInstanceData = data;
}
__finally {
_perfLock.ReleaseWriterLock();
}
Cleanup:
return hr;
}
/////////////////////////////////////////////////////////////////////////////
// Removes the given CPerfData from the list and deletes it
//
HRESULT CPerfCounterServer::CloseInstanceCounter(CPerfData * pInstanceData)
{
HRESULT hr = S_OK;
_perfLock.AcquireWriterLock();
__try {
int index = _perfDataAry.Find(pInstanceData);
if (index == -1)
EXIT();
CPerfData * perfData = _perfDataAry[index];
_perfDataAry.Delete(index);
delete perfData;
}
__finally {
_perfLock.ReleaseWriterLock();
}
Cleanup:
return hr;
}
/////////////////////////////////////////////////////////////////////////////
// Queries the system for all named pipes and sees if the perf counter
// named pipes in the registry still exist. If not, they are deleted
//
HRESULT CPerfCounterServer::CleanupNames()
{
HRESULT hr = S_OK;
HKEY hKey = NULL;
LONG retCode = 0;
DWORD index;
WCHAR keyName[MAX_PATH];
DWORD keyLength;
HashtableGeneric * nameTable = NULL;
HANDLE hPipe = NULL;
void * obj;
WCHAR name[MAX_PATH];
int cbLength;
HANDLE hFind = INVALID_HANDLE_VALUE;
WIN32_FIND_DATA findFileData;
CWCHARAry delKeysAry;
nameTable = new HashtableGeneric;
ON_OOM_EXIT(nameTable);
nameTable->Init(13);
hFind = FindFirstFileEx(L"\\\\.\\pipe\\*", FindExInfoStandard, &findFileData, (FINDEX_SEARCH_OPS ) 0, NULL, 0 );
if (hFind == INVALID_HANDLE_VALUE)
EXIT_WITH_LAST_ERROR();
do {
size_t iRemaining;
// Copy the pipe name into a new wchar buffer
hr = StringCchCopyNExW(name, MAX_PATH, findFileData.cFileName, MAX_PATH - 1, NULL, &iRemaining, NULL);
ON_ERROR_EXIT();
// Insert the name into the hashtable
cbLength = (MAX_PATH + 1 - ((int) iRemaining)) * sizeof(WCHAR);
hr = nameTable->Insert((BYTE *) name, cbLength, SimpleHash((BYTE*) name, cbLength), nameTable, NULL);
ON_ERROR_EXIT();
} while(FindNextFile(hFind, &findFileData));
// Now open registry key of previously stored name pipes
retCode = RegOpenKeyEx(HKEY_LOCAL_MACHINE, REGPATH_PERF_VERSIONED_NAMES_KEY_L, 0, KEY_READ | KEY_WRITE, &hKey);
ON_WIN32_ERROR_EXIT(retCode);
// On each name, see if it's in the hashtable -- if so, skip
for (index = 0;;index++) {
keyLength = ARRAY_SIZE(keyName) - 1;
retCode = RegEnumValue(hKey, index, (LPWSTR) &keyName, &keyLength, 0, 0, 0, NULL);
keyName[ARRAY_SIZE(keyName) - 1] = L'\0';
if (retCode == ERROR_SUCCESS) {
obj = NULL;
cbLength = (keyLength + 1) * sizeof(WCHAR);
nameTable->Find((BYTE*)keyName, cbLength, SimpleHash((BYTE*) keyName, cbLength), &obj);
// If name is not on the hashtable, keep its name around to delete later
if (obj == NULL) {
WCHAR * toDelName = new WCHAR[keyLength + 1];
hr = StringCchCopyNW(toDelName, keyLength + 1, keyName, keyLength);
delKeysAry.Append(toDelName);
}
}
else if (retCode == ERROR_NO_MORE_ITEMS) {
break;
}
else if (retCode != ERROR_MORE_DATA) {
EXIT_WITH_WIN32_ERROR(retCode);
}
}
for (int i = 0; i < delKeysAry.Size(); i++) {
retCode = RegDeleteValue(hKey, delKeysAry[i]);
ON_WIN32_ERROR_CONTINUE(retCode);
}
Cleanup:
if (hKey != NULL)
RegCloseKey(hKey);
if (hPipe != NULL)
CloseHandle(hPipe);
if (hFind != INVALID_HANDLE_VALUE)
FindClose(hFind);
for (int i = 0; i < delKeysAry.Size(); i++) {
WCHAR * toDelName = delKeysAry[i];
delete [] toDelName;
}
delete nameTable;
return hr;
}
/////////////////////////////////////////////////////////////////////////////
// Initializes the perf dll communication name pipe servers.
//
HRESULT CPerfCounterServer::InitPerfPipe()
{
HRESULT hr = S_OK;
// Cleanup the old names off the registry
CleanupNames();
hr = StartNewPipeInstance(TRUE);
ON_ERROR_EXIT();
Cleanup:
return hr;
}
HRESULT CPerfCounterServer::StartNewPipeInstance(BOOL firstOne)
{
HRESULT hr = S_OK;
HANDLE hPipe = NULL;
WCHAR * szName;
HKEY hKey = NULL;
PSECURITY_DESCRIPTOR pSd = NULL;
SECURITY_ATTRIBUTES sa;
DWORD maxRetry = 5;
DWORD pipeNum = InterlockedIncrement(&_pipeIndex);
CPerfPipeOverlapped * pipeData;
if (pipeNum >= MaxPipeInstances)
EXIT_WITH_HRESULT(E_UNEXPECTED);
ASSERT(_pipeServerData[pipeNum] == NULL);
_pipeServerData[pipeNum] = new CPerfPipeOverlapped;
ON_OOM_EXIT(_pipeServerData[pipeNum]);
pipeData = _pipeServerData[pipeNum];
// Don't forget to free the pSd!
hr = CreateSd(&pSd);
ON_ERROR_EXIT();
sa.nLength = sizeof(sa);
sa.lpSecurityDescriptor = pSd;
sa.bInheritHandle = FALSE;
pipeData->dwPipeNum = pipeNum;
pipeData->pCompletion = this;
// Create pipe
// Only on first create do we specify the first pipe flag
if (firstOne) {
// Copy the pipe prefix to the name buffer
_pipeName = new WCHAR[CPerfCounterServer::MaxPipeNameLength];
ON_OOM_EXIT(_pipeName);
hr = StringCchCopy(_pipeName, PIPE_PREFIX_LENGTH + 1, PIPE_PREFIX_L);
ON_ERROR_EXIT();
szName = _pipeName + PIPE_PREFIX_LENGTH;
while (maxRetry > 0) {
// Obtain the random pipe name
// GenerateRandomString will return only fill up the string to (size - 1) entries
hr = GenerateRandomString(szName, CPerfCounterServer::MaxPipeNameLength - PIPE_PREFIX_LENGTH);
ON_ERROR_EXIT();
szName[CPerfCounterServer::MaxPipeNameLength - PIPE_PREFIX_LENGTH - 1] = L'\0';
hPipe = CreateNamedPipe(_pipeName,
FILE_FLAG_OVERLAPPED | PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE,
PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,
MaxPipeInstances, 1024, 1024, 1000, &sa);
// Because we specify first pipe instance, creation will fail unless we're the creator
if (hPipe != INVALID_HANDLE_VALUE) {
// Put the pipe name into the registry
hr = RegOpenKeyEx(HKEY_LOCAL_MACHINE, REGPATH_PERF_VERSIONED_NAMES_KEY_L, 0, KEY_READ | KEY_WRITE, &hKey);
ON_WIN32_ERROR_EXIT(hr);
int val = GetCurrentProcessId();
hr = RegSetValueEx(hKey, szName, 0, REG_DWORD, (BYTE*) &val, sizeof(DWORD));
ON_WIN32_ERROR_EXIT(hr);
RegCloseKey(hKey);
hKey = NULL;
// Get out of the while loop
break;
}
maxRetry--;
}
}
else {
ASSERT(_pipeName != NULL);
hPipe = CreateNamedPipe(_pipeName,
FILE_FLAG_OVERLAPPED | PIPE_ACCESS_DUPLEX,
PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,
MaxPipeInstances, 1024, 1024, 1000, &sa);
}
if (hPipe == INVALID_HANDLE_VALUE)
EXIT_WITH_LAST_ERROR();
// Set pipe
pipeData->pipeHandle.SetHandle(hPipe);
hr = AttachHandleToThreadPool(hPipe);
ON_ERROR_EXIT();
hr = StartOverlapped(hPipe, pipeData);
ON_ERROR_EXIT();
Cleanup:
if (hKey != NULL) {
RegCloseKey(hKey);
}
DELETE_BYTES(pSd);
if (hr != S_OK) {
if (hPipe != INVALID_HANDLE_VALUE)
CloseHandle(hPipe);
}
return hr;
}
/////////////////////////////////////////////////////////////////////////////
// Starts the overlapped operation on the named pipe
//
HRESULT CPerfCounterServer::StartOverlapped(HANDLE hPipe, CPerfPipeOverlapped * pOverlapped)
{
HRESULT hr = S_OK;
pOverlapped->fWriteOprn = FALSE;
if (!ConnectNamedPipe(hPipe, pOverlapped)) {
DWORD lastError = GetLastError();
if (lastError != ERROR_PIPE_CONNECTED && lastError != ERROR_IO_PENDING) {
EXIT_WITH_LAST_ERROR();
}
}
Cleanup:
return hr;
}
/////////////////////////////////////////////////////////////////////////////
// Start reading from the pipe
//
HRESULT CPerfCounterServer::StartRead(HANDLE hPipe, CPerfPipeOverlapped * pOverlapped)
{
HRESULT hr = S_OK;
pOverlapped->fWriteOprn = FALSE;
if (!ReadFile(hPipe, &(pOverlapped->versionBuffer), sizeof(CPerfVersion), NULL, pOverlapped))
{
DWORD dwE = GetLastError();
if (dwE != ERROR_IO_PENDING && dwE != ERROR_MORE_DATA)
{
EXIT_WITH_LAST_ERROR();
}
}
Cleanup:
return hr;
}
/////////////////////////////////////////////////////////////////////////////
// Close
void CPerfCounterServer::ClosePipe(CPerfPipeOverlapped * pOverlapped)
{
pOverlapped->pipeHandle.Close();
}
/////////////////////////////////////////////////////////////////////////////
//
// CreateSids
//
// Create 3 Security IDs
//
// Caller must free memory allocated to SIDs on success.
//
// Returns: TRUE if successfull, FALSE if not.
//
HRESULT CPerfCounterServer::CreateSids(PSID *BuiltInAdministrators, PSID *ServiceUsers, PSID *AuthenticatedUsers)
{
HRESULT hr = S_OK;
PSID tmpAdmin = NULL;
PSID tmpService = NULL;
PSID tmpUser = NULL;
//
// An SID is built from an Identifier Authority and a set of Relative IDs
// (RIDs). The Authority of interest to us SECURITY_NT_AUTHORITY.
//
SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;
//
// Each RID represents a sub-unit of the authority. Two of the SIDs we
// want to build, Local Administrators, and Power Users, are in the "built
// in" domain. The other SID, for Authenticated users, is based directly
// off of the authority.
//
// For examples of other useful SIDs consult the list in
// \nt\public\sdk\inc\ntseapi.h.
//
if (!AllocateAndInitializeSid(&NtAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0,0,0,0,0,0, &tmpAdmin))
EXIT_WITH_LAST_ERROR();
if (!AllocateAndInitializeSid(&NtAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0,0,0,0,0,0, &tmpService))
EXIT_WITH_LAST_ERROR();
if (!AllocateAndInitializeSid(&NtAuthority, 1, SECURITY_AUTHENTICATED_USER_RID, 0,0,0,0,0,0,0, &tmpUser))
EXIT_WITH_LAST_ERROR();
*BuiltInAdministrators = tmpAdmin;
tmpAdmin = NULL;
*ServiceUsers = tmpService;
tmpService = NULL;
*AuthenticatedUsers = tmpUser;
tmpUser = NULL;
Cleanup:
FreeSid(tmpAdmin);
FreeSid(tmpService);
FreeSid(tmpUser);
return hr;
}
/////////////////////////////////////////////////////////////////////////////
//
// CreateSd
//
// Creates a SECURITY_DESCRIPTOR with specific DACLs. Modify the code to
// change.
//
// Caller must free the returned buffer if not NULL.
//
HRESULT CPerfCounterServer::CreateSd(PSECURITY_DESCRIPTOR * descriptor)
{
HRESULT hr = S_OK;
PSID AuthenticatedUsers;
PSID BuiltInAdministrators;
PSID ServiceUsers;
PSECURITY_DESCRIPTOR Sd = NULL;
LONG AclSize;
BuiltInAdministrators = NULL;
ServiceUsers = NULL;
AuthenticatedUsers = NULL;
hr = CreateSids(&BuiltInAdministrators, &ServiceUsers, &AuthenticatedUsers);
ON_ERROR_EXIT();
// Calculate the size of and allocate a buffer for the DACL, we need
// this value independently of the total alloc size for ACL init.
// "- sizeof (LONG)" represents the SidStart field of the
// ACCESS_ALLOWED_ACE. Since we're adding the entire length of the
// SID, this field is counted twice.
AclSize = sizeof (ACL) +
(3 * (sizeof (ACCESS_ALLOWED_ACE) - sizeof (LONG))) +
GetLengthSid(AuthenticatedUsers) +
GetLengthSid(BuiltInAdministrators) +
GetLengthSid(ServiceUsers);
Sd = (PSECURITY_DESCRIPTOR) NEW_BYTES(SECURITY_DESCRIPTOR_MIN_LENGTH + AclSize);
ON_OOM_EXIT(Sd);
ACL *Acl;
Acl = (ACL *)((BYTE *)Sd + SECURITY_DESCRIPTOR_MIN_LENGTH);
if (!InitializeAcl(Acl, AclSize, ACL_REVISION))
EXIT_WITH_LAST_ERROR();
if (!AddAccessAllowedAce(Acl, ACL_REVISION, GENERIC_READ | GENERIC_WRITE, AuthenticatedUsers))
EXIT_WITH_LAST_ERROR();
if (!AddAccessAllowedAce(Acl, ACL_REVISION, GENERIC_READ | GENERIC_WRITE, ServiceUsers))
EXIT_WITH_LAST_ERROR();
if (!AddAccessAllowedAce(Acl, ACL_REVISION, GENERIC_ALL, BuiltInAdministrators))
EXIT_WITH_LAST_ERROR();
if (!InitializeSecurityDescriptor(Sd, SECURITY_DESCRIPTOR_REVISION))
EXIT_WITH_LAST_ERROR();
if (!SetSecurityDescriptorDacl(Sd, TRUE, Acl, FALSE))
EXIT_WITH_LAST_ERROR();
*descriptor = Sd;
Sd = NULL;
Cleanup:
FreeSid(AuthenticatedUsers);
FreeSid(BuiltInAdministrators);
FreeSid(ServiceUsers);
DELETE_BYTES(Sd);
return hr;
}
/////////////////////////////////////////////////////////////////////////////
HRESULT CPerfCounterServer::QueryInterface(REFIID iid, void **ppvObj)
{
if (iid == IID_IUnknown || iid == __uuidof(ICompletion))
{
*ppvObj = (ICompletion *) this;
AddRef();
return S_OK;
}
*ppvObj = NULL;
return E_NOINTERFACE;
}
/////////////////////////////////////////////////////////////////////////////
ULONG CPerfCounterServer::AddRef()
{
return InterlockedIncrement(&_lPendingReadWriteCount);
}
/////////////////////////////////////////////////////////////////////////////
ULONG CPerfCounterServer::Release()
{
return InterlockedDecrement(&_lPendingReadWriteCount);
}
/////////////////////////////////////////////////////////////////////////////
// The call back once data arrives for a named pipe
//
HRESULT CPerfCounterServer::ProcessCompletion(HRESULT hr, int numBytes, LPOVERLAPPED pOver)
{
CPerfPipeOverlapped * pPipeOverlapped = NULL;
HANDLE hPipe = INVALID_HANDLE_VALUE;
int sendBufSize;
int dataSize;
CPerfData * message;
int startIndex;
if (pOver == NULL)
EXIT_WITH_HRESULT(E_INVALIDARG);
pPipeOverlapped = (CPerfPipeOverlapped *) pOver;
hPipe = pPipeOverlapped->pipeHandle.GetHandle();
////////////////////////////////////////////////////////////
// Step 1: Make sure the pipe is working
if (hPipe == INVALID_HANDLE_VALUE) // It's closed!
{
if (FAILED(hr) == FALSE)
hr = E_FAIL; // Make sure hr indicates failed
EXIT();
}
////////////////////////////////////////////////////////////
// Step 2: Did the operation succeed?
if (hr != S_OK) // It failed: maybe the file handle was closed...
{
// Do a call for debugging purposes
#if DBG
DWORD dwBytes = 0;
BOOL result = GetOverlappedResult(hPipe, pPipeOverlapped, &dwBytes, FALSE);
ASSERT(result == FALSE);
#endif
EXIT(); // Exit on all errors
}
////////////////////////////////////////////////////////////
// Step 3: In in write mode, check and see if there's any more
// data to send.
//
if (pPipeOverlapped->fWriteOprn == TRUE) {
// Check and see if we have more data to send
CPerfDataHeader * dataHeader = (CPerfDataHeader*) pPipeOverlapped->lpNextData;
// If the transmitDataSize is positive, then there's another packet of data to be sent
if (dataHeader->transmitDataSize > 0) {
pPipeOverlapped->lpNextData += dataHeader->transmitDataSize;
hr = SendPerfData(hPipe, pPipeOverlapped);
ON_ERROR_EXIT();
}
else { // Nope, last bit of data has been sent, so start a read
hr = StartRead(hPipe, pPipeOverlapped);
ON_ERROR_EXIT();
}
}
else {
////////////////////////////////////////////////////////////
// Responding to an async read
////////////////////////////////////////////////////////////
// Step 4: If the number of active pipes is the same
// as the number of instances, but we haven't
// hit the limit, then start a new instance
if (pPipeOverlapped->fClientConnected == FALSE) {
pPipeOverlapped->fClientConnected = TRUE;
InterlockedIncrement(&_pipesConnected);
if ((_pipesConnected == (_pipeIndex + 1)) && (_pipesConnected < MaxPipeInstances)) {
StartNewPipeInstance(FALSE);
}
}
////////////////////////////////////////////////////////////
// Step 5: If it's a ping (zero bytes), start another read
if (numBytes == 0)
{
// Start another read
hr = StartRead(hPipe, pPipeOverlapped);
ON_ERROR_EXIT();
}
else
{
////////////////////////////////////////////////////////
// Step 6: Received a message: deal with it
// Check and see if the received version buffer matches our version
if (pPipeOverlapped->versionBuffer.majorVersion == _currentVersion->majorVersion &&
pPipeOverlapped->versionBuffer.minorVersion == _currentVersion->minorVersion &&
pPipeOverlapped->versionBuffer.buildVersion == _currentVersion->buildVersion)
{
_perfLock.AcquireReaderLock();
__try {
DWORD totalDataSize = sizeof(CPerfDataHeader);
sendBufSize = 0;
startIndex = 0;
// Get total size needed for data buffer
for (int i = 0; i < _perfDataAry.Size(); i++) {
message = _perfDataAry[i];
dataSize = sizeof(CPerfData) + (message->nameLength * sizeof(message->name[0]));
// If the next data packet exceeds the max buffer send size, then it needs to be
// chunked into the next transmit.
if (sendBufSize + dataSize > CPerfDataHeader::MaxTransmitSize) {
totalDataSize += sizeof(CPerfDataHeader);
sendBufSize = 0;
}
sendBufSize += dataSize;
totalDataSize += dataSize;
}
// If buffer is too small, release and allocate a new one
if (totalDataSize > pPipeOverlapped->dwBufferSize) {
DELETE_BYTES(pPipeOverlapped->lpBuffer);
pPipeOverlapped->dwBufferSize = 0;
pPipeOverlapped->lpBuffer = (BYTE *) NEW_BYTES(totalDataSize);
ON_OOM_EXIT(pPipeOverlapped->lpBuffer);
pPipeOverlapped->dwBufferSize = totalDataSize;
}
BYTE * lpDataPtr = pPipeOverlapped->lpBuffer;
CPerfDataHeader * curHeader = (CPerfDataHeader *) lpDataPtr;
pPipeOverlapped->lpNextData = pPipeOverlapped->lpBuffer;
// Offset for the data header
lpDataPtr += sizeof(CPerfDataHeader);
sendBufSize = 0;
for (int i = 0; i < _perfDataAry.Size(); i++) {
message = _perfDataAry[i];
dataSize = sizeof(CPerfData) + (message->nameLength * sizeof(message->name[0]));
// If the next data packet exceeds the max buffer send size, then
// chunk the send and send the data to the client
if (sendBufSize + dataSize > CPerfDataHeader::MaxTransmitSize) {
curHeader->transmitDataSize = sendBufSize;
curHeader = (CPerfDataHeader *) lpDataPtr;
lpDataPtr += sizeof(CPerfDataHeader);
sendBufSize = 0;
}
CopyMemory(lpDataPtr, message, dataSize);
lpDataPtr += dataSize;
sendBufSize += dataSize;
}
// Set the transmitDataSize to be the negative of the buffer size
// to indicate that it's the last packet of data
curHeader->transmitDataSize = -sendBufSize;
}
__finally {
_perfLock.ReleaseReaderLock();
}
hr = SendPerfData(hPipe, pPipeOverlapped);
ON_ERROR_EXIT();
}
else {
// Nope, not the same version as ours
hr = E_INVALIDARG;
}
}
}
Cleanup:
if (hr != S_OK)
{
// On all errors, restart the read on the pipe
if (pPipeOverlapped != NULL && hPipe != INVALID_HANDLE_VALUE) {
DisconnectNamedPipe(hPipe);
pPipeOverlapped->fClientConnected = FALSE;
InterlockedDecrement(&_pipesConnected);
DELETE_BYTES(pPipeOverlapped->lpBuffer);
pPipeOverlapped->lpBuffer = NULL;
pPipeOverlapped->lpNextData = NULL;
pPipeOverlapped->dwBufferSize = 0;
StartOverlapped(hPipe, pPipeOverlapped);
}
}
if (pPipeOverlapped != NULL)
pPipeOverlapped->pipeHandle.ReleaseHandle();
return hr;
}
HRESULT CPerfCounterServer::SendPerfData(HANDLE hPipe, CPerfPipeOverlapped * lpOverlapped)
{
HRESULT hr = S_OK;
CPerfDataHeader *dataHeader;
dataHeader = (CPerfDataHeader*) lpOverlapped->lpNextData;
if (dataHeader->transmitDataSize < 0) {
lpOverlapped->dwBytes = -(dataHeader->transmitDataSize);
}
else {
lpOverlapped->dwBytes = dataHeader->transmitDataSize;
}
ASSERT(lpOverlapped->dwBytes <= CPerfDataHeader::MaxTransmitSize);
lpOverlapped->fWriteOprn = TRUE;
if (!WriteFile(hPipe, lpOverlapped->lpNextData, lpOverlapped->dwBytes + sizeof(CPerfDataHeader), NULL, lpOverlapped)) {
DWORD dwE = GetLastError();
if (dwE != ERROR_IO_PENDING) {
EXIT_WITH_LAST_ERROR();
}
}
Cleanup:
return hr;
}
/////////////////////////////////////////////////////////////////////////////
// A static method that returns the current product version
// Note: it'll return NULL if it couldn't allocate a CPerfVersion object
//
CPerfVersion * CPerfVersion::GetCurrentVersion()
{
CPerfVersion * version = new CPerfVersion;
if (version == NULL)
return NULL;
ASPNETVER curVersion(VER_PRODUCTVERSION_STR_L);
version->majorVersion = curVersion.Major();
version->minorVersion = curVersion.Minor();
version->buildVersion = curVersion.Build();
return version;
}
///////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////
// Init entry point for unmanaged code
//
HRESULT __stdcall PerfCounterInitialize()
{
return CPerfCounterServer::StaticInitialize();
}
///////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////
// Entry points from managed code
//
CPerfData * __stdcall PerfOpenGlobalCounters()
{
return CPerfCounterServer::g_GlobalCounterData;
}
CPerfData * __stdcall PerfOpenAppCounters(WCHAR * szAppName)
{
CPerfData * data = NULL;
CPerfCounterServer * perfServer = CPerfCounterServer::GetSingleton();
if (perfServer != NULL) {
perfServer->OpenInstanceCounter(&data, szAppName);
}
return data;
}
void __stdcall PerfCloseAppCounters(CPerfData * perfData)
{
CPerfCounterServer * perfServer = CPerfCounterServer::GetSingleton();
if (perfServer != NULL) {
perfServer->CloseInstanceCounter(perfData);
}
}
//
// Increment the specified global counter by 1
//
void __stdcall PerfIncrementGlobalCounter(DWORD number)
{
PerfIncrementCounter(CPerfCounterServer::g_GlobalCounterData, number);
}
//
// Decrement the specified global counter by 1
//
void __stdcall PerfDecrementGlobalCounter(DWORD number)
{
PerfDecrementCounter(CPerfCounterServer::g_GlobalCounterData, number);
}
//
// Increment the specified global counter by specified number
//
void __stdcall PerfIncrementGlobalCounterEx(DWORD number, int dwDelta)
{
PerfIncrementCounterEx(CPerfCounterServer::g_GlobalCounterData, number, dwDelta);
}
//
// Set the specified global counter to the specified value
//
void __stdcall PerfSetGlobalCounter(DWORD number, DWORD dwValue)
{
PerfSetCounter(CPerfCounterServer::g_GlobalCounterData, number, dwValue);
}
//
// Increment the specified (by number) counter by 1
//
void __stdcall PerfIncrementCounter(CPerfData *base, DWORD number)
{
if ((base != NULL) && (0 <= number) && (number < PERF_NUM_DWORDS))
{
InterlockedIncrement((LPLONG)&(base->data[number]));
}
}
//
// Decrement the specified (by number) counter by 1
//
void __stdcall PerfDecrementCounter(CPerfData *base, DWORD number)
{
if ((base != NULL) && (0 <= number) && (number < PERF_NUM_DWORDS))
{
InterlockedDecrement((LPLONG)&(base->data[number]));
}
}
//
// Get the specified counter value
//
DWORD __stdcall PerfGetCounter(CPerfData *base, DWORD number)
{
#if DBG
if ((base != NULL) && (0 <= number) && (number < PERF_NUM_DWORDS))
{
return base->data[number];
}
else
{
return (DWORD) -1;
}
#else
return (DWORD) -1;
#endif
}
//
// Increment the specified (by number) counter by specified number
//
void
__stdcall
PerfIncrementCounterEx(CPerfData *base, DWORD number, int dwDelta)
{
if ((base != NULL) && (0 <= number) && (number < PERF_NUM_DWORDS))
{
InterlockedExchangeAdd((LPLONG)&(base->data[number]), dwDelta);
}
}
//
// Set the specified counter to the specified value
//
void
__stdcall
PerfSetCounter(CPerfData *base, DWORD number, DWORD dwValue)
{
if ((base != NULL) && (0 <= number) && (number < PERF_NUM_DWORDS))
{
InterlockedExchange((LPLONG)&(base->data[number]), dwValue);
}
}
| 31.434316 | 137 | 0.571599 | [
"object"
] |
2ec9dda5b09a640255bd3a880caf863bf312b022 | 5,539 | cpp | C++ | llvm/lib/Target/WebAssembly/WebAssemblyDebugFixup.cpp | keryell/llvm-2 | 4dc23a26d1bd6ced23969c0525dedbddf8c6fddc | [
"Apache-2.0"
] | null | null | null | llvm/lib/Target/WebAssembly/WebAssemblyDebugFixup.cpp | keryell/llvm-2 | 4dc23a26d1bd6ced23969c0525dedbddf8c6fddc | [
"Apache-2.0"
] | null | null | null | llvm/lib/Target/WebAssembly/WebAssemblyDebugFixup.cpp | keryell/llvm-2 | 4dc23a26d1bd6ced23969c0525dedbddf8c6fddc | [
"Apache-2.0"
] | null | null | null | //===-- WebAssemblyDebugFixup.cpp - Debug Fixup ------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
///
/// \file
/// Several prior passes may "stackify" registers, here we ensure any references
/// in such registers in debug_value instructions become stack relative also.
/// This is done in a separate pass such that not all previous passes need to
/// track stack depth when values get stackified.
///
//===----------------------------------------------------------------------===//
#include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
#include "Utils/WebAssemblyUtilities.h"
#include "WebAssembly.h"
#include "WebAssemblyMachineFunctionInfo.h"
#include "WebAssemblySubtarget.h"
#include "llvm/ADT/SCCIterator.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineLoopInfo.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
#define DEBUG_TYPE "wasm-debug-fixup"
namespace {
class WebAssemblyDebugFixup final : public MachineFunctionPass {
StringRef getPassName() const override { return "WebAssembly Debug Fixup"; }
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.setPreservesCFG();
MachineFunctionPass::getAnalysisUsage(AU);
}
bool runOnMachineFunction(MachineFunction &MF) override;
public:
static char ID; // Pass identification, replacement for typeid
WebAssemblyDebugFixup() : MachineFunctionPass(ID) {}
};
} // end anonymous namespace
char WebAssemblyDebugFixup::ID = 0;
INITIALIZE_PASS(
WebAssemblyDebugFixup, DEBUG_TYPE,
"Ensures debug_value's that have been stackified become stack relative",
false, false)
FunctionPass *llvm::createWebAssemblyDebugFixup() {
return new WebAssemblyDebugFixup();
}
bool WebAssemblyDebugFixup::runOnMachineFunction(MachineFunction &MF) {
LLVM_DEBUG(dbgs() << "********** Debug Fixup **********\n"
"********** Function: "
<< MF.getName() << '\n');
WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
const auto *TII = MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
struct StackElem {
unsigned Reg;
MachineInstr *DebugValue;
};
std::vector<StackElem> Stack;
for (MachineBasicBlock &MBB : MF) {
// We may insert into this list.
for (auto MII = MBB.begin(); MII != MBB.end(); ++MII) {
MachineInstr &MI = *MII;
if (MI.isDebugValue()) {
auto &MO = MI.getOperand(0);
// Also check if not a $noreg: likely a DBG_VALUE we just inserted.
if (MO.isReg() && MO.getReg().isValid() &&
MFI.isVRegStackified(MO.getReg())) {
// Found a DBG_VALUE with a stackified register we will
// change into a stack operand.
// Search for register rather than assume it is on top (which it
// typically is if it appears right after the def), since
// DBG_VALUE's may shift under some circumstances.
for (auto &Elem : reverse(Stack)) {
if (MO.getReg() == Elem.Reg) {
auto Depth = static_cast<unsigned>(&Elem - &Stack[0]);
LLVM_DEBUG(dbgs() << "Debug Value VReg " << MO.getReg()
<< " -> Stack Relative " << Depth << "\n");
MO.ChangeToTargetIndex(WebAssembly::TI_OPERAND_STACK, Depth);
// Save the DBG_VALUE instruction that defined this stackified
// variable since later we need it to construct another one on
// pop.
Elem.DebugValue = &MI;
break;
}
}
// If the Reg was not found, we have a DBG_VALUE outside of its
// def-use range, and we leave it unmodified as reg, which means
// it will be culled later.
}
} else {
// Track stack depth.
for (MachineOperand &MO : reverse(MI.explicit_uses())) {
if (MO.isReg() && MFI.isVRegStackified(MO.getReg())) {
auto Prev = Stack.back();
Stack.pop_back();
assert(Prev.Reg == MO.getReg() &&
"WebAssemblyDebugFixup: Pop: Register not matched!");
if (Prev.DebugValue) {
// This stackified reg is a variable that started life at
// Prev.DebugValue, so now that we're popping it we must insert
// a $noreg DBG_VALUE for the variable to end it, right after
// the current instruction.
BuildMI(*Prev.DebugValue->getParent(), std::next(MII),
Prev.DebugValue->getDebugLoc(), TII->get(WebAssembly::DBG_VALUE), false,
Register(), Prev.DebugValue->getOperand(2).getMetadata(),
Prev.DebugValue->getOperand(3).getMetadata());
}
}
}
for (MachineOperand &MO : MI.defs()) {
if (MO.isReg() && MFI.isVRegStackified(MO.getReg())) {
Stack.push_back({MO.getReg(), nullptr});
}
}
}
}
assert(Stack.empty() &&
"WebAssemblyDebugFixup: Stack not empty at end of basic block!");
}
return true;
}
| 39.848921 | 94 | 0.609316 | [
"vector"
] |
2ed864129f9048992f8281f8985f29ead91ba245 | 6,684 | cp | C++ | examples/charts.cp | yzyzsun/CP-next | 98b3be73a58db010f35f4398182193183ec83b31 | [
"Apache-2.0"
] | 3 | 2022-02-10T04:01:29.000Z | 2022-02-10T08:08:28.000Z | examples/charts.cp | yzyzsun/CP-next | 98b3be73a58db010f35f4398182193183ec83b31 | [
"Apache-2.0"
] | null | null | null | examples/charts.cp | yzyzsun/CP-next | 98b3be73a58db010f35f4398182193183ec83b31 | [
"Apache-2.0"
] | null | null | null | --| Pass
open doc;
open svg;
config = {
width = 600;
height = 400;
margin = 30;
maxY = 140;
numY = 7;
line = false;
legend = true;
border = true;
label = {
data = true;
axes = ["Month"; "Price"]
}
};
factory = new html , svg , color;
type Data = {
name: String;
color: Hex;
d: [{ month: String; price: Int }];
};
apple = {
name = "Apple";
color = new factory.Red;
d = [
{ month = "Jan"; price = 81 };
{ month = "Feb"; price = 68 };
{ month = "Mar"; price = 61 };
{ month = "Apr"; price = 72 };
{ month = "May"; price = 80 };
{ month = "June"; price = 91 };
{ month = "July"; price = 96 };
{ month = "Aug"; price = 134 };
{ month = "Sept"; price = 117 };
{ month = "Oct"; price = 109 };
{ month = "Nov"; price = 123 };
{ month = "Dec"; price = 133 };
];
} : Data;
tsmc = {
name = "TSMC";
color = new factory.Blue;
d = [
{ month = "Jan"; price = 54 };
{ month = "Feb"; price = 54 };
{ month = "Mar"; price = 48 };
{ month = "Apr"; price = 53 };
{ month = "May"; price = 50 };
{ month = "June"; price = 57 };
{ month = "July"; price = 79 };
{ month = "Aug"; price = 79 };
{ month = "Sept"; price = 81 };
{ month = "Oct"; price = 84 };
{ month = "Nov"; price = 97 };
{ month = "Dec"; price = 109 };
];
} : Data;
type Base = {
data_ : [Data];
xAxis : HTML;
yAxis : HTML;
caption : HTML;
};
type Render = { render : HTML };
type Chart = Base & Render;
baseChart (data : [Data]) = trait implements Base => open factory in {
data_ = data;
xAxis = letrec xAxis' (i:Int) : HTML = open config in let d = (data!!0).d in
let x = margin + (width - margin) * (i*2 + 1) / (#d*2) in let y = height - margin in
if i == #d then `
\Line{ x1 = margin; y1 = y; x2 = width; y2 = y }
` else `
\Line{ x1 = x; y1 = y - 5; x2 = x; y2 = y }
\Text{ x = x - 10; y = y + 15 }[\((d!!i).month)]
\xAxis'(i+1)
` in xAxis' 0;
yAxis = letrec yAxis' (i:Int) : HTML = open config in
if i == numY then `` else let y = height - margin - (height - margin*2) * (i+1) / numY in `
\Line{ x1 = margin; y1 = y; x2 = margin + 5; y2 = y }
\Text{ x = margin - 22; y = y + 3 }[\(maxY * (i+1) / numY)]
\yAxis'(i+1)
` in yAxis' 0;
caption = letrec caption' (n:Int) : String =
if n == #data - 1 then (data!!n).name else (data!!n).name ++ " vs " ++ caption' (n+1)
in `\Text{ x = 50; y = 10 }[\(caption' 0)]`;
};
lineStrategy = trait [self : Base] implements Render => open factory in {
render = letrec lines' (n:Int) (i:Int) : HTML = open config in
if n == #data_ then `` else let c = (data_!!n).color in let d = (data_!!n).d in
if i == #d - 1 then `\lines'(n+1)(0)` else
let p1 = (d!!i).price in let p2 = (d!!(i+1)).price in `
\Line{
x1 = margin + (width - margin) * (i*2 + 1) / (#d*2);
y1 = height - margin - (height - margin*2) * p1 / maxY;
x2 = margin + (width - margin) * (i*2 + 3) / (#d*2);
y2 = height - margin - (height - margin*2) * p2 / maxY;
color = c;
}
\lines'(n)(i+1)
` in let lines = lines' 0 0 in `\xAxis \yAxis \lines \caption`
};
barStrategy = trait [self : Base] implements Render => open factory in {
render = letrec bars' (n:Int) (i:Int) : HTML = open config in
if n == #data_ then `` else let c = (data_!!n).color in let d = (data_!!n).d in
if i == #d then `\bars'(n+1)(0)` else let price = (d!!i).price in `
\Rect{
x = margin + (width - margin) * i / #d + 5;
y = height - margin - (height - margin*2) * price / maxY;
width = (width - margin) / #d - 10;
height = (height - margin*2) * price / maxY;
color = c;
}
\bars'(n)(i+1)
` in let bars = bars' 0 0 in `\xAxis \yAxis \bars \caption`
};
legendDecorator (chart : Trait<Chart>) =
trait [self : Chart] implements Chart inherits chart => open factory in {
override caption = letrec legends' (n:Int) : HTML = open config in
if n == #data_ then `` else let datum = data_ !! n in `
\Rect{ x = margin + 20 + 50*n; y = margin - 20; width = 5; height = 5; color = datum.color }
\Text{ x = margin + 30 + 50*n; y = margin - 15 }[\(datum.name)]
\legends'(n+1)
` in `\legends'(0)`
};
borderDecorator (chart : Trait<Chart>) =
trait [self : Chart] implements Chart inherits chart => open factory in {
override render = let sr = super.render in open config in `\sr
\Line{ x1 = margin; y1 = margin; x2 = width; y2 = margin }
\Line{ x1 = margin; y1 = margin; x2 = margin; y2 = height - margin }
\Line{ x1 = width - 1; y1 = margin; x2 = width - 1; y2 = height - margin }
`;
};
dataLabelDecorator (chart : Trait<Chart>) =
trait [self : Chart] implements Chart inherits chart => open factory in {
override render = letrec labels' (n:Int) (i:Int) : HTML = open config in
if n == #data_ then `` else let c = (data_!!n).color in let d = (data_!!n).d in
if i == #d then `\labels'(n+1)(0)` else let price = (d!!i).price in `
\Text{
x = margin + (width - margin) * (i*2 + 1) / (#d*2) - 6;
y = height - margin - (height - margin*2) * price / maxY - 3;
color = c;
}[\(price)]
\labels'(n)(i+1)
` in let sr = super.render in `\sr \labels'(0)(0)`;
};
axisLabelDecorator (labels : [String]) (chart : Trait<Chart>) =
trait [self : Chart] implements Chart inherits chart => open factory in {
override xAxis = let sx = super.xAxis in open config in `\sx
\Text{ x = (width + margin) / 2; y = height - margin + 30; color = Gray }[\(labels!!0)]
`;
override yAxis = let sy = super.yAxis in open config in `\sy
\Text{ x = margin - 30; y = height - margin - 10; color = Gray }[\(labels!!1)]
`;
};
type ChartSig<Element> = {
Chart : Chart -> Element;
};
chart = trait implements ChartSig<HTML> => {
Chart chart = trait => chart.render;
};
doc = trait [self : DocSig<HTML> & GraphicSig<HTML><Hex> & ColorSig<Hex> & ChartSig<HTML>] => {
body =
let chart = baseChart [apple; tsmc] in
let chart = chart , if config.line then lineStrategy else barStrategy in
let chart = if config.legend then legendDecorator chart else chart in
let chart = if config.border then borderDecorator chart else chart in
let chart = if config.label.data then dataLabelDecorator chart else chart in
let chart = if #config.label.axes == 2 then axisLabelDecorator config.label.axes chart else chart in `
\Graph{ width = config.width; height = config.height }[\Chart(new chart)]
`
};
(new html , svg , color , chart , doc).body.html
| 34.632124 | 106 | 0.54234 | [
"render"
] |
2eda57a4f285331f78ca7a1ca8dbc1529c126246 | 8,460 | cpp | C++ | motion-tracking-tut/final-code/motionTracking.cpp | kylehounslow/opencv-tuts | 2a943394c24fe712a40fdb775f01e43ab3786b93 | [
"MIT"
] | 59 | 2015-03-29T10:33:21.000Z | 2021-11-09T10:43:42.000Z | motion-tracking-tut/final-code/motionTracking.cpp | kylehounslow/opencv-tuts | 2a943394c24fe712a40fdb775f01e43ab3786b93 | [
"MIT"
] | 2 | 2015-05-17T02:26:14.000Z | 2018-03-16T18:12:55.000Z | motion-tracking-tut/final-code/motionTracking.cpp | kylehounslow/opencv-tuts | 2a943394c24fe712a40fdb775f01e43ab3786b93 | [
"MIT"
] | 48 | 2015-03-08T19:15:28.000Z | 2021-10-19T12:48:26.000Z | //motionTracking.cpp
//Written by Kyle Hounslow, December 2013
//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 <opencv\cv.h>
#include <opencv\highgui.h>
using namespace std;
using namespace cv;
//our sensitivity value to be used in the absdiff() function
const static int SENSITIVITY_VALUE = 20;
//size of blur used to smooth the intensity image output from absdiff() function
const static int BLUR_SIZE = 10;
//we'll have just one object to search for
//and keep track of its position.
int theObject[2] = {0,0};
//bounding rectangle of the object, we will use the center of this as its position.
Rect objectBoundingRectangle = Rect(0,0,0,0);
//int to string helper function
string intToString(int number){
//this function has a number input and string output
std::stringstream ss;
ss << number;
return ss.str();
}
void searchForMovement(Mat thresholdImage, Mat &cameraFeed){
//notice how we use the '&' operator for objectDetected and cameraFeed. This is because we wish
//to take the values passed into the function and manipulate them, rather than just working with a copy.
//eg. we draw to the cameraFeed to be displayed in the main() function.
bool objectDetected = false;
Mat temp;
thresholdImage.copyTo(temp);
//these two vectors needed for output of findContours
vector< vector<Point> > contours;
vector<Vec4i> hierarchy;
//find contours of filtered image using openCV findContours function
//findContours(temp,contours,hierarchy,CV_RETR_CCOMP,CV_CHAIN_APPROX_SIMPLE );// retrieves all contours
findContours(temp,contours,hierarchy,CV_RETR_EXTERNAL,CV_CHAIN_APPROX_SIMPLE );// retrieves external contours
//if contours vector is not empty, we have found some objects
if(contours.size()>0)objectDetected=true;
else objectDetected = false;
if(objectDetected){
//the largest contour is found at the end of the contours vector
//we will simply assume that the biggest contour is the object we are looking for.
vector< vector<Point> > largestContourVec;
largestContourVec.push_back(contours.at(contours.size()-1));
//make a bounding rectangle around the largest contour then find its centroid
//this will be the object's final estimated position.
objectBoundingRectangle = boundingRect(largestContourVec.at(0));
int xpos = objectBoundingRectangle.x+objectBoundingRectangle.width/2;
int ypos = objectBoundingRectangle.y+objectBoundingRectangle.height/2;
//update the objects positions by changing the 'theObject' array values
theObject[0] = xpos , theObject[1] = ypos;
}
//make some temp x and y variables so we dont have to type out so much
int x = theObject[0];
int y = theObject[1];
//draw some crosshairs around the object
circle(cameraFeed,Point(x,y),20,Scalar(0,255,0),2);
line(cameraFeed,Point(x,y),Point(x,y-25),Scalar(0,255,0),2);
line(cameraFeed,Point(x,y),Point(x,y+25),Scalar(0,255,0),2);
line(cameraFeed,Point(x,y),Point(x-25,y),Scalar(0,255,0),2);
line(cameraFeed,Point(x,y),Point(x+25,y),Scalar(0,255,0),2);
//write the position of the object to the screen
putText(cameraFeed,"Tracking object at (" + intToString(x)+","+intToString(y)+")",Point(x,y),1,1,Scalar(255,0,0),2);
}
int main(){
//some boolean variables for added functionality
bool objectDetected = false;
//these two can be toggled by pressing 'd' or 't'
bool debugMode = false;
bool trackingEnabled = false;
//pause and resume code
bool pause = false;
//set up the matrices that we will need
//the two frames we will be comparing
Mat frame1,frame2;
//their grayscale images (needed for absdiff() function)
Mat grayImage1,grayImage2;
//resulting difference image
Mat differenceImage;
//thresholded difference image (for use in findContours() function)
Mat thresholdImage;
//video capture object.
VideoCapture capture;
while(1){
//we can loop the video by re-opening the capture every time the video reaches its last frame
capture.open("bouncingBall.avi");
if(!capture.isOpened()){
cout<<"ERROR ACQUIRING VIDEO FEED\n";
getchar();
return -1;
}
//check if the video has reach its last frame.
//we add '-1' because we are reading two frames from the video at a time.
//if this is not included, we get a memory error!
while(capture.get(CV_CAP_PROP_POS_FRAMES)<capture.get(CV_CAP_PROP_FRAME_COUNT)-1){
//read first frame
capture.read(frame1);
//convert frame1 to gray scale for frame differencing
cv::cvtColor(frame1,grayImage1,COLOR_BGR2GRAY);
//copy second frame
capture.read(frame2);
//convert frame2 to gray scale for frame differencing
cv::cvtColor(frame2,grayImage2,COLOR_BGR2GRAY);
//perform frame differencing with the sequential images. This will output an "intensity image"
//do not confuse this with a threshold image, we will need to perform thresholding afterwards.
cv::absdiff(grayImage1,grayImage2,differenceImage);
//threshold intensity image at a given sensitivity value
cv::threshold(differenceImage,thresholdImage,SENSITIVITY_VALUE,255,THRESH_BINARY);
if(debugMode==true){
//show the difference image and threshold image
cv::imshow("Difference Image",differenceImage);
cv::imshow("Threshold Image", thresholdImage);
}else{
//if not in debug mode, destroy the windows so we don't see them anymore
cv::destroyWindow("Difference Image");
cv::destroyWindow("Threshold Image");
}
//blur the image to get rid of the noise. This will output an intensity image
cv::blur(thresholdImage,thresholdImage,cv::Size(BLUR_SIZE,BLUR_SIZE));
//threshold again to obtain binary image from blur output
cv::threshold(thresholdImage,thresholdImage,SENSITIVITY_VALUE,255,THRESH_BINARY);
if(debugMode==true){
//show the threshold image after it's been "blurred"
imshow("Final Threshold Image",thresholdImage);
}
else {
//if not in debug mode, destroy the windows so we don't see them anymore
cv::destroyWindow("Final Threshold Image");
}
//if tracking enabled, search for contours in our thresholded image
if(trackingEnabled){
searchForMovement(thresholdImage,frame1);
}
//show our captured frame
imshow("Frame1",frame1);
//check to see if a button has been pressed.
//this 10ms delay is necessary for proper operation of this program
//if removed, frames will not have enough time to referesh and a blank
//image will appear.
switch(waitKey(10)){
case 27: //'esc' key has been pressed, exit program.
return 0;
case 116: //'t' has been pressed. this will toggle tracking
trackingEnabled = !trackingEnabled;
if(trackingEnabled == false) cout<<"Tracking disabled."<<endl;
else cout<<"Tracking enabled."<<endl;
break;
case 100: //'d' has been pressed. this will debug mode
debugMode = !debugMode;
if(debugMode == false) cout<<"Debug mode disabled."<<endl;
else cout<<"Debug mode enabled."<<endl;
break;
case 112: //'p' has been pressed. this will pause/resume the code.
pause = !pause;
if(pause == true){ cout<<"Code paused, press 'p' again to resume"<<endl;
while (pause == true){
//stay in this loop until
switch (waitKey()){
//a switch statement inside a switch statement? Mind blown.
case 112:
//change pause back to false
pause = false;
cout<<"Code Resumed"<<endl;
break;
}
}
}
}
}
//release the capture before re-opening and looping again.
capture.release();
}
return 0;
} | 38.807339 | 151 | 0.733924 | [
"object",
"vector"
] |
2edb1bb8e6d0fe57c39ce880ca78b1131c082f3e | 1,449 | cpp | C++ | lib/graph/general/connectivity/dsu/dsu_compressed_graph.cpp | howdepressingitistoloveyou/lib | 42e515ef15914ba6e7c253cdce124944a72bf258 | [
"MIT"
] | null | null | null | lib/graph/general/connectivity/dsu/dsu_compressed_graph.cpp | howdepressingitistoloveyou/lib | 42e515ef15914ba6e7c253cdce124944a72bf258 | [
"MIT"
] | null | null | null | lib/graph/general/connectivity/dsu/dsu_compressed_graph.cpp | howdepressingitistoloveyou/lib | 42e515ef15914ba6e7c253cdce124944a72bf258 | [
"MIT"
] | 1 | 2021-09-03T16:52:21.000Z | 2021-09-03T16:52:21.000Z | #include <bits/stdc++.h>
#define pb push_back
#define ii pair<int, int>
#define fi first
#define se second
using namespace std;
const int maxN = 2e5 + 5;
int n, m;
int A[maxN], B[maxN];
vector<int> adj[maxN], g[maxN];
int p[maxN];
int Find(int x) {
return (x == p[x] ? x : p[x] = Find(p[x]));
}
void Merge(int u, int v) {
u = Find(u), v = Find(v);
if(u == v) return;
p[v] = u;
}
bool in_tree[maxN];
bool vis[maxN];
int h[maxN], parent[maxN];
void dfs(int u) {
vis[u] = true;
for(auto id : adj[u]) {
int v = (A[id] == u ? B[id] : A[id]);
if(!vis[v]) {
h[v] = h[u] + 1;
parent[v] = u;
in_tree[id] = true;
dfs(v);
}
}
}
signed main() {
cin >> n >> m;
for(int i = 1; i <= n; i++) {
p[i] = i;
}
for(int i = 1; i <= m; i++) {
cin >> A[i] >> B[i];
adj[A[i]].pb(i);
adj[B[i]].pb(i);
}
for(int i = 1; i <= n; i++) {
if(!vis[i]) {
dfs(i);
}
}
for(int i = 1; i <= m; i++) {
int u = A[i], v = B[i];
if(in_tree[i]) continue;
u = Find(u);
v = Find(v);
if(h[u] > h[v]) swap(u, v);
while(u != v) {
int nxt = Find(parent[v]);
Merge(nxt, v);
v = nxt;
}
}
for(int i = 1; i <= m; i++) {
int u = A[i], v = B[i];
u = Find(u), v = Find(v);
if(u != v) {
g[u].pb(v);
g[v].pb(u);
}
}
cout << "condensed graph: \n";
for(int i = 1; i <= n; i++) {
cout << i << ": ";
for(auto j : g[i]) {
cout << j << ' ';
}
cout << '\n';
}
}
| 16.655172 | 45 | 0.440994 | [
"vector"
] |
2ee154e006a284ccc1ccc0b9982e2df4391f5bab | 7,021 | cpp | C++ | Source/Directional.cpp | AhmetMelihIslam/ToolKit | 2752d9aa425ff4389f2b705abfbe4580fca1f214 | [
"MIT"
] | null | null | null | Source/Directional.cpp | AhmetMelihIslam/ToolKit | 2752d9aa425ff4389f2b705abfbe4580fca1f214 | [
"MIT"
] | null | null | null | Source/Directional.cpp | AhmetMelihIslam/ToolKit | 2752d9aa425ff4389f2b705abfbe4580fca1f214 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "Directional.h"
#include "Node.h"
#include "Util.h"
#include "DebugNew.h"
namespace ToolKit
{
Directional::Directional()
{
}
Directional::~Directional()
{
}
void Directional::Pitch(float angle)
{
Quaternion q = glm::angleAxis(angle, Vec3(1.0f, 0.0f, 0.0f));
m_node->Rotate(q, TransformationSpace::TS_LOCAL);
}
void Directional::Yaw(float angle)
{
Quaternion q = glm::angleAxis(angle, Vec3(0.0f, 1.0f, 0.0f));
m_node->Rotate(q, TransformationSpace::TS_LOCAL);
}
void Directional::Roll(float angle)
{
Quaternion q = glm::angleAxis(angle, Vec3(0.0f, 0.0f, 1.0f));
m_node->Rotate(q, TransformationSpace::TS_LOCAL);
}
void Directional::Translate(Vec3 pos)
{
m_node->Translate(pos, TransformationSpace::TS_LOCAL);
}
void Directional::RotateOnUpVector(float angle)
{
m_node->Rotate(glm::angleAxis(angle, Vec3(0.0f, 1.0f, 0.0f)), TransformationSpace::TS_WORLD);
}
void Directional::GetLocalAxis(Vec3& dir, Vec3& up, Vec3& right) const
{
Mat4 transform = m_node->GetTransform(TransformationSpace::TS_WORLD);
right = glm::column(transform, 0);
up = glm::column(transform, 1);
dir = -glm::column(transform, 2);
}
Vec3 Directional::GetDir() const
{
Mat4 transform = m_node->GetTransform(TransformationSpace::TS_WORLD);
return -glm::column(transform, 2);
}
Vec3 Directional::GetUp() const
{
Mat4 transform = m_node->GetTransform(TransformationSpace::TS_WORLD);
return glm::column(transform, 1);
}
Vec3 Directional::GetRight() const
{
Mat4 transform = m_node->GetTransform(TransformationSpace::TS_WORLD);
return glm::column(transform, 0);
}
void Directional::LookAt(Vec3 target)
{
Vec3 eye = m_node->GetTranslation(TransformationSpace::TS_WORLD);
Vec3 tdir = target - eye;
tdir.y = 0.0f; // project on xz
tdir = glm::normalize(tdir);
Vec3 dir = GetDir();
dir.y = 0.0f; // project on xz
dir = glm::normalize(dir);
if (glm::all(glm::epsilonEqual(tdir, dir, { 0.01f, 0.01f, 0.01f })))
{
return;
}
Vec3 rotAxis = glm::normalize(glm::cross(dir, tdir));
float yaw = glm::acos(glm::dot(tdir, dir));
yaw *= glm::sign(glm::dot(Y_AXIS, rotAxis));
RotateOnUpVector(yaw);
tdir = target - eye;
tdir = glm::normalize(tdir);
dir = glm::normalize(GetDir());
rotAxis = glm::normalize(glm::cross(dir, tdir));
float pitch = glm::acos(glm::dot(tdir, dir));
pitch *= glm::sign(glm::dot(GetRight(), rotAxis));
Pitch(pitch);
// Check upside down case
if (glm::dot(GetUp(), Y_AXIS) < 0.0f)
{
Roll(glm::pi<float>());
}
}
EntityType Directional::GetType() const
{
return EntityType::Entity_Directional;
}
Camera::Camera(XmlNode* node)
{
DeSerialize(nullptr, node);
if (m_ortographic)
{
SetLens(m_left, m_right, m_bottom, m_top, m_near, m_far);
}
else
{
SetLens(m_fov, m_aspect * m_height, m_height);
}
}
Camera::Camera()
{
SetLens(glm::radians(90.0f), 640.0f, 480.0f, 0.01f, 1000.0f);
}
Camera::~Camera()
{
}
void Camera::SetLens(float fov, float width, float height)
{
SetLens(fov, width, height, 0.01f, 1000.0f);
}
void Camera::SetLens(float fov, float width, float height, float near, float far)
{
m_projection = glm::perspectiveFov(fov, width, height, near, far);
m_fov = fov;
m_aspect = width / height;
m_near = near;
m_far = far;
m_height = height;
m_ortographic = false;
}
void Camera::SetLens(float left, float right, float bottom, float top, float near, float far)
{
m_projection = glm::ortho(left, right, bottom, top, near, far);
m_left = left;
m_right = right;
m_top = top;
m_bottom = bottom;
m_fov = 0.0f;
m_aspect = 1.0f;
m_near = near;
m_far = far;
m_height = top - bottom;
m_ortographic = true;
}
Mat4 Camera::GetViewMatrix() const
{
Mat4 view = m_node->GetTransform(TransformationSpace::TS_WORLD);
return glm::inverse(view);
}
Mat4 Camera::GetProjectionMatrix() const
{
return m_projection;
}
bool Camera::IsOrtographic() const
{
return m_ortographic;
}
Camera::CamData Camera::GetData() const
{
CamData data;
data.dir = GetDir();
data.pos = m_node->GetTranslation(TransformationSpace::TS_WORLD);
data.projection = m_projection;
data.fov = m_fov;
data.aspect = m_aspect;
data.nearDist = m_near;
data.height = m_height;
data.ortographic = m_ortographic;
return data;
}
EntityType Camera::GetType() const
{
return EntityType::Entity_Camera;
}
void Camera::Serialize(XmlDocument* doc, XmlNode* parent) const
{
Entity::Serialize(doc, parent);
parent = parent->last_node();
XmlNode* node = doc->allocate_node(rapidxml::node_element, "Camera");
parent->append_node(node);
WriteAttr(node, doc, "fov", std::to_string(m_fov));
WriteAttr(node, doc, "aspect", std::to_string(m_aspect));
WriteAttr(node, doc, "near", std::to_string(m_near));
WriteAttr(node, doc, "far", std::to_string(m_far));
WriteAttr(node, doc, "height", std::to_string(m_height));
WriteAttr(node, doc, "ortographic", std::to_string(m_ortographic));
WriteAttr(node, doc, "left", std::to_string(m_left));
WriteAttr(node, doc, "right", std::to_string(m_right));
WriteAttr(node, doc, "top", std::to_string(m_top));
WriteAttr(node, doc, "bottom", std::to_string(m_bottom));
}
void Camera::DeSerialize(XmlDocument* doc, XmlNode* parent)
{
Entity::DeSerialize(doc, parent);
if (XmlNode* node = parent->first_node("Camera"))
{
ReadAttr(node, "fov", m_fov);
ReadAttr(node, "aspect", m_aspect);
ReadAttr(node, "near", m_near);
ReadAttr(node, "far", m_far);
ReadAttr(node, "height", m_height);
ReadAttr(node, "ortographic", m_ortographic);
ReadAttr(node, "left", m_left);
ReadAttr(node, "right", m_right);
ReadAttr(node, "top", m_top);
ReadAttr(node, "bottom", m_bottom);
}
}
Entity* Camera::CopyTo(Entity* copyTo) const
{
Directional::CopyTo(copyTo);
Camera* cpy = static_cast<Camera*> (copyTo);
cpy->m_fov = m_fov;
cpy->m_aspect = m_aspect;
cpy->m_near = m_near;
cpy->m_far = m_far;
cpy->m_height = m_height;
cpy->m_left = m_left;
cpy->m_right = m_right;
cpy->m_bottom = m_bottom;
cpy->m_ortographic = m_ortographic;
cpy->m_projection = m_projection;
return cpy;
}
Light::Light()
{
m_color = Vec3(1.0f, 1.0f, 1.0f);
m_intensity = 1.0f;
}
Light::~Light()
{
}
Light::LightData Light::GetData() const
{
LightData data;
data.dir = GetDir();
data.pos = m_node->GetTranslation(TransformationSpace::TS_WORLD);
data.color = m_color;
data.intensity = m_intensity;
return data;
}
EntityType Light::GetType() const
{
return EntityType::Entity_Light;
}
}
| 24.463415 | 97 | 0.637089 | [
"transform"
] |
2ee2fd957ced4eb5854bae2b784f34256d962207 | 1,731 | cc | C++ | planner/FAST-DOWNWARD/src/search/cost_adapted_task.cc | karthikv792/PlanningAssistance | 5693c844e9067591ea1414ee9586bcd2dfff6f51 | [
"MIT"
] | 4 | 2019-04-23T10:41:35.000Z | 2019-10-27T05:14:42.000Z | planner/FAST-DOWNWARD/src/search/cost_adapted_task.cc | karthikv792/PlanningAssistance | 5693c844e9067591ea1414ee9586bcd2dfff6f51 | [
"MIT"
] | null | null | null | planner/FAST-DOWNWARD/src/search/cost_adapted_task.cc | karthikv792/PlanningAssistance | 5693c844e9067591ea1414ee9586bcd2dfff6f51 | [
"MIT"
] | 4 | 2018-01-16T00:00:22.000Z | 2019-11-01T23:35:01.000Z | #include "cost_adapted_task.h"
#include "option_parser.h"
#include "plugin.h"
#include "utilities.h"
#include <iostream>
#include <memory>
using namespace std;
CostAdaptedTask::CostAdaptedTask(const Options &opts)
: DelegatingTask(opts.get<shared_ptr<AbstractTask>>("transform")),
cost_type(OperatorCost(opts.get<int>("cost_type"))),
is_unit_cost(compute_is_unit_cost()) {
}
bool CostAdaptedTask::compute_is_unit_cost() const {
int num_ops = parent->get_num_operators();
for (int op_index = 0; op_index < num_ops; ++op_index) {
if (parent->get_operator_cost(op_index, false) != 1)
return false;
}
return true;
}
int CostAdaptedTask::get_operator_cost(int index, bool is_axiom) const {
int original_cost = parent->get_operator_cost(index, is_axiom);
// Don't change axiom costs. Usually they have cost 0, but we don't enforce this.
if (is_axiom)
return original_cost;
switch (cost_type) {
case NORMAL:
return original_cost;
case ONE:
return 1;
case PLUSONE:
if (is_unit_cost)
return 1;
else
return original_cost + 1;
default:
cerr << "Unknown cost type" << endl;
exit_with(EXIT_CRITICAL_ERROR);
}
}
static shared_ptr<AbstractTask> _parse(OptionParser &parser) {
parser.add_option<shared_ptr<AbstractTask>>(
"transform",
"Parent task transformation",
"no_transform");
add_cost_type_option_to_parser(parser);
Options opts = parser.parse();
if (parser.dry_run())
return nullptr;
else
return make_shared<CostAdaptedTask>(opts);
}
static PluginShared<AbstractTask> _plugin("adapt_costs", _parse);
| 26.227273 | 85 | 0.667244 | [
"transform"
] |
2eef5e8e9a35e75b04ca02c90c215aa0924b5efa | 1,071 | cc | C++ | src/runtime/objects/Function.cc | atjhc/sif | 8e40d6895f0113a3f88524f29113779b6e625f49 | [
"Apache-2.0"
] | 1 | 2021-11-02T17:04:01.000Z | 2021-11-02T17:04:01.000Z | src/runtime/objects/Function.cc | atjhc/sif | 8e40d6895f0113a3f88524f29113779b6e625f49 | [
"Apache-2.0"
] | null | null | null | src/runtime/objects/Function.cc | atjhc/sif | 8e40d6895f0113a3f88524f29113779b6e625f49 | [
"Apache-2.0"
] | null | null | null | // 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 "runtime/objects/Function.h"
SIF_NAMESPACE_BEGIN
Function::Function(const Signature &signature, const Strong<Bytecode> &bytecode)
: _signature(signature), _bytecode(bytecode) {}
const Strong<Bytecode> &Function::bytecode() const { return _bytecode; }
std::string Function::typeName() const { return "function"; }
std::string Function::description() const { return _signature.name(); }
bool Function::equals(Strong<Object> object) const { return this == object.get(); }
SIF_NAMESPACE_END
| 35.7 | 83 | 0.743231 | [
"object"
] |
2ef4aea3e71f0a36ae5a4fe7576bc6afc5cf8008 | 47,292 | cpp | C++ | src/UsgsAstroFrameSensorModel.cpp | kberryUSGS/CSM-CameraModel | 9bcdc9730b73d2235f704fee693186e4a8218163 | [
"Unlicense"
] | null | null | null | src/UsgsAstroFrameSensorModel.cpp | kberryUSGS/CSM-CameraModel | 9bcdc9730b73d2235f704fee693186e4a8218163 | [
"Unlicense"
] | null | null | null | src/UsgsAstroFrameSensorModel.cpp | kberryUSGS/CSM-CameraModel | 9bcdc9730b73d2235f704fee693186e4a8218163 | [
"Unlicense"
] | null | null | null | #include "UsgsAstroFrameSensorModel.h"
#include <iomanip>
#include <iostream>
#include <sstream>
#include <json.hpp>
#include <Error.h>
#include <Version.h>
using json = nlohmann::json;
using namespace std;
// Declaration of static variables
const std::string UsgsAstroFrameSensorModel::_SENSOR_MODEL_NAME
= "USGS_ASTRO_FRAME_SENSOR_MODEL";
const int UsgsAstroFrameSensorModel::NUM_PARAMETERS = 7;
const std::string UsgsAstroFrameSensorModel::m_parameterName[] = {
"X Sensor Position (m)", // 0
"Y Sensor Position (m)", // 1
"Z Sensor Position (m)", // 2
"w", // 3
"v1", // 4
"v2", // 5
"v3" // 6
};
const int UsgsAstroFrameSensorModel::_NUM_STATE_KEYWORDS = 32;
UsgsAstroFrameSensorModel::UsgsAstroFrameSensorModel() {
reset();
}
void UsgsAstroFrameSensorModel::reset() {
m_modelName = _SENSOR_MODEL_NAME;
m_majorAxis = 0.0;
m_minorAxis = 0.0;
m_focalLength = 0.0;
m_startingDetectorSample = 0.0;
m_startingDetectorLine = 0.0;
m_targetName = "";
m_ifov = 0;
m_instrumentID = "";
m_focalLengthEpsilon = 0.0;
m_linePp = 0.0;
m_samplePp = 0.0;
m_originalHalfLines = 0.0;
m_spacecraftName = "";
m_pixelPitch = 0.0;
m_ephemerisTime = 0.0;
m_originalHalfSamples = 0.0;
m_nLines = 0;
m_nSamples = 0;
m_currentParameterValue = std::vector<double>(NUM_PARAMETERS, 0.0);
m_currentParameterCovariance = std::vector<double>(NUM_PARAMETERS*NUM_PARAMETERS,0.0);
m_noAdjustments = std::vector<double>(NUM_PARAMETERS,0.0);
m_ccdCenter = std::vector<double>(2, 0.0);
m_spacecraftVelocity = std::vector<double>(3, 0.0);
m_sunPosition = std::vector<double>(3, 0.0);
m_odtX = std::vector<double>(10, 0.0);
m_odtY = std::vector<double>(10, 0.0);
m_transX = std::vector<double>(3, 0.0);
m_transY = std::vector<double>(3, 0.0);
m_iTransS = std::vector<double>(3, 0.0);
m_iTransL = std::vector<double>(3, 0.0);
m_boresight = std::vector<double>(3, 0.0);
m_parameterType = std::vector<csm::param::Type>(NUM_PARAMETERS, csm::param::REAL);
}
UsgsAstroFrameSensorModel::~UsgsAstroFrameSensorModel() {}
/**
* @brief UsgsAstroFrameSensorModel::groundToImage
* @param groundPt
* @param desiredPrecision
* @param achievedPrecision
* @param warnings
* @return Returns <line, sample> coordinate in the image corresponding to the ground point
* without bundle adjustment correction.
*/
csm::ImageCoord UsgsAstroFrameSensorModel::groundToImage(const csm::EcefCoord &groundPt,
double desiredPrecision,
double *achievedPrecision,
csm::WarningList *warnings) const {
return groundToImage(groundPt, m_noAdjustments, desiredPrecision, achievedPrecision, warnings);
}
/**
* @brief UsgsAstroFrameSensorModel::groundToImage
* @param groundPt
* @param adjustments
* @param desired_precision
* @param achieved_precision
* @param warnings
* @return Returns <line,sample> coordinate in the image corresponding to the ground point.
* This function applies bundle adjustments to the final value.
*/
csm::ImageCoord UsgsAstroFrameSensorModel::groundToImage(
const csm::EcefCoord& groundPt,
const std::vector<double>& adjustments,
double desired_precision,
double* achieved_precision,
csm::WarningList* warnings ) const {
double x = groundPt.x;
double y = groundPt.y;
double z = groundPt.z;
double xo = x - getValue(0,adjustments);
double yo = y - getValue(1,adjustments);
double zo = z - getValue(2,adjustments);
double f;
f = m_focalLength;
// Camera rotation matrix
double m[3][3];
calcRotationMatrix(m,adjustments);
// Sensor position
double undistortedx, undistortedy, denom;
denom = m[0][2] * xo + m[1][2] * yo + m[2][2] * zo;
undistortedx = (f * (m[0][0] * xo + m[1][0] * yo + m[2][0] * zo)/denom) + m_samplePp; //m_samplePp like this assumes mm
undistortedy = (f * (m[0][1] * xo + m[1][1] * yo + m[2][1] * zo)/denom) + m_linePp;
// Apply the distortion to the line/sample location and then convert back to line/sample
double distortedx, distortedy;
distortionFunction(undistortedx, undistortedy, distortedx, distortedy);
// Convert distorted mm into line/sample
double sample, line;
sample = m_iTransS[0] + m_iTransS[1] * distortedx + m_iTransS[2] * distortedy + m_ccdCenter[1];
line = m_iTransL[0] + m_iTransL[1] * distortedx + m_iTransL[2] * distortedy + m_ccdCenter[0];
return csm::ImageCoord(line, sample);
}
csm::ImageCoordCovar UsgsAstroFrameSensorModel::groundToImage(const csm::EcefCoordCovar &groundPt,
double desiredPrecision,
double *achievedPrecision,
csm::WarningList *warnings) const {
throw csm::Error(csm::Error::UNSUPPORTED_FUNCTION,
"Unsupported function",
"UsgsAstroFrameSensorModel::groundToImage");
}
csm::EcefCoord UsgsAstroFrameSensorModel::imageToGround(const csm::ImageCoord &imagePt,
double height,
double desiredPrecision,
double *achievedPrecision,
csm::WarningList *warnings) const {
double sample = imagePt.samp;
double line = imagePt.line;
// Here is where we should be able to apply an adjustment to opk
double m[3][3];
calcRotationMatrix(m);
// Apply the principal point offset, assuming the pp is given in pixels
double xl, yl, zl, lo, so;
lo = line - m_linePp;
so = sample - m_samplePp;
// Convert from the pixel space into the metric space
double line_center, sample_center, x_camera, y_camera;
line_center = m_ccdCenter[0];
sample_center = m_ccdCenter[1];
y_camera = m_transY[0] + m_transY[1] * (lo - line_center) + m_transY[2] * (so - sample_center);
x_camera = m_transX[0] + m_transX[1] * (lo - line_center) + m_transX[2] * (so - sample_center);
// Apply the distortion model (remove distortion)
double undistorted_cameraX, undistorted_cameraY = 0.0;
setFocalPlane(x_camera, y_camera, undistorted_cameraX, undistorted_cameraY);
// Now back from distorted mm to pixels
double udx, udy; //distorted line and sample
udx = undistorted_cameraX;
udy = undistorted_cameraY;
xl = m[0][0] * udx + m[0][1] * udy - m[0][2] * -m_focalLength;
yl = m[1][0] * udx + m[1][1] * udy - m[1][2] * -m_focalLength;
zl = m[2][0] * udx + m[2][1] * udy - m[2][2] * -m_focalLength;
double x, y, z;
double xc, yc, zc;
xc = m_currentParameterValue[0];
yc = m_currentParameterValue[1];
zc = m_currentParameterValue[2];
// Intersect with some height about the ellipsoid.
losEllipsoidIntersect(height, xc, yc, zc, xl, yl, zl, x, y, z);
return csm::EcefCoord(x, y, z);
}
csm::EcefCoordCovar UsgsAstroFrameSensorModel::imageToGround(const csm::ImageCoordCovar &imagePt, double height,
double heightVariance, double desiredPrecision,
double *achievedPrecision,
csm::WarningList *warnings) const {
throw csm::Error(csm::Error::UNSUPPORTED_FUNCTION,
"Unsupported function",
"UsgsAstroFrameSensorModel::imageToGround");
}
csm::EcefLocus UsgsAstroFrameSensorModel::imageToProximateImagingLocus(const csm::ImageCoord &imagePt,
const csm::EcefCoord &groundPt,
double desiredPrecision,
double *achievedPrecision,
csm::WarningList *warnings) const {
// Ignore the ground point?
return imageToRemoteImagingLocus(imagePt);
}
csm::EcefLocus UsgsAstroFrameSensorModel::imageToRemoteImagingLocus(const csm::ImageCoord &imagePt,
double desiredPrecision,
double *achievedPrecision,
csm::WarningList *warnings) const {
// Find the line,sample on the focal plane (mm)
// CSM center = 0.5, MDIS IK center = 1.0
double row = imagePt.line - m_ccdCenter[0];
double col = imagePt.samp - m_ccdCenter[1];
double focalPlaneX = m_transX[0] + m_transX[1] * row + m_transX[2] * col;
double focalPlaneY = m_transY[0] + m_transY[1] * row + m_transY[2] * col;
// Distort
double undistortedFocalPlaneX = focalPlaneX;
double undistortedFocalPlaneY = focalPlaneY;
setFocalPlane(focalPlaneX, focalPlaneY, undistortedFocalPlaneX, undistortedFocalPlaneY);
// Get rotation matrix and transform to a body-fixed frame
double m[3][3];
calcRotationMatrix(m);
std::vector<double> lookC { undistortedFocalPlaneX, undistortedFocalPlaneY, m_focalLength };
std::vector<double> lookB {
m[0][0] * lookC[0] + m[0][1] * lookC[1] + m[0][2] * lookC[2],
m[1][0] * lookC[0] + m[1][1] * lookC[1] + m[1][2] * lookC[2],
m[2][0] * lookC[0] + m[2][1] * lookC[1] + m[2][2] * lookC[2]
};
// Get unit vector
double mag = sqrt(lookB[0] * lookB[0] + lookB[1] * lookB[1] + lookB[2] * lookB[2]);
std::vector<double> lookBUnit {
lookB[0] / mag,
lookB[1] / mag,
lookB[2] / mag
};
return csm::EcefLocus(m_currentParameterValue[0], m_currentParameterValue[1], m_currentParameterValue[2],
lookBUnit[0], lookBUnit[1], lookBUnit[2]);
}
csm::ImageCoord UsgsAstroFrameSensorModel::getImageStart() const {
csm::ImageCoord start;
start.samp = m_startingDetectorSample;
start.line = m_startingDetectorLine;
return start;
}
csm::ImageVector UsgsAstroFrameSensorModel::getImageSize() const {
csm::ImageVector size;
size.line = m_nLines;
size.samp = m_nSamples;
return size;
}
std::pair<csm::ImageCoord, csm::ImageCoord> UsgsAstroFrameSensorModel::getValidImageRange() const {
csm::ImageCoord min_pt(m_startingDetectorLine, m_startingDetectorSample);
csm::ImageCoord max_pt(m_nLines, m_nSamples);
return std::pair<csm::ImageCoord, csm::ImageCoord>(min_pt, max_pt);
}
std::pair<double, double> UsgsAstroFrameSensorModel::getValidHeightRange() const {
return std::pair<double, double>(m_minElevation, m_maxElevation);
}
csm::EcefVector UsgsAstroFrameSensorModel::getIlluminationDirection(const csm::EcefCoord &groundPt) const {
// ground (body-fixed) - sun (body-fixed) gives us the illumination direction.
return csm::EcefVector {
groundPt.x - m_sunPosition[0],
groundPt.y - m_sunPosition[1],
groundPt.z - m_sunPosition[2]
};
}
double UsgsAstroFrameSensorModel::getImageTime(const csm::ImageCoord &imagePt) const {
// check if the image point is in range
if (imagePt.samp >= m_startingDetectorSample &&
imagePt.samp <= (m_startingDetectorSample + m_nSamples) &&
imagePt.line >= m_startingDetectorSample &&
imagePt.line <= (m_startingDetectorLine + m_nLines)) {
return m_ephemerisTime;
}
else {
throw csm::Error(csm::Error::BOUNDS,
"Image Coordinate out of Bounds",
"UsgsAstroFrameSensorModel::getImageTime");
}
}
csm::EcefCoord UsgsAstroFrameSensorModel::getSensorPosition(const csm::ImageCoord &imagePt) const {
// check if the image point is in range
if (imagePt.samp >= m_startingDetectorSample &&
imagePt.samp <= (m_startingDetectorSample + m_nSamples) &&
imagePt.line >= m_startingDetectorSample &&
imagePt.line <= (m_startingDetectorLine + m_nLines)) {
csm::EcefCoord sensorPosition;
sensorPosition.x = m_currentParameterValue[0];
sensorPosition.y = m_currentParameterValue[1];
sensorPosition.z = m_currentParameterValue[2];
return sensorPosition;
}
else {
throw csm::Error(csm::Error::BOUNDS,
"Image Coordinate out of Bounds",
"UsgsAstroFrameSensorModel::getSensorPosition");
}
}
csm::EcefCoord UsgsAstroFrameSensorModel::getSensorPosition(double time) const {
if (time == m_ephemerisTime){
csm::EcefCoord sensorPosition;
sensorPosition.x = m_currentParameterValue[0];
sensorPosition.y = m_currentParameterValue[1];
sensorPosition.z = m_currentParameterValue[2];
return sensorPosition;
} else {
std::string aMessage = "Valid image time is %d", m_ephemerisTime;
throw csm::Error(csm::Error::BOUNDS,
aMessage,
"UsgsAstroFrameSensorModel::getSensorPosition");
}
}
csm::EcefVector UsgsAstroFrameSensorModel::getSensorVelocity(const csm::ImageCoord &imagePt) const {
// Make sure the passed coordinate is with the image dimensions.
if (imagePt.samp < 0.0 || imagePt.samp > m_nSamples ||
imagePt.line < 0.0 || imagePt.line > m_nLines) {
throw csm::Error(csm::Error::BOUNDS, "Image coordinate out of bounds.",
"UsgsAstroFrameSensorModel::getSensorVelocity");
}
// Since this is a frame, just return the sensor velocity the ISD gave us.
return csm::EcefVector {
m_spacecraftVelocity[0],
m_spacecraftVelocity[1],
m_spacecraftVelocity[2]
};
}
csm::EcefVector UsgsAstroFrameSensorModel::getSensorVelocity(double time) const {
if (time == m_ephemerisTime){
return csm::EcefVector {
m_spacecraftVelocity[0],
m_spacecraftVelocity[1],
m_spacecraftVelocity[2]
};
} else {
std::string aMessage = "Valid image time is %d", m_ephemerisTime;
throw csm::Error(csm::Error::BOUNDS,
aMessage,
"UsgsAstroFrameSensorModel::getSensorVelocity");
}
}
csm::RasterGM::SensorPartials UsgsAstroFrameSensorModel::computeSensorPartials(int index,
const csm::EcefCoord &groundPt,
double desiredPrecision,
double *achievedPrecision,
csm::WarningList *warnings) const {
csm::ImageCoord img_pt = groundToImage(groundPt, desiredPrecision, achievedPrecision);
return computeSensorPartials(index, img_pt, groundPt, desiredPrecision, achievedPrecision);
}
/**
* @brief UsgsAstroFrameSensorModel::computeSensorPartials
* @param index
* @param imagePt
* @param groundPt
* @param desiredPrecision
* @param achievedPrecision
* @param warnings
* @return The partial derivatives in the line,sample directions.
*
* Research: We should investigate using a central difference scheme to approximate
* the partials. It is more accurate, but it might be costlier calculation-wise.
*
*/
csm::RasterGM::SensorPartials UsgsAstroFrameSensorModel::computeSensorPartials(int index,
const csm::ImageCoord &imagePt,
const csm::EcefCoord &groundPt,
double desiredPrecision,
double *achievedPrecision,
csm::WarningList *warnings) const {
const double delta = 1.0;
// Update the parameter
std::vector<double>adj(NUM_PARAMETERS, 0.0);
adj[index] = delta;
csm::ImageCoord imagePt1 = groundToImage(groundPt,adj,desiredPrecision,achievedPrecision);
csm::RasterGM::SensorPartials partials;
partials.first = (imagePt1.line - imagePt.line)/delta;
partials.second = (imagePt1.samp - imagePt.samp)/delta;
return partials;
}
std::vector<csm::RasterGM::SensorPartials> UsgsAstroFrameSensorModel::computeAllSensorPartials(
const csm::ImageCoord& imagePt,
const csm::EcefCoord& groundPt,
csm::param::Set pset,
double desiredPrecision,
double *achievedPrecision,
csm::WarningList *warnings) const {
std::vector<int> indices = getParameterSetIndices(pset);
size_t num = indices.size();
std::vector<csm::RasterGM::SensorPartials> partials;
for (int index = 0;index < num;index++){
partials.push_back(computeSensorPartials(
indices[index],
imagePt, groundPt,
desiredPrecision, achievedPrecision, warnings));
}
return partials;
}
std::vector<csm::RasterGM::SensorPartials> UsgsAstroFrameSensorModel::computeAllSensorPartials(
const csm::EcefCoord& groundPt,
csm::param::Set pset,
double desiredPrecision,
double *achievedPrecision,
csm::WarningList *warnings) const {
csm::ImageCoord imagePt = groundToImage(groundPt,
desiredPrecision, achievedPrecision, warnings);
return computeAllSensorPartials(imagePt, groundPt,
pset, desiredPrecision, achievedPrecision, warnings);
}
std::vector<double> UsgsAstroFrameSensorModel::computeGroundPartials(const csm::EcefCoord
&groundPt) const {
// Partials of line, sample wrt X, Y, Z
// Uses collinearity equations
std::vector<double> partials(6, 0.0);
double m[3][3];
calcRotationMatrix(m, m_noAdjustments);
double xo, yo, zo;
xo = groundPt.x - m_currentParameterValue[0];
yo = groundPt.y - m_currentParameterValue[1];
zo = groundPt.z - m_currentParameterValue[2];
double u, v, w;
u = m[0][0] * xo + m[0][1] * yo + m[0][2] * zo;
v = m[1][0] * xo + m[1][1] * yo + m[1][2] * zo;
w = m[2][0] * xo + m[2][1] * yo + m[2][2] * zo;
double fdw, udw, vdw;
fdw = m_focalLength / w;
udw = u / w;
vdw = v / w;
double upx, vpx, wpx;
upx = m[0][0];
vpx = m[1][0];
wpx = m[2][0];
partials[0] = -fdw * ( upx - udw * wpx );
partials[3] = -fdw * ( vpx - vdw * wpx );
double upy, vpy, wpy;
upy = m[0][1];
vpy = m[1][1];
wpy = m[2][1];
partials[1] = -fdw * ( upy - udw * wpy );
partials[4] = -fdw * ( vpy - vdw * wpy );
double upz, vpz, wpz;
upz = m[0][2];
vpz = m[1][2];
wpz = m[2][2];
partials[2] = -fdw * ( upz - udw * wpz );
partials[5] = -fdw * ( vpz - vdw * wpz );
return partials;
}
const csm::CorrelationModel& UsgsAstroFrameSensorModel::getCorrelationModel() const {
return _no_corr_model;
}
std::vector<double> UsgsAstroFrameSensorModel::getUnmodeledCrossCovariance(const csm::ImageCoord &pt1,
const csm::ImageCoord &pt2) const {
throw csm::Error(csm::Error::UNSUPPORTED_FUNCTION,
"Unsupported function",
"UsgsAstroFrameSensorModel::getUnmodeledCrossCovariance");
}
csm::Version UsgsAstroFrameSensorModel::getVersion() const {
return csm::Version(0,1,0);
}
std::string UsgsAstroFrameSensorModel::getModelName() const {
return _SENSOR_MODEL_NAME;
}
std::string UsgsAstroFrameSensorModel::getPedigree() const {
throw csm::Error(csm::Error::UNSUPPORTED_FUNCTION,
"Unsupported function",
"UsgsAstroFrameSensorModel::getPedigree");
}
std::string UsgsAstroFrameSensorModel::getImageIdentifier() const {
throw csm::Error(csm::Error::UNSUPPORTED_FUNCTION,
"Unsupported function",
"UsgsAstroFrameSensorModel::getImageIdentifier");
}
void UsgsAstroFrameSensorModel::setImageIdentifier(const std::string& imageId,
csm::WarningList* warnings) {
throw csm::Error(csm::Error::UNSUPPORTED_FUNCTION,
"Unsupported function",
"UsgsAstroFrameSensorModel::setImageIdentifier");
}
std::string UsgsAstroFrameSensorModel::getSensorIdentifier() const {
throw csm::Error(csm::Error::UNSUPPORTED_FUNCTION,
"Unsupported function",
"UsgsAstroFrameSensorModel::getSensorIdentifier");
}
std::string UsgsAstroFrameSensorModel::getPlatformIdentifier() const {
throw csm::Error(csm::Error::UNSUPPORTED_FUNCTION,
"Unsupported function",
"UsgsAstroFrameSensorModel::getPlatformIdentifier");
}
std::string UsgsAstroFrameSensorModel::getCollectionIdentifier() const {
throw csm::Error(csm::Error::UNSUPPORTED_FUNCTION,
"Unsupported function",
"UsgsAstroFrameSensorModel::getCollectionIdentifier");
}
std::string UsgsAstroFrameSensorModel::getTrajectoryIdentifier() const {
throw csm::Error(csm::Error::UNSUPPORTED_FUNCTION,
"Unsupported function",
"UsgsAstroFrameSensorModel::getTrajectoryIdentifier");
}
std::string UsgsAstroFrameSensorModel::getSensorType() const {
return CSM_SENSOR_TYPE_EO;
}
std::string UsgsAstroFrameSensorModel::getSensorMode() const {
return CSM_SENSOR_MODE_FRAME;
}
std::string UsgsAstroFrameSensorModel::getReferenceDateAndTime() const {
throw csm::Error(csm::Error::UNSUPPORTED_FUNCTION,
"Unsupported function",
"UsgsAstroFrameSensorModel::getReferenceDateAndTime");
}
std::string UsgsAstroFrameSensorModel::getModelState() const {
json state = {
{"m_modelName", _SENSOR_MODEL_NAME},
{"m_focalLength" , m_focalLength},
{"m_iTransS", {m_iTransS[0], m_iTransS[1], m_iTransS[2]}},
{"m_iTransL", {m_iTransL[0], m_iTransL[1], m_iTransL[2]}},
{"m_boresight", {m_boresight[0], m_boresight[1], m_boresight[2]}},
{"m_transX", {m_transX[0], m_transX[1], m_transX[2]}},
{"m_transY", {m_transY[0], m_transY[1], m_transY[2]}},
{"m_iTransS", {m_iTransS[0], m_iTransS[1], m_iTransS[2]}},
{"m_iTransL", {m_iTransL[0], m_iTransL[1], m_iTransL[2]}},
{"m_majorAxis", m_majorAxis},
{"m_minorAxis", m_minorAxis},
{"m_spacecraftVelocity", {m_spacecraftVelocity[0], m_spacecraftVelocity[1], m_spacecraftVelocity[2]}},
{"m_sunPosition", {m_sunPosition[0], m_sunPosition[1], m_sunPosition[2]}},
{"m_startingDetectorSample", m_startingDetectorSample},
{"m_startingDetectorLine", m_startingDetectorLine},
{"m_targetName", m_targetName},
{"m_ifov", m_ifov},
{"m_instrumentID", m_instrumentID},
{"m_focalLengthEpsilon", m_focalLengthEpsilon},
{"m_ccdCenter", {m_ccdCenter[0], m_ccdCenter[1]}},
{"m_linePp", m_linePp},
{"m_samplePp", m_samplePp},
{"m_minElevation", m_minElevation},
{"m_maxElevation", m_maxElevation},
{"m_odtX", {m_odtX[0], m_odtX[1], m_odtX[2], m_odtX[3], m_odtX[4],
m_odtX[5], m_odtX[6], m_odtX[7], m_odtX[8], m_odtX[9]}},
{"m_odtY", {m_odtY[0], m_odtY[1], m_odtY[2], m_odtY[3], m_odtY[4],
m_odtY[5], m_odtY[6], m_odtY[7], m_odtY[8], m_odtY[9]}},
{"m_originalHalfLines", m_originalHalfLines},
{"m_originalHalfSamples", m_originalHalfSamples},
{"m_spacecraftName", m_spacecraftName},
{"m_pixelPitch", m_pixelPitch},
{"m_ephemerisTime", m_ephemerisTime},
{"m_nLines", m_nLines},
{"m_nSamples", m_nSamples},
{"m_currentParameterValue", {m_currentParameterValue[0], m_currentParameterValue[1],
m_currentParameterValue[2], m_currentParameterValue[3],
m_currentParameterValue[4], m_currentParameterValue[5],
m_currentParameterValue[6]}},
{"m_currentParameterCovariance", m_currentParameterCovariance}
};
return state.dump();
}
bool UsgsAstroFrameSensorModel::isValidModelState(const std::string& stringState, csm::WarningList *warnings) {
std::vector<std::string> requiredKeywords = {
"m_modelName",
"m_majorAxis",
"m_minorAxis",
"m_focalLength",
"m_startingDetectorSample",
"m_startingDetectorLine",
"m_focalLengthEpsilon",
"m_nLines",
"m_nSamples",
"m_currentParameterValue",
"m_ccdCenter",
"m_spacecraftVelocity",
"m_sunPosition",
"m_odtX",
"m_odtY",
"m_transX",
"m_transY",
"m_iTransS",
"m_iTransL"
};
json jsonState = json::parse(stringState);
std::vector<std::string> missingKeywords;
for (auto &key : requiredKeywords) {
if (jsonState.find(key) == jsonState.end()) {
missingKeywords.push_back(key);
}
}
if (!missingKeywords.empty()) {
std::ostringstream oss;
std::copy(missingKeywords.begin(), missingKeywords.end(), std::ostream_iterator<std::string>(oss, " "));
warnings->push_back(csm::Warning(
csm::Warning::DATA_NOT_AVAILABLE,
"State has missing keywrods: " + oss.str(),
"UsgsAstroFrameSensorModel::isValidModelState"
));
}
std::string modelName = jsonState.value<std::string>("m_modelName", "");
if (modelName != _SENSOR_MODEL_NAME) {
warnings->push_back(csm::Warning(
csm::Warning::DATA_NOT_AVAILABLE,
"Incorrect model name in state, expected " + _SENSOR_MODEL_NAME + " but got " + modelName,
"UsgsAstroFrameSensorModel::isValidModelState"
));
}
return modelName == _SENSOR_MODEL_NAME && missingKeywords.empty();
}
bool UsgsAstroFrameSensorModel::isValidIsd(const std::string& Isd, csm::WarningList *warnings) {
// no obvious clean way to truely validate ISD with it's nested structure,
// or rather, it would be a pain to maintain, so just check if
// we can get a valid state from ISD. Once ISD schema is 100% clear
// we can change this.
try {
std::string state = constructStateFromIsd(Isd, warnings);
return isValidModelState(state, warnings);
}
catch(...) {
return false;
}
}
void UsgsAstroFrameSensorModel::replaceModelState(const std::string& stringState) {
json state = json::parse(stringState);
// The json library's .at() will except if key is missing
try {
m_modelName = state.at("m_modelName").get<std::string>();
m_majorAxis = state.at("m_majorAxis").get<double>();
m_minorAxis = state.at("m_minorAxis").get<double>();
m_focalLength = state.at("m_focalLength").get<double>();
m_startingDetectorSample = state.at("m_startingDetectorSample").get<double>();
m_startingDetectorLine = state.at("m_startingDetectorLine").get<double>();
m_focalLengthEpsilon = state.at("m_focalLengthEpsilon").get<double>();
m_nLines = state.at("m_nLines").get<int>();
m_nSamples = state.at("m_nSamples").get<int>();
m_currentParameterValue = state.at("m_currentParameterValue").get<std::vector<double>>();
m_ccdCenter = state.at("m_ccdCenter").get<std::vector<double>>();
m_spacecraftVelocity = state.at("m_spacecraftVelocity").get<std::vector<double>>();
m_sunPosition = state.at("m_sunPosition").get<std::vector<double>>();
m_odtX = state.at("m_odtX").get<std::vector<double>>();
m_odtY = state.at("m_odtY").get<std::vector<double>>();
m_transX = state.at("m_transX").get<std::vector<double>>();
m_transY = state.at("m_transY").get<std::vector<double>>();
m_iTransS = state.at("m_iTransS").get<std::vector<double>>();
m_iTransL = state.at("m_iTransL").get<std::vector<double>>();
// Leaving unused params commented out
// m_targetName = state.at("m_targetName").get<std::string>();
// m_ifov = state.at("m_ifov").get<double>();
// m_instrumentID = state.at("m_instrumentID").get<std::string>();
// m_currentParameterCovariance = state.at("m_currentParameterCovariance").get<std::vector<double>>();
// m_noAdjustments = state.at("m_noAdjustments").get<std::vector<double>>();
// m_linePp = state.at("m_linePp").get<double>();
// m_samplePp = state.at("m_samplePp").get<double>();
// m_originalHalfLines = state.at("m_originalHalfLines").get<double>();
// m_spacecraftName = state.at("m_spacecraftName").get<std::string>();
// m_pixelPitch = state.at("m_pixelPitch").get<double>();
// m_ephemerisTime = state.at("m_ephemerisTime").get<double>();
// m_originalHalfSamples = state.at("m_originalHalfSamples").get<double>();
// m_boresight = state.at("m_boresight").get<std::vector<double>>();
// Cast int vector to csm::param::Type vector by simply copying it
// std::vector<int> paramType = state.at("m_parameterType").get<std::vector<int>>();
// m_parameterType = std::vector<csm::param::Type>();
// for(auto &t : paramType){
// paramType.push_back(static_cast<csm::param::Type>(t));
// }
}
catch(std::out_of_range& e) {
throw csm::Error(csm::Error::SENSOR_MODEL_NOT_CONSTRUCTIBLE,
"State keywords required to generate sensor model missing: " + std::string(e.what()) + "\nUsing model string: " + stringState,
"UsgsAstroFrameSensorModel::replaceModelState");
}
}
std::string UsgsAstroFrameSensorModel::constructStateFromIsd(const std::string& jsonIsd, csm::WarningList* warnings) {
auto metric_conversion = [](double val, std::string from, std::string to="m") {
json typemap = {
{"m", 0},
{"km", 3}
};
// everything to lowercase
std::transform(from.begin(), from.end(), from.begin(), ::tolower);
std::transform(to.begin(), to.end(), to.begin(), ::tolower);
return val*pow(10, typemap[from].get<int>() - typemap[to].get<int>());
};
json isd = json::parse(jsonIsd);
json state = {};
try {
state["m_modelName"] = isd.at("name_model");
std::cerr << "Model Name Parsed!" << std::endl;
state["m_startingDetectorSample"] = isd.at("starting_detector_sample");
state["m_startingDetectorLine"] = isd.at("starting_detector_line");
std::cerr << "Detector Starting Pixel Parsed!" << std::endl;
// get focal length
{
json jayson = isd.at("focal_length_model");
json focal_length = jayson.at("focal_length");
json epsilon = jayson.at("focal_epsilon");
state["m_focalLength"] = focal_length;
state["m_focalLengthEpsilon"] = epsilon;
std::cerr << "Focal Length Parsed!" << std::endl;
}
// get sensor_position
{
json jayson = isd.at("sensor_position");
json positions = jayson.at("positions")[0];
json velocities = jayson.at("velocities")[0];
json unit = jayson.at("unit");
unit = unit.get<std::string>();
state["m_currentParameterValue"] = json();
state["m_currentParameterValue"][0] = metric_conversion(positions[0].get<double>(), unit);
state["m_currentParameterValue"][1] = metric_conversion(positions[1].get<double>(), unit);
state["m_currentParameterValue"][2] = metric_conversion(positions[2].get<double>(), unit);
state["m_spacecraftVelocity"] = velocities;
std::cerr << "Sensor Location Parsed!" << std::endl;
}
// get sun_position
// sun position is not strictly necessary, but is required for getIlluminationDirection.
{
json jayson = isd.at("sun_position");
json positions = jayson.at("positions")[0];
json unit = jayson.at("unit");
unit = unit.get<std::string>();
state["m_sunPosition"] = json();
state["m_sunPosition"][0] = metric_conversion(positions[0].get<double>(), unit);
state["m_sunPosition"][1] = metric_conversion(positions[1].get<double>(), unit);
state["m_sunPosition"][2] = metric_conversion(positions[2].get<double>(), unit);
std::cerr << "Sun Position Parsed!" << std::endl;
}
// get sensor_orientation quaternion
{
json jayson = isd.at("sensor_orientation");
json quaternion = jayson.at("quaternions")[0];
state["m_currentParameterValue"][3] = quaternion[0];
state["m_currentParameterValue"][4] = quaternion[1];
state["m_currentParameterValue"][5] = quaternion[2];
state["m_currentParameterValue"][6] = quaternion[3];
std::cerr << "Sensor Orientation Parsed!" << std::endl;
}
// get optical_distortion
{
json jayson = isd.at("optical_distortion");
std::vector<double> xDistortion = jayson.at("transverse").at("x");
std::vector<double> yDistortion = jayson.at("transverse").at("y");
xDistortion.resize(10, 0.0);
yDistortion.resize(10, 0.0);
state["m_odtX"] = xDistortion;
state["m_odtY"] = yDistortion;
std::cerr << "Distortion Parsed!" << std::endl;
}
// get detector_center
{
json jayson = isd.at("detector_center");
json sample = jayson.at("sample");
json line = jayson.at("line");
state["m_ccdCenter"][0] = line;
state["m_ccdCenter"][1] = sample;
std::cerr << "Detector Center Parsed!" << std::endl;
}
// get radii
{
json jayson = isd.at("radii");
json semiminor = jayson.at("semiminor");
json semimajor = jayson.at("semimajor");
json unit = jayson.at("unit");
unit = unit.get<std::string>();
state["m_minorAxis"] = metric_conversion(semiminor.get<double>(), unit);
state["m_majorAxis"] = metric_conversion(semimajor.get<double>(), unit);
std::cerr << "Target Radii Parsed!" << std::endl;
}
// get reference_height
{
json reference_height = isd.at("reference_height");
json maxheight = reference_height.at("maxheight");
json minheight = reference_height.at("minheight");
json unit = reference_height.at("unit");
unit = unit.get<std::string>();
state["m_minElevation"] = metric_conversion(minheight.get<double>(), unit);
state["m_maxElevation"] = metric_conversion(maxheight.get<double>(), unit);
std::cerr << "Reference Height Parsed!" << std::endl;
}
state["m_ephemerisTime"] = isd.at("center_ephemeris_time");
state["m_nLines"] = isd.at("image_lines");
state["m_nSamples"] = isd.at("image_samples");
state["m_iTransL"] = isd.at("focal2pixel_lines");
state["m_iTransS"] = isd.at("focal2pixel_samples");
// We don't pass the pixel to focal plane transformation so invert the
// focal plane to pixel transformation
double determinant = state["m_iTransL"][1].get<double>() * state["m_iTransS"][2].get<double>() -
state["m_iTransL"][2].get<double>() * state["m_iTransS"][1].get<double>();
state["m_transX"][1] = state["m_iTransL"][1].get<double>() / determinant;
state["m_transX"][2] = -state["m_iTransS"][1].get<double>() / determinant;
state["m_transX"][0] = -(state["m_transX"][1].get<double>() * state["m_iTransL"][0].get<double>() +
state["m_transX"][2].get<double>() * state["m_iTransS"][0].get<double>());
state["m_transY"][1] = -state["m_iTransL"][2].get<double>() / determinant;
state["m_transY"][2] = state["m_iTransS"][2].get<double>() / determinant;
state["m_transY"][0] = -(state["m_transY"][1].get<double>() * state["m_iTransL"][0].get<double>() +
state["m_transY"][2].get<double>() * state["m_iTransS"][0].get<double>());
std::cerr << "Focal To Pixel Transformation Parsed!" << std::endl;
}
catch(std::out_of_range& e) {
throw csm::Error(csm::Error::SENSOR_MODEL_NOT_CONSTRUCTIBLE,
"ISD missing necessary keywords to create sensor model: " + std::string(e.what()),
"UsgsAstroFrameSensorModel::constructStateFromIsd");
}
catch(...) {
throw csm::Error(csm::Error::SENSOR_MODEL_NOT_CONSTRUCTIBLE,
"ISD is invalid for creating the sensor model.",
"UsgsAstroFrameSensorModel::constructStateFromIsd");
}
return state.dump();
}
csm::EcefCoord UsgsAstroFrameSensorModel::getReferencePoint() const {
throw csm::Error(csm::Error::UNSUPPORTED_FUNCTION,
"Unsupported function",
"UsgsAstroFrameSensorModel::getReferencePoint");
}
void UsgsAstroFrameSensorModel::setReferencePoint(const csm::EcefCoord &groundPt) {
throw csm::Error(csm::Error::UNSUPPORTED_FUNCTION,
"Unsupported function",
"UsgsAstroFrameSensorModel::setReferencePoint");
}
int UsgsAstroFrameSensorModel::getNumParameters() const {
return NUM_PARAMETERS;
}
std::string UsgsAstroFrameSensorModel::getParameterName(int index) const {
return m_parameterName[index];
}
std::string UsgsAstroFrameSensorModel::getParameterUnits(int index) const {
if (index < 3) {
return "m";
}
else {
return "radians";
}
}
bool UsgsAstroFrameSensorModel::hasShareableParameters() const {
throw csm::Error(csm::Error::UNSUPPORTED_FUNCTION,
"Unsupported function",
"UsgsAstroFrameSensorModel::hasShareableParameters");
}
bool UsgsAstroFrameSensorModel::isParameterShareable(int index) const {
throw csm::Error(csm::Error::UNSUPPORTED_FUNCTION,
"Unsupported function",
"UsgsAstroFrameSensorModel::isParameterShareable");
}
csm::SharingCriteria UsgsAstroFrameSensorModel::getParameterSharingCriteria(int index) const {
throw csm::Error(csm::Error::UNSUPPORTED_FUNCTION,
"Unsupported function",
"UsgsAstroFrameSensorModel::getParameterSharingCriteria");
}
double UsgsAstroFrameSensorModel::getParameterValue(int index) const {
return m_currentParameterValue[index];
}
void UsgsAstroFrameSensorModel::setParameterValue(int index, double value) {
m_currentParameterValue[index] = value;
}
csm::param::Type UsgsAstroFrameSensorModel::getParameterType(int index) const {
return m_parameterType[index];
}
void UsgsAstroFrameSensorModel::setParameterType(int index, csm::param::Type pType) {
m_parameterType[index] = pType;
}
double UsgsAstroFrameSensorModel::getParameterCovariance(int index1, int index2) const {
throw csm::Error(csm::Error::UNSUPPORTED_FUNCTION,
"Unsupported function",
"UsgsAstroFrameSensorModel::getParameterCovariance");
}
void UsgsAstroFrameSensorModel::setParameterCovariance(int index1, int index2, double covariance) {
throw csm::Error(csm::Error::UNSUPPORTED_FUNCTION,
"Unsupported function",
"UsgsAstroFrameSensorModel::setParameterCovariance");
}
int UsgsAstroFrameSensorModel::getNumGeometricCorrectionSwitches() const {
throw csm::Error(csm::Error::UNSUPPORTED_FUNCTION,
"Unsupported function",
"UsgsAstroFrameSensorModel::getNumGeometricCorrectionSwitches");
}
std::string UsgsAstroFrameSensorModel::getGeometricCorrectionName(int index) const {
throw csm::Error(csm::Error::UNSUPPORTED_FUNCTION,
"Unsupported function",
"UsgsAstroFrameSensorModel::getGeometricCorrectionName");
}
void UsgsAstroFrameSensorModel::setGeometricCorrectionSwitch(int index,
bool value,
csm::param::Type pType) {
throw csm::Error(csm::Error::UNSUPPORTED_FUNCTION,
"Unsupported function",
"UsgsAstroFrameSensorModel::setGeometricCorrectionSwitch");
}
bool UsgsAstroFrameSensorModel::getGeometricCorrectionSwitch(int index) const {
throw csm::Error(csm::Error::UNSUPPORTED_FUNCTION,
"Unsupported function",
"UsgsAstroFrameSensorModel::getGeometricCorrectionSwitch");
}
std::vector<double> UsgsAstroFrameSensorModel::getCrossCovarianceMatrix(
const GeometricModel &comparisonModel,
csm::param::Set pSet,
const GeometricModelList &otherModels) const {
throw csm::Error(csm::Error::UNSUPPORTED_FUNCTION,
"Unsupported function",
"UsgsAstroFrameSensorModel::getCrossCovarianceMatrix");
}
void UsgsAstroFrameSensorModel::calcRotationMatrix(
double m[3][3]) const {
// Trigonometric functions for rotation matrix
double w = m_currentParameterValue[3];
double x = m_currentParameterValue[4];
double y = m_currentParameterValue[5];
double z = m_currentParameterValue[6];
m[0][0] = w*w + x*x - y*y - z*z;
m[0][1] = 2 * (x*y - w*z);
m[0][2] = 2 * (w*y + x*z);
m[1][0] = 2 * (x*y + w*z);
m[1][1] = w*w - x*x + y*y - z*z;
m[1][2] = 2 * (y*z - w*x);
m[2][0] = 2 * (x*z - w*y);
m[2][1] = 2 * (w*x + y*z);
m[2][2] = w*w - x*x - y*y + z*z;
}
void UsgsAstroFrameSensorModel::calcRotationMatrix(
double m[3][3], const std::vector<double> &adjustments) const {
// Trigonometric functions for rotation matrix
double w = getValue(3, adjustments);
double x = getValue(4, adjustments);
double y = getValue(5, adjustments);
double z = getValue(6, adjustments);
m[0][0] = w*w + x*x - y*y - z*z;
m[0][1] = 2 * (x*y - w*z);
m[0][2] = 2 * (w*y + x*z);
m[1][0] = 2 * (x*y + w*z);
m[1][1] = w*w - x*x + y*y - z*z;
m[1][2] = 2 * (y*z - w*x);
m[2][0] = 2 * (x*z - w*y);
m[2][1] = 2 * (w*x + y*z);
m[2][2] = w*w - x*x - y*y + z*z;
}
void UsgsAstroFrameSensorModel::losEllipsoidIntersect(
const double height,
const double xc,
const double yc,
const double zc,
const double xl,
const double yl,
const double zl,
double& x,
double& y,
double& z ) const
{
// Helper function which computes the intersection of the image ray
// with an expanded ellipsoid. All vectors are in earth-centered-fixed
// coordinate system with origin at the center of the earth.
double ap, bp, k;
ap = m_majorAxis + height;
bp = m_minorAxis + height;
k = ap * ap / (bp * bp);
// Solve quadratic equation for scale factor
// applied to image ray to compute ground point
double at, bt, ct, quadTerm;
at = xl * xl + yl * yl + k * zl * zl;
bt = 2.0 * (xl * xc + yl * yc + k * zl * zc);
ct = xc * xc + yc * yc + k * zc * zc - ap * ap;
quadTerm = bt * bt - 4.0 * at * ct;
// If quadTerm is negative, the image ray does not
// intersect the ellipsoid. Setting the quadTerm to
// zero means solving for a point on the ray nearest
// the surface of the ellisoid.
if ( 0.0 > quadTerm )
{
quadTerm = 0.0;
}
double scale;
scale = (-bt - sqrt (quadTerm)) / (2.0 * at);
// Compute ground point vector
x = xc + scale * xl;
y = yc + scale * yl;
z = zc + scale * zl;
}
/**
* @brief Compute undistorted focal plane x/y.
*
* Computes undistorted focal plane (x,y) coordinates given a distorted focal plane (x,y)
* coordinate. The undistorted coordinates are solved for using the Newton-Raphson
* method for root-finding if the distortionFunction method is invoked.
*
* @param dx distorted focal plane x in millimeters
* @param dy distorted focal plane y in millimeters
* @param undistortedX The undistorted x coordinate, in millimeters.
* @param undistortedY The undistorted y coordinate, in millimeters.
*
* @return if the conversion was successful
* @todo Review the tolerance and maximum iterations of the root-
* finding algorithm.
* @todo Review the handling of non-convergence of the root-finding
* algorithm.
* @todo Add error handling for near-zero determinant.
*/
bool UsgsAstroFrameSensorModel::setFocalPlane(double dx,double dy,
double &undistortedX,
double &undistortedY ) const {
// Solve the distortion equation using the Newton-Raphson method.
// Set the error tolerance to about one millionth of a NAC pixel.
const double tol = 1.4E-5;
// The maximum number of iterations of the Newton-Raphson method.
const int maxTries = 60;
double x;
double y;
double fx;
double fy;
double Jxx;
double Jxy;
double Jyx;
double Jyy;
// Initial guess at the root
x = dx;
y = dy;
distortionFunction(x, y, fx, fy);
for (int count = 1; ((fabs(fx) +fabs(fy)) > tol) && (count < maxTries); count++) {
this->distortionFunction(x, y, fx, fy);
fx = dx - fx;
fy = dy - fy;
distortionJacobian(x, y, Jxx, Jxy, Jyx, Jyy);
double determinant = Jxx * Jyy - Jxy * Jyx;
if (fabs(determinant) < 1E-6) {
undistortedX = x;
undistortedY = y;
//
// Near-zero determinant. Add error handling here.
//
//-- Just break out and return with no convergence
return false;
}
x = x + (Jyy * fx - Jxy * fy) / determinant;
y = y + (Jxx * fy - Jyx * fx) / determinant;
}
if ( (fabs(fx) + fabs(fy)) <= tol) {
// The method converged to a root.
undistortedX = x;
undistortedY = y;
return true;
}
else {
// The method did not converge to a root within the maximum
// number of iterations. Return with no distortion.
undistortedX = dx;
undistortedY = dy;
return false;
}
return true;
}
/**
* @description Jacobian of the distortion function. The Jacobian was computed
* algebraically from the function described in the distortionFunction
* method.
*
* @param x
* @param y
* @param Jxx Partial_xx
* @param Jxy Partial_xy
* @param Jyx Partial_yx
* @param Jyy Partial_yy
*/
void UsgsAstroFrameSensorModel::distortionJacobian(double x, double y, double &Jxx, double &Jxy,
double &Jyx, double &Jyy) const {
double d_dx[10];
d_dx[0] = 0;
d_dx[1] = 1;
d_dx[2] = 0;
d_dx[3] = 2 * x;
d_dx[4] = y;
d_dx[5] = 0;
d_dx[6] = 3 * x * x;
d_dx[7] = 2 * x * y;
d_dx[8] = y * y;
d_dx[9] = 0;
double d_dy[10];
d_dy[0] = 0;
d_dy[1] = 0;
d_dy[2] = 1;
d_dy[3] = 0;
d_dy[4] = x;
d_dy[5] = 2 * y;
d_dy[6] = 0;
d_dy[7] = x * x;
d_dy[8] = 2 * x * y;
d_dy[9] = 3 * y * y;
Jxx = 0.0;
Jxy = 0.0;
Jyx = 0.0;
Jyy = 0.0;
for (int i = 0; i < 10; i++) {
Jxx = Jxx + d_dx[i] * m_odtX[i];
Jxy = Jxy + d_dy[i] * m_odtX[i];
Jyx = Jyx + d_dx[i] * m_odtY[i];
Jyy = Jyy + d_dy[i] * m_odtY[i];
}
}
/**
* @description Compute distorted focal plane (dx,dy) coordinate given an undistorted focal
* plane (ux,uy) coordinate. This describes the third order Taylor approximation to the
* distortion model.
*
* @param ux Undistored x
* @param uy Undistored y
* @param dx Result distorted x
* @param dy Result distorted y
*/
void UsgsAstroFrameSensorModel::distortionFunction(double ux, double uy, double &dx, double &dy) const {
double f[10];
f[0] = 1;
f[1] = ux;
f[2] = uy;
f[3] = ux * ux;
f[4] = ux * uy;
f[5] = uy * uy;
f[6] = ux * ux * ux;
f[7] = ux * ux * uy;
f[8] = ux * uy * uy;
f[9] = uy * uy * uy;
dx = 0.0;
dy = 0.0;
for (int i = 0; i < 10; i++) {
dx = dx + f[i] * m_odtX[i];
dy = dy + f[i] * m_odtY[i];
}
}
/***** Helper Functions *****/
double UsgsAstroFrameSensorModel::getValue(
int index,
const std::vector<double> &adjustments) const
{
return m_currentParameterValue[index] + adjustments[index];
}
| 34.369186 | 149 | 0.630445 | [
"vector",
"model",
"transform"
] |
2ef5ec7778ea2801ae3e005ba478c268f7b4a2b7 | 8,625 | cpp | C++ | thirdparty/GeometricTools/WildMagic5/LibCore/ObjectSystems/Wm5Object.cpp | SoMa-Project/vision | ea8199d98edc363b2be79baa7c691da3a5a6cc86 | [
"BSD-2-Clause-FreeBSD"
] | 1 | 2020-07-24T23:40:01.000Z | 2020-07-24T23:40:01.000Z | thirdparty/GeometricTools/WildMagic5/LibCore/ObjectSystems/Wm5Object.cpp | SoMa-Project/vision | ea8199d98edc363b2be79baa7c691da3a5a6cc86 | [
"BSD-2-Clause-FreeBSD"
] | 4 | 2020-05-19T18:14:33.000Z | 2021-03-19T15:53:43.000Z | thirdparty/GeometricTools/WildMagic5/LibCore/ObjectSystems/Wm5Object.cpp | SoMa-Project/vision | ea8199d98edc363b2be79baa7c691da3a5a6cc86 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | // Geometric Tools, LLC
// Copyright (c) 1998-2014
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
//
// File Version: 5.0.0 (2010/01/01)
#include "Wm5CorePCH.h"
#include "Wm5Object.h"
using namespace Wm5;
//----------------------------------------------------------------------------
Object::Object ()
{
}
//----------------------------------------------------------------------------
Object::~Object ()
{
}
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// Run-time type information.
//----------------------------------------------------------------------------
const Rtti Object::TYPE("Wm5.Object", 0);
//----------------------------------------------------------------------------
const Rtti& Object::GetRttiType () const
{
return TYPE;
}
//----------------------------------------------------------------------------
bool Object::IsExactly (const Rtti& type) const
{
return GetRttiType().IsExactly(type);
}
//----------------------------------------------------------------------------
bool Object::IsDerived (const Rtti& type) const
{
return GetRttiType().IsDerived(type);
}
//----------------------------------------------------------------------------
bool Object::IsExactlyTypeOf (const Object* object) const
{
return object && GetRttiType().IsExactly(object->GetRttiType());
}
//----------------------------------------------------------------------------
bool Object::IsDerivedTypeOf (const Object* object) const
{
return object && GetRttiType().IsDerived(object->GetRttiType());
}
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// Names.
//----------------------------------------------------------------------------
void Object::SetName (const std::string& name)
{
mName = name;
}
//----------------------------------------------------------------------------
const std::string& Object::GetName () const
{
return mName;
}
//----------------------------------------------------------------------------
Object* Object::GetObjectByName (const std::string& name)
{
return (name == mName ? this : 0);
}
//----------------------------------------------------------------------------
void Object::GetAllObjectsByName (const std::string& name,
std::vector<Object*>& objects)
{
if (name == mName)
{
objects.push_back(this);
}
}
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// Streaming.
//----------------------------------------------------------------------------
Object::FactoryMap* Object::msFactories = 0;
bool Object::msStreamRegistered = false;
//----------------------------------------------------------------------------
Object* Object::Factory (InStream&)
{
assertion(false, "Abstract classes have no factory.\n");
return 0;
}
//----------------------------------------------------------------------------
bool Object::RegisterFactory ()
{
if (!msStreamRegistered)
{
InitTerm::AddInitializer(Object::InitializeFactory);
InitTerm::AddTerminator(Object::TerminateFactory);
msStreamRegistered = true;
}
return msStreamRegistered;
}
//----------------------------------------------------------------------------
void Object::InitializeFactory ()
{
if (!msFactories)
{
msFactories = new0 Object::FactoryMap();
}
msFactories->insert(std::make_pair(TYPE.GetName(), Factory));
}
//----------------------------------------------------------------------------
void Object::TerminateFactory ()
{
delete0(msFactories);
msFactories = 0;
}
//----------------------------------------------------------------------------
Object::FactoryFunction Object::Find (const std::string& name)
{
assertion(msFactories != 0, "FactoryMap was not yet allocated.\n");
FactoryMap::iterator iter = msFactories->find(name);
if (iter != msFactories->end())
{
return iter->second;
}
return 0;
}
//----------------------------------------------------------------------------
Object::Object (LoadConstructor)
{
}
//----------------------------------------------------------------------------
void Object::Load (InStream& source)
{
WM5_BEGIN_DEBUG_STREAM_LOAD(source);
// The RTTI name was already read from the stream in order to look up the
// correct Load function for the object.
// Read the unique identifier of the object. This provides information
// for the linking phase.
source.ReadUniqueID(this);
// Read the name of the object.
source.ReadString(mName);
WM5_END_DEBUG_STREAM_LOAD(Object, source);
}
//----------------------------------------------------------------------------
void Object::Link (InStream&)
{
// Object has no Object* members.
}
//----------------------------------------------------------------------------
void Object::PostLink ()
{
// Object has no postlink semantics.
}
//----------------------------------------------------------------------------
bool Object::Register (OutStream& target) const
{
return target.RegisterRoot(this);
}
//----------------------------------------------------------------------------
void Object::Save (OutStream& target) const
{
WM5_BEGIN_DEBUG_STREAM_SAVE(target);
// Write the RTTI name for factory function lookup during Load.
target.WriteString(GetRttiType().GetName());
// Write the unique identifier for the object. This is used during
// loading and linking.
target.WriteUniqueID(this);
// Write the name of the object.
target.WriteString(mName);
WM5_END_DEBUG_STREAM_SAVE(Object, target);
}
//----------------------------------------------------------------------------
int Object::GetStreamingSize () const
{
// The RTTI name.
int size = WM5_STRINGSIZE(GetRttiType().GetName());
// The unique identifier for the object.
size += sizeof(unsigned int);
// The name of the object.
size += WM5_STRINGSIZE(mName);
return size;
}
//----------------------------------------------------------------------------
#if 0
Object* Object::Copy (const std::string& uniqueNameAppend) const
{
// Save the object to a memory buffer.
Stream<Object> saveStream;
saveStream.Insert((Object*)this);
int bufferSize = 0;
char* buffer = 0;
bool saved = saveStream.Save(bufferSize, buffer, BufferIO::BM_WRITE);
assertion(saved, "Copy function failed on save\n");
if (!saved)
{
return 0;
}
// Load the object from the memory buffer.
Stream<Object> loadStream;
bool loaded = loadStream.Load(bufferSize, buffer, BufferIO::BM_READ);
assertion(loaded, "Copy function failed on load\n");
if (!loaded)
{
return 0;
}
delete1(buffer);
if (uniqueNameAppend != "")
{
// The names of the input scene were copied as is. Generate unique
// names for the output scene.
const std::vector<Object*>& ordered = loadStream.GetLoadedObjects();
std::vector<Object*>::const_iterator iter = ordered.begin();
std::vector<Object*>::const_iterator end = ordered.end();
for (/**/; iter != end; ++iter)
{
Object* object = *iter;
std::string name = object->GetName();
if (name.length() > 0)
{
// The object has a name. Append a string to make the name
// unique. TODO: This code does not ensure that the
// appended name is some other name in the copied scene. To
// do this would require building a set of names and verifying
// that the appended names are not in this set. For now we
// think this is not worth the effort, but maybe later we can
// add code to do this.
name += uniqueNameAppend;
object->SetName(name);
}
}
}
return loadStream.GetObjectAt(0);
}
#endif
//----------------------------------------------------------------------------
| 34.090909 | 79 | 0.432696 | [
"object",
"vector"
] |
2efadf22552376dbb7ff673684a8bf4b7d2fd1b1 | 433 | hpp | C++ | include/Wg/WidgetList.hpp | iSLC/vaca | c9bc3284c2a1325f7056f455fd5ff1e47e7673bc | [
"MIT"
] | null | null | null | include/Wg/WidgetList.hpp | iSLC/vaca | c9bc3284c2a1325f7056f455fd5ff1e47e7673bc | [
"MIT"
] | null | null | null | include/Wg/WidgetList.hpp | iSLC/vaca | c9bc3284c2a1325f7056f455fd5ff1e47e7673bc | [
"MIT"
] | null | null | null | // Vaca - Visual Application Components Abstraction
// Copyright (c) 2005-2010 David Capello
//
// This file is distributed under the terms of the MIT license,
// please read LICENSE.txt for more information.
#pragma once
#include "Wg/Base.hpp"
#include <vector>
namespace Wg {
/**
Collection of widgets.
Used to handle the list of children of each widget.
*/
typedef std::vector<Widget *> WidgetList;
} // namespace Wg
| 18.826087 | 63 | 0.720554 | [
"vector"
] |
2c07e8fefb4d64e29a070d11d29cf83b4292c31d | 687 | hh | C++ | src/fml/_internals/dimops.hh | wrathematics/fml | e6db9c67a530b31f80a7fc0fe16d0f88c1d9a18e | [
"BSL-1.0"
] | 15 | 2020-01-29T08:59:34.000Z | 2020-01-31T04:21:52.000Z | src/fml/_internals/dimops.hh | wrathematics/fml | e6db9c67a530b31f80a7fc0fe16d0f88c1d9a18e | [
"BSL-1.0"
] | null | null | null | src/fml/_internals/dimops.hh | wrathematics/fml | e6db9c67a530b31f80a7fc0fe16d0f88c1d9a18e | [
"BSL-1.0"
] | null | null | null | // This file is part of fml which is released under the Boost Software
// License, Version 1.0. See accompanying file LICENSE or copy at
// https://www.boost.org/LICENSE_1_0.txt
#ifndef FML__INTERNALS_DIMOPS_H
#define FML__INTERNALS_DIMOPS_H
#pragma once
namespace fml
{
namespace dimops
{
enum sweep_op
{
/**
Arithmetic operations for `dimops::rowsweep()` and `dimops::colsweep()`
functions. These operate by either row or column-wise taking a matrix and
applying an appropriately sized vector to the entries of that matrix by
addition, subtraction, multiplication, or division.
*/
SWEEP_ADD, SWEEP_SUB, SWEEP_MUL, SWEEP_DIV
};
}
}
#endif
| 23.689655 | 79 | 0.727802 | [
"vector"
] |
2c096c920739f22ac95d58a0cf992c29f0356899 | 11,270 | cc | C++ | lib/nu_program.cc | eantcal/nubasic | c9928aa526ee0fc97085c2deb783192274db295f | [
"MIT"
] | 29 | 2016-06-02T14:58:27.000Z | 2022-02-17T13:59:58.000Z | lib/nu_program.cc | eantcal/nubasic | c9928aa526ee0fc97085c2deb783192274db295f | [
"MIT"
] | 4 | 2018-05-29T01:36:38.000Z | 2020-09-21T21:12:45.000Z | lib/nu_program.cc | eantcal/nubasic | c9928aa526ee0fc97085c2deb783192274db295f | [
"MIT"
] | 2 | 2019-10-23T11:09:16.000Z | 2020-05-12T20:17:29.000Z | //
// This file is part of nuBASIC
// Copyright (c) Antonino Calderone (antonino.calderone@gmail.com)
// All rights reserved.
// Licensed under the MIT License.
// See COPYING file in the project root for full license information.
//
/* -------------------------------------------------------------------------- */
#include "nu_program.h"
#include "nu_interpreter.h"
#include "nu_rt_prog_ctx.h"
#include "nu_stmt_block.h"
#include "nu_stmt_call.h"
#include <algorithm>
#include <cassert>
#include <iostream>
#include <memory>
#include <string.h>
#include <string>
/* -------------------------------------------------------------------------- */
namespace nu {
/* -------------------------------------------------------------------------- */
class prog_line_iterator_t : public prog_line_t::iterator {
};
/* -------------------------------------------------------------------------- */
program_t::program_t(prog_line_t& pl, rt_prog_ctx_t& ctx, bool chkpt)
: _prog_line(pl)
, _ctx(ctx)
, _function_call(chkpt)
{
}
/* -------------------------------------------------------------------------- */
void program_t::goto_end_block(prog_line_iterator_t& prog_ptr,
stmt_t::stmt_cl_t begin, stmt_t::stmt_cl_t end, bool& flg)
{
int while_cnt = 1;
while (prog_ptr != _prog_line.end()) {
if (prog_ptr->second.first->get_cl() == begin) {
++while_cnt;
}
else if (prog_ptr->second.first->get_cl() == end) {
--while_cnt;
if (while_cnt < 1) {
flg = false;
break;
}
}
++prog_ptr;
}
}
/* -------------------------------------------------------------------------- */
bool program_t::run_statement(stmt_t::handle_t stmt_handle, size_t stmt_id,
prog_line_iterator_t& prog_ptr)
{
auto block_ptr = dynamic_cast<stmt_block_t*>(stmt_handle.get());
if (block_ptr && stmt_id > 0) {
auto stmt_pos = block_ptr->find_stmt_pos(int(stmt_id));
if (stmt_pos >= 0) {
if (++stmt_pos < int(block_ptr->size())) {
// resume execution from next statement
if (!block_ptr->run_pos(_ctx, stmt_pos)) {
// if not break condition returned
// go to next line
++prog_ptr;
}
}
else {
// no stmt found in this line
// go to next line
++prog_ptr;
}
}
else {
// no stmt found in this line
// goto next line
++prog_ptr;
}
}
else {
// stmt executed, for default go to next line
stmt_handle->run(_ctx);
++prog_ptr;
}
NU_TRACE_CTX(_ctx);
return true;
}
/* -------------------------------------------------------------------------- */
bool program_t::run(line_num_t start_from)
{
return _run(start_from, 0, false);
}
/* -------------------------------------------------------------------------- */
bool program_t::cont(line_num_t start_from, stmt_num_t stmt_id)
{
return _run(start_from, stmt_id, false);
}
/* -------------------------------------------------------------------------- */
bool program_t::run_next(line_num_t start_from)
{
return _run(start_from, 0, true);
}
/* -------------------------------------------------------------------------- */
bool program_t::get_dbg_info(line_num_t line, dbginfo_t& dbg)
{
auto code_line = _prog_line.find(line);
if (code_line == _prog_line.end()) {
return false;
}
dbg = code_line->second.second;
return true;
}
/* -------------------------------------------------------------------------- */
bool program_t::set_dbg_info(line_num_t line, const dbginfo_t& dbg)
{
auto code_line = _prog_line.find(line);
if (code_line == _prog_line.end()) {
return false;
}
code_line->second.second = dbg;
return true;
}
/* -------------------------------------------------------------------------- */
bool program_t::_run(line_num_t start_from, stmt_num_t stmt_id, bool next)
{
checkpoint_data_t cp_data;
reset_break_event();
if (_function_call) {
cp_data.flag = _ctx.flag;
cp_data.goingto_pc = _ctx.goingto_pc;
cp_data.runtime_pc = _ctx.runtime_pc;
cp_data.return_stack = _ctx.return_stack;
_ctx.return_stack.clear();
}
auto prog_ptr = _prog_line.begin();
if (start_from) {
auto jump = _prog_line.find(start_from);
if (next && jump != _prog_line.end()) {
++jump;
}
if (jump == _prog_line.end()) {
std::string err = "Line " + nu::to_string(start_from);
err += next ? " is last line in program" : " does not exist";
throw exception_t(err);
}
prog_ptr = jump;
}
auto check_break_event = [&]() {
if (break_event()) {
reset_break_event();
_ctx.flag.set(rt_prog_ctx_t::FLG_END_REQUEST, true);
}
};
auto return_stmt_id = stmt_id;
while (prog_ptr != _prog_line.end()) {
_ctx.runtime_pc.set(prog_ptr->first, return_stmt_id);
if (_ctx.flag[rt_prog_ctx_t::FLG_STOP_REQUEST]) {
dbginfo_t dbg;
dbg.break_point = true;
set_dbg_info(prog_ptr->first, dbg);
_ctx.flag.set(rt_prog_ctx_t::FLG_STOP_REQUEST, false);
}
if (prog_ptr->second.second.single_step_break_point
&& !_function_call)
{
prog_ptr->second.second.single_step_break_point = false;
_ctx.flag.set(rt_prog_ctx_t::FLG_END_REQUEST, true);
break;
}
if (prog_ptr->second.second.break_point && !_function_call) {
if (prog_ptr->second.second.condition_stmt != nullptr) {
prog_ptr->second.second.condition_stmt->run(_ctx);
}
else {
_ctx.flag.set(rt_prog_ctx_t::FLG_END_REQUEST, true);
}
if (_ctx.flag[rt_prog_ctx_t::FLG_END_REQUEST]) {
break;
}
}
else if (prog_ptr->second.second.continue_after_break) {
// Reset breakpoint for next stmt execution
prog_ptr->second.second.break_point = true;
prog_ptr->second.second.continue_after_break = false;
}
// Skip execute empty stmt
if (prog_ptr->second.first->get_cl() == stmt_t::stmt_cl_t::EMPTY) {
++prog_ptr;
continue;
}
// Run statement and update prog_ptr
if (run_statement(prog_ptr->second.first, return_stmt_id,
static_cast<prog_line_iterator_t&>(prog_ptr)))
{
return_stmt_id = 0;
}
check_break_event();
_yield_host_os();
if (_ctx.flag[rt_prog_ctx_t::FLG_END_REQUEST]) {
break;
}
if (_ctx.flag[rt_prog_ctx_t::FLG_RETURN_REQUEST]) {
auto return_point = _ctx.get_return_line();
line_num_t line = return_point.first;
return_stmt_id = return_point.second;
_ctx.flag.set(rt_prog_ctx_t::FLG_RETURN_REQUEST, false);
// If checkpoint enabled and line is zero
// it means we ware executing a function call (in another stack
// context) and we have to return to the main program
if (_function_call && line == 0) {
break;
}
auto jump = _prog_line.find(line);
if (jump == _prog_line.end()) {
if (line) {
std::string err = "Runtime error. ";
err += "Cannot return to line ";
err += nu::to_string(prog_ptr->first);
err += ": line " + nu::to_string(line);
err += " not found.";
throw exception_t(err);
}
else {
std::string err = "Runtime error.";
throw exception_t(err);
}
}
if (jump == _prog_line.end()) {
break;
}
prog_ptr = jump;
}
else if (_ctx.flag[rt_prog_ctx_t::FLG_JUMP_REQUEST]) {
line_num_t line = _ctx.goingto_pc.get_line();
auto jump = _prog_line.find(line);
return_stmt_id = 0;
_ctx.go_to_next(); // ack goto instruction
if (jump == _prog_line.end()) {
if (line) {
std::string err = "Runtime error at line ";
err += nu::to_string(prog_ptr->first);
err += ": line " + nu::to_string(line);
err += " not found.";
throw exception_t(err);
}
else {
std::string err = "Runtime error.";
throw exception_t(err);
}
}
prog_ptr = jump;
}
else if (_ctx.flag[rt_prog_ctx_t::FLG_SKIP_TILL_NEXT]) {
auto flg = _ctx.flag.get(rt_prog_ctx_t::FLG_SKIP_TILL_NEXT);
goto_end_block(static_cast<prog_line_iterator_t&>(prog_ptr),
stmt_t::stmt_cl_t::FOR_BEGIN, stmt_t::stmt_cl_t::FOR_END, flg);
_ctx.flag.set(rt_prog_ctx_t::FLG_SKIP_TILL_NEXT, flg);
}
if (prog_ptr != _prog_line.end() && _ctx.step_mode_active) {
auto& breakp = prog_ptr->second.second;
breakp.single_step_break_point = true;
}
}
bool end_flg = _ctx.flag[rt_prog_ctx_t::FLG_END_REQUEST];
_ctx.flag.set(rt_prog_ctx_t::FLG_END_REQUEST, false);
NU_TRACE_CTX(_ctx);
if (_function_call) {
_ctx.flag = cp_data.flag;
_ctx.goingto_pc = cp_data.goingto_pc;
_ctx.runtime_pc = cp_data.runtime_pc;
_ctx.return_stack = cp_data.return_stack;
// Propagate end-program flag
_ctx.flag.set(rt_prog_ctx_t::FLG_END_REQUEST, end_flg);
}
return prog_ptr != _prog_line.end();
}
/* -------------------------------------------------------------------------- */
bool program_t::run(
const std::string& name, const std::vector<expr_any_t::handle_t>& args)
{
// Convert args in the stmt_call_t's argument list
//
arg_list_t arg_list;
for (auto& arg : args) {
variant_t value = arg->eval(_ctx);
expr_any_t::handle_t hvalue = std::make_shared<expr_literal_t>(value);
arg_list.push_back(std::make_pair(
hvalue, '\0' /*0 is a dummy value, unused in this context*/));
}
// Create a call-able object
stmt_call_t call(arg_list, name, _ctx, true);
// Create a CALL-statement
call.run(_ctx, 0);
// Retrieve the function prototype
auto prototype = _ctx.proc_prototypes.data.find(name);
syntax_error_if(prototype == _ctx.proc_prototypes.data.end(),
"Cannot execute function " + name + ", prototype not found");
// Finally executes the function
return run(prototype->second.first.get_line());
}
/* -------------------------------------------------------------------------- */
} // namespace nu
| 27.487805 | 80 | 0.505501 | [
"object",
"vector"
] |
2c0b1e3f865e485ad5caa672d915d3f38b190cc8 | 3,869 | cc | C++ | main/lsp/LSPInput.cc | judocode/sorbet | fc1ee942d9dfe0903268063f1a300d4f7cf399e8 | [
"Apache-2.0"
] | 3,269 | 2019-06-20T17:10:46.000Z | 2022-03-31T15:00:37.000Z | main/lsp/LSPInput.cc | judocode/sorbet | fc1ee942d9dfe0903268063f1a300d4f7cf399e8 | [
"Apache-2.0"
] | 2,812 | 2019-06-20T17:23:04.000Z | 2022-03-31T22:57:17.000Z | main/lsp/LSPInput.cc | judocode/sorbet | fc1ee942d9dfe0903268063f1a300d4f7cf399e8 | [
"Apache-2.0"
] | 440 | 2019-06-20T18:12:40.000Z | 2022-03-30T23:43:39.000Z | #include "main/lsp/LSPInput.h"
#include "main/lsp/LSPMessage.h"
#include "spdlog/spdlog.h"
#include <iterator>
using namespace std;
namespace sorbet::realmain::lsp {
LSPFDInput::LSPFDInput(shared_ptr<spdlog::logger> logger, int inputFd) : logger(move(logger)), inputFd(inputFd) {}
LSPInput::ReadOutput LSPFDInput::read(int timeoutMs) {
int length = -1;
string allRead;
{
// Break and return if a timeout occurs. Bound loop to prevent infinite looping here. There's typically only two
// lines in a header.
for (int i = 0; i < 10; i += 1) {
auto maybeLine = FileOps::readLineFromFd(inputFd, buffer, timeoutMs);
if (maybeLine.result != FileOps::ReadResult::Success) {
// Line not read. Abort. Store what was read thus far back into buffer
// for use in next call to function.
buffer = absl::StrCat(allRead, buffer);
return ReadOutput{maybeLine.result, nullptr};
}
const string &line = *maybeLine.output;
absl::StrAppend(&allRead, line, "\n");
if (line == "\r") {
// End of headers.
break;
}
sscanf(line.c_str(), "Content-Length: %i\r", &length);
}
logger->trace("final raw read: {}, length: {}", allRead, length);
}
if (length < 0) {
logger->trace("No \"Content-Length: %i\" header found.");
// Throw away what we've read and start over.
return ReadOutput{FileOps::ReadResult::Timeout, nullptr};
}
if (buffer.length() < length) {
// Need to read more.
int moreNeeded = length - buffer.length();
vector<char> buf(moreNeeded);
int result = FileOps::readFd(inputFd, buf);
if (result > 0) {
buffer.append(buf.begin(), buf.begin() + result);
}
if (result < 0) {
return ReadOutput{FileOps::ReadResult::ErrorOrEof, nullptr};
}
if (result != moreNeeded) {
// Didn't get enough data. Return read data to `buffer`.
buffer = absl::StrCat(allRead, buffer);
return ReadOutput{FileOps::ReadResult::Timeout, nullptr};
}
}
ENFORCE(buffer.length() >= length);
string json = buffer.substr(0, length);
buffer.erase(0, length);
logger->debug("Read: {}\n", json);
return ReadOutput{FileOps::ReadResult::Success, LSPMessage::fromClient(json)};
}
LSPInput::ReadOutput LSPProgrammaticInput::read(int timeoutMs) {
absl::MutexLock lock(&mtx);
if (closed && available.empty()) {
return ReadOutput{FileOps::ReadResult::ErrorOrEof, nullptr};
}
mtx.AwaitWithTimeout(
absl::Condition(
+[](deque<unique_ptr<LSPMessage>> *available) -> bool { return !available->empty(); }, &available),
absl::Milliseconds(timeoutMs));
if (available.empty()) {
return ReadOutput{FileOps::ReadResult::Timeout, nullptr};
}
auto msg = move(available.front());
available.pop_front();
return ReadOutput{FileOps::ReadResult::Success, move(msg)};
}
void LSPProgrammaticInput::write(unique_ptr<LSPMessage> message) {
absl::MutexLock lock(&mtx);
if (closed) {
Exception::raise("Cannot write to a closed input.");
}
available.push_back(move(message));
}
void LSPProgrammaticInput::write(vector<unique_ptr<LSPMessage>> messages) {
absl::MutexLock lock(&mtx);
if (closed) {
Exception::raise("Cannot write to a closed input.");
}
available.insert(available.end(), make_move_iterator(messages.begin()), make_move_iterator(messages.end()));
}
void LSPProgrammaticInput::close() {
absl::MutexLock lock(&mtx);
if (closed) {
Exception::raise("Input already ended.");
}
closed = true;
}
} // namespace sorbet::realmain::lsp
| 33.938596 | 120 | 0.607909 | [
"vector"
] |
2c0f4cb9d04749d092165736ca593aec897027bf | 23,887 | cpp | C++ | Cbc/Cbc/test/gamsTest.cpp | fadi-alkhoury/coin-or-cbc-with-cmake | b4a216118d8e773b694b44c5f27cd75a251cc2cb | [
"MIT"
] | null | null | null | Cbc/Cbc/test/gamsTest.cpp | fadi-alkhoury/coin-or-cbc-with-cmake | b4a216118d8e773b694b44c5f27cd75a251cc2cb | [
"MIT"
] | null | null | null | Cbc/Cbc/test/gamsTest.cpp | fadi-alkhoury/coin-or-cbc-with-cmake | b4a216118d8e773b694b44c5f27cd75a251cc2cb | [
"MIT"
] | null | null | null | // $Id: gamsTest.cpp 2483 2019-02-09 15:15:51Z unxusr $
// Copyright (C) 2008, Stefan Vigerske, International Business Machines
// Corporation and others. All Rights Reserved.
// This code is licensed under the terms of the Eclipse Public License (EPL).
#if defined(_MSC_VER)
// Turn off compiler warning about long names
#pragma warning(disable : 4786)
#endif
#include <cassert>
#include <iostream>
using namespace std;
#include "CoinHelperFunctions.hpp"
#include "CoinError.hpp"
#include "CbcSolver.hpp"
#include "CbcModel.hpp"
#include "CbcBranchActual.hpp" //for CbcSOS
#include "CbcBranchLotsize.hpp" //for CbcLotsize
#include "OsiClpSolverInterface.hpp"
#define testtol 1e-6
/** model sos1a from the GAMS test library
* http://www.gams.com/testlib/libhtml/sos1a.htm */
void sos1a(int &error_count, int &warning_count);
/** model sos2a from the GAMS test library
* http://www.gams.com/testlib/libhtml/sos2a.htm */
void sos2a(int &error_count, int &warning_count);
/** model semicon1 from the GAMS test library
* http://www.gams.com/testlib/libhtml/semicon1.htm */
void semicon1(int &error_count, int &warning_count);
/** model semiint1 from the GAMS test library
* http://www.gams.com/testlib/libhtml/semiint1.htm */
void semiint1(int &error_count, int &warning_count);
int main(int argc, const char *argv[])
{
WindowsErrorPopupBlocker();
// only in CoinUtils/trunk: WindowsErrorPopupBlocker();
int error_count = 0;
int warning_count = 0;
sos1a(error_count, warning_count);
cout << "\n***********************\n"
<< endl;
sos2a(error_count, warning_count);
cout << "\n***********************\n"
<< endl;
semicon1(error_count, warning_count);
cout << "\n***********************\n"
<< endl;
semiint1(error_count, warning_count);
cout << endl
<< "Finished - there have been " << error_count << " errors and " << warning_count << " warnings." << endl;
return error_count;
}
void sos1a(int &error_count, int &warning_count)
{
OsiClpSolverInterface solver1;
int numcols = 3;
int numrows = 1;
int nnz = 3;
CoinBigIndex *start = new int[numcols + 1];
int *index = new int[nnz];
double *value = new double[nnz];
double *collb = new double[numcols];
double *colub = new double[numcols];
double *obj = new double[numcols];
double *rowlb = new double[numrows];
double *rowub = new double[numrows];
// objective
obj[0] = .9;
obj[1] = 1.;
obj[2] = 1.1;
// column bounds
collb[0] = 0.;
colub[0] = .8;
collb[1] = 0.;
colub[1] = .6;
collb[2] = 0.;
colub[2] = .6;
// matrix
start[0] = 0;
index[0] = 0;
value[0] = 1.;
start[1] = 1;
index[1] = 0;
value[1] = 1.;
start[2] = 2;
index[2] = 0;
value[2] = 1.;
start[3] = 3;
// row bounds
rowlb[0] = -solver1.getInfinity();
rowub[0] = 1.;
solver1.loadProblem(numcols, numrows, start, index, value, collb, colub, obj, rowlb, rowub);
solver1.setObjSense(-1);
CbcSolverUsefulData data;
CbcModel model(solver1);
CbcMain0(model, data);
int which[3] = { 0, 1, 2 };
CbcObject *sosobject = new CbcSOS(&model, 3, which, NULL, 0, 1);
model.addObjects(1, &sosobject);
delete sosobject;
const char *argv2[] = { "gamstest_sos1a", "-solve", "-quit" };
CbcMain1(3, argv2, model, NULL, data);
cout << endl;
if (!model.isProvenOptimal()) {
cerr << "Error: Model sos1a not solved to optimality." << endl;
++error_count;
return; // other tests make no sense ---- memory leak here
}
OsiSolverInterface *solver = model.solver();
assert(solver);
cout << "Objective value model: " << model.getObjValue()
<< "\t solver: " << solver->getObjValue()
<< "\t expected: 0.72" << endl;
if (CoinAbs(model.getObjValue() - 0.72) > testtol || CoinAbs(solver->getObjValue() - 0.72) > testtol) {
cerr << "Error: Objective value incorrect." << endl;
++error_count;
}
cout << "Primal value variable 0 in model: " << model.bestSolution()[0]
<< "\t in solver: " << solver->getColSolution()[0]
<< "\t expected: 0.8" << endl;
if (CoinAbs(model.bestSolution()[0] - 0.8) > testtol || CoinAbs(solver->getColSolution()[0] - 0.8) > testtol) {
cerr << "Error: Primal value incorrect." << endl;
++error_count;
}
cout << "Primal value variable 1 in model: " << model.bestSolution()[1]
<< "\t in solver: " << solver->getColSolution()[1]
<< "\t expected: 0.0" << endl;
if (CoinAbs(model.bestSolution()[1]) > testtol || CoinAbs(solver->getColSolution()[1]) > testtol) {
cerr << "Error: Primal value incorrect." << endl;
++error_count;
}
cout << "Primal value variable 2 in model: " << model.bestSolution()[2]
<< "\t in solver: " << solver->getColSolution()[2]
<< "\t expected: 0.0" << endl;
if (CoinAbs(model.bestSolution()[2]) > testtol || CoinAbs(solver->getColSolution()[2]) > testtol) {
cerr << "Error: Primal value incorrect." << endl;
++error_count;
}
delete[] start;
delete[] index;
delete[] value;
delete[] collb;
delete[] colub;
delete[] obj;
delete[] rowlb;
delete[] rowub;
}
void sos2a(int &error_count, int &warning_count)
{
OsiClpSolverInterface solver1;
int numcols = 7; // w1, w2, w3, x, fx, fplus, fminus
int numrows = 5; // wsum, xdef, fxdef, gapplus, gapminus
int nnz = 15;
CoinBigIndex *start = new int[numcols + 1];
int *index = new int[nnz];
double *value = new double[nnz];
double *collb = new double[numcols];
double *colub = new double[numcols];
double *obj = new double[numcols];
double *rowlb = new double[numrows];
double *rowub = new double[numrows];
// objective
obj[0] = 0.;
obj[1] = 0.;
obj[2] = 0.;
obj[3] = 0.;
obj[4] = 0.;
obj[5] = 1.;
obj[6] = 1.;
// column bounds
collb[0] = 0.;
colub[0] = solver1.getInfinity();
collb[1] = 0.;
colub[1] = solver1.getInfinity();
collb[2] = 0.;
colub[2] = solver1.getInfinity();
collb[3] = -solver1.getInfinity();
colub[3] = solver1.getInfinity();
collb[4] = -solver1.getInfinity();
colub[4] = solver1.getInfinity();
collb[5] = 0.;
colub[5] = solver1.getInfinity();
collb[6] = 0.;
colub[6] = solver1.getInfinity();
// matrix
start[0] = 0;
index[0] = 0;
value[0] = 1.;
index[1] = 1;
value[1] = 1.;
index[2] = 2;
value[2] = 1.;
start[1] = 3;
index[3] = 0;
value[3] = 1.;
index[4] = 1;
value[4] = 2.;
index[5] = 2;
value[5] = 2.;
start[2] = 6;
index[6] = 0;
value[6] = 1.;
index[7] = 1;
value[7] = 3.;
index[8] = 2;
value[8] = 3.;
start[3] = 9;
index[9] = 1;
value[9] = -1.;
start[4] = 10;
index[10] = 2;
value[10] = -1.;
index[11] = 3;
value[11] = -1.;
index[12] = 4;
value[12] = 1.;
start[5] = 13;
index[13] = 3;
value[13] = 1.;
start[6] = 14;
index[14] = 4;
value[14] = 1.;
start[7] = 15;
// row bounds
rowlb[0] = 1.;
rowub[0] = 1.;
rowlb[1] = 0.;
rowub[1] = 0.;
rowlb[2] = 0.;
rowub[2] = 0.;
rowlb[3] = -1.3;
rowub[3] = solver1.getInfinity();
rowlb[4] = 1.3;
rowub[4] = solver1.getInfinity();
solver1.loadProblem(numcols, numrows, start, index, value, collb, colub, obj, rowlb, rowub);
double *primalval = new double[numcols];
double *redcost = new double[numcols];
double optvalue = solver1.getInfinity();
for (int testcase = 0; testcase < 2; ++testcase) {
switch (testcase) {
case 0:
solver1.setColLower(0, 0.);
optvalue = 0.;
primalval[0] = .7;
redcost[0] = 0.;
primalval[1] = .3;
redcost[1] = 0.;
primalval[2] = 0.;
redcost[2] = 0.;
primalval[3] = 1.3;
redcost[3] = 0.;
primalval[4] = 1.3;
redcost[4] = 0.;
primalval[5] = 0.;
redcost[5] = 1.;
primalval[6] = 0.;
redcost[6] = 1.;
break;
case 1:
solver1.setColLower(0, .8);
optvalue = 0.1;
primalval[0] = .8;
redcost[0] = 1.;
primalval[1] = .2;
redcost[1] = 0.;
primalval[2] = 0.;
redcost[2] = -1.;
primalval[3] = 1.2;
redcost[3] = 0.;
primalval[4] = 1.2;
redcost[4] = 0.;
primalval[5] = 0.;
redcost[5] = 1.;
primalval[6] = 0.1;
redcost[6] = 0.;
break;
}
CbcModel model(solver1);
CbcSolverUsefulData data;
CbcMain0(model, data);
int which[3] = { 0, 1, 2 };
CbcObject *sosobject = new CbcSOS(&model, 3, which, NULL, 0, 2);
model.addObjects(1, &sosobject);
delete sosobject;
const char *argv2[] = { "gamstest_sos2a", "-solve", "-quit" };
cout << "\nSolving sos2a model with w1 having lower bound " << solver1.getColLower()[0] << endl;
CbcMain1(3, argv2, model, NULL, data);
cout << endl;
if (!model.isProvenOptimal()) {
cerr << "Error: Model sos2a not solved to optimality." << endl;
++error_count;
continue; // other tests make no sense
}
OsiSolverInterface *solver = model.solver();
assert(solver);
cout << "Objective value model: " << model.getObjValue()
<< "\t solver: " << solver->getObjValue()
<< "\t expected: " << optvalue << endl;
if (CoinAbs(model.getObjValue() - optvalue) > testtol || CoinAbs(solver->getObjValue() - optvalue) > testtol) {
cerr << "Error: Objective value incorrect." << endl;
++error_count;
}
for (int i = 0; i < numcols; ++i) {
cout << "Primal value variable " << i << " in model: " << model.bestSolution()[i]
<< "\t in solver: " << solver->getColSolution()[i]
<< "\t expected: " << primalval[i]
<< endl;
if (CoinAbs(model.bestSolution()[i] - primalval[i]) > testtol || CoinAbs(solver->getColSolution()[i] - primalval[i]) > testtol) {
cerr << "Error: Primal value incorrect." << endl;
++error_count;
}
}
for (int i = 0; i < numcols; ++i) {
cout << "Reduced cost variable " << i << " in model: " << model.getReducedCost()[i]
<< "\t in solver: " << solver->getReducedCost()[i]
<< "\t expected: " << redcost[i]
<< endl;
if (CoinAbs(model.getReducedCost()[i] - redcost[i]) > testtol || CoinAbs(solver->getReducedCost()[i] - redcost[i]) > testtol) {
cerr << "Warning: Reduced cost incorrect." << endl;
++warning_count;
}
}
}
delete[] start;
delete[] index;
delete[] value;
delete[] collb;
delete[] colub;
delete[] obj;
delete[] rowlb;
delete[] rowub;
delete[] primalval;
delete[] redcost;
}
void semicon1(int &error_count, int &warning_count)
{
OsiClpSolverInterface solver1;
int numcols = 4; // s, pup, plo, x
int numrows = 3; // bigx, smallx, f
int nnz = 6;
CoinBigIndex *start = new int[numcols + 1];
int *index = new int[nnz];
double *value = new double[nnz];
double *collb = new double[numcols];
double *colub = new double[numcols];
double *obj = new double[numcols];
double *rowlb = new double[numrows];
double *rowub = new double[numrows];
// objective
obj[0] = 0;
obj[1] = 1.;
obj[2] = 1;
obj[3] = 0;
// column bounds
collb[0] = 0.;
colub[0] = 10.;
collb[1] = 0.;
colub[1] = solver1.getInfinity();
collb[2] = 0.;
colub[2] = solver1.getInfinity();
collb[3] = 0.;
colub[3] = solver1.getInfinity();
// matrix
start[0] = 0;
index[0] = 2;
value[0] = 1.;
start[1] = 1;
index[1] = 0;
value[1] = -1.;
start[2] = 2;
index[2] = 1;
value[2] = 1.;
start[3] = 3;
index[3] = 0;
value[3] = 1.;
index[4] = 1;
value[4] = 1.;
index[5] = 2;
value[5] = 1.;
start[4] = nnz;
// row bounds
rowlb[0] = -solver1.getInfinity();
rowub[0] = 8.9;
rowlb[1] = 8.9;
rowub[1] = solver1.getInfinity();
rowlb[2] = 10.;
rowub[2] = 10.;
solver1.loadProblem(numcols, numrows, start, index, value, collb, colub, obj, rowlb, rowub);
for (int testcase = 0; testcase < 5; ++testcase) {
CbcModel model(solver1);
CbcSolverUsefulData data;
CbcMain0(model, data);
double points[4] = { 0., 0., 0., 10. };
double objval;
double primalval[4];
double redcost[4];
double row2marg;
redcost[1] = 1.0;
redcost[2] = 1.0;
redcost[3] = 0.0;
switch (testcase) {
case 0:
points[2] = 0.;
objval = 0.;
primalval[0] = 1.1;
primalval[1] = 0.0;
primalval[2] = 0.0;
primalval[3] = 8.9;
redcost[0] = 0.0;
row2marg = 0.0;
break;
case 1:
points[2] = 1.;
objval = 0.;
primalval[0] = 1.1;
primalval[1] = 0.0;
primalval[2] = 0.0;
primalval[3] = 8.9;
redcost[0] = 0.0;
row2marg = 0.0;
break;
case 2:
points[2] = 1.5;
objval = 0.4;
primalval[0] = 1.5;
primalval[1] = 0.0;
primalval[2] = 0.4;
primalval[3] = 8.5;
redcost[0] = 1.0;
row2marg = -1.0;
break;
case 3:
points[2] = 2.1;
objval = 1.0;
primalval[0] = 2.1;
primalval[1] = 0.0;
primalval[2] = 1.0;
primalval[3] = 7.9;
redcost[0] = 1.0;
row2marg = -1.0;
break;
case 4:
points[2] = 2.8;
objval = 1.1;
primalval[0] = 0.0;
primalval[1] = 1.1;
primalval[2] = 0.0;
primalval[3] = 10.0;
redcost[0] = -1.0;
row2marg = 1.0;
break;
default: // to please the compile
redcost[0] = 0.;
row2marg = 0.;
objval = 0.;
}
CbcObject *semiconobject = new CbcLotsize(&model, 0, 2, points, true);
model.addObjects(1, &semiconobject);
delete semiconobject;
cout << "\nSolving semicon1 model for lotsize variable being either 0 or between " << points[2] << " and 10.\n"
<< endl;
const char *argv2[] = { "gamstest_semicon1", "-solve", "-quit" };
CbcMain1(3, argv2, model, NULL, data);
cout << endl;
if (!model.isProvenOptimal()) {
cerr << "Error: Model semicon1 not solved to optimality." << endl;
++error_count;
continue; // other tests make no sense
}
OsiSolverInterface *solver = model.solver();
assert(solver);
cout << "Objective value in model: " << model.getObjValue()
<< "\t in solver: " << solver->getObjValue()
<< "\t expected: " << objval << endl;
if (CoinAbs(model.getObjValue() - objval) > testtol || CoinAbs(solver->getObjValue() - objval) > testtol) {
cerr << "Error: Objective value incorrect." << endl;
++error_count;
}
for (int i = 0; i < numcols; ++i) {
cout << "Primal value variable " << i << " in model: " << model.bestSolution()[i]
<< "\t in solver: " << solver->getColSolution()[i]
<< "\t expected: " << primalval[i]
<< endl;
if (CoinAbs(model.bestSolution()[i] - primalval[i]) > testtol || CoinAbs(solver->getColSolution()[i] - primalval[i]) > testtol) {
cerr << "Error: Primal value incorrect." << endl;
++error_count;
}
}
cout << "Reduced cost variable " << 0 << " in model: " << model.getReducedCost()[0]
<< "\t in solver: " << solver->getReducedCost()[0]
<< "\t expected: " << redcost[0]
<< endl;
if (CoinAbs(model.getReducedCost()[0] - redcost[0]) > testtol || CoinAbs(solver->getReducedCost()[0] - redcost[0]) > testtol) {
cerr << "Warning: Reduced cost incorrect." << endl;
++warning_count;
}
cout << "Reduced cost variable " << 3 << " in model: " << model.getReducedCost()[3]
<< "\t in solver: " << solver->getReducedCost()[3]
<< "\t expected: " << redcost[3]
<< endl;
if (CoinAbs(model.getReducedCost()[3] - redcost[3]) > testtol || CoinAbs(solver->getReducedCost()[3] - redcost[3]) > testtol) {
cerr << "Warning: Reduced cost incorrect." << endl;
++warning_count;
}
cout << "Reduced cost variable 1 plus - dual of row 0 in model: " << model.getReducedCost()[1] - model.getRowPrice()[0]
<< "\t expected: " << redcost[1]
<< endl;
if (CoinAbs(model.getReducedCost()[1] - model.getRowPrice()[0] - redcost[1]) > testtol) {
cerr << "Warning: Reduced cost or row margin incorrect." << endl;
++warning_count;
}
cout << "Reduced cost variable 2 plus + dual of row 1 in model: " << model.getReducedCost()[2] + model.getRowPrice()[1]
<< "\t expected: " << redcost[2]
<< endl;
if (CoinAbs(model.getReducedCost()[2] + model.getRowPrice()[1] - redcost[2]) > testtol) {
cerr << "Warning: Reduced cost or row margin incorrect." << endl;
++warning_count;
}
cout << "Row 2 marginal (price) in model: " << model.getRowPrice()[2]
<< "\t in solver: " << solver->getRowPrice()[2]
<< "\t expected: " << row2marg << endl;
if (CoinAbs(model.getRowPrice()[2] - row2marg) > testtol || CoinAbs(solver->getRowPrice()[2] - row2marg) > testtol) {
cerr << "Warning: Row price incorrect." << endl;
++warning_count;
}
}
delete[] start;
delete[] index;
delete[] value;
delete[] collb;
delete[] colub;
delete[] obj;
delete[] rowlb;
delete[] rowub;
}
void semiint1(int &error_count, int &warning_count)
{
OsiClpSolverInterface solver1;
int numcols = 4; // s, pup, plo, x
int numrows = 3; // bigx, smallx, f
int nnz = 6;
CoinBigIndex *start = new int[numcols + 1];
int *index = new int[nnz];
double *value = new double[nnz];
double *collb = new double[numcols];
double *colub = new double[numcols];
double *obj = new double[numcols];
double *rowlb = new double[numrows];
double *rowub = new double[numrows];
// objective
obj[0] = 0;
obj[1] = 1.;
obj[2] = 1;
obj[3] = 0;
// column bounds
collb[0] = 0.;
colub[0] = 10.;
collb[1] = 0.;
colub[1] = solver1.getInfinity();
collb[2] = 0.;
colub[2] = solver1.getInfinity();
collb[3] = 0.;
colub[3] = solver1.getInfinity();
// matrix
start[0] = 0;
index[0] = 2;
value[0] = 1.;
start[1] = 1;
index[1] = 0;
value[1] = -1.;
start[2] = 2;
index[2] = 1;
value[2] = 1.;
start[3] = 3;
index[3] = 0;
value[3] = 1.;
index[4] = 1;
value[4] = 1.;
index[5] = 2;
value[5] = 1.;
start[4] = nnz;
// row bounds
rowlb[0] = -solver1.getInfinity();
rowub[0] = 7.9;
rowlb[1] = 7.9;
rowub[1] = solver1.getInfinity();
rowlb[2] = 10.;
rowub[2] = 10.;
solver1.loadProblem(numcols, numrows, start, index, value, collb, colub, obj, rowlb, rowub);
solver1.setInteger(0);
for (int testcase = 0; testcase < 6; ++testcase) {
CbcModel model(solver1);
CbcSolverUsefulData data;
CbcMain0(model, data);
double points[10];
points[0] = 0.;
int nrpoints = 0;
double objval;
double primalval[4];
double redcost[4];
double row2marg;
redcost[2] = 1.0;
redcost[3] = 0.0;
switch (testcase) {
case 0:
nrpoints = 0; // pure integer case
objval = 0.1;
primalval[0] = 2.0;
primalval[1] = 0.1;
primalval[2] = 0.0;
primalval[3] = 8;
redcost[0] = -1.0;
redcost[1] = 0.0;
row2marg = 1.0;
break;
case 1:
nrpoints = 0; // pure integer case too
objval = 0.1;
primalval[0] = 2.0;
primalval[1] = 0.1;
primalval[2] = 0.0;
primalval[3] = 8.0;
redcost[0] = -1.0;
redcost[1] = 0.0;
row2marg = 1.0;
break;
case 2:
for (nrpoints = 1; nrpoints < 10; ++nrpoints)
points[nrpoints] = nrpoints + 1;
objval = 0.1;
primalval[0] = 2.0;
primalval[1] = 0.1;
primalval[2] = 0.0;
primalval[3] = 8.0;
redcost[0] = -1.0;
redcost[1] = 0.0;
row2marg = 1.0;
break;
case 3:
for (nrpoints = 1; nrpoints < 9; ++nrpoints)
points[nrpoints] = nrpoints + 2;
objval = 0.9;
primalval[0] = 3.0;
primalval[1] = 0.0;
primalval[2] = 0.9;
primalval[3] = 7.0;
redcost[0] = 1.0;
redcost[1] = 1.0;
row2marg = -1.0;
break;
case 4:
for (nrpoints = 1; nrpoints < 8; ++nrpoints)
points[nrpoints] = nrpoints + 3;
objval = 1.9;
primalval[0] = 4.0;
primalval[1] = 0.0;
primalval[2] = 1.9;
primalval[3] = 6.0;
redcost[0] = 1.0;
redcost[1] = 1.0;
row2marg = -1.0;
break;
case 5:
for (nrpoints = 1; nrpoints < 7; ++nrpoints)
points[nrpoints] = nrpoints + 4;
objval = 2.1;
primalval[0] = 0.0;
primalval[1] = 2.1;
primalval[2] = 0.0;
primalval[3] = 10.0;
redcost[0] = -1.0;
redcost[1] = 0.0;
row2marg = 1.0;
break;
default: // to please the compile
redcost[0] = 0.;
redcost[1] = 0.;
row2marg = 0.;
objval = 0.;
}
if (nrpoints) {
CbcObject *semiintobject = new CbcLotsize(&model, 0, nrpoints, points);
model.addObjects(1, &semiintobject);
delete semiintobject;
}
cout << "\nSolving semiint1 model for integer lotsize variable being either 0 or between " << points[2] << " and 10.\n"
<< endl;
const char *argv2[] = { "gamstest_semiint1", "-solve", "-quit" };
CbcMain1(3, argv2, model, NULL, data);
cout << endl;
if (!model.isProvenOptimal()) {
cerr << "Error: Model semiint1 not solved to optimality." << endl;
++error_count;
continue; // other tests make no sense
}
OsiSolverInterface *solver = model.solver();
assert(solver);
cout << "Objective value in model: " << model.getObjValue()
<< "\t in solver: " << solver->getObjValue()
<< "\t expected: " << objval << endl;
if (CoinAbs(model.getObjValue() - objval) > testtol || CoinAbs(solver->getObjValue() - objval) > testtol) {
cerr << "Error: Objective value incorrect." << endl;
++error_count;
}
for (int i = 0; i < numcols; ++i) {
cout << "Primal value variable " << i << " in model: " << model.bestSolution()[i]
<< "\t in solver: " << solver->getColSolution()[i]
<< "\t expected: " << primalval[i]
<< endl;
if (CoinAbs(model.bestSolution()[i] - primalval[i]) > testtol || CoinAbs(solver->getColSolution()[i] - primalval[i]) > testtol) {
cerr << "Error: Primal value incorrect." << endl;
++error_count;
}
}
cout << "Reduced cost variable " << 0 << " in model: " << model.getReducedCost()[0]
<< "\t in solver: " << solver->getReducedCost()[0]
<< "\t expected: " << redcost[0]
<< endl;
if (CoinAbs(model.getReducedCost()[0] - redcost[0]) > testtol || CoinAbs(solver->getReducedCost()[0] - redcost[0]) > testtol) {
cerr << "Warning: Reduced cost incorrect." << endl;
++warning_count;
}
cout << "Reduced cost variable " << 3 << " in model: " << model.getReducedCost()[3]
<< "\t in solver: " << solver->getReducedCost()[3]
<< "\t expected: " << redcost[3]
<< endl;
if (CoinAbs(model.getReducedCost()[3] - redcost[3]) > testtol || CoinAbs(solver->getReducedCost()[3] - redcost[3]) > testtol) {
cerr << "Warning: Reduced cost incorrect." << endl;
++warning_count;
}
cout << "Row 2 marginal (price) in model: " << model.getRowPrice()[2]
<< "\t in solver: " << solver->getRowPrice()[2]
<< "\t expected: " << row2marg << endl;
if (CoinAbs(model.getRowPrice()[2] - row2marg) > testtol || CoinAbs(solver->getRowPrice()[2] - row2marg) > testtol) {
cerr << "Warning: Row price incorrect." << endl;
++warning_count;
}
cout << "Row 2 marginal (price) in model: " << model.getRowPrice()[2]
<< "\t in solver: " << solver->getRowPrice()[2]
<< "\t expected: " << row2marg << endl;
if (CoinAbs(model.getRowPrice()[2] - row2marg) > testtol || CoinAbs(solver->getRowPrice()[2] - row2marg) > testtol) {
cerr << "Warning: Row price incorrect." << endl;
++warning_count;
}
}
delete[] start;
delete[] index;
delete[] value;
delete[] collb;
delete[] colub;
delete[] obj;
delete[] rowlb;
delete[] rowub;
}
| 30.429299 | 135 | 0.564826 | [
"model"
] |
2c133bc93012b7d4d65a35766913477bfa5e5a75 | 5,627 | cpp | C++ | Plugins/SciberQuestToolKit/eigen-3.0.3/eigen-eigen-3.0.3/unsupported/test/sparse_llt.cpp | mathstuf/ParaView | e867e280545ada10c4ed137f6a966d9d2f3db4cb | [
"Apache-2.0"
] | 1 | 2020-05-21T20:20:59.000Z | 2020-05-21T20:20:59.000Z | Plugins/SciberQuestToolKit/eigen-3.0.3/eigen-eigen-3.0.3/unsupported/test/sparse_llt.cpp | mathstuf/ParaView | e867e280545ada10c4ed137f6a966d9d2f3db4cb | [
"Apache-2.0"
] | null | null | null | Plugins/SciberQuestToolKit/eigen-3.0.3/eigen-eigen-3.0.3/unsupported/test/sparse_llt.cpp | mathstuf/ParaView | e867e280545ada10c4ed137f6a966d9d2f3db4cb | [
"Apache-2.0"
] | 5 | 2016-04-14T13:42:37.000Z | 2021-05-22T04:59:42.000Z | // This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2010 Gael Guennebaud <g.gael@free.fr>
//
// Eigen 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 3 of the License, or (at your option) any later version.
//
// Alternatively, 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.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
#include "sparse.h"
#include <Eigen/SparseExtra>
#ifdef EIGEN_CHOLMOD_SUPPORT
#include <Eigen/CholmodSupport>
#endif
template<typename Scalar> void sparse_llt(int rows, int cols)
{
double density = (std::max)(8./(rows*cols), 0.01);
typedef Matrix<Scalar,Dynamic,Dynamic> DenseMatrix;
typedef Matrix<Scalar,Dynamic,1> DenseVector;
// TODO fix the issue with complex (see SparseLLT::solveInPlace)
SparseMatrix<Scalar> m2(rows, cols);
DenseMatrix refMat2(rows, cols);
DenseVector b = DenseVector::Random(cols);
DenseVector ref_x(cols), x(cols);
DenseMatrix B = DenseMatrix::Random(rows,cols);
DenseMatrix ref_X(rows,cols), X(rows,cols);
initSparse<Scalar>(density, refMat2, m2, ForceNonZeroDiag|MakeLowerTriangular, 0, 0);
for(int i=0; i<rows; ++i)
m2.coeffRef(i,i) = refMat2(i,i) = internal::abs(internal::real(refMat2(i,i)));
ref_x = refMat2.template selfadjointView<Lower>().llt().solve(b);
if (!NumTraits<Scalar>::IsComplex)
{
x = b;
SparseLLT<SparseMatrix<Scalar> > (m2).solveInPlace(x);
VERIFY(ref_x.isApprox(x,test_precision<Scalar>()) && "LLT: default");
}
#ifdef EIGEN_CHOLMOD_SUPPORT
// legacy API
{
// Cholmod, as configured in CholmodSupport.h, only supports self-adjoint matrices
SparseMatrix<Scalar> m3 = m2.adjoint()*m2;
DenseMatrix refMat3 = refMat2.adjoint()*refMat2;
ref_x = refMat3.template selfadjointView<Lower>().llt().solve(b);
x = b;
SparseLLT<SparseMatrix<Scalar>, Cholmod>(m3).solveInPlace(x);
VERIFY((m3*x).isApprox(b,test_precision<Scalar>()) && "LLT legacy: cholmod solveInPlace");
x = SparseLLT<SparseMatrix<Scalar>, Cholmod>(m3).solve(b);
VERIFY(ref_x.isApprox(x,test_precision<Scalar>()) && "LLT legacy: cholmod solve");
}
// new API
{
// Cholmod, as configured in CholmodSupport.h, only supports self-adjoint matrices
SparseMatrix<Scalar> m3 = m2 * m2.adjoint(), m3_lo(rows,rows), m3_up(rows,rows);
DenseMatrix refMat3 = refMat2 * refMat2.adjoint();
m3_lo.template selfadjointView<Lower>().rankUpdate(m2,0);
m3_up.template selfadjointView<Upper>().rankUpdate(m2,0);
// with a single vector as the rhs
ref_x = refMat3.template selfadjointView<Lower>().llt().solve(b);
x = CholmodDecomposition<SparseMatrix<Scalar>, Lower>(m3).solve(b);
VERIFY(ref_x.isApprox(x,test_precision<Scalar>()) && "LLT: cholmod solve, single dense rhs");
x = CholmodDecomposition<SparseMatrix<Scalar>, Upper>(m3).solve(b);
VERIFY(ref_x.isApprox(x,test_precision<Scalar>()) && "LLT: cholmod solve, single dense rhs");
x = CholmodDecomposition<SparseMatrix<Scalar>, Lower>(m3_lo).solve(b);
VERIFY(ref_x.isApprox(x,test_precision<Scalar>()) && "LLT: cholmod solve, single dense rhs");
x = CholmodDecomposition<SparseMatrix<Scalar>, Upper>(m3_up).solve(b);
VERIFY(ref_x.isApprox(x,test_precision<Scalar>()) && "LLT: cholmod solve, single dense rhs");
// with multiple rhs
ref_X = refMat3.template selfadjointView<Lower>().llt().solve(B);
#ifndef EIGEN_DEFAULT_TO_ROW_MAJOR
// TODO make sure the API is properly documented about this fact
X = CholmodDecomposition<SparseMatrix<Scalar>, Lower>(m3).solve(B);
VERIFY(ref_X.isApprox(X,test_precision<Scalar>()) && "LLT: cholmod solve, multiple dense rhs");
X = CholmodDecomposition<SparseMatrix<Scalar>, Upper>(m3).solve(B);
VERIFY(ref_X.isApprox(X,test_precision<Scalar>()) && "LLT: cholmod solve, multiple dense rhs");
#endif
// with a sparse rhs
SparseMatrix<Scalar> spB(rows,cols), spX(rows,cols);
B.diagonal().array() += 1;
spB = B.sparseView(0.5,1);
ref_X = refMat3.template selfadjointView<Lower>().llt().solve(DenseMatrix(spB));
spX = CholmodDecomposition<SparseMatrix<Scalar>, Lower>(m3).solve(spB);
VERIFY(ref_X.isApprox(spX.toDense(),test_precision<Scalar>()) && "LLT: cholmod solve, multiple sparse rhs");
spX = CholmodDecomposition<SparseMatrix<Scalar>, Upper>(m3).solve(spB);
VERIFY(ref_X.isApprox(spX.toDense(),test_precision<Scalar>()) && "LLT: cholmod solve, multiple sparse rhs");
}
#endif
}
void test_sparse_llt()
{
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_1(sparse_llt<double>(8, 8) );
int s = internal::random<int>(1,300);
CALL_SUBTEST_2(sparse_llt<std::complex<double> >(s,s) );
CALL_SUBTEST_1(sparse_llt<double>(s,s) );
}
} | 40.192857 | 114 | 0.691665 | [
"vector"
] |
2c15bf672d3cc3a9383fa0a6fac3374b960a5f46 | 936 | cpp | C++ | test/yj_vertex_add_path_sum.test.cpp | kmyk/rsk0315-library | 344f8f8c6c8c8951637154d6cb87cfb3dbc50376 | [
"MIT"
] | 7 | 2020-03-30T11:05:43.000Z | 2022-03-24T06:18:38.000Z | test/yj_vertex_add_path_sum.test.cpp | kmyk/rsk0315-library | 344f8f8c6c8c8951637154d6cb87cfb3dbc50376 | [
"MIT"
] | null | null | null | test/yj_vertex_add_path_sum.test.cpp | kmyk/rsk0315-library | 344f8f8c6c8c8951637154d6cb87cfb3dbc50376 | [
"MIT"
] | 2 | 2021-07-27T05:48:29.000Z | 2022-03-24T06:18:40.000Z | #define PROBLEM "https://judge.yosupo.jp/problem/vertex_add_path_sum"
#include <cstdint>
#include <cstdio>
#include <utility>
#include <vector>
#include "Graph/hl_decomposition.cpp"
#include "DataStructure/basic_segment_tree.cpp"
int main() {
size_t n, q;
scanf("%zu %zu", &n, &q);
std::vector<intmax_t> a(n);
for (auto& ai: a) scanf("%jd", &ai);
std::vector<std::pair<size_t, size_t>> es;
es.reserve(n-1);
for (size_t i = 1; i < n; ++i) {
size_t u, v;
scanf("%zu %zu", &u, &v);
es.emplace_back(u, v);
}
hl_decomposed_tree<basic_segment_tree<intmax_t>, value_on_vertex_tag> g(a, es);
for (size_t i = 0; i < q; ++i) {
int t;
scanf("%d", &t);
if (t == 0) {
size_t p;
intmax_t x;
scanf("%zu %jd", &p, &x);
a[p] += x;
g.set(p, a[p]);
} else if (t == 1) {
size_t u, v;
scanf("%zu %zu", &u, &v);
printf("%jd\n", g.fold(u, v));
}
}
}
| 21.272727 | 81 | 0.548077 | [
"vector"
] |
2c1a4094487db886913f02e376fefe5b84fe2dc5 | 2,400 | cc | C++ | console_display_buffer.cc | lyrahgames/tree-traversal | 60cb2b6cb8aa51269f4e4a521b6c88339959ee49 | [
"MIT"
] | null | null | null | console_display_buffer.cc | lyrahgames/tree-traversal | 60cb2b6cb8aa51269f4e4a521b6c88339959ee49 | [
"MIT"
] | null | null | null | console_display_buffer.cc | lyrahgames/tree-traversal | 60cb2b6cb8aa51269f4e4a521b6c88339959ee49 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <utility>
#include <vector>
using namespace std;
template <typename ForwardIt, typename RandomIt, typename KeyFunction>
void counting_sort(
ForwardIt first, ForwardIt last, RandomIt out, KeyFunction key,
decltype(std::declval<KeyFunction>()(*std::declval<ForwardIt>())) min_hint,
decltype(min_hint) max_hint) {
const auto offset = min_hint;
const auto size = max_hint - min_hint + 1;
int counts[size]{}; // this int is an independent implementation detail
for (auto it = first; it != last; ++it) ++counts[key(*it) - offset];
auto sum = counts[0];
counts[0] = 0;
for (int i = 1; i < static_cast<int>(size); ++i) {
auto tmp = sum;
sum += counts[i];
counts[i] = tmp;
}
for (auto it = first; it != last; ++it)
out[counts[key(*it) - offset]++] = *it;
}
template <typename ForwardIt, typename RandomIt, typename KeyFunction>
void counting_sort(ForwardIt first, ForwardIt last, RandomIt out,
KeyFunction key = {}) {
auto it = first;
auto min = key(*it);
auto max = key(*it);
for (; it != last; ++it) {
max = std::max(max, key(*it));
min = std::min(min, key(*it));
}
counting_sort(first, last, out, key, min, max);
}
struct console_display_buffer {
struct element {
element() = default;
element(int r, int c, const string& t) : row{r}, column{c}, text{t} {}
element(int r, int c, string&& t) : row{r}, column{c}, text{move(t)} {}
int row;
int column;
string text;
};
vector<element> data;
template <typename... Args>
console_display_buffer& emplace(Args&&... args) {
data.emplace_back(std::forward<Args>(args)...);
return *this;
}
};
ostream& operator<<(ostream& os, const console_display_buffer& buffer) {
auto tmp = buffer.data;
counting_sort(begin(buffer.data), end(buffer.data), begin(tmp),
[](const auto& e) { return e.row; });
auto row = 0;
auto column = 0;
for (const auto& e : tmp) {
if (row != e.row) {
os << string(e.row - row, '\n');
row = e.row;
column = 0;
}
os << string(e.column, ' ') << e.text;
column = e.column + size(e.text);
}
return os << '\n';
}
int main() {
console_display_buffer buffer;
buffer.emplace(0, 0, "----")
.emplace(4, 0, "----")
.emplace(2, 2, "xxx")
.emplace(1, 1, "hello");
cout << buffer;
} | 26.086957 | 79 | 0.600417 | [
"vector"
] |
2c269c830a5e678cbcaa96efee53240bc7e1e761 | 2,302 | cpp | C++ | aws-cpp-sdk-ds/source/model/Computer.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-ds/source/model/Computer.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2021-10-14T16:57:00.000Z | 2021-10-18T10:47:24.000Z | aws-cpp-sdk-ds/source/model/Computer.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2022-03-23T15:17:18.000Z | 2022-03-23T15:17:18.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/ds/model/Computer.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace DirectoryService
{
namespace Model
{
Computer::Computer() :
m_computerIdHasBeenSet(false),
m_computerNameHasBeenSet(false),
m_computerAttributesHasBeenSet(false)
{
}
Computer::Computer(JsonView jsonValue) :
m_computerIdHasBeenSet(false),
m_computerNameHasBeenSet(false),
m_computerAttributesHasBeenSet(false)
{
*this = jsonValue;
}
Computer& Computer::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("ComputerId"))
{
m_computerId = jsonValue.GetString("ComputerId");
m_computerIdHasBeenSet = true;
}
if(jsonValue.ValueExists("ComputerName"))
{
m_computerName = jsonValue.GetString("ComputerName");
m_computerNameHasBeenSet = true;
}
if(jsonValue.ValueExists("ComputerAttributes"))
{
Array<JsonView> computerAttributesJsonList = jsonValue.GetArray("ComputerAttributes");
for(unsigned computerAttributesIndex = 0; computerAttributesIndex < computerAttributesJsonList.GetLength(); ++computerAttributesIndex)
{
m_computerAttributes.push_back(computerAttributesJsonList[computerAttributesIndex].AsObject());
}
m_computerAttributesHasBeenSet = true;
}
return *this;
}
JsonValue Computer::Jsonize() const
{
JsonValue payload;
if(m_computerIdHasBeenSet)
{
payload.WithString("ComputerId", m_computerId);
}
if(m_computerNameHasBeenSet)
{
payload.WithString("ComputerName", m_computerName);
}
if(m_computerAttributesHasBeenSet)
{
Array<JsonValue> computerAttributesJsonList(m_computerAttributes.size());
for(unsigned computerAttributesIndex = 0; computerAttributesIndex < computerAttributesJsonList.GetLength(); ++computerAttributesIndex)
{
computerAttributesJsonList[computerAttributesIndex].AsObject(m_computerAttributes[computerAttributesIndex].Jsonize());
}
payload.WithArray("ComputerAttributes", std::move(computerAttributesJsonList));
}
return payload;
}
} // namespace Model
} // namespace DirectoryService
} // namespace Aws
| 23.489796 | 138 | 0.753692 | [
"model"
] |
2c2796dc372110745665afd1bc807938562b2433 | 8,339 | cpp | C++ | xcore/Map.cpp | blazeroni/foxc | c143edb63b90a6c500193ea5eac95f9c89e3c4ff | [
"MIT"
] | null | null | null | xcore/Map.cpp | blazeroni/foxc | c143edb63b90a6c500193ea5eac95f9c89e3c4ff | [
"MIT"
] | null | null | null | xcore/Map.cpp | blazeroni/foxc | c143edb63b90a6c500193ea5eac95f9c89e3c4ff | [
"MIT"
] | null | null | null | #include "includes.h"
#include "Map.h"
#include "Wall.h"
#include "MapTile.h"
#include "Terrain.h"
#include "Event.h"
#include "MapLoadEvent.h"
#include "UnsupportedOperationException.h"
namespace xcore
{
map<string, TerrainType> Map::_terrainMap;
spMap Map::makeMap(spEntityFactory factory)
{
return makeMapHelper<Map>(factory);
}
Map::Map(spEntityFactory factory) :
_factory(factory),
_width(0),
_height(0),
_name("")
{
static bool mapped = false;
if (!mapped)
{
_terrainMap["grass"] = GRASS;
_terrainMap["water"] = WATER;
_terrainMap["floor"] = FLOOR;
_terrainMap["snows"] = SNOWS;
mapped = true;
}
}
Map::~Map()
{
}
spMapTile Map::getTile(int x, int y) const
{
unsigned int index = y + (x * _height);
if (index < _mapTiles.size() && x >= 0 && x < _width && y >= 0 && y < _height)
{
return _mapTiles[index];
}
else
{
return spMapTile();
}
}
//vector<spMapTile> Map::getMapTiles()
//{
// return _mapTiles;
//}
//spMapTile Map::getMouseOverTile()
//{
// return _mouseOverTile;
//}
//void Map::updateMouseOverTile(Point offset)
//{
// Point mouse = Input::instance().getMousePosition();
// _mouseOverTile = getTile(mouse, offset);
//}
bool Map::load(string fileName)
{
_fileName = "";
try
{
ticpp::Document doc(fileName);
doc.LoadFile();
ticpp::Element* root = doc.FirstChildElement("map");
root->GetAttribute("name", &_name);
root->GetAttribute("width", &_width);
root->GetAttribute("height", &_height);
// empty the current map
_mapTiles.resize(0);
// make enough room for the current map size to avoid reallocations
_mapTiles.reserve(_width * _height);
int x = 0;
int y = 0;
string id;
string terrain;
uint16 startPlayer;
uint16 startPref;
map<string, spMapTile> idTileMap;
map<spMapTile, bool> walls;
map<spMapTile, bool> doors;
ticpp::Element* tiles = root->FirstChildElement("tiles");
ticpp::Iterator< ticpp::Element > child;
for ( child = tiles->FirstChildElement(); child != child.end(); child++ )
{
child->GetAttribute("id", &id);
child->GetAttribute("x", &x);
child->GetAttribute("y", &y);
child->GetAttribute("terrain", &terrain);
spMapTile tile = makeMapTile(_terrainMap[terrain], x, y);
child->GetAttributeOrDefault("startPlayer", &startPlayer, 0);
if (startPlayer != 0)
{
child->GetAttribute("startPref", &startPref);
_playerStartPrefs[startPlayer][startPref] = tile;
}
ticpp::Element* object = child->FirstChildElement(false);
if (object != NULL)
{
string type;
object->GetAttribute("type", &type);
if (type == "wall")
{
walls[tile] = true;
doors[tile] = false;
//tile->addObject(_factory->makeWall());
}
else if (type == "door")
{
walls[tile] = true;
doors[tile] = true;
// TODO replace w/ a real door
//tile->addObject(_factory->makeWall(WT_DOOR));
}
}
else
{
walls[tile] = false;
doors[tile] = false;
}
idTileMap[id] = tile;
populateTileNeighbors(tile);
_mapTiles.push_back(tile);
}
loadWalls(walls, doors);
}
catch (ticpp::Exception& e)
{
cout << e.m_details;
return false;
}
_fileName = fileName;
return true;
}
void Map::loadWalls(map<spMapTile, bool> walls, map<spMapTile, bool> doors)
{
map<spMapTile, bool>::iterator iter;
for (iter = walls.begin(); iter != walls.end(); ++iter)
{
if (iter->second == true)
{
WALL_TYPE type;
uint8 wallType = 0;
spMapTile temp = iter->first->getTileInDirection(Direction::NE);
if (temp.get() && walls[temp])
{
wallType |= WD_NE;
}
temp = iter->first->getTileInDirection(Direction::NW);
if (temp.get() && walls[temp])
{
wallType |= WD_NW;
}
temp = iter->first->getTileInDirection(Direction::SE);
if (temp.get() && walls[temp])
{
wallType |= WD_SE;
}
temp = iter->first->getTileInDirection(Direction::SW);
if (temp.get() && walls[temp])
{
wallType |= WD_SW;
}
type = WALL_TYPE(wallType);
if (doors[iter->first] == true)
{
iter->first->addObject(_factory->makeDoor(type));
}
else
{
iter->first->addObject(_factory->makeWall(type));
}
}
}
}
spMapTile Map::getPlayerStartPref(uint16 playerNum, uint16 startPref)
{
return _playerStartPrefs[playerNum][startPref];
}
spMapTile Map::getNextStartPref(uint16 playerNum)
{
map<int, spMapTile> tiles = _playerStartPrefs[playerNum];
spMapTile empty = spMapTile();
map<int, spMapTile>::iterator iter;
for (iter = tiles.begin(); iter != tiles.end(); ++iter)
{
if (!iter->second->hasUnit())
{
empty = iter->second;
break;
}
}
return empty;
}
spMapTile Map::makeMapTile(TerrainType type, int x, int y)
{
return MapTile::makeMapTile(type, x, y);
}
/*spWall Map::makeWall()
{
return spWall(new Wall());
}*/
void Map::populateTileNeighbors(spMapTile tile)
{
int x = tile->getX();
int y = tile->getY();
vector<const Direction*> directions = Direction::getAllDirections();
vector<const Direction*>::const_iterator iter;
for (iter = directions.begin(); iter != directions.end(); ++iter)
{
spMapTile t = getTile(x + (*iter)->offset().x, y + (*iter)->offset().y);
if (t.get())
{
tile->addTileInDirection( t, *(*iter) );
}
}
}
void Map::drawTerrainLayer(const Point& offset)
{
throw UnsupportedOperationException();
}
void Map::drawObjectLayer(const Point& offset)
{
throw UnsupportedOperationException();
}
/*
void Map::drawMinimap()
{
int minimapTileSize = 4;
int minimapScreenMargin = 10;
Display& d = Display::instance();
SDL_Rect border = { minimapScreenMargin, d.getScreenHeight()-minimapTileSize*_height-2 - minimapScreenMargin, _width*minimapTileSize+2, _height*minimapTileSize+2 };
SDL_Color white = { 0xFF, 0xFF, 0xFF };
SDL_Color green = { 0x00, 0x79, 0x1B };
SDL_Color blue = { 0x00, 0x71, 0xFE };
SDL_Color red = { 0xFF, 0x00, 0x00 };
SDL_Color gray = { 0x74, 0x74, 0x74 };
Display::instance().drawRect( &border, &white );
for ( int i = 0; i < _height; ++i )
{
for ( int j = 0; j < _width; ++j )
{
SDL_Rect tile = { border.x + 1 + minimapTileSize*j, border.y + 1 + minimapTileSize*i, minimapTileSize, minimapTileSize };
if ( getTile(i,j)->hasUnit() )
d.drawRect( &tile, &red );
else if ( getTile(i,j)->getTerrainType() == GRASS )
{
if ( getTile(i, j)->isPassable() )
d.drawRect( &tile, &green );
else
d.drawRect( &tile, &gray );
}
else if ( getTile(i,j)->getTerrainType() == WATER )
d.drawRect( &tile, &blue );
}
}
}
*/
void Map::highlightMouseOverTile(const Point& offset)
{
throw UnsupportedOperationException();
}
int Map::getHeight() const
{
return _height;
}
int Map::getWidth() const
{
return _width;
}
spMapTile Map::getMouseOverTile() const
{
throw UnsupportedOperationException();
}
void Map::updateMouseOverTile(const Point& mouse, const Point& offset)
{
throw UnsupportedOperationException();
}
string Map::getName() const
{
return _name;
}
string Map::getFileName() const
{
return _fileName;
}
} // namespace
| 24.671598 | 169 | 0.546708 | [
"object",
"vector"
] |
2c29712ef0b7e17e4f72588a0bac95f51701fa93 | 1,584 | cpp | C++ | ObjectOrientedProgramming/TestClassSmartPointers/main.cpp | Sebery/CPP-Practice-Projects | cf200e7753be79d13042f9f9de666d25c8215d69 | [
"MIT"
] | null | null | null | ObjectOrientedProgramming/TestClassSmartPointers/main.cpp | Sebery/CPP-Practice-Projects | cf200e7753be79d13042f9f9de666d25c8215d69 | [
"MIT"
] | null | null | null | ObjectOrientedProgramming/TestClassSmartPointers/main.cpp | Sebery/CPP-Practice-Projects | cf200e7753be79d13042f9f9de666d25c8215d69 | [
"MIT"
] | null | null | null | #include <iostream>
#include <memory>
#include <vector>
class Test {
private:
int data;
public:
Test() : data{0} { std::cout << "\tTest constructor (" << data << ")" << std::endl; }
Test(int data) : data {data} { std::cout << "\tTest constructor (" << data << ")" << std::endl; }
int get_data() const {return data; }
~Test() {std::cout << "\tTest destructor (" << data << ")" << std::endl; }
};
// Function prototypes
std::unique_ptr<std::vector<std::shared_ptr<Test>>> make();
void fill(std::vector<std::shared_ptr<Test>> &vec, int num);
void display(const std::vector<std::shared_ptr<Test>>&vec);
int main() {
std::unique_ptr<std::vector<std::shared_ptr<Test>>> vec_ptr;
vec_ptr = make();
std::cout << "How many data points do you want to enter: ";
int num;
std::cin >> num;
fill(*vec_ptr, num);
display(*vec_ptr);
return 0;
}
std::unique_ptr<std::vector<std::shared_ptr<Test>>> make() {
return std::make_unique<std::vector<std::shared_ptr<Test>>>();
}
void fill(std::vector<std::shared_ptr<Test>> &vec, int num) {
for (size_t i{0}; i < num; i++) {
std::cout << "Enter data point [" << i << "] : ";
int num{0};
std::cin >> num;
vec.push_back(std::make_shared<Test>(num));
}
}
void display(const std::vector<std::shared_ptr<Test>>&vec) {
std::cout << "\nDisplaying vector data\n";
std::cout << "===================================\n";
for (const auto &t : vec)
std::cout << t->get_data() << "\n";
std::cout << "===================================\n";
}
| 28.8 | 101 | 0.551768 | [
"vector"
] |
2c2e40aa1d76d64bb8367ad3a32ab68542bfe2f2 | 5,584 | cpp | C++ | test/tbb/test_arena_constraints.cpp | alvdd/oneTBB | d87e076d530007b48f619b2f58b53fb0d1a173b1 | [
"Apache-2.0"
] | null | null | null | test/tbb/test_arena_constraints.cpp | alvdd/oneTBB | d87e076d530007b48f619b2f58b53fb0d1a173b1 | [
"Apache-2.0"
] | null | null | null | test/tbb/test_arena_constraints.cpp | alvdd/oneTBB | d87e076d530007b48f619b2f58b53fb0d1a173b1 | [
"Apache-2.0"
] | null | null | null | /*
Copyright (c) 2019-2020 Intel Corporation
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 test_arena_constraints.cpp
//! \brief Test for [preview] functionality
#include "common/common_arena_constraints.h"
#include "common/spin_barrier.h"
#include "common/memory_usage.h"
#include "tbb/parallel_for.h"
#if __TBB_HWLOC_PRESENT
void recursive_arena_binding(int* numa_indexes, size_t count,
std::vector<numa_validation::affinity_mask>& affinity_masks) {
if (count > 0) {
tbb::task_arena current_level_arena;
current_level_arena.initialize(tbb::task_arena::constraints(numa_indexes[count - 1]));
current_level_arena.execute(
[&numa_indexes, &count, &affinity_masks]() {
affinity_masks.push_back(numa_validation::allocate_current_cpu_set());
recursive_arena_binding(numa_indexes, --count, affinity_masks);
}
);
} else {
// Validation of assigned affinity masks at the deepest recursion step
numa_validation::affinity_set_verification(affinity_masks.begin(), affinity_masks.end());
}
if (!affinity_masks.empty()) {
REQUIRE_MESSAGE(numa_validation::affinity_masks_isequal(affinity_masks.back(),
numa_validation::allocate_current_cpu_set()),
"After binding to different NUMA node thread affinity was not returned to previous state.");
affinity_masks.pop_back();
}
}
//! Testing binding correctness during passing through netsed arenas
//! \brief \ref interface \ref error_guessing
TEST_CASE("Test binding to NUMA nodes with nested arenas") {
if (is_system_environment_supported()) {
numa_validation::initialize_system_info();
std::vector<int> numa_indexes = tbb::info::numa_nodes();
std::vector<numa_validation::affinity_mask> affinity_masks;
recursive_arena_binding(numa_indexes.data(), numa_indexes.size(), affinity_masks);
}
}
//! Testing constraints propagation during arenas copy construction
//! \brief \ref regression
TEST_CASE("Test constraints propagation during arenas copy construction") {
if (is_system_environment_supported()) {
numa_validation::initialize_system_info();
std::vector<int> numa_indexes = tbb::info::numa_nodes();
for (auto index: numa_indexes) {
numa_validation::affinity_mask constructed_mask, copied_mask;
tbb::task_arena constructed{tbb::task_arena::constraints(index)};
constructed.execute([&constructed_mask]() {
constructed_mask = numa_validation::allocate_current_cpu_set();
});
tbb::task_arena copied(constructed);
copied.execute([&copied_mask]() {
copied_mask = numa_validation::allocate_current_cpu_set();
});
REQUIRE_MESSAGE(numa_validation::affinity_masks_isequal(constructed_mask, copied_mask),
"Affinity mask brokes during copy construction");
}
}
}
#endif /*__TBB_HWLOC_PRESENT*/
void collect_all_threads_on_barrier() {
utils::SpinBarrier barrier;
barrier.initialize(tbb::this_task_arena::max_concurrency());
tbb::parallel_for(tbb::blocked_range<size_t>(0, tbb::this_task_arena::max_concurrency()),
[&barrier](const tbb::blocked_range<size_t>&) {
barrier.wait();
});
};
//! Testing memory leaks absence
//! \brief \ref resource_usage
TEST_CASE("Test memory leaks") {
std::vector<int> numa_indexes = tbb::info::numa_nodes();
size_t num_traits = 1000;
size_t current_memory_usage = 0, previous_memory_usage = 0, stability_counter = 0;
bool no_memory_leak = false;
for (size_t i = 0; i < num_traits; i++) {
{ /* All DTORs must be called before GetMemoryUsage() call*/
std::vector<tbb::task_arena> arenas(numa_indexes.size());
std::vector<tbb::task_group> task_groups(numa_indexes.size());
for(unsigned j = 0; j < numa_indexes.size(); j++) {
arenas[j].initialize(tbb::task_arena::constraints(numa_indexes[j]));
arenas[j].execute(
[&task_groups, &j](){
task_groups[j].run([](){
collect_all_threads_on_barrier();
});
});
}
for(unsigned j = 0; j < numa_indexes.size(); j++) {
arenas[j].execute([&task_groups, &j](){ task_groups[j].wait(); });
}
}
current_memory_usage = utils::GetMemoryUsage();
stability_counter = current_memory_usage==previous_memory_usage ? stability_counter + 1 : 0;
// If the amount of used memory has not changed during 10% of executions,
// then we can assume that the check was successful
if (stability_counter > num_traits / 10) {
no_memory_leak = true;
break;
}
previous_memory_usage = current_memory_usage;
}
REQUIRE_MESSAGE(no_memory_leak, "Seems we get memory leak here.");
}
| 40.759124 | 104 | 0.658489 | [
"vector"
] |
2c2fc134bc783ac76ac167198491340733632de0 | 2,942 | cpp | C++ | Source/LevelDesign/DestructibleTrigger.cpp | thatguyabass/Kill-O-Byte-Source | 0d4dfea226514161bb9799f55359f91da0998256 | [
"Apache-2.0"
] | 2 | 2016-12-13T19:13:10.000Z | 2017-08-14T04:46:52.000Z | Source/LevelDesign/DestructibleTrigger.cpp | thatguyabass/Kill-O-Byte-Source | 0d4dfea226514161bb9799f55359f91da0998256 | [
"Apache-2.0"
] | null | null | null | Source/LevelDesign/DestructibleTrigger.cpp | thatguyabass/Kill-O-Byte-Source | 0d4dfea226514161bb9799f55359f91da0998256 | [
"Apache-2.0"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#include "Snake_Project.h"
#include "DestructibleTrigger.h"
#include "Powers/AttackHelper.h"
#include "Utility/AttackTypeDataAsset.h"
// Sets default values
ADestructibleTrigger::ADestructibleTrigger()
{
RootSceneComponent = CreateDefaultSubobject<USceneComponent>(TEXT("RootSceneComponent"));
RootComponent = RootSceneComponent;
MeshComponent = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("MeshComponent"));
MeshComponent->AttachTo(RootComponent);
//Remove any Mesh Collision
MeshComponent->SetCollisionEnabled(ECollisionEnabled::NoCollision);
MeshComponent->SetCollisionResponseToAllChannels(ECR_Ignore);
MaxHealth = 10;
bDead = false;
PrimaryColorName = "Primary Color";
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
}
// Called when the game starts or when spawned
void ADestructibleTrigger::PostInitializeComponents()
{
Super::PostInitializeComponents();
SetHealth(MaxHealth);
}
float ADestructibleTrigger::TakeDamage(float DamageAmount, FDamageEvent const& DamageEvent, AController* EventInstigator, AActor* DamageCauser)
{
if (DamageAmount <= 0.0f)
{
return 0.0f;
}
int32 DamageTaken = DamageAmount;
AttackHelper::CalculateDamage(DamageTaken, DamageEvent, GetAttackType());
GEngine->AddOnScreenDebugMessage(-1, 1, FColor::Red, FString::SanitizeFloat(DamageTaken));
// Check if the state is a valid player state. If false, a bot must have fired the projectile.
ASnakePlayerState* State = Cast<ASnakePlayerState>(DamageCauser);
if (State)
{
ReduceHealth(DamageTaken);
}
return 0.0f;
}
FAttackType ADestructibleTrigger::GetAttackType()
{
return AttackTypeDataAsset ? AttackTypeDataAsset->Data : FAttackType();
}
void ADestructibleTrigger::ReduceHealth(float DamageAmount)
{
if (DamageAmount < 0)
{
return;
}
Health -= DamageAmount;
if (Health <= 0)
{
HideAndDestroy();
}
}
void ADestructibleTrigger::SetHealth(int32 InHealth)
{
if (InHealth <= 0)
{
return;
}
Health = InHealth;
if (Health > MaxHealth)
{
Health = MaxHealth;
}
}
void ADestructibleTrigger::HideAndDestroy()
{
if (!bDead)
{
//Call the Blueprint Event to trigger. Also remvoe any attached Collision objects
Trigger();
SetActorHiddenInGame(true);
SetLifeSpan(2.0f);
bDead = true;
}
}
void ADestructibleTrigger::CreateAndSetDMI()
{
DMI.Empty();
if (MeshComponent && MeshComponent->GetNumMaterials() > 0)
{
for (int32 c = 0; c < MeshComponent->GetNumMaterials(); c++)
{
DMI.Add(MeshComponent->CreateAndSetMaterialInstanceDynamic(c));
}
}
SetMaterialColor();
}
void ADestructibleTrigger::SetMaterialColor()
{
if (DMI.Num() > 0)
{
for (int32 c = 0; c < DMI.Num(); c++)
{
DMI[c]->SetVectorParameterValue(PrimaryColorName, GetAttackType().ColorData.PrimaryColor);
}
}
} | 22.458015 | 143 | 0.745071 | [
"mesh"
] |
2c306346a21ef0a99f2ca7089f75ce463db3155b | 3,086 | cpp | C++ | atcoder/heuristics/introduction/a.cpp | zaurus-yusya/atcoder | 5fc345b3da50222fa1366d1ce52ae58799488cef | [
"MIT"
] | 3 | 2020-05-27T16:27:12.000Z | 2021-01-27T12:47:12.000Z | atcoder/heuristics/introduction/a.cpp | zaurus-yusya/Competitive-Programming | c72e13a11f76f463510bd4a476b86631d9d1b13a | [
"MIT"
] | null | null | null | atcoder/heuristics/introduction/a.cpp | zaurus-yusya/Competitive-Programming | c72e13a11f76f463510bd4a476b86631d9d1b13a | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
typedef long long ll;
typedef long double ld;
#define rep(i,n) for(ll i=0;i<(n);i++)
#define repr(i,n) for(ll i=(n-1);i>=0;i--)
#define all(x) x.begin(),x.end()
#define br cout << "\n";
using namespace std;
const long long INF = 1e10;
const long long MOD = 1e9+7;
using Graph = vector<vector<ll>>;
using pll = pair<ll, ll>;
template<class T> inline bool chmin(T &a, T b) { if(a > b){ a = b; return true;} return false;}
template<class T> inline bool chmax(T &a, T b) { if(a < b){ a = b; return true;} return false;}
// 0 false, 1 true
// string to int : -48
// a to A : -32
// ceil(a) 1.2->2.0
// c++17 g++ -std=c++17 a.cpp
ll d;
vector<ll> c(26);
vector<vector<ll>> vec(d, vector<ll>(26));
ll calc(vector<ll> t){
ll res = 0;
vector<ll> last(26);
rep(i, d){
rep(j, 26){
if(t[i] == j){
res += vec[i][j];
last[j] = 0;
}else{
last[j]++;
}
}
rep(j, 26){
res -= c[j]*last[j];
}
}
return res;
}
int main() {
std::cout << std::fixed << std::setprecision(15);
cin >> d;
clock_t start = clock();
rep(i, 26){
cin >> c[i];
}
vec.resize(d, vector<ll>(26));
rep(i, d){
rep(j, 26){
cin >> vec[i][j];
}
}
ll ans = 0;
vector<ll> last(26);
vector<ll> t;
rep(i, d){
ll max_value = -1;
ll contest_type = -1;
//それぞれの日を選んだ場合
ll max_val = -INF;
ll tmp_day = -1;
rep(j, 26){
ll tmp = 0;
rep(k, 26){
if(j == k){
tmp += vec[i][j];
}
else{
tmp -= c[k] * (last[k] + 1);
}
}
if(max_val < tmp){
max_val = tmp;
tmp_day = j;
}
}
//cout << tmp_day + 1 << endl;
t.push_back(tmp_day);
ans += max_val;
//後処理
rep(j, 26){
if(j == tmp_day){
last[j] = 0;
}else{
last[j]++;
}
}
}
//cout << ans << endl;
while(true){
srand(time(NULL));
ll before = rand() % 26 + 1;
ll after = rand() % 26 + 1;
if(t[before] != after){
ll old = t[before];
t[before] = after;
ll res = 0;
res = calc(t);
if(ans < res){
ans = res;
}else{
t[before] = old;
}
}
clock_t end = clock();
const double time = static_cast<double>(end - start) / CLOCKS_PER_SEC * 1000.0;
//printf("time %lf[ms]\n", time);
if(time > 1950){
break;
}
}
rep(i, t.size()){
cout << t[i] + 1 << endl;
}
/*
clock_t end = clock();
const double time = static_cast<double>(end - start) / CLOCKS_PER_SEC * 1000.0;
printf("time %lf[ms]\n", time);
*/
} | 20.993197 | 95 | 0.408296 | [
"vector"
] |
2c349e7cf515d0486dd213fa91196716b04dd8d2 | 17,541 | hpp | C++ | TZK_Objects/HPP/CfgAmmo_Tank_inherit.hpp | Darker1990/Project-TZK-Since2.12 | 3f1162b51f1f24f41b1000e97102be537d162b76 | [
"MIT"
] | null | null | null | TZK_Objects/HPP/CfgAmmo_Tank_inherit.hpp | Darker1990/Project-TZK-Since2.12 | 3f1162b51f1f24f41b1000e97102be537d162b76 | [
"MIT"
] | null | null | null | TZK_Objects/HPP/CfgAmmo_Tank_inherit.hpp | Darker1990/Project-TZK-Since2.12 | 3f1162b51f1f24f41b1000e97102be537d162b76 | [
"MIT"
] | null | null | null | //Ammos used mainly by tanks.
class M1Sabot_xj400: Shell120 {
hit = 575; indirectHit = 10; indirectHitRange = 5;
minRange = 1; minRangeProbab = 0.95;
midRange = 1000; midRangeProbab = 0.95;
maxRange = 2500; maxRangeProbab = 0.95;
soundHit[] = {"Explosions\expl4",100, 1};
};
class M1Heat_xj400: Heat120 {
airLock = 0;
hit = 350; indirectHit = 150; indirectHitRange = 8;
minRange = 5; minRangeProbab = 0.95;
midRange = 1000; midRangeProbab = 0.95;
maxRange = 2500; maxRangeProbab = 0.95;
soundHit[] = {"Explosions\expl4",100, 1};
timeToLive = 60; // For Artillery shotShell only (invalid to missile/rocket). Default value is 20.
};
class T80Sabot_xj400: Shell120 {
hit = 575; indirectHit = 10; indirectHitRange = 5;
minRange = 1; minRangeProbab = 0.95;
midRange = 1000; midRangeProbab = 0.95;
maxRange = 2500; maxRangeProbab = 0.95;
soundHit[] = {"Explosions\expl4",100, 1};
};
class T80Heat_xj400: Heat120 {
airLock = 0;
hit = 350; indirectHit = 150; indirectHitRange = 8;
minRange = 5; minRangeProbab = 0.95;
midRange = 1000; midRangeProbab = 0.95;
maxRange = 2500; maxRangeProbab = 0.95;
soundHit[] = {"Explosions\expl4",100, 1};
timeToLive = 60; // For Artillery shotShell only (invalid to missile/rocket). Default value is 20.
};
class LeoSabot_xj400: Shell120 {
hit = 575; indirectHit = 10; indirectHitRange = 5;
minRange = 1; minRangeProbab = 0.95;
midRange = 1000; midRangeProbab = 0.95;
maxRange = 5000; maxRangeProbab = 0.95;
soundHit[] = {"Explosions\expl4",100, 1};
soundFly[] = {"\TZK_Sounds_4_0_0\Leo2A6\fly.wss",25, 0.8};
model = "\TZK_Model_4_0_0\wp\DM63.p3d";
};
class LeoHeat_xj400: Heat120 {
airLock = 0;
hit = 350; indirectHit = 150; indirectHitRange = 8;
minRange = 5; minRangeProbab = 0.95;
midRange = 1000; midRangeProbab = 0.95;
maxRange = 5000; maxRangeProbab = 0.95;
soundHit[] = {"Explosions\explosion_large1.wss",15, 1};
soundFly[] = {"\TZK_Sounds_4_0_0\Leo2A6\fly.wss",25, 0.8};
model = "\TZK_Model_4_0_0\wp\DM63.p3d";
};
class M12Sabot_xj400: M1Sabot_xj400 {
soundHit[] = {"Explosions\explosion_large1",100, 1};
soundFly[] = {"\TZK_Sounds_4_0_0\inq_m1\shellfly.wss",8, 1.0};
soundHit2[] = {"\TZK_Sounds_4_0_0\Shellground.wss",10, 1};
hitGround[] = {soundHit2,1};
soundHit3[] = {"\TZK_Sounds_4_0_0\Shellground.wss",10, 1};
hitBuilding[] = {soundHit3,1};
};
class M12Heat_xj400: M1Heat_xj400 {
soundHit[] = {"Explosions\explosion_large1",100, 1};
soundFly[] = {"\TZK_Sounds_4_0_0\inq_m1\shellfly.wss",8, 1.0};
soundHit2[] = {"\TZK_Sounds_4_0_0\Shellground.wss",10, 1};
soundHit3[] = {"\TZK_Sounds_4_0_0\Shellground.wss",10, 1};
soundHit4[] = {"\TZK_Sounds_4_0_0\Heat-Hit.wss",10, 1};
hitArmor[] = {soundHit4,1};
soundHit5[] = {"\TZK_Sounds_4_0_0\Explosion4.wss",10, 1};
hitGround[] = {soundHit5,1};
soundHit6[] = {"\TZK_Sounds_4_0_0\Explosion3.wss",10, 1};
hitBuilding[] = {soundHit6,1};
};
class PLASabot_xj400: Shell120 {
hit = 575; indirectHit = 10; indirectHitRange = 5;
minRange = 1; minRangeProbab = 0.95;
midRange = 1000; midRangeProbab = 0.95;
maxRange = 2500; maxRangeProbab = 0.95;
soundHit[] = {"\TZK_Sounds_4_0_0\VME\e.wss", 100,1};
soundHitArmor1[] = {"\TZK_Sounds_4_0_0\VME\e2.wss", 100,1};
soundHitArmor2[] = {"\TZK_Sounds_4_0_0\VME\e3.wss", 100,1};
soundHitArmor3[] = {"\TZK_Sounds_4_0_0\VME\e4.wss", 100,1};
hitGround[] = {"soundHit",1};
hitArmor[] = {"soundHitArmor1",0.35,"soundHitArmor2",0.35,"soundHitArmor3",0.3};
soundFly[] = {"\TZK_Sounds_4_0_0\VME\s.ogg",1,0};
};
class PLAHeat_xj400: Heat120 {
airLock = 0;
hit = 350; indirectHit = 150; indirectHitRange = 8;
minRange = 5; minRangeProbab = 0.95;
midRange = 1000; midRangeProbab = 0.95;
maxRange = 2500; maxRangeProbab = 0.95;
soundHit[] = {"Explosions\expl4",100, 1};
soundHitArmor1[] = {"\TZK_Sounds_4_0_0\VME\sabot1.wss",100,1};
soundHitArmor2[] = {"\TZK_Sounds_4_0_0\VME\sabot2.wss",100,1};
hitArmor[] = {"soundHitArmor1",0.5,"soundHitArmor2",0.5};
soundFly[] = {"\TZK_Sounds_4_0_0\VME\s.ogg",1,0};
};
class 9M112_xj400: AA {
hit = 250;
indirectHit = 10;
indirectHitRange = 2.500000;
minRange = 100;
minRangeProbab = 0.500000;
midRange = 400;
midRangeProbab = 0.950000;
maxRange = 5000;
maxRangeProbab = 0.500000;
model = "AT1";
simulation = "shotmissile";
simulationStep = 0.050000;
cost = 5000;
soundFly[] = {"\TZK_Sounds_4_0_0\icp_t72s\missilefly.ogg",2,0.7};
soundHit[] = {"\TZK_Sounds_4_0_0\icp_t72s\explosion.wss",31.622778,1};
soundEngine[] = {"\TZK_Sounds_4_0_0\icp_t72s\noise.wss",0.001,1};
maxSpeed = 300;
airLock = 1;
irLock = 1;
laserlock = 1;
manualControl = 1;
maxControlRange = 2500;
initTime = 0.150000;
thrustTime = 10;
thrust = 600;
maneuvrability = 5;
};
class 9M120_xj400: AA {
hit = 500;
indirectHit = 70;
indirectHitRange = 2.500000;
minRange = 100;
minRangeProbab = 0.500000;
midRange = 400;
midRangeProbab = 0.950000;
maxRange = 5000;
maxRangeProbab = 0.500000;
model = "AT1";
simulation = "shotmissile";
simulationStep = 0.050000;
cost = 5000;
soundFly[] = {"\TZK_Sounds_4_0_0\icp_t72s\missilefly.ogg",2,0.7};
soundHit[] = {"\TZK_Sounds_4_0_0\icp_t72s\explosion.wss",31.622778,1};
soundEngine[] = {"\TZK_Sounds_4_0_0\icp_t72s\noise.wss",0.001, 1};
maxSpeed = 350;
irLock = 1;
airlock = 0;
laserlock = 1;
manualControl = 1;
maxControlRange = 2500;
initTime = 0.150000;
thrustTime = 15;
thrust = 700;
maneuvrability = 10;
};
class PLA_ATGM125_xj400: AT3 {
hit = 1400;indirectHit = 1200;indirectHitRange = 2.0;
minRange = 1000;
minRangeProbab = 0.500000;
midRange = 2000;
midRangeProbab = 0.950000;
maxRange = 5000;
maxRangeProbab = 0.750000;
maxSpeed = 500;
laserlock = true;
soundHit[] = {"\TZK_Sounds_4_0_0\VME\AA2.wav",100,1};
soundHitArmor1[] = {"\TZK_Sounds_4_0_0\VME\AA.wav",100,1};
soundHitArmor2[] = {"\TZK_Sounds_4_0_0\VME\AA3.wav",100,1};
soundHitArmor3[] = {"\TZK_Sounds_4_0_0\VME\AA4.wav",100,1};
hitGround[] = {"soundHit",1,};
hitArmor[] = {"soundHitArmor1",0.35,"soundHitArmor2",0.35,"soundHitArmor3",0.3};
soundFly[] = {"\TZK_Sounds_4_0_0\VME\towfly.ogg",10,1};
maxControlRange = 2500;
initTime = 0.150000;
thrustTime = 15;
thrust = 700;
maneuvrability = 10;
};
class 9M120_t90ms_xj400: AT3 {
hit = 650;
indirectHit = 70;
indirectHitRange = 2.500000;
minRange = 100;
minRangeProbab = 0.500000;
midRange = 400;
midRangeProbab = 0.950000;
maxRange = 5000;
maxRangeProbab = 0.500000;
model = "AT1";
simulation = "shotmissile";
simulationStep = 0.050000;
cost = 5000;
soundFly[] = {"\TZK_Sounds_4_0_0\mfm_cfg_t90ms\missilefly.ogg",2,0.7};
soundHit[] = {"\TZK_Sounds_4_0_0\mfm_cfg_t90ms\explosion.wav",31.622778,1};
soundEngine[] = {"\TZK_Sounds_4_0_0\mfm_cfg_t90ms\noise.wss",0.001, 1};
maxSpeed = 350;
irLock = 1;
airlock = 0;
//laserlock = 1;
//manualControl = 1;
maxControlRange = 2500;
initTime = 0.150000;
thrustTime = 15;
thrust = 700;
maneuvrability = 4;
};
class 3OF26_t90ms_xj400: Shell125 {
// hit = 200; indirectHit = 170; indirectHitRange = 9;
hit = 350; indirectHit = 150; indirectHitRange = 8;
minRange = 10; minRangeProbab = 1;
midRange = 1500; midRangeProbab = 0.9;
maxRange = 2500; maxRangeProbab = 0.7;
cost = 500;
};
class 3BK29M_t90ms_xj400: Heat125 {
hit = 500; indirectHit = 16; indirectHitRange = 5;
minRange = 10; minRangeProbab = 1;
midRange = 1500; midRangeProbab = 0.95;
maxRange = 2500; maxRangeProbab = 0.7;
cost = 800;
soundFly[] = {"\TZK_Sounds_4_0_0\mfm_cfg_t90ms\125fly.ogg",1,3};
};
class 3BM42_t90ms_xj400: Heat125 {
// hit = 900; indirectHit = 8; indirectHitRange = 2;
hit = 575; indirectHit = 10; indirectHitRange = 5;
minRange = 20; minRangeProbab = 1;
midRange = 1500; midRangeProbab = 0.95;
maxRange = 2500; maxRangeProbab = 0.6;
soundFly[] = {"\TZK_Sounds_4_0_0\mfm_cfg_t90ms\125fly.ogg",1,3};
cost = 1000;
};
class CoaxW_xj400: Bullet7_6 {
hit = 6; cost = 5;
tracerColor[] = {1,0.25000,0.12500,0.5};
minRange = 1; minRangeProbab = 1;
midRange = 800; midRangeProbab = 0.5;
maxRange = 1600; maxRangeProbab = 0.1;
};
class 50calW_xj400: Bullet12_7 {
airLock = 1; hit = 19; cost = 10;
tracerColor[] = {1,0.25000,0.12500,1};
minRange = 1; minRangeProbab = 1;
midRange = 1000; midRangeProbab = 0.5;
maxRange = 2000; maxRangeProbab = 0.1;
};
class CoaxE_xj400: Bullet7_6 {
hit = 6; cost = 5;
tracerColor[] = {0.12500,0.25000,1,0.5};
minRange = 1; minRangeProbab = 1;
midRange = 800; midRangeProbab = 0.5;
maxRange = 1600; maxRangeProbab = 0.1;
};
class 50calE_xj400: Bullet12_7 {
airLock = 1; hit = 19; cost = 10;
tracerColor[] = {0.12500,0.25000,1,1};
minRange = 1; minRangeProbab = 1;
midRange = 1000; midRangeProbab = 0.5;
maxRange = 2000; maxRangeProbab = 0.1;
};
// M109 Paladin from CoC
class HEAT155_DKMM_xj400: Heat125 {
airLock = 0; irlock = 1; laserlock = 1;
hit = 950; indirectHit = 490; indirectHitRange = 20;
minRange = 50; minRangeProbab = 1;
midRange = 2000; midRangeProbab = 0.9;
maxRange = 4000; maxrangeprobab = 0.75;
model = "\TZK_Model_4_0_0\wp\heat155.p3d";
tracerColor[] = {1,0.25000,0.12500,1};
soundFly[] = {"\TZK_Sounds_4_0_0\COC\155mmFly.wss", 0.05, 1};
soundHit[] = {"\TZK_Sounds_4_0_0\COC\impact.wss",db+40,1};
explosive = 1;
visibleFire = 32; audibleFire = 32; visibleFireTime = 6;
cost = 500;
recoil = {1.00,3.5,1.0};
timeToLive = 60; // For Artillery shotShell only (invalid to missile/rocket). Default value is 20.
};
class AP155_DKMM_xj400: HEAT155_DKMM_xj400 {
hit = 1500; indirectHit = 200; indirectHitRange = 5;
minRange = 30; minRangeProbab = 0.5;
};
// TOS from DKM.
class FAE220_DKMM_xj400: Shell125 {
hit = 200; indirectHit = 0; indirectHitRange = 0; explosive = 0; // Power required or AI vehicle won't fire it.
minRange = 250; minRangeProbab = 0.50;
midRange = 1500; midRangeProbab = 0.95;
maxRange = 3500; maxRangeProbab = 0.50;
cost = 1;
soundHit[] = {"",1,1};
hitGround[] = {"soundHit",1}; hitMan[] = {"soundHit",1}; hitArmor[] = {"soundHit",1}; hitBuilding[] = {"soundHit",1};
soundFly[] = {"\TZK_Sounds_4_0_0\DKM\miss_air.wss", db+20, 1};
model = "\TZK_Model_4_0_0\wp\FAE220_DKMM.p3d";
airLock = 0; irLock = 1; laserLock = 1;
visibleFire = 32; audibleFire = 32; visibleFireTime = 8;
simulation = "shotShell";
timeToLive = 60; // For Artillery shotShell only (invalid to missile/rocket). Default value is 20.
// proxyShape = "\TZK_Model_4_0_0\TOS_Rocket.p3d";
};
class M26_CoC_xj400: FAE220_DKMM_xj400 {
minRange = 150; minRangeProbab = 0.99;
midRange = 2000; midRangeProbab = 0.99;
maxRange = 10000; maxRangeProbab = 0.99;
soundFly[] = {"\TZK_Sounds_4_0_0\DKM\miss_air.wss", db+20, 1};
model = "\TZK_Model_4_0_0\wp\FAE220_DKMM.p3d";
recoil = "155maingun";
visibleFire = 12; audibleFire = 2; visibleFireTime = 2;
cost = 1;
};
class FAE220_SubBomb_xj400: Shell125 {
hit = 120; indirectHit = 60; indirectHitRange = 10;
soundFly[] = {"",1,1}; soundEngine[] = {"",1,1}; soundHit[] = {"",1,1};
hitGround[] = {"soundHit",1}; hitMan[] = {"soundHit",1}; hitArmor[] = {"soundHit",1}; hitBuilding[] = {"soundHit",1};
cost = 1;
explosive = 0 ;
};
class M26_SubBomb_xj400: FAE220_SubBomb_xj400{};
class FAE220_Sound_xj400: Shell125 {
hit = 1; indirectHit = 20; indirectHitRange = 85; explosive = 0;
// Zero-detect
visibleFire = 0; audibleFire = 0; visibleFireTime = 0;
// Zero-feel
tracerColor[] = {0,0,0,0}; tracerColorR[] = {0,0,0,0};
soundFly[] = {"",1,1}; soundEngine[] = {"",1,1};
soundHit[] = {"\TZK_Sounds_4_0_0\DKM\fae220_deton.wss", 100, 1};
hitGround[] = {"soundHit",1}; hitMan[] = {"soundHit",1}; hitArmor[] = {"soundHit",1}; hitBuilding[] = {"soundHit",1};
cost = 0;
};
class M26_Sound_xj400: FAE220_Sound_xj400 { soundHit[] = {"\TZK_Sounds_4_0_0\m29064mm\xpl.wss", 100, 1}; };
// 2S25 Sprut-SD from mfm
class Sprut_3BM42_xj400: T80Sabot_xj400 {
soundFly[] = {"\TZK_Sounds_4_0_0\2S25\125fly.ogg",1,3};
};
class Sprut_3OF26_xj400: T80Heat_xj400 {
soundFly[] = {"\TZK_Sounds_4_0_0\2S25\125fly.ogg",1,3};
};
// M101/M55 from CoC. Seems not well designed.
class HE155_CoC_xj400: Heat125 {
model = "shell";
hit = 980; indirectHit = 490; indirectHitRange = 11;
minRange = 50; minRangeProbab = 1;
midRange = 2000; midRangeProbab = 0.9;
maxRange = 4000; maxrangeprobab = 0.75;
tracerColor[] = {1,0.25000,0.12500,1};
soundFly[] = {"\TZK_Sounds_4_0_0\COC\155mmFly.wss", 0.05, 1};
soundHit[] = {"",db+40,1};
explosive = 1;
airLock = 0; irlock = 1; laserlock = 0;
sideAirFriction = 0;
visibleFire = 32; // how much is visible when this weapon is fired
audibleFire = 32;
visibleFireTime = 6;
maxControlRange = 100000;
maneuvrability = 0.0;
maxSpeed = 5000;
initTime = 0;
thrustTime = 0;
thrust = 2400;
cost = 500;
recoil = "155maingun";
simulation = "shotMissile";
};
class HE152_CoC_x200: HE155_CoC_xj400{};
class HE105_CoC_xj400: HE155_CoC_xj400 {
hit = 490; indirectHit = 250; indirectHitRange = 9;
cost = 250;
soundFly[] = {"\TZK_Sounds_4_0_0\DKM\shellfly.wss", db-22, 0.9};
soundHit[] = {"\TZK_Sounds_4_0_0\COC\impact.wss",db+430,1};
};
class AAShell_xj400: Shell120 {
airLock = 1;
};
// Structure.
// Mortar
class Mortar4Ammo_xj400: MortarShell {
hit = 600; indirectHit = 200; indirectHitRange = 20;
minRange = 75; minRangeProbab = 0.950000;
midRange = 500; midRangeProbab = 0.950000;
maxRange = 1000; maxRangeProbab = 0.950000;
soundHit[] = {"\TZK_Objects\Sound\Pack_Mortar\exp.ogg",db60,1};
soundFly[] = {"objects\bulletnoise",0.251189,0.700000};
soundHit1[] = {"\TZK_Objects\Sound\Pack_Mortar\grenade1.ogg",38.333333,1};
soundHit2[] = {"\TZK_Objects\Sound\Pack_Mortar\grenade2.ogg",38.333333,1};
soundHit3[] = {"\TZK_Objects\Sound\Pack_Mortar\grenade3.ogg",38.333333,1};
hitGround[] = {"soundHit1",0.330000,"soundHit2",0.330000,"soundHit3",0.330000};
hitArmor[] = {"soundHit1",0.330000,"soundHit2",0.330000,"soundHit3",0.330000};
hitBuilding[] = {"soundHit1",0.330000,"soundHit2",0.330000,"soundHit3",0.330000};
hitMan[] = {"soundHit1",0.300000,"soundHit2",0.300000,"soundHit3",0.300000};
timeToLive = 60; // For Artillery shotShell only (invalid to missile/rocket). Default value is 20.
};
class Mortar_500m_xj400: Mortar4Ammo_xj400 {
minRange = 75; minRangeProbab = 0.950000;
midRange = 300; midRangeProbab = 0.950000;
maxRange = 550; maxRangeProbab = 0.950000;
};
class Mortar_1000m_xj400: Mortar_500m_xj400 {
minRange = 75; minRangeProbab = 0.950000;
midRange = 500; midRangeProbab = 0.950000;
maxRange = 1000; maxRangeProbab = 0.950000;
};
class Mortar_1500m_xj400: Mortar_1000m_xj400 {
minRange = 75; minRangeProbab = 0.950000;
midRange = 800; midRangeProbab = 0.950000;
maxRange = 1500; maxRangeProbab = 0.950000;
};
class AP105_xj400: Shell {
hit = 450; indirectHit = 150; indirectHitRange = 1;
minRange = 10;
minRangeProbab = 0.5;
midRange = 700;
midRangeProbab = 1;
maxRange = 1200;
maxRangeProbab = 1;
cost = 500;
soundFly[] = {"\TZK_Sounds_4_0_0\M101\Shell_flyby.wss",db+2,1};
soundHit[] = {"\TZK_Sounds_4_0_0\M101\Shell_expl.wss",100,1};
timeToLive = 60; // For Artillery shotShell only (invalid to missile/rocket). Default value is 20.
};
class HE105_xj400: AP105_xj400 {
hit = 150; indirectHit = 110; indirectHitRange = 8;
minRange = 50;
minRangeProbab = 0.5;
midRange = 2000;
midRangeProbab = 1;
maxRange = 4500;
maxRangeProbab = 1;
cost = 300;
};
class AP122_xj400: Shell {
hit = 460; indirectHit = 40; indirectHitRange = 2;
minRange = 10;
minRangeProbab = 0.6;
midRange = 1000;
midRangeProbab = 0.9;
maxRange = 4000;
maxRangeProbab = 0.6;
cost = 800;
explosive = 1;
soundHit[] = {"\TZK_Sounds_4_0_0\D30\gun.wss",100,1};
soundFly[] = {"\TZK_Sounds_4_0_0\D30\fly.wss",1,0};
timeToLive = 60; // For Artillery shotShell only (invalid to missile/rocket). Default value is 20.
};
class HE122_xj400: AP122_xj400 {
hit = 250; indirectHit = 159; indirectHitRange = 8.4;
minRange = 15;
minRangeProbab = 0.3;
midRange = 1000;
midRangeProbab = 1.0;
maxRange = 5000;
maxRangeProbab = 0.8;
cost = 500;
};
class AP130_xj400: Heat73 {
// hit = 700; indirectHit = 50; indirectHitRange = 4; // Original power defined in dkmm_m46
hit = 730; indirectHit = 40; indirectHitRange = 4; // Value calculated by linear interpolation depending on 125 and 155 ammo.
soundFly[] = {"\TZK_Sounds_4_0_0\DKM\ShellFly.wss","db+2",1};
visibleFire = 25;
audibleFire = 25;
visibleFireTime = 3;
cost = 600;
model = "\TZK_Model_4_0_0\wp\HEAT130.p3d";
timeToLive = 60; // For Artillery shotShell only (invalid to missile/rocket). Default value is 20.
};
class HE130_xj400: shell73 {
// hit = 190; indirectHit = 60; indirectHitRange = 11; // Original power defined in dkmm_m46
hit = 450; indirectHit = 205; indirectHitRange = 10; // Value calculated by linear interpolation depending on 125 and 155 ammo.
soundFly[] = {"\TZK_Sounds_4_0_0\DKM\ShellFly.wss","db+2",4};
visibleFire = 25;
audibleFire = 25;
visibleFireTime = 3;
cost = 300;
model = "\TZK_Model_4_0_0\wp\HEAT130.p3d";
timeToLive = 60; // For Artillery shotShell only (invalid to missile/rocket). Default value is 20.
};
//EOF | 34.734653 | 129 | 0.671455 | [
"model"
] |
2c3746d3a986512c93337810be90253ec447ea5a | 1,222 | cpp | C++ | source/442FindAllDuplicatesinanArray.cpp | zuisixian/LeetCode | 851498561e5006d4803151cff467864d36a1dc2e | [
"MIT"
] | null | null | null | source/442FindAllDuplicatesinanArray.cpp | zuisixian/LeetCode | 851498561e5006d4803151cff467864d36a1dc2e | [
"MIT"
] | 1 | 2018-01-20T16:25:13.000Z | 2018-01-20T16:25:13.000Z | source/442FindAllDuplicatesinanArray.cpp | zuisixian/LeetCode | 851498561e5006d4803151cff467864d36a1dc2e | [
"MIT"
] | 1 | 2018-01-09T14:08:06.000Z | 2018-01-09T14:08:06.000Z | //Solution1
class Solution {
public:
vector<int> findDuplicates(vector<int>& nums) {
//Firstly, we put each element x in nums[x - 1]. Since x ranges from 1 to N, then x - 1 ranges from 0 to N - 1, it won't exceed the //bound of the array.
//Secondly, we check through the array. If a number x doesn't present in nums[x - 1], then x is absent.
class Solution {
vector<int> res;
for(int i =0;i<nums.size();){
if(nums[i] !=nums[nums[i]-1]) swap(nums[i], nums[nums[i]-1]);
else i++;
}
for(int i =0;i<nums.size();i++){
if(nums[i] != i+1) res.push_back(nums[i]);
}
return res;
}
};
//solution 2
class Solution2 {
public:
//when find a number i, filp the number at the position i-1 to negative.
//if the number at position i-1 is already negative, i is the number that occurs twive.
vector<int> findDuplicates(vector<int>& nums) {
vector<int> res;
for(int i =0;i<nums.size();i++){
int index = abs(nums[i])-1;
if(nums[index] < 0)
res.push_back(abs(index+1));
nums[index] = -nums[index];
}
return res;
}
};
| 31.333333 | 171 | 0.548282 | [
"vector"
] |
2c376ec5cc22fc26d908cf45d11e8c2c4684dcf6 | 3,309 | hh | C++ | source/codestream.hh | astolap/WaSPR | 27dfc715b3024aa4a4ae57c4c6c676f175cf704c | [
"BSD-2-Clause"
] | 1 | 2021-03-30T08:36:06.000Z | 2021-03-30T08:36:06.000Z | source/codestream.hh | astolap/WaSPR | 27dfc715b3024aa4a4ae57c4c6c676f175cf704c | [
"BSD-2-Clause"
] | null | null | null | source/codestream.hh | astolap/WaSPR | 27dfc715b3024aa4a4ae57c4c6c676f175cf704c | [
"BSD-2-Clause"
] | 2 | 2020-02-02T17:35:34.000Z | 2021-06-28T13:04:20.000Z | /*BSD 2-Clause License
* Copyright(c) 2019, Pekka Astola
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met :
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CODESTREAM_HH
#define CODESTREAM_HH
#include "view.hh"
#include "minconf.hh"
#include <iostream>
#include <cstdint>
using std::int32_t;
using std::uint32_t;
using std::int16_t;
using std::uint16_t;
using std::int8_t;
using std::uint8_t;
class viewParametersConstruct {
private:
std::vector<uint8_t> rawbytes; /*stores LF parameters as bytes*/
const std::string gzippath;
const std::string rawfile;
const std::string mode;
view *LF;
int32_t nviews;
uint8_t *dec_iter;
void convertLFtoBytes(); /*from LF to rawbytes*/
void convertBytesToLF(); /*from rawbytes to LF*/
template<class T1>
void addRawBytes(T1 datai)
{
std::vector<uint8_t> bytesi(sizeof(T1), 0);
memcpy(bytesi.data(), &datai, sizeof(T1));
rawbytes.insert(rawbytes.end(), bytesi.begin(), bytesi.end());
}
template<class T1>
void getRawBytes(T1 &dataout)
{
memcpy(&dataout, dec_iter, sizeof(T1));
dec_iter += sizeof(T1);
}
void addSPM();
void addSPW();
void addSPP();
void addSTD();
void addLSW();
void addNRefs();
void addNNDRefs();
void addNDRefs();
void addRefs();
void addY();
void addX();
void addMconfs();
void getSPM();
void getSPW();
void getSPP();
void getSTD();
void getLSW();
void getNRefs();
void getNNDRefs();
void getNDRefs();
void getRefs();
void getY();
void getX();
void getMconfs();
public:
viewParametersConstruct(
view *LF,
const int32_t nviews,
const std::string gzippath,
const std::string rawfile,
const std::string mode);
~viewParametersConstruct();
};
void viewHeaderToCodestream(
int32_t &n_bytes_prediction,
view *SAI,
FILE *output_LF_file);
void codestreamToViewHeader(
int32_t &n_bytes_prediction,
view *SAI,
FILE *input_LF);
#endif
| 24.879699 | 83 | 0.689332 | [
"vector"
] |
2c453a8ca98ee774e6b155397a4e207bc2a6ed6c | 13,319 | cc | C++ | chrome/browser/extensions/activity_log/fullstream_ui_policy_unittest.cc | MIPS/external-chromium_org | e31b3128a419654fd14003d6117caa8da32697e7 | [
"BSD-3-Clause"
] | 2 | 2018-11-24T07:58:44.000Z | 2019-02-22T21:02:46.000Z | chrome/browser/extensions/activity_log/fullstream_ui_policy_unittest.cc | carlosavignano/android_external_chromium_org | 2b5652f7889ccad0fbdb1d52b04bad4c23769547 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/extensions/activity_log/fullstream_ui_policy_unittest.cc | carlosavignano/android_external_chromium_org | 2b5652f7889ccad0fbdb1d52b04bad4c23769547 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 3 | 2017-07-31T19:09:52.000Z | 2019-01-04T18:48:50.000Z | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/cancelable_callback.h"
#include "base/command_line.h"
#include "base/memory/scoped_ptr.h"
#include "base/run_loop.h"
#include "base/synchronization/waitable_event.h"
#include "base/test/simple_test_clock.h"
#include "chrome/browser/extensions/activity_log/activity_log.h"
#include "chrome/browser/extensions/activity_log/fullstream_ui_policy.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/test_extension_system.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/extensions/extension_builder.h"
#include "chrome/test/base/chrome_render_view_host_test_harness.h"
#include "chrome/test/base/testing_profile.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "sql/statement.h"
#include "testing/gtest/include/gtest/gtest.h"
#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/chromeos/settings/cros_settings.h"
#include "chrome/browser/chromeos/settings/device_settings_service.h"
#endif
namespace extensions {
class FullStreamUIPolicyTest : public testing::Test {
public:
FullStreamUIPolicyTest()
: thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP),
saved_cmdline_(CommandLine::NO_PROGRAM) {
#if defined OS_CHROMEOS
test_user_manager_.reset(new chromeos::ScopedTestUserManager());
#endif
CommandLine command_line(CommandLine::NO_PROGRAM);
saved_cmdline_ = *CommandLine::ForCurrentProcess();
profile_.reset(new TestingProfile());
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExtensionActivityLogging);
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExtensionActivityLogTesting);
extension_service_ = static_cast<TestExtensionSystem*>(
ExtensionSystem::Get(profile_.get()))->CreateExtensionService
(&command_line, base::FilePath(), false);
}
virtual ~FullStreamUIPolicyTest() {
#if defined OS_CHROMEOS
test_user_manager_.reset();
#endif
base::RunLoop().RunUntilIdle();
profile_.reset(NULL);
base::RunLoop().RunUntilIdle();
// Restore the original command line and undo the affects of SetUp().
*CommandLine::ForCurrentProcess() = saved_cmdline_;
}
// A helper function to call ReadData on a policy object and wait for the
// results to be processed.
void CheckReadData(
ActivityLogPolicy* policy,
const std::string& extension_id,
const int day,
const base::Callback<void(scoped_ptr<Action::ActionVector>)>& checker) {
// Submit a request to the policy to read back some data, and call the
// checker function when results are available. This will happen on the
// database thread.
policy->ReadData(
extension_id,
day,
base::Bind(&FullStreamUIPolicyTest::CheckWrapper,
checker,
base::MessageLoop::current()->QuitClosure()));
// Set up a timeout that will trigger after 5 seconds; if we haven't
// received any results by then assume that the test is broken.
base::CancelableClosure timeout(
base::Bind(&FullStreamUIPolicyTest::TimeoutCallback));
base::MessageLoop::current()->PostDelayedTask(
FROM_HERE, timeout.callback(), base::TimeDelta::FromSeconds(5));
// Wait for results; either the checker or the timeout callbacks should
// cause the main loop to exit.
base::MessageLoop::current()->Run();
timeout.Cancel();
}
static void CheckWrapper(
const base::Callback<void(scoped_ptr<Action::ActionVector>)>& checker,
const base::Closure& done,
scoped_ptr<Action::ActionVector> results) {
checker.Run(results.Pass());
done.Run();
}
static void TimeoutCallback() {
base::MessageLoop::current()->QuitWhenIdle();
FAIL() << "Policy test timed out waiting for results";
}
static void RetrieveActions_LogAndFetchActions(
scoped_ptr<std::vector<scoped_refptr<Action> > > i) {
ASSERT_EQ(2, static_cast<int>(i->size()));
}
static void Arguments_Present(scoped_ptr<Action::ActionVector> i) {
scoped_refptr<Action> last = i->front();
std::string args =
"ID=odlameecjipmbmbejkplpemijjgpljce CATEGORY=api_call "
"API=extension.connect ARGS=[\"hello\",\"world\"]";
ASSERT_EQ(args, last->PrintForDebug());
}
static void Arguments_GetTodaysActions(
scoped_ptr<Action::ActionVector> actions) {
std::string api_print =
"ID=punky CATEGORY=api_call API=brewster ARGS=[\"woof\"]";
std::string dom_print =
"ID=punky CATEGORY=dom_access API=lets ARGS=[\"vamoose\"] "
"PAGE_URL=http://www.google.com/";
ASSERT_EQ(2, static_cast<int>(actions->size()));
ASSERT_EQ(dom_print, actions->at(0)->PrintForDebug());
ASSERT_EQ(api_print, actions->at(1)->PrintForDebug());
}
static void Arguments_GetOlderActions(
scoped_ptr<Action::ActionVector> actions) {
std::string api_print =
"ID=punky CATEGORY=api_call API=brewster ARGS=[\"woof\"]";
std::string dom_print =
"ID=punky CATEGORY=dom_access API=lets ARGS=[\"vamoose\"] "
"PAGE_URL=http://www.google.com/";
ASSERT_EQ(2, static_cast<int>(actions->size()));
ASSERT_EQ(dom_print, actions->at(0)->PrintForDebug());
ASSERT_EQ(api_print, actions->at(1)->PrintForDebug());
}
protected:
ExtensionService* extension_service_;
scoped_ptr<TestingProfile> profile_;
content::TestBrowserThreadBundle thread_bundle_;
// Used to preserve a copy of the original command line.
// The test framework will do this itself as well. However, by then,
// it is too late to call ActivityLog::RecomputeLoggingIsEnabled() in
// TearDown().
CommandLine saved_cmdline_;
#if defined OS_CHROMEOS
chromeos::ScopedTestDeviceSettingsService test_device_settings_service_;
chromeos::ScopedTestCrosSettings test_cros_settings_;
scoped_ptr<chromeos::ScopedTestUserManager> test_user_manager_;
#endif
};
TEST_F(FullStreamUIPolicyTest, Construct) {
ActivityLogPolicy* policy = new FullStreamUIPolicy(profile_.get());
scoped_refptr<const Extension> extension =
ExtensionBuilder()
.SetManifest(DictionaryBuilder()
.Set("name", "Test extension")
.Set("version", "1.0.0")
.Set("manifest_version", 2))
.Build();
extension_service_->AddExtension(extension.get());
scoped_ptr<base::ListValue> args(new base::ListValue());
scoped_refptr<Action> action = new Action(extension->id(),
base::Time::Now(),
Action::ACTION_API_CALL,
"tabs.testMethod");
action->set_args(args.Pass());
policy->ProcessAction(action);
policy->Close();
}
TEST_F(FullStreamUIPolicyTest, LogAndFetchActions) {
ActivityLogPolicy* policy = new FullStreamUIPolicy(profile_.get());
scoped_refptr<const Extension> extension =
ExtensionBuilder()
.SetManifest(DictionaryBuilder()
.Set("name", "Test extension")
.Set("version", "1.0.0")
.Set("manifest_version", 2))
.Build();
extension_service_->AddExtension(extension.get());
GURL gurl("http://www.google.com");
// Write some API calls
scoped_refptr<Action> action_api = new Action(extension->id(),
base::Time::Now(),
Action::ACTION_API_CALL,
"tabs.testMethod");
action_api->set_args(make_scoped_ptr(new base::ListValue()));
policy->ProcessAction(action_api);
scoped_refptr<Action> action_dom = new Action(extension->id(),
base::Time::Now(),
Action::ACTION_DOM_ACCESS,
"document.write");
action_dom->set_args(make_scoped_ptr(new base::ListValue()));
action_dom->set_page_url(gurl);
policy->ProcessAction(action_dom);
CheckReadData(
policy,
extension->id(),
0,
base::Bind(&FullStreamUIPolicyTest::RetrieveActions_LogAndFetchActions));
policy->Close();
}
TEST_F(FullStreamUIPolicyTest, LogWithArguments) {
ActivityLogPolicy* policy = new FullStreamUIPolicy(profile_.get());
scoped_refptr<const Extension> extension =
ExtensionBuilder()
.SetManifest(DictionaryBuilder()
.Set("name", "Test extension")
.Set("version", "1.0.0")
.Set("manifest_version", 2))
.Build();
extension_service_->AddExtension(extension.get());
scoped_ptr<base::ListValue> args(new base::ListValue());
args->Set(0, new base::StringValue("hello"));
args->Set(1, new base::StringValue("world"));
scoped_refptr<Action> action = new Action(extension->id(),
base::Time::Now(),
Action::ACTION_API_CALL,
"extension.connect");
action->set_args(args.Pass());
policy->ProcessAction(action);
CheckReadData(policy,
extension->id(),
0,
base::Bind(&FullStreamUIPolicyTest::Arguments_Present));
policy->Close();
}
TEST_F(FullStreamUIPolicyTest, GetTodaysActions) {
ActivityLogPolicy* policy = new FullStreamUIPolicy(profile_.get());
// Use a mock clock to ensure that events are not recorded on the wrong day
// when the test is run close to local midnight. Note: Ownership is passed
// to the policy, but we still keep a pointer locally. The policy will take
// care of destruction; this is safe since the policy outlives all our
// accesses to the mock clock.
base::SimpleTestClock* mock_clock = new base::SimpleTestClock();
mock_clock->SetNow(base::Time::Now().LocalMidnight() +
base::TimeDelta::FromHours(12));
policy->SetClockForTesting(scoped_ptr<base::Clock>(mock_clock));
// Record some actions
scoped_refptr<Action> action =
new Action("punky",
mock_clock->Now() - base::TimeDelta::FromMinutes(40),
Action::ACTION_API_CALL,
"brewster");
action->mutable_args()->AppendString("woof");
policy->ProcessAction(action);
action =
new Action("punky", mock_clock->Now(), Action::ACTION_DOM_ACCESS, "lets");
action->mutable_args()->AppendString("vamoose");
action->set_page_url(GURL("http://www.google.com"));
policy->ProcessAction(action);
action = new Action(
"scoobydoo", mock_clock->Now(), Action::ACTION_DOM_ACCESS, "lets");
action->mutable_args()->AppendString("vamoose");
action->set_page_url(GURL("http://www.google.com"));
policy->ProcessAction(action);
CheckReadData(
policy,
"punky",
0,
base::Bind(&FullStreamUIPolicyTest::Arguments_GetTodaysActions));
policy->Close();
}
// Check that we can read back less recent actions in the db.
TEST_F(FullStreamUIPolicyTest, GetOlderActions) {
ActivityLogPolicy* policy = new FullStreamUIPolicy(profile_.get());
// Use a mock clock to ensure that events are not recorded on the wrong day
// when the test is run close to local midnight.
base::SimpleTestClock* mock_clock = new base::SimpleTestClock();
mock_clock->SetNow(base::Time::Now().LocalMidnight() +
base::TimeDelta::FromHours(12));
policy->SetClockForTesting(scoped_ptr<base::Clock>(mock_clock));
// Record some actions
scoped_refptr<Action> action =
new Action("punky",
mock_clock->Now() - base::TimeDelta::FromDays(3) -
base::TimeDelta::FromMinutes(40),
Action::ACTION_API_CALL,
"brewster");
action->mutable_args()->AppendString("woof");
policy->ProcessAction(action);
action = new Action("punky",
mock_clock->Now() - base::TimeDelta::FromDays(3),
Action::ACTION_DOM_ACCESS,
"lets");
action->mutable_args()->AppendString("vamoose");
action->set_page_url(GURL("http://www.google.com"));
policy->ProcessAction(action);
action = new Action("punky",
mock_clock->Now(),
Action::ACTION_DOM_ACCESS,
"lets");
action->mutable_args()->AppendString("too new");
action->set_page_url(GURL("http://www.google.com"));
policy->ProcessAction(action);
action = new Action("punky",
mock_clock->Now() - base::TimeDelta::FromDays(7),
Action::ACTION_DOM_ACCESS,
"lets");
action->mutable_args()->AppendString("too old");
action->set_page_url(GURL("http://www.google.com"));
policy->ProcessAction(action);
CheckReadData(
policy,
"punky",
3,
base::Bind(&FullStreamUIPolicyTest::Arguments_GetOlderActions));
policy->Close();
}
} // namespace extensions
| 38.944444 | 80 | 0.655229 | [
"object",
"vector"
] |
2c46fd3e1491c75e942b264c67d28c37e2d43a03 | 1,672 | cpp | C++ | CentipedeGame_gageoconnor/Game Components/BulletFactory.cpp | Shaditto/centipede-teal | f078b11eaecddae17709dc9f917348b7b0733d56 | [
"MIT"
] | null | null | null | CentipedeGame_gageoconnor/Game Components/BulletFactory.cpp | Shaditto/centipede-teal | f078b11eaecddae17709dc9f917348b7b0733d56 | [
"MIT"
] | null | null | null | CentipedeGame_gageoconnor/Game Components/BulletFactory.cpp | Shaditto/centipede-teal | f078b11eaecddae17709dc9f917348b7b0733d56 | [
"MIT"
] | 1 | 2019-11-13T19:26:34.000Z | 2019-11-13T19:26:34.000Z | /* BulletFactory.cpp - Gage O'Connor, October 2017 */
#include "TEAL/CommonElements.h"
#include "BulletFactory.h"
#include "Bullet.h"
#include "SoundManager.h"
#include "CommandSound.h"
BulletFactory *BulletFactory::pInstance = nullptr;
BulletFactory::BulletFactory()
{
// This command is created once only and reused every time this game object is active
pSound = SoundManager::GetSoundCommand(SoundManager::SoundEvents::FireSnd);
}
void BulletFactory::privateCreateBullet(sf::Vector2f pos, Player *player)
{
Bullet *bullet;
if (recycledBullets.empty())
{
ConsoleMsg::WriteLine("New Bullet");
bullet = new Bullet(player);
// Object will return here instead of being destroyed
bullet->SetExternalManagement(recycleBullet);
}
else
{
ConsoleMsg::WriteLine("Recycled Bullet");
bullet = recycledBullets.top();
recycledBullets.pop();
// Register back to scene
bullet->RegisterToCurrentScene();
}
bullet->Initialize(pos);
}
void BulletFactory::privateRecycleBullet(GameObject *bullet)
{
recycledBullets.push((Bullet*)bullet);
ConsoleMsg::WriteLine("Recycled Stack Size: " + Tools::ToString(recycledBullets.size()));
}
void BulletFactory::Terminate()
{
delete pInstance;
pInstance = nullptr;
}
void BulletFactory::PlaySound()
{
//ConsoleMsg::WriteLine("Bullet Sound: Sending bullet sound command\n");
SoundManager::SendSoundCommand(Instance().pSound);
}
BulletFactory::~BulletFactory()
{
//ConsoleMsg::WriteLine("Deleting Recycled Bullet (" + Tools::ToString(recycledBullets.size()) + ")");
// Forcefully delete Recycled Bullets
while (!recycledBullets.empty())
{
delete recycledBullets.top();
recycledBullets.pop();
}
} | 22.90411 | 103 | 0.741627 | [
"object"
] |
2c4c676a124e4eabb56bff45fc4b07cf439f46d9 | 10,276 | cpp | C++ | library/test/test_api_create_device_android.cpp | KhronosGroup/Vulkan-Profiles | 493351df53f712bffc2d01316ff08f64a0d94761 | [
"BSD-2-Clause",
"Apache-2.0"
] | 43 | 2022-01-25T14:50:23.000Z | 2022-03-31T13:03:36.000Z | library/test/test_api_create_device_android.cpp | KhronosGroup/Vulkan-Profiles | 493351df53f712bffc2d01316ff08f64a0d94761 | [
"BSD-2-Clause",
"Apache-2.0"
] | 163 | 2022-01-25T14:43:12.000Z | 2022-03-31T17:25:57.000Z | library/test/test_api_create_device_android.cpp | KhronosGroup/Vulkan-Profiles | 493351df53f712bffc2d01316ff08f64a0d94761 | [
"BSD-2-Clause",
"Apache-2.0"
] | 4 | 2022-01-25T21:33:44.000Z | 2022-03-17T14:25:49.000Z | /*
* Copyright (c) 2021-2022 Valve Corporation
* Copyright (c) 2021-2022 LunarG, 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.
*
* Authors:
* - Christophe Riccio <christophe@lunarg.com>
* Mark Lobodzinski <mark@lunarg.com>
*/
#define VK_ENABLE_BETA_EXTENSIONS 1
#include "test.hpp"
#include <vulkan/vulkan_android.h>
#include <vulkan/debug/vulkan_profiles.hpp>
bool IsShieldTv(VkPhysicalDevice pdev) {
// This identifier should cover ShieldTV and ShieldTVb devices, but not other Tegra devices
std::string shield_tv_identifier = "(nvgpu)";
VkPhysicalDeviceProperties pdev_props{};
vkGetPhysicalDeviceProperties(pdev, &pdev_props);
bool result = false;
std::string device_name = pdev_props.deviceName;
if (device_name.find(shield_tv_identifier) != std::string::npos) {
result = true;
}
return result;
}
#include <android/native_window.h>
#include <android/log.h>
#include <android_native_app_glue.h>
const char *appTag = "VpLibrary_test_api_create_device_android";
static bool initialized = false;
static bool active = false;
static android_app *g_app;
static TestScaffold* scaffold = nullptr;
void addFullTestCommentIfPresent(const ::testing::TestInfo &test_info, std::string &error_message) {
const char *const type_param = test_info.type_param();
const char *const value_param = test_info.value_param();
if (type_param != NULL || value_param != NULL) {
error_message.append(", where ");
if (type_param != NULL) {
error_message.append("TypeParam = ").append(type_param);
if (value_param != NULL) error_message.append(" and ");
}
if (value_param != NULL) {
error_message.append("GetParam() = ").append(value_param);
}
}
}
// Inspired by https://github.com/google/googletest/blob/master/googletest/docs/AdvancedGuide.md
class LogcatPrinter : public ::testing::EmptyTestEventListener {
// Called before a test starts.
virtual void OnTestStart(const ::testing::TestInfo &test_info) {
__android_log_print(ANDROID_LOG_INFO, appTag, "[ RUN ] %s.%s", test_info.test_case_name(), test_info.name());
}
// Called after a failed assertion or a SUCCEED() invocation.
virtual void OnTestPartResult(const ::testing::TestPartResult &result) {
// If the test part succeeded, we don't need to do anything.
if (result.type() == ::testing::TestPartResult::kSuccess) return;
__android_log_print(ANDROID_LOG_INFO, appTag, "%s in %s:%d %s", result.failed() ? "*** Failure" : "Success",
result.file_name(), result.line_number(), result.summary());
}
// Called after a test ends.
virtual void OnTestEnd(const ::testing::TestInfo &info) {
std::string result;
if (info.result()->Passed()) {
result.append("[ OK ]");
} else {
result.append("[ FAILED ]");
}
result.append(info.test_case_name()).append(".").append(info.name());
if (info.result()->Failed()) addFullTestCommentIfPresent(info, result);
if (::testing::GTEST_FLAG(print_time)) {
std::ostringstream os;
os << info.result()->elapsed_time();
result.append(" (").append(os.str()).append(" ms)");
}
__android_log_print(ANDROID_LOG_INFO, appTag, "%s", result.c_str());
};
};
// Convert Intents to argv
std::vector<std::string> get_args(android_app &app, const char *intent_extra_data_key) {
std::vector<std::string> args;
JavaVM &vm = *app.activity->vm;
JNIEnv *p_env;
if (vm.AttachCurrentThread(&p_env, nullptr) != JNI_OK) return args;
JNIEnv &env = *p_env;
jobject activity = app.activity->clazz;
jmethodID get_intent_method = env.GetMethodID(env.GetObjectClass(activity), "getIntent", "()Landroid/content/Intent;");
jobject intent = env.CallObjectMethod(activity, get_intent_method);
jmethodID get_string_extra_method =
env.GetMethodID(env.GetObjectClass(intent), "getStringExtra", "(Ljava/lang/String;)Ljava/lang/String;");
jvalue get_string_extra_args;
get_string_extra_args.l = env.NewStringUTF(intent_extra_data_key);
jstring extra_str = static_cast<jstring>(env.CallObjectMethodA(intent, get_string_extra_method, &get_string_extra_args));
std::string args_str;
if (extra_str) {
const char *extra_utf = env.GetStringUTFChars(extra_str, nullptr);
args_str = extra_utf;
env.ReleaseStringUTFChars(extra_str, extra_utf);
env.DeleteLocalRef(extra_str);
}
env.DeleteLocalRef(get_string_extra_args.l);
env.DeleteLocalRef(intent);
vm.DetachCurrentThread();
// split args_str
std::stringstream ss(args_str);
std::string arg;
while (std::getline(ss, arg, ' ')) {
if (!arg.empty()) args.push_back(arg);
}
return args;
}
static int32_t processInput(struct android_app *app, AInputEvent *event) { return 0; }
static void processCommand(struct android_app *app, int32_t cmd) {
switch (cmd) {
case APP_CMD_INIT_WINDOW: {
if (app->window) {
initialized = true;
}
break;
}
case APP_CMD_GAINED_FOCUS: {
active = true;
break;
}
case APP_CMD_LOST_FOCUS: {
active = false;
break;
}
}
}
static void destroyActivity(struct android_app *app) {
ANativeActivity_finish(app->activity);
// Wait for APP_CMD_DESTROY
while (app->destroyRequested == 0) {
struct android_poll_source *source = nullptr;
int events = 0;
int result = ALooper_pollAll(-1, nullptr, &events, reinterpret_cast<void **>(&source));
if ((result >= 0) && (source)) {
source->process(app, source);
} else {
break;
}
}
}
void android_main(struct android_app *app) {
static ANativeWindow *window;
app->onAppCmd = processCommand;
app->onInputEvent = processInput;
g_app = app;
while (1) {
int events;
struct android_poll_source *source;
while (ALooper_pollAll(active ? 0 : -1, NULL, &events, (void **)&source) >= 0) {
if (source) {
source->process(app, source);
}
if (app->destroyRequested != 0) {
return;
}
}
if (initialized && active) {
// Use the following key to send arguments to gtest, i.e.
// --es args "--gtest_filter=-VkLayerTest.foo"
const char key[] = "args";
std::vector<std::string> args = get_args(*app, key);
std::string filter = "";
if (args.size() > 0) {
__android_log_print(ANDROID_LOG_INFO, appTag, "Intent args = %s", args[0].c_str());
filter += args[0];
} else {
__android_log_print(ANDROID_LOG_INFO, appTag, "No Intent args detected");
}
int argc = 2;
char *argv[] = {(char *)"foo", (char *)filter.c_str()};
__android_log_print(ANDROID_LOG_DEBUG, appTag, "filter = %s", argv[1]);
// Route output to files until we can override the gtest output
freopen("/sdcard/Android/data/com.example.VpLibrary_test_api_create_device_android/files/out.txt", "w", stdout);
freopen("/sdcard/Android/data/com.example.VpLibrary_test_api_create_device_android/files/err.txt", "w", stderr);
::testing::InitGoogleTest(&argc, argv);
::testing::TestEventListeners &listeners = ::testing::UnitTest::GetInstance()->listeners();
listeners.Append(new LogcatPrinter);
::scaffold = new TestScaffold;
int result = RUN_ALL_TESTS();
if (result != 0) {
__android_log_print(ANDROID_LOG_INFO, appTag, "==== Tests FAILED ====");
} else {
__android_log_print(ANDROID_LOG_INFO, appTag, "==== Tests PASSED ====");
}
fclose(stdout);
fclose(stderr);
destroyActivity(app);
delete ::scaffold;
::scaffold = nullptr;
raise(SIGTERM);
return;
}
}
}
TEST(library_api, vpCreateDevice) {
TestScaffold scaffold;
const VpProfileProperties profile = {VP_ANDROID_BASELINE_2021_NAME, VP_ANDROID_BASELINE_2021_SPEC_VERSION};
VkDeviceCreateInfo info = {};
info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
info.pNext = nullptr;
info.queueCreateInfoCount = 1;
info.pQueueCreateInfos = &scaffold.queueCreateInfo;
info.enabledExtensionCount = 0;
info.ppEnabledExtensionNames = nullptr;
info.pEnabledFeatures = nullptr;
VpDeviceCreateInfo profileInfo = {};
profileInfo.pCreateInfo = &info;
profileInfo.pProfile = &profile;
VkDevice device = VK_NULL_HANDLE;
VkResult res = vpCreateDevice(scaffold.physicalDevice, &profileInfo, nullptr, &device);
#if defined(ANDROID)
EXPECT_TRUE(res == VK_SUCCESS);
EXPECT_TRUE(device != VK_NULL_HANDLE);
#else
EXPECT_TRUE(res != VK_SUCCESS);
#endif
}
TEST(library_api, vpGetPhysicalDeviceProfileSupport) {
TestScaffold scaffold;
if (IsShieldTv(scaffold.physicalDevice)) {
__android_log_print(ANDROID_LOG_INFO, appTag, " Shield TV is too old to support the Android profile, skipping test");
return;
}
VpProfileProperties profile{VP_ANDROID_BASELINE_2021_NAME, VP_ANDROID_BASELINE_2021_SPEC_VERSION};
VkBool32 supported = VK_FALSE;
vpGetPhysicalDeviceProfileSupport(scaffold.instance, scaffold.physicalDevice, &profile, &supported);
EXPECT_EQ(VK_TRUE, supported);
}
| 34.716216 | 134 | 0.642857 | [
"vector"
] |
2c50b67cc669f66cd1f81fca0f7c24f04c821ef2 | 908 | cpp | C++ | 139.cpp | Alex-Amber/LeetCode | c8d09e86cee52648f84ca2afed8dd0f13e51ab58 | [
"MIT"
] | null | null | null | 139.cpp | Alex-Amber/LeetCode | c8d09e86cee52648f84ca2afed8dd0f13e51ab58 | [
"MIT"
] | null | null | null | 139.cpp | Alex-Amber/LeetCode | c8d09e86cee52648f84ca2afed8dd0f13e51ab58 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
using ull = uint64_t;
using ll = int64_t;
using ld = long double;
typedef vector<int> vi;
typedef pair<int, int> ii;
typedef vector<ii> vii;
class Solution
{
public:
vi memo;
bool matchWord(const string& s, int start, unordered_set<string>& wordDict)
{
if (start == s.size())
return true;
if (memo[start] != -1)
return (bool) memo[start];
int rest_len = s.size() - start;
for (int len = rest_len; len > 0; --len)
{
if (wordDict.count(s.substr(start, len)) && matchWord(s, start + len, wordDict))
return memo[start] = true;
}
return memo[start] = false;
}
bool wordBreak(string s, vector<string>& wordDict)
{
unordered_set<string> wordSet;
for (vector<string>::iterator iter = wordDict.begin(); iter != wordDict.end(); ++iter)
wordSet.insert(*iter);
memo.assign(s.size(), -1);
return matchWord(s, 0, wordSet);
}
};
| 23.282051 | 88 | 0.655286 | [
"vector"
] |
2c572d631cabee40dcaee5b95905364608a61a52 | 314 | hpp | C++ | src/scene/scene.hpp | Sylvain-Durand/RT-EXplorer | 8e2f8de39483bae27702657864f0557635e7036a | [
"MIT"
] | null | null | null | src/scene/scene.hpp | Sylvain-Durand/RT-EXplorer | 8e2f8de39483bae27702657864f0557635e7036a | [
"MIT"
] | null | null | null | src/scene/scene.hpp | Sylvain-Durand/RT-EXplorer | 8e2f8de39483bae27702657864f0557635e7036a | [
"MIT"
] | null | null | null | #pragma once
#include <scene/ecs/entity_manager.hpp>
namespace RTEX {
/**
* @brief Interface definition for an RTEX scene
*
*/
class Scene {
public:
/**
* @brief Construct a new Scene object
*
*/
Scene() = default;
private:
EntityManager m_entity_manager;
};
} // namespace RTEX
| 13.083333 | 48 | 0.633758 | [
"object"
] |
2c5ffb3b4960a5b26ae54d28dc4917e3f65f66bb | 872 | cpp | C++ | Difficulty 3/shopping_list.cpp | BrynjarGeir/Kattis | a151972cbae3db04a8e6764d5fa468d0146c862b | [
"MIT"
] | null | null | null | Difficulty 3/shopping_list.cpp | BrynjarGeir/Kattis | a151972cbae3db04a8e6764d5fa468d0146c862b | [
"MIT"
] | null | null | null | Difficulty 3/shopping_list.cpp | BrynjarGeir/Kattis | a151972cbae3db04a8e6764d5fa468d0146c862b | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <algorithm>
#include<bits/stdc++.h>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
string w;
vector<string> in_every;
for(int i = 0; i < m; i++) {
cin >> w;
in_every.push_back(w);
}
for(int i = 1; i < n; i++) {
vector<string> this_one;
for(int j = 0; j < m; j++) {
cin >> w;
this_one.push_back(w);
}
for(string s: in_every) {
if (find(this_one.begin(), this_one.end(), s) != this_one.end()) continue;
else {
int pos = find(in_every.begin(), in_every.end(), s) - in_every.begin();
in_every.erase(in_every.begin() + pos);
}
}
}
cout << in_every.size() << endl;
for(string s: in_every) {
cout << s << endl;
}
} | 22.358974 | 87 | 0.474771 | [
"vector"
] |
2c6347db8a6f2682dad07731be595a851721e9d9 | 2,756 | hpp | C++ | include/cru/osx/graphics/quartz/TextLayout.hpp | crupest/cru | 3c3a08a02a0f8fc56dc2da3374f025d4fdaf62c5 | [
"Apache-2.0"
] | 1 | 2021-09-30T11:43:03.000Z | 2021-09-30T11:43:03.000Z | include/cru/osx/graphics/quartz/TextLayout.hpp | crupest/cru | 3c3a08a02a0f8fc56dc2da3374f025d4fdaf62c5 | [
"Apache-2.0"
] | 11 | 2021-08-22T12:55:56.000Z | 2022-03-13T15:01:29.000Z | include/cru/osx/graphics/quartz/TextLayout.hpp | crupest/cru | 3c3a08a02a0f8fc56dc2da3374f025d4fdaf62c5 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "Resource.hpp"
#include "Font.hpp"
#include "cru/common/Base.hpp"
#include "cru/platform/graphics/TextLayout.hpp"
#include <memory>
namespace cru::platform::graphics::osx::quartz {
class OsxCTTextLayout : public OsxQuartzResource, public virtual ITextLayout {
public:
OsxCTTextLayout(IGraphicsFactory* graphics_factory,
std::shared_ptr<OsxCTFont> font, const String& str);
CRU_DELETE_COPY(OsxCTTextLayout)
CRU_DELETE_MOVE(OsxCTTextLayout)
~OsxCTTextLayout() override;
public:
String GetText() override { return text_; }
void SetText(String new_text) override;
std::shared_ptr<IFont> GetFont() override { return font_; }
void SetFont(std::shared_ptr<IFont> font) override;
void SetMaxWidth(float max_width) override;
void SetMaxHeight(float max_height) override;
bool IsEditMode() override;
void SetEditMode(bool enable) override;
Index GetLineIndexFromCharIndex(Index char_index) override;
Index GetLineCount() override;
float GetLineHeight(Index line_index) override;
Rect GetTextBounds(bool includingTrailingSpace = false) override;
std::vector<Rect> TextRangeRect(const TextRange& text_range) override;
Rect TextSinglePoint(Index position, bool trailing) override;
TextHitTestResult HitTest(const Point& point) override;
CTFrameRef GetCTFrameRef() const { return ct_frame_; }
CTFrameRef CreateFrameWithColor(const Color& color);
Matrix GetTransform() { return transform_; }
String GetDebugString() override;
private:
void DoSetText(String text);
void ReleaseResource();
void RecreateFrame();
CGRect DoGetTextBounds(bool includingTrailingSpace = false);
CGRect DoGetTextBoundsIncludingEmptyLines(
bool includingTrailingSpace = false);
std::vector<CGRect> DoTextRangeRect(const TextRange& text_range);
CGRect DoTextSinglePoint(Index position, bool trailing);
private:
float max_width_;
float max_height_;
bool edit_mode_;
std::shared_ptr<OsxCTFont> font_;
String text_;
String actual_text_;
CFMutableAttributedStringRef cf_attributed_text_;
CTFramesetterRef ct_framesetter_ = nullptr;
float suggest_height_;
CTFrameRef ct_frame_ = nullptr;
int line_count_;
std::vector<CGPoint> line_origins_;
std::vector<CTLineRef> lines_;
std::vector<float> line_ascents_;
std::vector<float> line_descents_;
std::vector<float> line_heights_;
// The empty line count in the front of the lines.
int head_empty_line_count_;
// The trailing empty line count in the back of the lines.
int tail_empty_line_count_;
// Just for cache.
CGRect text_bounds_without_trailing_space_;
CGRect text_bounds_with_trailing_space_;
Matrix transform_;
};
} // namespace cru::platform::graphics::osx::quartz
| 28.708333 | 78 | 0.769231 | [
"vector"
] |
ef1cae3e548df2d6959621a2f44ef7f0ece5986d | 8,621 | cpp | C++ | src/test_app/main.cpp | publiqnet/mesh.pp | a85e393c0de82b5b477b48bf23f0b89f6ac82c26 | [
"MIT"
] | 1 | 2020-02-22T16:50:11.000Z | 2020-02-22T16:50:11.000Z | src/test_app/main.cpp | publiqnet/mesh.pp | a85e393c0de82b5b477b48bf23f0b89f6ac82c26 | [
"MIT"
] | null | null | null | src/test_app/main.cpp | publiqnet/mesh.pp | a85e393c0de82b5b477b48bf23f0b89f6ac82c26 | [
"MIT"
] | null | null | null |
#define _VERSION_ 2
#if (_VERSION_ == 1)
#include <belt.pp/parser.hpp>
#include <iostream>
#include <string>
using operator_lexers =
beltpp::typelist::type_list<
class operator_plus_lexer,
class operator_minus_lexer,
class operator_multiply_lexer,
class operator_brakets_lexer,
class value_number_lexer,
class white_space_lexer
>;
class operator_plus_lexer :
public beltpp::operator_lexer_base<operator_plus_lexer,
operator_lexers>
{
public:
size_t right = 1;
size_t left_max = -1;
size_t left_min = 0;
enum { grow_priority = 1 };
beltpp::e_three_state_result check(char ch)
{
return beltpp::standard_operator_check<beltpp::standard_operator_set<void>>(ch);
}
template <typename T_iterator>
bool final_check(T_iterator const& it_begin,
T_iterator const& it_end) const
{
return std::string(it_begin, it_end) == "+";
}
};
class operator_minus_lexer :
public beltpp::operator_lexer_base<operator_minus_lexer,
operator_lexers>
{
public:
size_t right = 3;
size_t left_max = -1;
size_t left_min = 1;
enum { grow_priority = 1 };
beltpp::e_three_state_result check(char ch)
{
return beltpp::standard_operator_check<beltpp::standard_operator_set<void>>(ch);
}
template <typename T_iterator>
bool final_check(T_iterator const& it_begin,
T_iterator const& it_end) const
{
return std::string(it_begin, it_end) == "-";
}
};
class operator_multiply_lexer :
public beltpp::operator_lexer_base<operator_multiply_lexer,
operator_lexers>
{
public:
size_t right = 1;
size_t left_max = 1;
size_t left_min = 1;
enum { grow_priority = 1 };
beltpp::e_three_state_result check(char ch)
{
return beltpp::standard_operator_check<beltpp::standard_operator_set<void>>(ch);
}
template <typename T_iterator>
bool final_check(T_iterator const& it_begin,
T_iterator const& it_end) const
{
return std::string(it_begin, it_end) == "*";
}
};
class operator_brakets_lexer :
public beltpp::operator_lexer_base<operator_brakets_lexer,
operator_lexers>
{
bool state_must_open = false;
public:
size_t right = 1;
size_t left_max = 1;
size_t left_min = 1;
enum { grow_priority = 1 };
beltpp::e_three_state_result check(char ch)
{
if ((ch >= 'a' && ch <= 'z') ||
(ch >= 'A' && ch <= 'Z'))
{
state_must_open = true;
return beltpp::e_three_state_result::attempt;
}
if (state_must_open && ch == '}')
return beltpp::e_three_state_result::error;
if (false == state_must_open && ch == '}')
{
right = 0;
left_min = 0;
left_max = 1;
return beltpp::e_three_state_result::success;
}
if (ch == '{')
{
right = 1;
left_min = 0;
left_max = 0;
return beltpp::e_three_state_result::success;
}
return beltpp::e_three_state_result::error;
}
template <typename T_iterator>
bool final_check(T_iterator const& it_begin,
T_iterator const& it_end) const
{
std::string value(it_begin, it_end);
return (value == "{" || value == "}");
}
};
class value_number_lexer :
public beltpp::value_lexer_base<value_number_lexer,
operator_lexers>
{
std::string value;
private:
bool _check(std::string const& v) const
{
size_t pos = 0;
beltpp::stod(v, pos);
if (pos != v.length())
beltpp::stoll(v, pos);
if (pos != v.length())
return false;
return true;
}
public:
beltpp::e_three_state_result check(char ch)
{
value += ch;
if ("." == value || "-" == value || "-." == value)
return beltpp::e_three_state_result::attempt;
else if (_check(value))
return beltpp::e_three_state_result::attempt;
else
return beltpp::e_three_state_result::error;
}
template <typename T_iterator>
bool final_check(T_iterator const& it_begin,
T_iterator const& it_end) const
{
return _check(std::string(it_begin, it_end));
}
bool scan_beyond() const
{
return false;
}
};
class white_space_lexer :
public beltpp::discard_lexer_base<white_space_lexer,
operator_lexers,
beltpp::standard_white_space_set<void>>
{};
int main()
{
std::unique_ptr<
beltpp::expression_tree<operator_lexers,
std::string>> ptr_expression;
//std::string test("\'+-\'+0x2 + s{- 0x3}\"str\\\"ing\'\"-\'k\\\'\"l\'");
//std::string test("{{{{{{}}}}}+\'192.168.1.1\'-1 2 3}");
std::string test("1*2-3+4 4*1 5+6+7");
//std::string test("1+{2}+ + + 3+4+5");
//std::string test("+");
auto it_begin = test.begin();
auto it_end = test.end();
auto it_begin_keep = it_begin;
while (beltpp::parse(ptr_expression, it_begin, it_end))
{
if (it_begin == it_begin_keep)
break;
else
{
std::cout << std::string(it_begin_keep, it_begin) << std::endl;
it_begin_keep = it_begin;
}
}
if (nullptr == ptr_expression)
return 0;
while (auto parent = ptr_expression->parent)
{
ptr_expression.release();
ptr_expression.reset(parent);
}
auto p_iterator = ptr_expression.get();
std::vector<size_t> track;
size_t depth = 0;
std::cout << "=====\n";
while (p_iterator)
{
if (track.size() == depth)
track.push_back(0);
if (track.size() == depth + 1)
{
for (size_t index = 0; index != depth; ++index)
std::cout << '.';
std::cout << p_iterator->lexem.value;
if (p_iterator->lexem.right > 0)
std::cout << " !!!! ";
std::cout << std::endl;
}
size_t next_child_index = -1;
if (false == p_iterator->children.empty())
{
size_t childindex = 0;
if (track.size() > depth + 1)
{
++track[depth + 1];
childindex = track[depth + 1];
}
if (childindex < p_iterator->children.size())
next_child_index = childindex;
}
if (size_t(-1) != next_child_index)
{
p_iterator = p_iterator->children[next_child_index];
++depth;
if (track.size() > depth + 1)
track.resize(depth + 1);
}
else
{
p_iterator = p_iterator->parent;
--depth;
}
}
std::cout << "depth is " << ptr_expression->depth() << std::endl;
return 0;
}
#elif (_VERSION_ == 2)
#include <belt.pp/json.hpp>
#include <string>
#include <iostream>
using std::string;
using std::cout;
using std::endl;
int main()
{
size_t const limit = 2;
beltpp::json::ptr_expression_tree pexp;
beltpp::json::expression_tree* proot = nullptr;
{
string test1 = "{\"rtt\":{},\"message\":{\"rtt\":4},\"\" :1";
auto it_begin = test1.begin();
auto it_end = test1.end();
auto code = beltpp::json::parse_stream(pexp, it_begin, it_end, limit, 10, proot);
cout << &(*it_begin) << endl;
if (beltpp::e_three_state_result::error == code)
cout << "test1 error" << endl;
else
{
cout << "<===" << endl;
cout << beltpp::dump(proot) << endl;
cout << "===>" << endl;
if (beltpp::e_three_state_result::success == code)
return 0;
}
}
{
string test1 = "21}";
auto it_begin = test1.begin();
auto it_end = test1.end();
auto code = beltpp::json::parse_stream(pexp, it_begin, it_end, limit, 10, proot);
cout << &(*it_begin) << endl;
if (beltpp::e_three_state_result::error == code)
cout << "test2 error" << endl;
else
{
cout << "<===" << endl;
cout << beltpp::dump(proot) << endl;
cout << "===>" << endl;
if (beltpp::e_three_state_result::success == code)
return 0;
}
}
return 0;
}
#endif
| 26.203647 | 88 | 0.540889 | [
"vector"
] |
ef28b79de78f8df4dde7677c9690c79caa65540c | 784 | hpp | C++ | ExerciseSoftware/treadmill_prototype.hpp | jorshi/exercise_software | d6fbc44f301395ad1c2408c1d7cd7745ef254b7d | [
"MIT"
] | null | null | null | ExerciseSoftware/treadmill_prototype.hpp | jorshi/exercise_software | d6fbc44f301395ad1c2408c1d7cd7745ef254b7d | [
"MIT"
] | null | null | null | ExerciseSoftware/treadmill_prototype.hpp | jorshi/exercise_software | d6fbc44f301395ad1c2408c1d7cd7745ef254b7d | [
"MIT"
] | null | null | null | //
// treadmill_prototype.hpp
// ExerciseSoftware
//
// Created by Jordie Shier on 2015-11-11.
// Copyright © 2015 Jordie Shier . All rights reserved.
//
#ifndef treadmill_prototype_hpp
#define treadmill_prototype_hpp
#include <stdio.h>
#include <string>
#include "equipment_prototype.hpp"
//! TreadmillPrototype Class
/*!
Used for holding information regarding a treadmill
*/
class TreadmillPrototype: public EquipmentPrototype
{
public:
//! Constructor
TreadmillPrototype();
//! Copy Constructor
TreadmillPrototype(const TreadmillPrototype&);
//! Clone
/*!
Returns a pointer to a new TreadmillPrototype object that is
identical to this one.
*/
EquipmentPrototype* clone() const;
};
#endif /* treadmill_prototype_hpp */ | 20.102564 | 65 | 0.710459 | [
"object"
] |
ef2a0da49dab4714ab6948118c4b2b726dc9765e | 2,255 | cpp | C++ | main.cpp | SamSavitz/E8-Quasicrystals | 3c66dcc40e9645f6cd59b0cd534ccc51af199345 | [
"MIT"
] | 2 | 2022-03-19T20:55:32.000Z | 2022-03-19T20:55:36.000Z | main.cpp | SamSavitz/E8-Quasicrystals | 3c66dcc40e9645f6cd59b0cd534ccc51af199345 | [
"MIT"
] | null | null | null | main.cpp | SamSavitz/E8-Quasicrystals | 3c66dcc40e9645f6cd59b0cd534ccc51af199345 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <array>
#include <cassert>
#include <chrono>
#define _USE_MATH_DEFINES
#include <cmath>
//#include <execution>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <random>
#include <sstream>
#include <vector>
using namespace std;
using namespace chrono;
#include <tbb/parallel_for.h>
using Z = ptrdiff_t;
using R = float;
constexpr Z D = 8;
constexpr Z N = 240;
constexpr R SKEW = 15;
constexpr R minE = -N/SKEW;
constexpr R maxE = N ;
#include "codec.h"
#include "color.h"
using ZV = array <Z, D>;
using RV = array <R, D>;
using RVP = array <RV, 2>;
#include "data.h"
constexpr Z W = 1920;
constexpr Z H = 1080;
constexpr Z P = H*W;
constexpr R RES = 55;
constexpr R XO = W/2;
constexpr R YO = H/2;
constexpr Z FS = 360;
constexpr R EPSILON = 1e-9;
constexpr Z SEED = 2;
#include "vectors.h"
int main(int argc, const char* argv[]) {
RGBEncoder encoder("out.mp4", W, H, 30, 1);
preprocess();
stringstream ss;
high_resolution_clock::time_point ot;
Z oy;
Z yp = -1;
RGB* const rgbFrame = new RGB [P ];
//YUV420* const yuvFrame = new YUV420[P/4];
for (Z n = 0; n < XY.size(); ++n)
for (Z f = 0; f < FS; ++f) {
const Z ff = FS*n + f;
cerr << n << ' ' << f << ' ' << ff << endl;
RVP xy = interpolate(XY[n], XY[n + 1], f);
tbb::parallel_for(
//execution::par_unseq,
tbb::blocked_range <int> (0, H),
[&] (tbb::blocked_range <int> r) {
for (Z y = r.begin(); y < r.end(); ++y) {
const R yf = (y - YO)/RES;
for (Z x = 0; x < W; ++x) {
const R xf = (x - XO)/RES;
const RV z = mix(xf, xy[0], yf, xy[1] );
R sum = 0;
for (const ZV& r : ROOTS)
sum += cos(dot(r, z));
sum *= 2;
rgbFrame[W*y + x] = color(sum);
}
}
}
);
//rgb2yuv420(W, H, rgbFrame, yuvFrame);
encoder.writeFrame(rgbFrame);
}
delete [] rgbFrame;//, yuvFrame;
}
| 19.955752 | 68 | 0.490909 | [
"vector"
] |
ef2ba2c473ac47c444de173eca088ea74d7f2151 | 1,436 | cpp | C++ | Math/Determinant under Composite Modulo.cpp | bazzyadb/all-code | cf3039641b5aa84b1c5b184a95d69bd4091974c9 | [
"MIT"
] | 1,639 | 2021-09-15T09:12:06.000Z | 2022-03-31T22:58:57.000Z | Math/Determinant under Composite Modulo.cpp | bazzyadb/all-code | cf3039641b5aa84b1c5b184a95d69bd4091974c9 | [
"MIT"
] | 16 | 2022-01-15T17:50:08.000Z | 2022-01-28T12:55:21.000Z | Math/Determinant under Composite Modulo.cpp | bazzyadb/all-code | cf3039641b5aa84b1c5b184a95d69bd4091974c9 | [
"MIT"
] | 444 | 2021-09-15T09:17:41.000Z | 2022-03-29T18:21:46.000Z | #include<bits/stdc++.h>
using namespace std;
const int N = 3e5 + 9;
//O(n^3 logn)
int Gauss(vector<vector<int>> a, const int mod) {
int n = (int)a.size(); if (n != a[0].size()) return 0;
int det = 1;
for(int col = 0, row = 0; col < n && row < n; ++col) {
int mx = row;
for(int i = row; i < n; i++) if(a[i][col] > a[mx][col]) mx = i;
if(a[mx][col] == 0) return 0;
for(int i = col; i < n; i++) swap(a[row][i], a[mx][i]);
if (row != mx) det = det == 0 ? 0: mod - det;
for(int i = row + 1; i < n; i++) {
while (a[row][col]) {
int t = a[i][col] / a[row][col];
for (int j = col; j < n; j++) {
a[i][j] -= 1LL * a[row][j] * t % mod;
if (a[i][j] < 0) a[i][j] += mod;
swap(a[i][j], a[row][j]);
}
det = det == 0 ? 0: mod - det;
}
for (int j = col; j < n; j++) swap(a[row][j], a[i][j]);
det = det == 0 ? 0: mod - det;
}
det = 1LL * det * a[row][col] % mod;
++row;
}
return det;
}
int32_t main() {
int n, mod;
while (cin >> n >> mod) {
vector<vector<int>> a(n, vector<int>(n, 0));
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int k; cin >> k;
k %= mod; if (k < 0) k += mod;
a[i][j] = k;
}
}
cout << Gauss(a, mod) << '\n';
}
return 0;
}
//https://www.spoj.com/problems/DETER3/en/
| 28.72 | 68 | 0.405292 | [
"vector"
] |
ef2c5d2b1a73f74a4090368526cc45fbaf0ab2ba | 8,907 | cpp | C++ | client/OAIItemReference.cpp | owncloud/libre-graph-api-qt5 | 7f7c9cf64394ef2771310c53bd1950011383d7bf | [
"Apache-2.0"
] | null | null | null | client/OAIItemReference.cpp | owncloud/libre-graph-api-qt5 | 7f7c9cf64394ef2771310c53bd1950011383d7bf | [
"Apache-2.0"
] | null | null | null | client/OAIItemReference.cpp | owncloud/libre-graph-api-qt5 | 7f7c9cf64394ef2771310c53bd1950011383d7bf | [
"Apache-2.0"
] | null | null | null | // model-body.mustache
// licenseInfo.mustache
/**
* Libre Graph API
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: v0.14.2
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "OAIItemReference.h"
#include <QDebug>
#include <QJsonArray>
#include <QJsonDocument>
#include <QObject>
#include "OAIHelpers.h"
namespace OpenAPI {
class OAIItemReferencePrivate {
friend class OAIItemReference;
QString drive_id;
bool drive_id_isSet;
bool drive_id_isValid;
QString drive_type;
bool drive_type_isSet;
bool drive_type_isValid;
QString id;
bool id_isSet;
bool id_isValid;
QString name;
bool name_isSet;
bool name_isValid;
QString path;
bool path_isSet;
bool path_isValid;
QString share_id;
bool share_id_isSet;
bool share_id_isValid;
};
OAIItemReference::OAIItemReference()
: d_ptr()
{
}
OAIItemReference::OAIItemReference(const OAIItemReference& other)
: d_ptr(other.d_ptr)
{
}
OAIItemReference::OAIItemReference(QString json)
: d_ptr(nullptr)
{
this->fromJson(json);
}
OAIItemReference::~OAIItemReference() = default;
void OAIItemReference::initializeModel() {
if (d_ptr == nullptr) {
d_ptr.reset(new OAIItemReferencePrivate{});
Q_D(OAIItemReference);
d->drive_id_isSet = false;
d->drive_id_isValid = false;
d->drive_type_isSet = false;
d->drive_type_isValid = false;
d->id_isSet = false;
d->id_isValid = false;
d->name_isSet = false;
d->name_isValid = false;
d->path_isSet = false;
d->path_isValid = false;
d->share_id_isSet = false;
d->share_id_isValid = false;
}
}
void OAIItemReference::fromJson(QString jsonString) {
QByteArray array(jsonString.toUtf8());
QJsonDocument doc = QJsonDocument::fromJson(array);
QJsonObject jsonObject = doc.object();
this->fromJsonObject(jsonObject);
}
void OAIItemReference::fromJsonObject(QJsonObject json) {
initializeModel();
Q_D(OAIItemReference);
d->drive_id_isValid = ::OpenAPI::fromJsonValue(d->drive_id, json[QString("driveId")]);
d->drive_id_isSet = !json[QString("driveId")].isNull() && d->drive_id_isValid;
d->drive_type_isValid = ::OpenAPI::fromJsonValue(d->drive_type, json[QString("driveType")]);
d->drive_type_isSet = !json[QString("driveType")].isNull() && d->drive_type_isValid;
d->id_isValid = ::OpenAPI::fromJsonValue(d->id, json[QString("id")]);
d->id_isSet = !json[QString("id")].isNull() && d->id_isValid;
d->name_isValid = ::OpenAPI::fromJsonValue(d->name, json[QString("name")]);
d->name_isSet = !json[QString("name")].isNull() && d->name_isValid;
d->path_isValid = ::OpenAPI::fromJsonValue(d->path, json[QString("path")]);
d->path_isSet = !json[QString("path")].isNull() && d->path_isValid;
d->share_id_isValid = ::OpenAPI::fromJsonValue(d->share_id, json[QString("shareId")]);
d->share_id_isSet = !json[QString("shareId")].isNull() && d->share_id_isValid;
}
QString OAIItemReference::asJson() const {
QJsonObject obj = this->asJsonObject();
QJsonDocument doc(obj);
QByteArray bytes = doc.toJson();
return QString(bytes);
}
QJsonObject OAIItemReference::asJsonObject() const {
Q_D(const OAIItemReference);
if(!d){
return {};
}
QJsonObject obj;
if (d->drive_id_isSet) {
obj.insert(QString("driveId"), ::OpenAPI::toJsonValue(d->drive_id));
}
if (d->drive_type_isSet) {
obj.insert(QString("driveType"), ::OpenAPI::toJsonValue(d->drive_type));
}
if (d->id_isSet) {
obj.insert(QString("id"), ::OpenAPI::toJsonValue(d->id));
}
if (d->name_isSet) {
obj.insert(QString("name"), ::OpenAPI::toJsonValue(d->name));
}
if (d->path_isSet) {
obj.insert(QString("path"), ::OpenAPI::toJsonValue(d->path));
}
if (d->share_id_isSet) {
obj.insert(QString("shareId"), ::OpenAPI::toJsonValue(d->share_id));
}
return obj;
}
QString OAIItemReference::getDriveId() const {
Q_D(const OAIItemReference);
if(!d){
return {};
}
return d->drive_id;
}
void OAIItemReference::setDriveId(const QString &drive_id) {
Q_D(OAIItemReference);
Q_ASSERT(d);
d->drive_id = drive_id;
d->drive_id_isSet = true;
}
bool OAIItemReference::is_drive_id_Set() const{
Q_D(const OAIItemReference);
if(!d){
return false;
}
return d->drive_id_isSet;
}
bool OAIItemReference::is_drive_id_Valid() const{
Q_D(const OAIItemReference);
if(!d){
return false;
}
return d->drive_id_isValid;
}
QString OAIItemReference::getDriveType() const {
Q_D(const OAIItemReference);
if(!d){
return {};
}
return d->drive_type;
}
void OAIItemReference::setDriveType(const QString &drive_type) {
Q_D(OAIItemReference);
Q_ASSERT(d);
d->drive_type = drive_type;
d->drive_type_isSet = true;
}
bool OAIItemReference::is_drive_type_Set() const{
Q_D(const OAIItemReference);
if(!d){
return false;
}
return d->drive_type_isSet;
}
bool OAIItemReference::is_drive_type_Valid() const{
Q_D(const OAIItemReference);
if(!d){
return false;
}
return d->drive_type_isValid;
}
QString OAIItemReference::getId() const {
Q_D(const OAIItemReference);
if(!d){
return {};
}
return d->id;
}
void OAIItemReference::setId(const QString &id) {
Q_D(OAIItemReference);
Q_ASSERT(d);
d->id = id;
d->id_isSet = true;
}
bool OAIItemReference::is_id_Set() const{
Q_D(const OAIItemReference);
if(!d){
return false;
}
return d->id_isSet;
}
bool OAIItemReference::is_id_Valid() const{
Q_D(const OAIItemReference);
if(!d){
return false;
}
return d->id_isValid;
}
QString OAIItemReference::getName() const {
Q_D(const OAIItemReference);
if(!d){
return {};
}
return d->name;
}
void OAIItemReference::setName(const QString &name) {
Q_D(OAIItemReference);
Q_ASSERT(d);
d->name = name;
d->name_isSet = true;
}
bool OAIItemReference::is_name_Set() const{
Q_D(const OAIItemReference);
if(!d){
return false;
}
return d->name_isSet;
}
bool OAIItemReference::is_name_Valid() const{
Q_D(const OAIItemReference);
if(!d){
return false;
}
return d->name_isValid;
}
QString OAIItemReference::getPath() const {
Q_D(const OAIItemReference);
if(!d){
return {};
}
return d->path;
}
void OAIItemReference::setPath(const QString &path) {
Q_D(OAIItemReference);
Q_ASSERT(d);
d->path = path;
d->path_isSet = true;
}
bool OAIItemReference::is_path_Set() const{
Q_D(const OAIItemReference);
if(!d){
return false;
}
return d->path_isSet;
}
bool OAIItemReference::is_path_Valid() const{
Q_D(const OAIItemReference);
if(!d){
return false;
}
return d->path_isValid;
}
QString OAIItemReference::getShareId() const {
Q_D(const OAIItemReference);
if(!d){
return {};
}
return d->share_id;
}
void OAIItemReference::setShareId(const QString &share_id) {
Q_D(OAIItemReference);
Q_ASSERT(d);
d->share_id = share_id;
d->share_id_isSet = true;
}
bool OAIItemReference::is_share_id_Set() const{
Q_D(const OAIItemReference);
if(!d){
return false;
}
return d->share_id_isSet;
}
bool OAIItemReference::is_share_id_Valid() const{
Q_D(const OAIItemReference);
if(!d){
return false;
}
return d->share_id_isValid;
}
bool OAIItemReference::isSet() const {
Q_D(const OAIItemReference);
if(!d){
return false;
}
bool isObjectUpdated = false;
do {
if (d->drive_id_isSet) {
isObjectUpdated = true;
break;
}
if (d->drive_type_isSet) {
isObjectUpdated = true;
break;
}
if (d->id_isSet) {
isObjectUpdated = true;
break;
}
if (d->name_isSet) {
isObjectUpdated = true;
break;
}
if (d->path_isSet) {
isObjectUpdated = true;
break;
}
if (d->share_id_isSet) {
isObjectUpdated = true;
break;
}
} while (false);
return isObjectUpdated;
}
bool OAIItemReference::isValid() const {
Q_D(const OAIItemReference);
if(!d){
return false;
}
// only required properties are required for the object to be considered valid
return true;
}
} // namespace OpenAPI
| 21.884521 | 109 | 0.63074 | [
"object",
"model"
] |
ef3e492cc18241c039c5f1427930e9af9cd0dc5a | 7,245 | hpp | C++ | src/Voxie/OldFilterMask/Selection2DMask.hpp | voxie-viewer/voxie | d2b5e6760519782e9ef2e51f5322a3baa0cb1198 | [
"MIT"
] | 4 | 2016-06-03T18:41:43.000Z | 2020-04-17T20:28:58.000Z | src/Voxie/OldFilterMask/Selection2DMask.hpp | voxie-viewer/voxie | d2b5e6760519782e9ef2e51f5322a3baa0cb1198 | [
"MIT"
] | null | null | null | src/Voxie/OldFilterMask/Selection2DMask.hpp | voxie-viewer/voxie | d2b5e6760519782e9ef2e51f5322a3baa0cb1198 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2014-2022 The Voxie Authors
*
* 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.
*/
#pragma once
#include <Voxie/Voxie.hpp>
#include <Voxie/OldFilterMask/ellipse.hpp>
#include <Voxie/OldFilterMask/ellipseData.hpp>
#include <Voxie/OldFilterMask/polygon.hpp>
#include <Voxie/OldFilterMask/polygonData.hpp>
#include <Voxie/OldFilterMask/polygonPoint.hpp>
#include <Voxie/OldFilterMask/rectangle.hpp>
#include <Voxie/OldFilterMask/rectangleData.hpp>
#include <Voxie/OldFilterMask/shapes.hpp>
#include <VoxieBackend/OpenCL/CLInstance.hpp>
#include <QtCore/QMutex>
#include <QtCore/QObject>
#include <QtGui/QPainterPath>
namespace vx {
namespace filter {
/**
* Selection2DMask is class which every 2DFilter contains. This is for 2D masks.
* This class provides several methods for creating a 2D Selection mask in the
* forms, Rectangle, Ellipse and Polygon. This Forms can also be deleted. By
* changing the origin, this mask will be retained when the slice before and the
* new one are equal. For these there are the slots translateOrigin whene origin
* is moved and rotate when origin is rotated.
* @brief The Selection2DMask class is for all masks on 2D. This classes offers
* methods for creating masks, deleting them and manipulating them when
* something changed from the origin. It also contains the drawing of the masks.
*/
class VOXIECORESHARED_EXPORT Selection2DMask : public QObject {
Q_OBJECT
private:
QVector<Rectangle*> rectangles;
QVector<Ellipse*> ellipses;
QVector<Polygon*> polygons;
QMutex mutex;
public:
QMutex& getLock() { return mutex; }
/**
* @brief isEmpty looks if a shape exists.
* @return true if no shapes inside the mask, else it returns false when at
* least one shape exist.
*/
bool isEmpty() {
return rectangles.isEmpty() && ellipses.isEmpty() && polygons.isEmpty();
}
Selection2DMask(QObject* parent = nullptr)
: QObject(parent), mutex(QMutex::Recursive) {}
//-----------CPU---------------------------------
QPainterPath getPath();
/**
* @brief Returns all ellipse transformation matrixs where are created on this
* mask
* @return A QVector which contains the ellipseData
*/
QVector<ellipseData> getEllipseCoords();
/**
* @brief Returns all rectangle transformation matrixs where are created on
* this mask
* @return A QVector which contains the rectangleData
*/
QVector<rectangleData> getRectangleCoords();
/**
* @brief Returns all polygon Coordinates where are created on this mask
* @return A QVector which contains the polygonData
*/
QVector<polygonData> getPolygonCoords();
//------------GPU---------------------------------
/**
* @brief getEllipseBuffer creates cl Buffers for all ellipses
* @param instance the instance for creating the buffers.
* @return the cl Buffer full with ellipses.
*/
cl::Buffer getEllipseBuffer(vx::opencl::CLInstance* instance);
/**
* @brief getRectangleBuffer creates cl Buffers for all rectangle.
* @param instance the instance for creating the buffers.
* @return the cl Buffers full with rectangles.
*/
cl::Buffer getRectangleBuffer(vx::opencl::CLInstance* instance);
/**
* @brief getPolygonBuffer creates cl Buffers for all polygons.
* @param instance the instance for creating the buffers.
* @return the cl Buffers full with polygons
*/
cl::Buffer getPolygonBuffer(vx::opencl::CLInstance* instance);
/**
* @brief getPolygonBufferOffset creates cl Buffer with integers which
* describes the offset for the polygon buffer.
* @param instance the instance for creating the buffers.
* @return cl Buffer as a offset.
*/
cl::Buffer getPolygonBufferOffset(vx::opencl::CLInstance* instance);
/**
* @brief getRectangleSize
* @return the number of all existing rectangles of this mask.
*/
int getRectangleSize() { return rectangles.size(); }
/**
* @brief getEllipseSize
* @return the number of all existing ellipses of this mask.
*/
int getEllipseSize() { return ellipses.size(); }
/**
* @brief getPolygonSize
* @return the number of all existing polygons of this mask.
*/
int getPolygonSize() { return polygons.size(); }
//------------------------------------------------
/**
* @brief addEllipse adds a new ellipse shape
* @param midPointX the midpoint of the x axis of the ellipse
* @param midPointY the midpoint of the y axis of the ellipse
* @param radiusX the radius of the x axis of the ellipse
* @param radiusY the radius of the y axis of the ellipse
*/
void addEllipse(qreal midPointX, qreal midPointY, qreal radiusX,
qreal radiusY);
/**
* @brief addRectangle adds a new rectangle shape
* @param startX the start point of the x direction
* @param startY the start point of the y direction
* @param endX the end position of the x direction
* @param endY the end position of the y direction
*/
void addRectangle(qreal startX, qreal startY, qreal endX, qreal endY);
/**
* @brief addPolygon adds a new polygon shape
* @param polygonCoords a QVector which contains points.
*/
void addPolygon(QVector<QPointF> polygonCoords);
/**
* @brief deleteMask delets the mask, it deletes every content of the shapes.
*/
void clearMask();
void addMaskFromJson(const QJsonObject& json);
QJsonObject getMaskJson();
/**
* @brief Checks a given Point of Floats, if the point is inside the mask or
* outside. It only works on CPU
* @param coords which contains the given Point to check.
* @return A boolean with true, if the Point is inside the Mask, else false.
*/
bool isPointIn(QPointF coord);
public Q_SLOTS:
/**
* @brief translateOrigin translates the masks in dircetin of origin
* translation.
* @param x the amount of translation in x direction.
* @param y the amount of translation in y direction.
*/
void translateOrigin(qreal x, qreal y);
/**
* @brief rotate rotates the masks along the direction which the images is
* rotated.
* @param angel the rotation angle
*/
void rotate(qreal angel);
Q_SIGNALS:
void changed();
};
} // namespace filter
} // namespace vx
| 34.336493 | 80 | 0.708075 | [
"shape"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.