hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bfb56b443794fdceecef3c032ecc390fbadd32c8 | 2,468 | cpp | C++ | test/runtime/local/kernels/SyrkTest.cpp | daphne-eu/daphne | 64d4040132cf4059efaf184c4e363dbb921c87d6 | [
"Apache-2.0"
] | 10 | 2022-03-31T21:49:35.000Z | 2022-03-31T23:37:06.000Z | test/runtime/local/kernels/SyrkTest.cpp | daphne-eu/daphne | 64d4040132cf4059efaf184c4e363dbb921c87d6 | [
"Apache-2.0"
] | 3 | 2022-03-31T22:10:10.000Z | 2022-03-31T22:46:30.000Z | test/runtime/local/kernels/SyrkTest.cpp | daphne-eu/daphne | 64d4040132cf4059efaf184c4e363dbb921c87d6 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2021 The DAPHNE Consortium
*
* 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/local/datagen/GenGivenVals.h>
#include <runtime/local/datastructures/DenseMatrix.h>
#include <runtime/local/kernels/CheckEq.h>
#include <runtime/local/kernels/MatMul.h>
#include <runtime/local/kernels/Transpose.h>
#include <runtime/local/kernels/Syrk.h>
#include <runtime/local/kernels/PrintObj.h>
#include <tags.h>
#include <catch.hpp>
#include <vector>
template<class DT>
void checkSyrk(const DT * arg) {
DT * resExp = nullptr;
DT * argT = nullptr;
transpose(argT, arg, nullptr);
matMul(resExp, argT, arg, nullptr);
DT * resAct = nullptr;
syrk(resAct, arg, nullptr);
CHECK(*resAct == *resExp);
DataObjectFactory::destroy(resAct);
DataObjectFactory::destroy(resExp);
}
TEMPLATE_PRODUCT_TEST_CASE("Syrk", TAG_KERNELS, (DenseMatrix), (float, double)) {
using DT = TestType;
auto m0 = genGivenVals<DT>(3, {
0, 0, 0,
0, 0, 0,
0, 0, 0,
});
auto m1 = genGivenVals<DT>(3, {
1, 2, 3,
3, 1, 2,
2, 3, 1,
});
auto m2 = genGivenVals<DT>(3, {
13, 13, 10,
10, 13, 13,
13, 10, 13,
});
auto m3 = genGivenVals<DT>(2, {
1, 0, 3, 0,
0, 0, 2, 0,
});
auto m4 = genGivenVals<DT>(4, {
0, 1,
2, 0,
1, 1,
0, 0,
});
auto m5 = genGivenVals<DT>(2, {
3, 4,
2, 2,
});
auto v0 = genGivenVals<DT>(3, {
0,
0,
0
});
auto v1 = genGivenVals<DT>(3, {
1,
1,
1
});
auto v2 = genGivenVals<DT>(3, {
1,
2,
3
});
checkSyrk(m0);
checkSyrk(m1);
checkSyrk(m2);
checkSyrk(m3);
checkSyrk(m4);
checkSyrk(m5);
checkSyrk(v0);
checkSyrk(v1);
checkSyrk(v2);
DataObjectFactory::destroy(m0, m1, m2, m3, m4, m5, v0, v1, v2);
} | 23.730769 | 81 | 0.583874 | daphne-eu |
bfb7d54b086a538137da0bc456e2c65a249a0bac | 385 | hpp | C++ | cpu.hpp | AVasK/core | e8f73f2b92be1ac0a98bda2824682181c5575748 | [
"MIT"
] | null | null | null | cpu.hpp | AVasK/core | e8f73f2b92be1ac0a98bda2824682181c5575748 | [
"MIT"
] | null | null | null | cpu.hpp | AVasK/core | e8f73f2b92be1ac0a98bda2824682181c5575748 | [
"MIT"
] | null | null | null | #pragma once
#if __APPLE__
#include "device_info/apple_platform.hpp"
#elif defined __has_include && __has_include(<sys/param.h>) && __has_include(<sys/sysctl.h>)
#include "device_info/sysctl_info.hpp"
// #elif __WIN32__
//! TODO: Add support for windows
// #elif (__x86_64__ || __amd64__)
//! TODO: Use x86 cpuid to query info
#else
#include "device_info/unknown_platform.hpp"
#endif
| 27.5 | 92 | 0.750649 | AVasK |
bfbb8ce249c73eb70e50b534fb0a53ea3bf5fdde | 510 | cpp | C++ | src/core/states/StateSelectPasswordId.cpp | Governikus/AusweisApp2-Omapi | 0d563e61cb385492cef96c2542d50a467e003259 | [
"Apache-2.0"
] | 1 | 2019-06-06T11:58:51.000Z | 2019-06-06T11:58:51.000Z | src/core/states/StateSelectPasswordId.cpp | ckahlo/AusweisApp2-Omapi | 5141b82599f9f11ae32ff7221b6de3b885e6e5f9 | [
"Apache-2.0"
] | 1 | 2022-01-28T11:08:59.000Z | 2022-01-28T12:05:33.000Z | src/core/states/StateSelectPasswordId.cpp | ckahlo/AusweisApp2-Omapi | 5141b82599f9f11ae32ff7221b6de3b885e6e5f9 | [
"Apache-2.0"
] | 3 | 2019-06-06T11:58:14.000Z | 2021-11-15T23:32:04.000Z | /*!
* \copyright Copyright (c) 2018-2019 Governikus GmbH & Co. KG, Germany
*/
#include "StateSelectPasswordId.h"
using namespace governikus;
StateSelectPasswordId::StateSelectPasswordId(const QSharedPointer<WorkflowContext>& pContext)
: AbstractGenericState(pContext)
{
}
void StateSelectPasswordId::run()
{
const bool canAllowed = getContext()->isCanAllowedMode();
qDebug() << "CAN allowed:" << canAllowed;
if (canAllowed)
{
Q_EMIT firePasswordIdCAN();
return;
}
Q_EMIT fireContinue();
}
| 17.586207 | 93 | 0.735294 | Governikus |
bfbedea09206a5cbc8ace6bc31ac9907bc5fd537 | 10,067 | hpp | C++ | include/gp/problem/problem.hpp | ho-ri1991/genetic-programming | 06d0c1f0719f4d2ddcf9c066d9de1d0bb67772b0 | [
"MIT"
] | null | null | null | include/gp/problem/problem.hpp | ho-ri1991/genetic-programming | 06d0c1f0719f4d2ddcf9c066d9de1d0bb67772b0 | [
"MIT"
] | null | null | null | include/gp/problem/problem.hpp | ho-ri1991/genetic-programming | 06d0c1f0719f4d2ddcf9c066d9de1d0bb67772b0 | [
"MIT"
] | null | null | null | #ifndef GP_PROBLEM_PROBLEM
#define GP_PROBLEM_PROBLEM
#include <any>
#include <algorithm>
#include <gp/utility/type.hpp>
#include <gp/utility/variable.hpp>
#include <gp/utility/result.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <limits>
namespace gp::problem {
namespace detail {
template <std::size_t offset, typename ...Ts>
utility::Result<utility::Variable> stringToVariableHelper(const std::string& str,
const utility::TypeInfo& type,
const std::tuple<std::function<Ts(const std::string&)>...>& stringToValues){
if(type == utility::typeInfo<
typename std::tuple_element_t<offset, std::decay_t<decltype(stringToValues)>>::result_type
>()) return utility::result::ok(utility::Variable(std::get<offset>(stringToValues)(str)));
if constexpr (offset + 1 < std::tuple_size_v<std::decay_t<decltype(stringToValues)>>) {
return stringToVariableHelper<offset + 1>(str, type, stringToValues);
} else {
return utility::result::err<utility::Variable>("failed to load problem, string to value conversion function of " + type.name() + "not registerd");
}
};
template <typename ...Ts>
utility::Result<utility::Variable> stringToVariable(const std::string& str,
const utility::TypeInfo& type,
const std::tuple<std::function<Ts(const std::string&)>...>& stringToValues) {
return stringToVariableHelper<0>(str, type, stringToValues);
}
}
namespace io {
constexpr const char* ROOT_FIELD = "problem";
constexpr const char* NAME_FIELD = "name";
constexpr const char* RETURN_TYPE_FIELD = "return_type";
constexpr const char* ARGUMENTS_FIELD = "arguments";
constexpr const char* VARIABLE_TYPE_FIELD = "type";
constexpr const char* TEACHER_DATA_SET_FIELD = "teacher_data_set";
constexpr const char* TEACHER_DATA_FIELD = "data";
constexpr const char* TEACHER_DATA_ARGUMENT_FIELD = "argument";
constexpr const char* TEACHER_DATA_ARGUMENT_INDEX_ATTRIBUTE = "idx";
constexpr const char* TEACHER_DATA_ANSWER_FIELD = "answer";
}
struct Problem {
using AnsArgPair = std::tuple<utility::Variable, std::vector<utility::Variable>>; //first: ans, second: args
std::string name;
const utility::TypeInfo* returnType;
std::vector<const utility::TypeInfo*> argumentTypes;
std::vector<AnsArgPair> ansArgList;
};
template <typename ...SupportTypes>
utility::Result<Problem> load(std::istream& in,
const utility::StringToType& stringToType,
const std::tuple<std::function<SupportTypes(const std::string&)>...>& stringToValues){
using namespace boost::property_tree;
using namespace utility;
ptree tree;
try {
xml_parser::read_xml(in, tree);
} catch (const std::exception& ex) {
return result::err<Problem>(std::string("failed to load problem\n") + ex.what());
}
Problem problem1;
//get problem name
auto nameResult = result::fromOptional(tree.template get_optional<std::string>(std::string(io::ROOT_FIELD) + "." + io::NAME_FIELD),
"failed to load problem, name field not found.");
if(!nameResult) return result::err<Problem>(std::move(nameResult).errMessage());
problem1.name = std::move(nameResult).unwrap();
//get return type
auto returnTypeResult = result::fromOptional(tree.template get_optional<std::string>(std::string(io::ROOT_FIELD) + "." + io::RETURN_TYPE_FIELD),
"failed to load problem, return_type field not found.")
.flatMap([&stringToType](const std::string& typeName){
using ResultType = const TypeInfo*;
if(!stringToType.hasType(typeName)) return result::err<ResultType>("failed to load problem, unknown type name \"" + typeName + "\"");
else return result::ok(&stringToType(typeName));
});
if(!returnTypeResult) return result::err<Problem>(std::move(returnTypeResult).errMessage());
problem1.returnType = std::move(returnTypeResult).unwrap();
//get argument types
auto argsResult = result::fromOptional(tree.get_child_optional(std::string(io::ROOT_FIELD) + "." + io::ARGUMENTS_FIELD),
"failed to load problem, arguments field not found")
.flatMap([&stringToType](ptree& child){
using ResultType = decltype(Problem{}.argumentTypes);
ResultType argumentTypes;
for(const auto& [key, val]: child) {
if(key != io::VARIABLE_TYPE_FIELD) continue;
const auto& typeStr = val.data();
if(!stringToType.hasType(typeStr)) return result::err<ResultType>(std::string("failed to load problem, unknown argument type name \"") + typeStr + "\"");
argumentTypes.push_back(&stringToType(typeStr));
}
return result::ok(std::move(argumentTypes));
});
if(!argsResult) return result::err<Problem>(std::move(argsResult).errMessage());
problem1.argumentTypes = std::move(argsResult).unwrap();
//get teacher data set
auto teacherDataResult = result::fromOptional(tree.get_child_optional(std::string(io::ROOT_FIELD) + "." + io::TEACHER_DATA_SET_FIELD),
"failed to load problem, teacher_data_set field not found")
.flatMap([&problem1, &stringToValues, argNum = std::size(problem1.argumentTypes)](ptree& child){
using ResultType = decltype(Problem{}.ansArgList);
ResultType ansArgList;
for(const auto& [key, value]: child) {
if(key != io::TEACHER_DATA_FIELD)continue;
auto dataResult = result::fromOptional(value.template get_optional<std::string>(io::TEACHER_DATA_ANSWER_FIELD),
"failed to load problem, answer field not found in the data field.")
.flatMap([&stringToValues, &problem1](auto&& answerStr){
return detail::stringToVariable(answerStr, *problem1.returnType, stringToValues);
});
if(!dataResult) return result::err<ResultType>(std::move(dataResult).errMessage());
auto ans = std::move(dataResult).unwrap();
std::vector<Variable> args(argNum);
for(const auto& [dataKey, dataValue]: value) {
if(dataKey != io::TEACHER_DATA_ARGUMENT_FIELD) continue;
auto idxResult = result::fromOptional(dataValue.template get_optional<std::string>(std::string("<xmlattr>.") + io::TEACHER_DATA_ARGUMENT_INDEX_ATTRIBUTE),
"failed to load problem, idx attribute not found int the argument field")
.flatMap([](auto&& idxStr){
if(idxStr.empty()
|| !std::all_of(std::begin(idxStr), std::end(idxStr), [](auto c){return '0' <= c && c <= '9';})
|| (1 < std::size(idxStr) && idxStr[0] == '0')
|| std::numeric_limits<int>::digits10 < std::size(idxStr)) return result::err<int>("failed to load problem, invalid idx \"" + idxStr + "\"");
auto idx = std::stoll(idxStr);
if (static_cast<long long>(INT_MAX) < idx) return result::err<int>("failed to load problem, invalid idx \"" + idxStr + "\"");
return result::ok(static_cast<int>(idx));
}).flatMap([argNum = std::size(problem1.argumentTypes)](int idx){
if(idx < 0 || argNum <= idx) return result::err<int>("failed to load problem, invalid idx \"" + std::to_string(idx) + "\"");
else return result::ok(idx);
});
if(!idxResult) return result::err<ResultType>(std::move(idxResult).errMessage());
auto idx = idxResult.unwrap();
auto argResult = detail::stringToVariable(dataValue.data(), *problem1.argumentTypes[idx], stringToValues);
if(!argResult) return result::err<ResultType>(std::move(argResult).errMessage());
args[idx] = std::move(argResult).unwrap();
}
if(!std::all_of(std::begin(args), std::end(args), [](auto x)->bool{return static_cast<bool>(x);})) return result::err<ResultType>("failed to load problem, some argument is lacking");
ansArgList.push_back(std::make_tuple(std::move(ans), std::move(args)));
}
return result::ok(std::move(ansArgList));
});
if(!teacherDataResult) return result::err<Problem>(std::move(teacherDataResult).errMessage());
problem1.ansArgList = std::move(teacherDataResult).unwrap();
return result::ok(std::move(problem1));
}
}
#endif
| 61.012121 | 206 | 0.548525 | ho-ri1991 |
bfbf097838dfd1611e2eba0f63106220413f9729 | 26,642 | cpp | C++ | App/EZDefaultAction.cpp | ouxianghui/ezcam | 195fb402202442b6d035bd70853f2d8c3f615de1 | [
"MIT"
] | 12 | 2021-03-26T03:23:30.000Z | 2021-12-31T10:05:44.000Z | App/EZDefaultAction.cpp | 15831944/ezcam | 195fb402202442b6d035bd70853f2d8c3f615de1 | [
"MIT"
] | null | null | null | App/EZDefaultAction.cpp | 15831944/ezcam | 195fb402202442b6d035bd70853f2d8c3f615de1 | [
"MIT"
] | 9 | 2021-06-23T08:26:40.000Z | 2022-01-20T07:18:10.000Z | #include "EZDefaultAction.h"
#include "RMouseEvent.h"
#include "RSettings.h"
#include "RMath.h"
#include "RGraphicsViewQt.h"
#include <QSharedPointer>
#include "REntity.h"
#include "REntityData.h"
#include "RBlock.h"
#include "RBlockReferenceEntity.h"
#include "RBlockReferenceData.h"
#include "RSnapFree.h"
#include "RSnapAuto.h"
#include <QString>
#include <QObject>
#include "RMoveReferencePointOperation.h"
#include "RMoveSelectionOperation.h"
#include "RAddObjectOperation.h"
#include "RAddObjectsOperation.h"
EZDefaultAction::EZDefaultAction(RGuiAction* pGuiAction)
:RActionAdapter(pGuiAction)
{
}
EZDefaultAction::~EZDefaultAction()
{
}
void EZDefaultAction::beginEvent()
{
m_nPickRangePixels = RSettings::getPickRange();
m_nMinPickRangePixels = std::min(m_nPickRangePixels / 2, 10);
m_d1Model = RVector::invalid;
m_d1Screen = RVector::invalid;
m_d2Model = RVector::invalid;
m_d2Screen = RVector::invalid;
m_pDocument = this->getDocument();
setState(Neutral);
m_blockRefId = RObject::INVALID_ID;
m_entityInBlockId = RObject::INVALID_ID;
}
void EZDefaultAction::setState(State state)
{
// oxh
//EAction.prototype.setState.call(this, state);
//var appWin = EAction.getMainWindow();
// oxh add
this->m_state = state;
if (this->m_state == MovingReference
|| this->m_state == SettingReference
|| this->m_state == MovingEntity
|| this->m_state == MovingEntityInBlock
|| this->m_state == SettingEntity)
{
documentInterface->setClickMode(RAction::PickCoordinate);
// oxh
//this->setCrosshairCursor();
//EAction.showSnapTools();
}
else
{
documentInterface->setClickMode(RAction::PickingDisabled);
// oxh
//this->setArrowCursor();
}
QString ltip = "Select entity or region";
switch (m_state)
{
case Neutral:
m_d1Model = RVector::invalid;
m_d1Screen = RVector::invalid;
m_d2Model = RVector::invalid;
m_d2Screen = RVector::invalid;
if (documentInterface->hasSelection())
{
ltip += "\n";
ltip += "Move entity or reference";
}
// oxh
//this->setLeftMouseTip(ltip);
//this->setRightMouseTip("");
//this->setCommandPrompt();
break;
case Dragging:
m_d2Model = RVector::invalid;
m_d2Screen = RVector::invalid;
break;
case SettingCorner2:
//this->setLeftMouseTip("Set second corner");
//this->setRightMouseTip("");
break;
case MovingReference:
case SettingReference:
//this->setLeftMouseTip("Specify target point of reference point");
//this->setRightMouseTip("");
break;
case MovingEntity:
case SettingEntity:
//this->setLeftMouseTip("Specify target point of selection");
//this->setRightMouseTip("");
break;
case MovingEntityInBlock:
//this->setLeftMouseTip("Move entity to desired location");
break;
default:
break;
}
}
void EZDefaultAction::suspendEvent()
{
if (this->guiAction)
{
this->guiAction->setChecked(false);
}
}
void EZDefaultAction::resumeEvent()
{
}
void EZDefaultAction::mouseMoveEvent(RMouseEvent& event)
{
// we're in the middle of panning: don't do anything:
if (event.buttons() == Qt::MidButton ||
(event.buttons() == Qt::LeftButton && event.modifiers() == Qt::ControlModifier))
{
return;
}
// if (isNull(m_nPickRangePixels))
// {
// return;
// }
RGraphicsView& view = event.getGraphicsView();
RVector screenPosition;
RVector referencePoint;
REntity::Id entityId = REntity::INVALID_ID;
double range = 0.0f;
switch (m_state)
{
case Neutral:
screenPosition = event.getScreenPosition();
referencePoint = view.getClosestReferencePoint(screenPosition, m_nMinPickRangePixels);
if (referencePoint.isValid())
{
this->highlightReferencePoint(referencePoint);
}
else
{
range = view.mapDistanceFromView(m_nPickRangePixels);
double strictRange = view.mapDistanceFromView(10);
RMouseEvent::setOriginalMousePos(event.globalPos());
entityId = documentInterface->getClosestEntity(event.getModelPosition(), range, strictRange, false);
RMouseEvent::resetOriginalMousePos();
if (entityId != RObject::INVALID_ID && m_pDocument->isEntityEditable(entityId))
{
this->highlightEntity(entityId);
}
}
break;
case Dragging:
m_d2Model = event.getModelPosition();
m_d2Screen = event.getScreenPosition();
//view = event.getGraphicsView();
if (!m_d1Screen.equalsFuzzy(m_d2Screen, 10 /*this.minPickRangePixels*/))
{
// if the dragging started on top of a reference point,
// start moving the reference point:
referencePoint = view.getClosestReferencePoint(m_d1Screen, m_nMinPickRangePixels);
if (referencePoint.isValid())
{
m_d1Model = referencePoint;
documentInterface->setRelativeZero(m_d1Model);
setState(MovingReference);
}
else
{
// if the dragging started on top of an entity,
// start moving the entity:
entityId = view.getClosestEntity(m_d1Screen, m_nMinPickRangePixels, 10, false);
// in block easy drag and drop:
if (entityId != RObject::INVALID_ID)
{
RDocument* doc = this->getDocument();
if (doc)
{
// oxh todo
QSharedPointer<REntity> entity = doc->queryEntityDirect(entityId);
if (!entity.isNull())
{
QSharedPointer<RBlockReferenceEntity> blockRefEntity = entity.dynamicCast<RBlockReferenceEntity>();
if (!blockRefEntity.isNull())
{
RBlock::Id blockId = blockRefEntity->getReferencedBlockId();
// oxh todo
QSharedPointer<RBlock> block = doc->queryBlock(blockId);
if (!block.isNull())
{
range = view.mapDistanceFromView(m_nPickRangePixels);
// cursor, mapped to block coordinates:
RVector pBlock = blockRefEntity->mapToBlock(m_d1Model);
RBox box = RBox(pBlock - RVector(range, range), pBlock + RVector(range, range));
QSet<REntity::Id> res = doc->queryIntersectedEntitiesXY(box, true, false, blockId);
REntity::Id entityInBlockId;
if (res.size() == 1)
{
entityInBlockId = *(res.begin());
}
else
{
entityInBlockId = doc->queryClosestXY(res, pBlock, range*2, false);
}
QSharedPointer<REntity> entityInBlock = doc->queryEntityDirect(entityInBlockId);
bool ok = entityInBlock->getCustomProperty("QCAD", "InBlockEasyDragAndDrop", "0") == "1";
if (entityInBlock && ok)
{
//QList<RVector> refP = entityInBlock->getReferencePoints();
QList<RRefPoint> refP = entityInBlock->getReferencePoints();
if (refP.length() > 0)
{
m_d1Model = refP[0]; //entity.mapToBlock(refP[0]);
}
else
{
m_d1Model = pBlock;
}
m_entityInBlockId = entityInBlockId;
m_blockRefId = entityId;
setState(MovingEntityInBlock);
RGuiAction* guiAction = RGuiAction::getByScriptFile("scripts/Snap/SnapFree/SnapFree.js");
if (guiAction)
{
guiAction->slotTrigger();
}
documentInterface->setSnap(new RSnapFree());
break;
}
}
}
}
}
}
if (entityId != RObject::INVALID_ID && m_pDocument->hasSelection())
{
// move start point of dragging operation to closest
// reference point:
// TODO: use auto snap instead here (optional?):
m_d1Model = view.getClosestReferencePoint(entityId, m_d1Screen);
documentInterface->setRelativeZero(m_d1Model);
setState(MovingEntity);
}
else
{
// if the dragging started in an empty space,
// start box selection:
setState(SettingCorner2);
// make sure one mouse move is enough to get a visible preview
// (for testing, one mouse move event has to be enough):
this->mouseMoveEvent(event);
}
}
}
break;
case SettingCorner2:
m_d2Model = event.getModelPosition();
previewSelectionBox(this->getDocumentInterface(),
RBox(m_d1Model, m_d2Model),
m_d1Model.x > m_d2Model.x);
break;
// easy in block entity drag and drop (point mark labels):
// case DefaultAction.State.MovingEntityInBlock:
// this.moveEntityInBlock(event.getModelPosition(), true);
// break;
default:
break;
}
}
void EZDefaultAction::previewSelectionBox(RDocumentInterface* di, RBox box, bool crossSelection) {
QList<RVector> points;
points.push_back(box.c1);
points.push_back(RVector(box.c1.x, box.c2.y));
points.push_back(box.c2);
points.push_back(RVector(box.c2.x, box.c1.y));
points.push_back(box.c1);
previewSelectionPolygon(di, points, crossSelection);
}
/**
* Adds a selection polygon with the given points to the preview.
* \param points Array of RVector objects
*/
void EZDefaultAction::previewSelectionPolygon(RDocumentInterface* di, const QList<RVector>& points, bool crossSelection)
{
RPolyline polygon = RPolyline(points, true);
RColor color = RSettings::getColor("GraphicsViewColors/SelectionBoxColor", RColor(128,0,0,255));
RLineweight::Lineweight lw = RLineweight::Weight000;
RColor c;
if (crossSelection)
{
c = RSettings::getColor("GraphicsViewColors/SelectionBoxBackgroundCrossColor", RColor(0,0,255,30));
}
else
{
c = RSettings::getColor("GraphicsViewColors/SelectionBoxBackgroundColor", RColor(0,255,0,30));
}
// TODO c.getQColor() doesn't work
QColor bgColor = QColor(c.red(), c.green(), c.blue(), c.alpha());
QBrush brush = QBrush(bgColor, Qt::SolidPattern);
if (crossSelection)
{
QList<qreal> dashes;
dashes.append(10.0f);
dashes.append(5.0f);
di->addShapeToPreview(polygon, color, brush, lw, Qt::CustomDashLine, dashes);
}
else
{
// TODO "Qt.SolidLine" doesn't convert to number
di->addShapeToPreview(polygon, color, brush, lw, Qt::SolidLine);
}
}
void EZDefaultAction::mouseReleaseEvent(RMouseEvent& event)
{
bool persistentSelection = RSettings::getBoolValue("GraphicsView/PersistentSelection", false);
bool add = false;
if ((event.modifiers() == Qt::ShiftModifier) || (event.modifiers() == Qt::ControlModifier) || persistentSelection == true)
{
add = true;
}
RGraphicsView& view = event.getGraphicsView();
double range = 0.0f;
double strictRange = 0.0f;
REntity::Id entityId = REntity::INVALID_ID;
if (event.button() == Qt::LeftButton)
{
switch (m_state)
{
case Dragging:
range = view.mapDistanceFromView(m_nPickRangePixels);
//range = view.mapDistanceFromView(10);
strictRange = view.mapDistanceFromView(10);
entityId = documentInterface->getClosestEntity(event.getModelPosition(), range, strictRange, false);
//qDebug("entity id: ", entityId);
if (entityId != -1)
{
if (add && m_pDocument->isSelected(entityId))
{
this->deselectEntity(entityId);
}
else
{
this->selectEntity(entityId, add);
}
}
else
{
if (!add)
{
if (persistentSelection == false)
{
documentInterface->clearSelection();
}
}
}
documentInterface->clearPreview();
documentInterface->repaintViews();
this->setState(Neutral);
break;
case SettingCorner2:
documentInterface->clearPreview();
m_d2Model = event.getModelPosition();
if ((event.modifiers() == Qt::ShiftModifier) || (event.modifiers() == Qt::ControlModifier) || persistentSelection == true)
{
// add all entities in window to the selection:
documentInterface->selectBoxXY(RBox(m_d1Model, m_d2Model), true);
}
else
{
// select entities in window only:
documentInterface->selectBoxXY(RBox(m_d1Model, m_d2Model), false);
}
// event.setConsumed(true);
this->setState(Neutral);
break;
// easy in block entity drag and drop (point mark labels):
// case DefaultAction.State.MovingEntityInBlock:
// this.moveEntityInBlock(event.getModelPosition(), false);
// break;
default:
break;
}
}
else if (event.button() == Qt::RightButton)
{
if (this->m_state != Neutral && m_state != MovingEntityInBlock)
{
documentInterface->clearPreview();
documentInterface->repaintViews();
this->setState(Neutral);
}
// use right-click into empty area to deselect everything:
else if (m_state == Neutral && RSettings::getBoolValue("GraphicsView/RightClickToDeselect", false))
{
int rightClickRange = RSettings::getIntValue("GraphicsView/RightClickRange", 10);
//view = event.getGraphicsView();
range = view.mapDistanceFromView(rightClickRange);
strictRange = view.mapDistanceFromView(10);
entityId = documentInterface->getClosestEntity(event.getModelPosition(), range, strictRange, false);
if (entityId != -1)
{
this->selectEntity(entityId, add);
// TODO: show entity context menu?
//CadToolBar.back();
}
else
{
if (documentInterface->hasSelection())
{
documentInterface->clearSelection();
documentInterface->clearPreview();
documentInterface->repaintViews();
}
else
{
// todo
//CadToolBar.back();
}
}
}
else
{
// todo
//CadToolBar.back();
}
}
}
void EZDefaultAction::mousePressEvent(RMouseEvent& event)
{
if (event.button() == Qt::LeftButton && event.modifiers() != Qt::ControlModifier)
{
if (m_state == Neutral)
{
m_d1Model = event.getModelPosition();
m_d1Screen = event.getScreenPosition();
this->setState(Dragging);
documentInterface->clearPreview();
}
}
}
void EZDefaultAction::mouseDoubleClickEvent(RMouseEvent& event)
{
if (event.button() == Qt::LeftButton && m_state == Neutral)
{
RGraphicsView& view = event.getGraphicsView();
double range = view.mapDistanceFromView(m_nPickRangePixels);
double strictRange = view.mapDistanceFromView(10);
REntity::Id entityId = documentInterface->getClosestEntity(event.getModelPosition(), range, strictRange, false);
if (entityId == RObject::INVALID_ID)
{
return;
}
this->entityDoubleClicked(entityId, event);
}
}
void EZDefaultAction::escapeEvent()
{
documentInterface->clearPreview();
documentInterface->repaintViews();
// todo
//CadToolBar.back();
this->setState(Neutral);
}
void EZDefaultAction::coordinateEvent(RCoordinateEvent& event)
{
pickCoordinate(event, false);
}
void EZDefaultAction::coordinateEventPreview(RCoordinateEvent& event)
{
pickCoordinate(event, true);
}
void EZDefaultAction::pickCoordinate(RCoordinateEvent& event, bool preview)
{
ROperation* op = NULL;
switch (m_state)
{
case MovingReference:
case SettingReference:
if (preview)
{
m_d2Model = event.getModelPosition();
op = new RMoveReferencePointOperation(m_d1Model, m_d2Model);
documentInterface->previewOperation(op);
}
else
{
if (m_state == MovingReference)
{
this->setState(SettingReference);
}
else
{
m_d2Model = event.getModelPosition();
op = new RMoveReferencePointOperation(m_d1Model, m_d2Model);
op->setText("Move Reference Point");
documentInterface->applyOperation(op);
documentInterface->clearPreview();
documentInterface->repaintViews();
// todo
//CadToolBar.back();
this->setState(Neutral);
}
}
break;
case MovingEntity:
case SettingEntity:
if (preview)
{
m_d2Model = event.getModelPosition();
op = new RMoveSelectionOperation(m_d1Model, m_d2Model);
documentInterface->previewOperation(op);
}
else
{
if (m_state == MovingEntity)
{
this->setState(SettingEntity);
}
else
{
m_d2Model = event.getModelPosition();
op = new RMoveSelectionOperation(m_d1Model, m_d2Model);
op->setText("Move Selection");
documentInterface->applyOperation(op);
documentInterface->clearPreview();
documentInterface->repaintViews();
// todo
//CadToolBar.back();
this->setState(Neutral);
}
}
break;
// easy in block entity drag and drop (point mark labels):
case MovingEntityInBlock:
{
RDocument* doc = this->getDocument();
if (!doc)
{
break;
}
QSharedPointer<REntity> block = doc->queryEntity(m_blockRefId);
if (block.isNull())
{
break;
}
QSharedPointer<RBlockReferenceEntity> blockRef = block.dynamicCast<RBlockReferenceEntity>();
if (blockRef.isNull())
{
break;
}
m_d2Model = blockRef->mapToBlock(event.getModelPosition());
QSharedPointer<REntity> entityInBlock = doc->queryEntity(m_entityInBlockId);
entityInBlock->move(m_d2Model - m_d1Model);
RAddObjectsOperation* op = new RAddObjectsOperation();
op->setText("Move Entity");
op->addObject(entityInBlock, false);
if (preview)
{
documentInterface->previewOperation(op);
}
else
{
doc->removeFromSpatialIndex(blockRef);
documentInterface->applyOperation(op);
blockRef->update();
doc->addToSpatialIndex(blockRef);
this->setState(Neutral);
RGuiAction* guiAction = RGuiAction::getByScriptFile("scripts/Snap/SnapAuto/SnapAuto.js");
if (guiAction)
{
guiAction->slotTrigger();
}
documentInterface->setSnap(new RSnapAuto());
}
break;
}
default:
break;
}
}
/**
* Called when the mouse cursor hovers over an entity.
*/
void EZDefaultAction::highlightEntity(REntity::Id& entityId)
{
if (!documentInterface)
{
return;
}
documentInterface->highlightEntity(entityId);
}
/**
* Called when the mouse cursor hovers over a reference point.
*/
void EZDefaultAction::highlightReferencePoint(const RVector& referencePoint)
{
if (!documentInterface)
{
return;
}
documentInterface->highlightReferencePoint(referencePoint);
}
/**
* Called when the user deselects a single entity.
*/
void EZDefaultAction::deselectEntity(REntity::Id& entityId)
{
if (!documentInterface)
{
return;
}
documentInterface->deselectEntity(entityId);
}
/**
* Called when the user selects a single entity.
*/
void EZDefaultAction::selectEntity(REntity::Id& entityId, bool add)
{
if (!documentInterface)
{
return;
}
documentInterface->selectEntity(entityId, add);
}
/**
* Called when the user selects a single entity.
*/
void EZDefaultAction::entityDoubleClicked(REntity::Id& entityId, RMouseEvent& event)
{
if (!documentInterface || !m_pDocument)
{
return;
}
QSharedPointer<REntity> entity = m_pDocument->queryEntity(entityId);
if (entity->getType() == RS::EntityText
|| entity->getType() == RS::EntityAttribute
|| entity->getType() == RS::EntityAttributeDefinition)
{
if (RSettings::getBoolValue("GraphicsView/DoubleClickEditText", true) == true)
{
// oxh todo
//include("scripts/Modify/EditText/EditText.js");
//EditText.editText(entity);
}
}
else if (entity->getType() == RS::EntityBlockRef)
{
QSharedPointer<RBlockReferenceEntity> blockEntity = entity.dynamicCast<RBlockReferenceEntity>();
if (!blockEntity.isNull())
{
// in block text editing with double-click:
RBlock::Id blockId = blockEntity->getReferencedBlockId();
QSharedPointer<RBlock> block = m_pDocument->queryBlock(blockId);
if (block)
{
RGraphicsView& view = event.getGraphicsView();
double range = view.mapDistanceFromView(m_nPickRangePixels);
// cursor, mapped to block coordinates:
RVector pBlock = blockEntity->mapToBlock(event.getModelPosition());
RBox box = RBox(pBlock - RVector(range,range), pBlock - RVector(range,range));
QSet<REntity::Id> res = m_pDocument->queryIntersectedEntitiesXY(box, true, false, blockId);
REntity::Id entityInBlockId;
if (res.size() == 1)
{
entityInBlockId = *(res.begin());
}
else
{
entityInBlockId = m_pDocument->queryClosestXY(res, pBlock, range*2, false);
}
QSharedPointer<REntity> entityInBlock = m_pDocument->queryEntity(entityInBlockId);
if (entityInBlock
&& entityInBlock->getType() == RS::EntityTextBased
&& entityInBlock->getCustomProperty("QCAD", "InBlockTextEdit", "0") == "1")
{
// todo
//include("scripts/Modify/EditText/EditText.js");
//EditText.editText(entityInBlock);
return;
}
}
if (RSettings::getBoolValue("GraphicsView/DoubleClickEditBlock", false) == true)
{
// todo oxh
//include("scripts/Block/Block.js");
//Block.editBlock(documentInterface, blockEntity->getReferencedBlockName());
}
}
}
}
void EZDefaultAction::keyPressEvent(QKeyEvent& event)
{
if (event.key() == Qt::Key_Z && event.modifiers() == Qt::ControlModifier)
{
documentInterface->undo();
}
else if (event.key() == Qt::Key_Z && event.modifiers() == (Qt::ControlModifier + Qt::ShiftModifier))
{
documentInterface->redo();
}
}
void EZDefaultAction::keyReleaseEvent(QKeyEvent& /*event*/)
{
}
| 34.15641 | 135 | 0.525073 | ouxianghui |
bfbf430d78da0096edb13b212a1b93be77a3ec01 | 2,044 | hpp | C++ | RUNETag/include/markerpose.hpp | GeReV/RUNEtag | e8319a132e325d73cdd7759a0d8a5f45f26dd129 | [
"MIT"
] | 31 | 2017-12-29T16:39:07.000Z | 2022-03-25T03:26:29.000Z | RUNETag/include/markerpose.hpp | GeReV/RUNEtag | e8319a132e325d73cdd7759a0d8a5f45f26dd129 | [
"MIT"
] | 7 | 2018-06-29T07:30:14.000Z | 2021-02-16T23:19:20.000Z | RUNETag/include/markerpose.hpp | GeReV/RUNEtag | e8319a132e325d73cdd7759a0d8a5f45f26dd129 | [
"MIT"
] | 13 | 2018-09-27T13:19:12.000Z | 2022-03-02T08:48:42.000Z | /**
* RUNETag fiducial markers library
*
* -----------------------------------------------------------------------------
* The MIT License (MIT)
*
* Copyright (c) 2015 Filippo Bergamasco
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#ifndef _MARKER_POSE_H
#define _MARKER_POSE_H
//#include "precomp.hpp"
#include <opencv2/opencv.hpp>
#include "markerdetected.hpp"
namespace cv
{
namespace runetag
{
const unsigned int FLAG_REPROJ_ERROR = 1;
const unsigned int FLAG_REFINE = 2;
/// <summary> Camera pose as a transformation from camera coordinates to world coordinates </summary>
struct Pose
{
/// <value> Rotation matrix </value>
cv::Mat R;
/// <value> Translation vector </value>
cv::Mat t;
};
extern Pose findPose( const MarkerDetected& detected, const cv::Mat& intrinsics, const cv::Mat& distortion, bool* pose_ok = 0, unsigned int method=CV_ITERATIVE, unsigned int flag = 0 );
} // namespace runetag
} // namespace cv
#endif
| 34.644068 | 189 | 0.695695 | GeReV |
bfc1fab970eb48f9eda9f80945f7bbee62921438 | 2,787 | hpp | C++ | libraries/chain/include/infrablockchain/chain/received_transaction_votes_object.hpp | YosemiteLabs/infrablockchain | da05af17a9bfb1c02dafca9d8033c9e1b00e92b3 | [
"Apache-2.0",
"MIT"
] | null | null | null | libraries/chain/include/infrablockchain/chain/received_transaction_votes_object.hpp | YosemiteLabs/infrablockchain | da05af17a9bfb1c02dafca9d8033c9e1b00e92b3 | [
"Apache-2.0",
"MIT"
] | null | null | null | libraries/chain/include/infrablockchain/chain/received_transaction_votes_object.hpp | YosemiteLabs/infrablockchain | da05af17a9bfb1c02dafca9d8033c9e1b00e92b3 | [
"Apache-2.0",
"MIT"
] | null | null | null | /**
* @file infrablockchain/chain/received_transaction_votes_object.hpp
* @author bezalel@infrablockchain.com
* @copyright defined in infrablockchain/LICENSE.txt
*/
#pragma once
#include <eosio/chain/database_utils.hpp>
#include <eosio/chain/multi_index_includes.hpp>
namespace infrablockchain { namespace chain {
using namespace eosio::chain;
using tx_votes_sum_type = uint64_t;
using tx_votes_sum_weighted_type = double;
/**
* @brief received transaction votes statistics for an account
*/
class received_transaction_votes_object : public chainbase::object<infrablockchain_received_transaction_votes_object_type, received_transaction_votes_object> {
OBJECT_CTOR(received_transaction_votes_object)
id_type id;
account_name account; // transaction vote target account
tx_votes_sum_type tx_votes = 0; // sum of received transaction votes
tx_votes_sum_weighted_type tx_votes_weighted = 0.0; // weighted (time-decaying) sum of received transaction votes
uint16_t tx_votes_weighted_unique_idx = 0; // shared_multi_index_container does not allow ordered_non_unique index, making tx_votes_weighted value to be uniquely indexed
};
struct by_tx_votes_account;
struct by_tx_votes_weighted;
using received_transaction_votes_multi_index = chainbase::shared_multi_index_container<
received_transaction_votes_object,
indexed_by<
ordered_unique< tag<by_id>, member<received_transaction_votes_object, received_transaction_votes_object::id_type, &received_transaction_votes_object::id> >,
ordered_unique< tag<by_tx_votes_account>, member<received_transaction_votes_object, account_name, &received_transaction_votes_object::account>>,
// ordered_non_unique< tag<by_tx_votes_weighted>, member<received_transaction_votes_object, tx_votes_sum_weighted_type, &received_transaction_votes_object::tx_votes_weighted>>
ordered_unique< tag<by_tx_votes_weighted>,
composite_key< received_transaction_votes_object,
member<received_transaction_votes_object, tx_votes_sum_weighted_type, &received_transaction_votes_object::tx_votes_weighted>,
member<received_transaction_votes_object, uint16_t, &received_transaction_votes_object::tx_votes_weighted_unique_idx>
>
>
>
>;
} } /// infrablockchain::chain
CHAINBASE_SET_INDEX_TYPE(infrablockchain::chain::received_transaction_votes_object, infrablockchain::chain::received_transaction_votes_multi_index)
FC_REFLECT(infrablockchain::chain::received_transaction_votes_object, (account)(tx_votes_weighted)(tx_votes)(tx_votes_weighted_unique_idx))
| 50.672727 | 194 | 0.759598 | YosemiteLabs |
bfc2b5b536ec8501beae3f71d4f36065bb826ddf | 2,017 | hpp | C++ | src/runtime/gpu/gpu_call_frame.hpp | pqLee/ngraph | ddfa95b26a052215baf9bf5aa1ca5d1f92aa00f7 | [
"Apache-2.0"
] | null | null | null | src/runtime/gpu/gpu_call_frame.hpp | pqLee/ngraph | ddfa95b26a052215baf9bf5aa1ca5d1f92aa00f7 | [
"Apache-2.0"
] | null | null | null | src/runtime/gpu/gpu_call_frame.hpp | pqLee/ngraph | ddfa95b26a052215baf9bf5aa1ca5d1f92aa00f7 | [
"Apache-2.0"
] | null | null | null | //*****************************************************************************
// Copyright 2017-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.
//*****************************************************************************
#pragma once
#include <functional>
#include <memory>
#include <unordered_map>
#include "gpu_compiled_function.hpp"
#include "gpu_tensor_wrapper.hpp"
namespace ngraph
{
namespace runtime
{
namespace gpu
{
class GPUCallFrame
{
public:
GPUCallFrame(const size_t& num_inputs, const size_t& num_outputs);
void resolve_reservations(
const GPUCompiledFunction* compiled_function,
const std::unordered_map<std::string, size_t>& memory_reservations);
void resolve_inputs(void** inputs, size_t num_inputs = 0);
void resolve_outputs(void** outputs, size_t num_outputs = 0);
std::vector<void*> get_tensor_io(const std::vector<GPUTensorWrapper>& tensors);
private:
void* get_pointer(const TensorRole& type,
const size_t& offset,
const std::string& name = "");
std::unordered_map<std::string, unsigned char*> m_memory_reservations;
std::vector<unsigned char*> m_inputs;
std::vector<unsigned char*> m_outputs;
};
}
}
}
| 36.672727 | 95 | 0.57412 | pqLee |
bfc542efa1d66f67a4cb602590dc486bd9d4dbbc | 801 | cpp | C++ | Medium/Partition Equal Subset Sum.cpp | TheCodeAlpha26/Lets-LeetCode | 00110044763a683d262fed196f7b0742d2e8505f | [
"Apache-2.0"
] | null | null | null | Medium/Partition Equal Subset Sum.cpp | TheCodeAlpha26/Lets-LeetCode | 00110044763a683d262fed196f7b0742d2e8505f | [
"Apache-2.0"
] | null | null | null | Medium/Partition Equal Subset Sum.cpp | TheCodeAlpha26/Lets-LeetCode | 00110044763a683d262fed196f7b0742d2e8505f | [
"Apache-2.0"
] | null | null | null | class Solution {
public:
bool tell_me(int sum,vector<int>& nums)
{
int l = nums.size();
vector<vector<bool>> dp((sum / 2 + 1),vector<bool>((l + 1),true));
for (int i = 1; i <= sum / 2; i++)
dp[i][0] = false;
for (int i = 1; i <= sum / 2; i++)
for (int j = 1; j <= l; j++)
{
dp[i][j] = dp[i][j - 1];
if (i >= nums[j - 1])
{
dp[i][j] = dp[i][j] || dp[i - nums[j - 1]][j - 1];
}
}
return dp[sum / 2][l];
}
bool canPartition(vector<int>& nums)
{
int sum = 0;
for(int x : nums)
sum += x;
if(sum & 1)
return false;
return tell_me(sum,nums);
}
};
| 25.83871 | 74 | 0.357054 | TheCodeAlpha26 |
bfc81a43b20d46752d4363393f543e00c1950721 | 576 | cpp | C++ | test/spring2d/test-spring2d.cpp | sathyamvellal/learnopengl | 54e9fd6193c6dc970b0802bc31c5b558c46586d5 | [
"MIT"
] | null | null | null | test/spring2d/test-spring2d.cpp | sathyamvellal/learnopengl | 54e9fd6193c6dc970b0802bc31c5b558c46586d5 | [
"MIT"
] | null | null | null | test/spring2d/test-spring2d.cpp | sathyamvellal/learnopengl | 54e9fd6193c6dc970b0802bc31c5b558c46586d5 | [
"MIT"
] | null | null | null | //
// Created by Sathyam Vellal on 19/03/2018.
//
#include <cmath>
#include <glm/glm.hpp>
#include "utils/logger.h"
#include "spring2d/spring2d.h"
#include "spring2d/spring2dsim.h"
int main(int argc, char **argv)
{
Spring2DSim spring2DSim(Spring2DSim(5.0));
spring2DSim.init();
glm::vec2 a(2, 3);
glm::vec2 b(1, 7);
glm::vec2 ub = b / glm::length(b);
glm::vec2 proja_b = glm::dot(a, ub) * ub;
std::cout << proja_b.x << std::endl;
std::cout << proja_b.y << std::endl;
std::cout << glm::length(proja_b) << std::endl;
return 0;
} | 18.580645 | 51 | 0.604167 | sathyamvellal |
bfc9baa4c12206be15bd567e3ce9949b4b671d82 | 1,526 | cpp | C++ | Cpp/Yandex/Algorithms/training2_4b/d_state_duma_elections/main.cpp | neon1ks/Study | 5d40171cf3bf5e8d3a95539e91f5afec54d1daf3 | [
"MIT"
] | null | null | null | Cpp/Yandex/Algorithms/training2_4b/d_state_duma_elections/main.cpp | neon1ks/Study | 5d40171cf3bf5e8d3a95539e91f5afec54d1daf3 | [
"MIT"
] | null | null | null | Cpp/Yandex/Algorithms/training2_4b/d_state_duma_elections/main.cpp | neon1ks/Study | 5d40171cf3bf5e8d3a95539e91f5afec54d1daf3 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <cmath>
#include <iostream>
#include <map>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
using namespace std;
struct greater_comp
{
template<class T>
bool operator()(T const &a, T const &b) const { return a > b; }
};
int main()
{
vector<string> party_list;
map<string, size_t> elections;
vector<pair<double, string>> remainder;
map<string, size_t> chairs;
string line;
size_t all_count{};
while (getline(cin, line)) {
auto index = line.find_last_of(" ");
string name = line.substr(0, index);
size_t count = stoul(line.substr(index + 1));
party_list.emplace_back(name);
elections[name] = count;
all_count += count;
}
double first_value = static_cast<double>(all_count) / 450.0F;
size_t all_chairs = 0;
for (const auto &name : party_list) {
auto a = static_cast<double>(elections[name]) / first_value;
auto b = floor(a);
chairs[name] = static_cast<size_t>(b);
all_chairs += chairs[name];
remainder.emplace_back(a - b, name);
}
sort(remainder.begin(), remainder.end(), greater_comp());
//reverse(remainder.begin(), remainder.end());
for (const auto &[r, name] : remainder) {
if (all_chairs >= 450) {
break;
}
++chairs[name];
++all_chairs;
}
for (const auto &name : party_list) {
cout << name << ' ' << chairs[name] << endl;
}
return 0;
}
| 23.476923 | 68 | 0.591088 | neon1ks |
bfccffb0592842178fb180a8dfabee277730d4dd | 7,029 | cpp | C++ | src/AbstractComponent.cpp | benzap/Kampf | 9cf4fb0d6ec22bc35ade9b476d29df34902c6689 | [
"Zlib"
] | 2 | 2018-05-13T05:27:29.000Z | 2018-05-29T06:35:57.000Z | src/AbstractComponent.cpp | benzap/Kampf | 9cf4fb0d6ec22bc35ade9b476d29df34902c6689 | [
"Zlib"
] | null | null | null | src/AbstractComponent.cpp | benzap/Kampf | 9cf4fb0d6ec22bc35ade9b476d29df34902c6689 | [
"Zlib"
] | null | null | null | #include "AbstractComponent.hpp"
#include <iostream>
#include <cassert>
AbstractComponent::AbstractComponent(stringType name, enumComponentFamily family, bool bIsParent) :
name(name),
family(family),
bIsParent(bIsParent) {
}
AbstractComponent::~AbstractComponent() {
}
const stringType& AbstractComponent::getName() {
return this->name;
}
void AbstractComponent::setName(stringType name) {
this->name = name;
}
enumComponentFamily AbstractComponent::getFamily() {
return this->family;
}
bool AbstractComponent::isParent() {
return this->bIsParent;
}
bool AbstractComponent::isActive() {
return this->bActive;
}
void AbstractComponent::setActive() {
this->bActive = true;
}
void AbstractComponent::setInactive() {
this->bActive = false;
}
//value types
boolType AbstractComponent::getCustomAttribute_bool(stringType keyname) {
assert(this->hasCustomAttribute(keyname));
return this->customAttributeMap[keyname].get_bool();
}
stringType AbstractComponent::setCustomAttribute(stringType keyname, boolType bValue) {
if (this->hasCustomAttribute(keyname)) {
customAttributeMap[keyname].set(bValue);
}
else {
auto customAttribute = CustomAttribute(bValue);
customAttributeMap[keyname] = customAttribute;
}
return keyname;
}
integerType AbstractComponent::getCustomAttribute_int(stringType keyname) {
assert(this->hasCustomAttribute(keyname));
//TODO: check type
return this->customAttributeMap[keyname].get_int();
}
stringType AbstractComponent::setCustomAttribute(stringType keyname, integerType iValue) {
if (this->hasCustomAttribute(keyname)) {
customAttributeMap[keyname].set(iValue);
}
else {
auto customAttribute = CustomAttribute(iValue);
customAttributeMap[keyname] = customAttribute;
}
return keyname;
}
floatType AbstractComponent::getCustomAttribute_float(stringType keyname) {
assert(this->hasCustomAttribute(keyname));
//TODO: check type
return customAttributeMap[keyname].get_float();
}
stringType AbstractComponent::setCustomAttribute(stringType keyname, floatType fValue) {
if (this->hasCustomAttribute(keyname)) {
customAttributeMap[keyname].set(fValue);
}
else {
auto customAttribute = CustomAttribute(fValue);
customAttributeMap[keyname] = customAttribute;
}
return keyname;
}
charType AbstractComponent::getCustomAttribute_char(stringType keyname) {
assert(this->hasCustomAttribute(keyname));
//TODO: check type
return customAttributeMap[keyname].get_char();
}
stringType AbstractComponent::setCustomAttribute(stringType keyname, charType cValue) {
if (this->hasCustomAttribute(keyname)) {
customAttributeMap[keyname].set(cValue);
}
else {
auto customAttribute = CustomAttribute(cValue);
customAttributeMap[keyname] = customAttribute;
}
return keyname;
}
//ptr types
const intArrayType& AbstractComponent::getCustomAttribute_intArray(stringType keyname) {
assert(this->hasCustomAttribute(keyname));
return customAttributeMap[keyname].get_intArray();
}
stringType AbstractComponent::setCustomAttribute(stringType keyname, intArrayType iaValue) {
if (this->hasCustomAttribute(keyname)) {
customAttributeMap[keyname].set(iaValue);
}
else {
auto customAttribute = CustomAttribute(iaValue);
customAttributeMap[keyname] = customAttribute;
}
return keyname;
}
const floatArrayType& AbstractComponent::getCustomAttribute_floatArray(stringType keyname) {
assert(this->hasCustomAttribute(keyname));
//TODO: check type
return customAttributeMap[keyname].get_floatArray();
}
stringType AbstractComponent::setCustomAttribute(stringType keyname, floatArrayType faValue) {
if (this->hasCustomAttribute(keyname)) {
customAttributeMap[keyname].set(faValue);
}
else {
auto customAttribute = CustomAttribute(faValue);
customAttributeMap[keyname] = customAttribute;
}
return keyname;
}
const stringType& AbstractComponent::getCustomAttribute_string(stringType keyname) {
assert(this->hasCustomAttribute(keyname));
//TODO: check type
return customAttributeMap[keyname].get_string();
}
stringType AbstractComponent::setCustomAttribute(stringType keyname, stringType sValue) {
auto sValuePtr = new stringType(sValue);
if (this->hasCustomAttribute(keyname)) {
customAttributeMap[keyname].set(sValuePtr);
}
else {
auto customAttribute = CustomAttribute(sValuePtr);
customAttributeMap[keyname] = customAttribute;
}
return keyname;
}
void* AbstractComponent::getCustomAttribute_void(stringType keyname) {
assert(this->hasCustomAttribute(keyname));
//TODO: check type
return customAttributeMap[keyname].get_void();
}
stringType AbstractComponent::setCustomAttribute(stringType keyname, void* vValue) {
if (this->hasCustomAttribute(keyname)) {
customAttributeMap[keyname].set(vValue);
}
else {
auto customAttribute = CustomAttribute(vValue);
customAttributeMap[keyname] = customAttribute;
}
return keyname;
}
const Vector3& AbstractComponent::getCustomAttribute_vector(stringType keyname) {
assert(this->hasCustomAttribute(keyname));
return customAttributeMap[keyname].get_vector();
}
stringType AbstractComponent::setCustomAttribute(stringType keyname, Vector3 vsValue) {
if (this->hasCustomAttribute(keyname)) {
customAttributeMap[keyname].set(vsValue);
}
else {
auto customAttribute = CustomAttribute(vsValue);
customAttributeMap[keyname] = customAttribute;
}
return keyname;
}
bool AbstractComponent::hasCustomAttribute(stringType keyname) {
if (this->customAttributeMap.find(keyname) == this->customAttributeMap.end()) {
return false;
}
return true;
}
enumAttribute AbstractComponent::getCustomAttributeType(stringType keyname) {
return customAttributeMap[keyname].getType();
}
void AbstractComponent::deleteCustomAttribute(stringType keyname) {
if(this->hasCustomAttribute(keyname)) {
auto iterAttribute = this->customAttributeMap.find(keyname);
this->customAttributeMap.erase(iterAttribute);
}
}
void AbstractComponent::addChild(AbstractComponent* component) {
this->children.push_back(component);
}
AbstractComponent*
AbstractComponent::createChild(stringType name) {
auto component = new AbstractComponent(name, enumComponentFamily::ABSTRACT, false);
this->children.push_back(component);
return component;
}
bool AbstractComponent::hasChildren() {
if (this->children.empty()) {
return false;
}
return true;
}
CustomAttribute* AbstractComponent::get(stringType keyname) {
return &(customAttributeMap[keyname]);
}
void AbstractComponent::set(stringType keyname, CustomAttribute attr) {
customAttributeMap[keyname] = attr;
}
const componentContainerType* AbstractComponent::getChildContainer() {
return &this->children;
}
AbstractComponent* createAbstractComponent(
stringType name,
boolType bIsParent) {
auto abstractComponent = new AbstractComponent(
name,
enumComponentFamily::ABSTRACT,
bIsParent);
return abstractComponent;
}
| 26.625 | 99 | 0.762982 | benzap |
bfd44d57b02fb0074077693ec5c9e82befb3069a | 1,217 | cpp | C++ | Boolean_set_operations_2/examples/Boolean_set_operations_2/draw_polygon_set.cpp | ffteja/cgal | c1c7f4ad9a4cd669e33ca07a299062a461581812 | [
"CC0-1.0"
] | 3,227 | 2015-03-05T00:19:18.000Z | 2022-03-31T08:20:35.000Z | Boolean_set_operations_2/examples/Boolean_set_operations_2/draw_polygon_set.cpp | ffteja/cgal | c1c7f4ad9a4cd669e33ca07a299062a461581812 | [
"CC0-1.0"
] | 5,574 | 2015-03-05T00:01:56.000Z | 2022-03-31T15:08:11.000Z | Boolean_set_operations_2/examples/Boolean_set_operations_2/draw_polygon_set.cpp | ffteja/cgal | c1c7f4ad9a4cd669e33ca07a299062a461581812 | [
"CC0-1.0"
] | 1,274 | 2015-03-05T00:01:12.000Z | 2022-03-31T14:47:56.000Z | /*! \file draw_polygon_set.cpp
* Drawing a polygon set.
*/
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/Polygon_2.h>
#include <CGAL/Polygon_with_holes_2.h>
#include <CGAL/Polygon_set_2.h>
#include <CGAL/draw_polygon_set_2.h>
typedef CGAL::Exact_predicates_exact_constructions_kernel K;
typedef CGAL::Polygon_2<K> Polygon_2;
typedef CGAL::Polygon_with_holes_2<K> Polygon_with_holes_2;
typedef CGAL::Polygon_set_2<K> Polygon_set_2;
typedef CGAL::Point_2<K> Point_2;
Polygon_2 rectangle(int l)
{
// Create a rectangle with given side length.
Polygon_2 P;
P.push_back(Point_2(-l,-l));
P.push_back(Point_2(l,-l));
P.push_back(Point_2(l,l));
P.push_back(Point_2(-l,l));
return P;
}
int main()
{
// Create a large rectangle A, with a hole and a smaller rectangle
// B inside A's hole.
Polygon_with_holes_2 A(rectangle(3));
Polygon_2 H(rectangle(2));
H.reverse_orientation();
A.add_hole(H);
Polygon_2 B(rectangle(1));
// Add them to a polygon set and draw it.
Polygon_set_2 S;
S.insert(A);
S.insert(B);
CGAL::draw(S);
return 0;
}
| 25.354167 | 79 | 0.660641 | ffteja |
bfd8545519f23831a646f62db06fe9cf80d3cc8a | 4,438 | cpp | C++ | src/GamePanel.cpp | MCRewind/Ludum-Dare-40 | cac9d17adbba69cf3b26eb36155d002a499bdf06 | [
"MIT"
] | null | null | null | src/GamePanel.cpp | MCRewind/Ludum-Dare-40 | cac9d17adbba69cf3b26eb36155d002a499bdf06 | [
"MIT"
] | null | null | null | src/GamePanel.cpp | MCRewind/Ludum-Dare-40 | cac9d17adbba69cf3b26eb36155d002a499bdf06 | [
"MIT"
] | null | null | null | #include "GamePanel.h"
#include <string>
int keyOneState = 0;
int keyTwoState = 0;
int keyThreeState = 0;
int buyOneTime = 20;
int buyTwoTime = 20;
int buyThreeTime = 20;
GamePanel::GamePanel(Window * window, Camera * camera) : Panel(window, camera) {
state = 0;
this->window = window;
this->camera = camera;
map = new Map(window, camera, camera->getWidth() / 16, camera->getHeight() / 16);
health = new ColRect(camera, 1, 0, 0, 1, camera->getWidth() / 2 - 75, camera->getHeight() - 10, 0, 50, 10);
selected = new TexRect(camera, "res/textures/selected.png", camera->getWidth() - 40, 0, 0, 40, 40);
death = new TexRect(camera, "res/textures/death.png", camera->getWidth() / 2 - 64, camera->getHeight() / 2 - 64, 0, 128, 128);
boneSign = new TexRect(camera, "res/textures/boneSign.png", 60, 2, 0, 15, 10.5);
waves = new TexRect(camera, "res/textures/waves.png", 110, 6, 0, 21.25, 3.75);
std::vector<const char*> digitPaths =
{
"res/textures/0.png",
"res/textures/1.png",
"res/textures/2.png",
"res/textures/3.png",
"res/textures/4.png",
"res/textures/5.png",
"res/textures/6.png",
"res/textures/7.png",
"res/textures/8.png",
"res/textures/9.png",
};
digitOne = new MultiRect(camera, digitPaths, 77, 4, 0, 6, 8);
digitTwo = new MultiRect(camera, digitPaths, 87, 4, 0, 6, 8);
digitThree = new MultiRect(camera, digitPaths, 97, 4, 0, 6, 8);
waveCount = new MultiRect(camera, digitPaths, 130, 4, 0, 6, 8);
std::vector<const char*> keyOnePaths =
{
"res/textures/keyOne.png",
"res/textures/keyOnePressed.png"
};
std::vector<const char*> keyTwoPaths =
{
"res/textures/keyTwo.png",
"res/textures/keyTwoPressed.png"
};
std::vector<const char*> keyThreePaths =
{
"res/textures/keyThree.png",
"res/textures/keyThreePressed.png"
};
keyOne = new MultiRect(camera, keyOnePaths, 0, 0, 0, 16, 16);
keyTwo = new MultiRect(camera, keyTwoPaths, 20, 0, 0, 16, 16);
keyThree = new MultiRect(camera, keyThreePaths, 40, 0, 0, 16, 16);
wave = 0;
map->spawnWave(wave);
}
void GamePanel::update() {
if (map->zombies.size() <= 0)
{
wave++;
map->spawnWave(wave);
}
map->update();
health->setWidth(map->getPlayer()->getHealth());
if (window->isKeyPressed(GLFW_KEY_1))
keyOnePress();
else
keyOneState = 0;
if (window->isKeyPressed(GLFW_KEY_2))
keyTwoPress();
else
keyTwoState = 0;
if (window->isKeyPressed(GLFW_KEY_3))
keyThreePress();
else
keyThreeState = 0;
if (map->getPlayer()->getHealth() < 0)
if (window->isKeyPressed(GLFW_KEY_X))
{
GamePanel(window, camera);
}
buyOneTime > 100 ? buyOneTime = 100 : buyOneTime++;
buyTwoTime > 100 ? buyTwoTime = 100 : buyTwoTime++;
buyThreeTime > 100 ? buyThreeTime = 100 : buyThreeTime++;
/*if (window->isKeyPressed(GLFW_KEY_LEFT))
camera->translate(glm::vec3(-3, 0, 0));
if (window->isKeyPressed(GLFW_KEY_RIGHT))
camera->translate(glm::vec3(3, 0, 0));
if (window->isKeyPressed(GLFW_KEY_UP))
camera->translate(glm::vec3(0, -3, 0));
if (window->isKeyPressed(GLFW_KEY_DOWN))
camera->translate(glm::vec3(0, 3, 0));
if (window->isKeyPressed(GLFW_KEY_N))
camera->zoomi();
if (window->isKeyPressed(GLFW_KEY_M))
camera->zoomo();*/
}
void GamePanel::keyOnePress()
{
keyOneState = 1;
if (buyOneTime > 20)
{
if (map->getPlayer()->bones >= 5)
{
map->spawnBlock(1);
map->getPlayer()->bones -= 5;
buyOneTime = 0;
}
}
}
void GamePanel::keyTwoPress()
{
keyTwoState = 1;
if (buyTwoTime > 20)
{
if (map->getPlayer()->bones >= 15)
{
map->spawnBlock(2);
map->getPlayer()->bones -= 15;
buyTwoTime = 0;
}
}
}
void GamePanel::keyThreePress()
{
keyThreeState = 1;
if (buyThreeTime > 20)
{
if (map->getPlayer()->bones >= 50)
{
map->spawnBlock(3);
map->getPlayer()->bones -= 50;
buyThreeTime = 0;
}
}
}
void GamePanel::render() {
waveCount->render(wave);
waves->render();
boneSign->render();
std::string s = std::to_string(map->getPlayer()->bones);
if (s.size() > 0)
digitOne->render(s.at(0) - '0');
if (s.size() > 1)
digitTwo->render(s.at(1) - '0');
if (s.size() > 2)
digitThree->render(s.at(2) - '0');
keyOne->render(keyOneState);
keyTwo->render(keyTwoState);
keyThree->render(keyThreeState);
if (map->getPlayer()->getHealth() < 0)
death->render();
selected->render();
if (map->getPlayer()->getHealth() > 0)
health->render();
map->render();
}
void GamePanel::setActive()
{
state = 0;
}
GamePanel::~GamePanel() {
delete map;
} | 23.73262 | 127 | 0.646462 | MCRewind |
bfd8c471bf8e2b3d9249588c4719e70fa46d37ed | 837 | cpp | C++ | code/shader_light_types.cpp | Ihaa21/ToonShading | f6f8e6037273b36d57e96ab7ee109957058e1992 | [
"MIT"
] | null | null | null | code/shader_light_types.cpp | Ihaa21/ToonShading | f6f8e6037273b36d57e96ab7ee109957058e1992 | [
"MIT"
] | null | null | null | code/shader_light_types.cpp | Ihaa21/ToonShading | f6f8e6037273b36d57e96ab7ee109957058e1992 | [
"MIT"
] | null | null | null |
struct directional_light
{
vec3 Color;
vec3 Dir;
vec3 AmbientLight;
mat4 VPTransform;
};
struct point_light
{
vec3 Color;
vec3 Pos; // NOTE: Camera Space Position
float MaxDistance; // TODO: Rename to radius
};
vec3 PointLightAttenuate(vec3 SurfacePos, point_light Light)
{
vec3 Result = vec3(0);
/*
// NOTE: This is regular attenuation model
float Distance = length(Light.Pos - SurfacePos);
float Attenuation = 1.0 / (Distance * Distance);
Result = Light.Color * Attenuation;
*/
// NOTE: This is a sorta fake attenuation model but gives a more exact sphere size
float Distance = length(Light.Pos - SurfacePos);
float PercentDist = clamp((Light.MaxDistance - Distance) / Light.MaxDistance, 0, 1);
Result = Light.Color * PercentDist;
return Result;
}
| 23.25 | 88 | 0.671446 | Ihaa21 |
bfda9a62777dae9f19e3be0a4eea25127880b160 | 1,671 | cpp | C++ | ddsrouter_event/src/cpp/wait/BooleanWaitHandler.cpp | eProsima/DDS-Router | 59ff7e87acc718fad7ad9e38912100210675cbca | [
"Apache-2.0"
] | 25 | 2021-11-17T11:48:40.000Z | 2022-03-28T05:59:45.000Z | ddsrouter_event/src/cpp/wait/BooleanWaitHandler.cpp | eProsima/DDS-Router | 59ff7e87acc718fad7ad9e38912100210675cbca | [
"Apache-2.0"
] | 128 | 2021-11-16T11:38:59.000Z | 2022-03-25T10:32:12.000Z | ddsrouter_event/src/cpp/wait/BooleanWaitHandler.cpp | eProsima/DDS-Router | 59ff7e87acc718fad7ad9e38912100210675cbca | [
"Apache-2.0"
] | 4 | 2021-12-17T18:14:36.000Z | 2022-03-11T10:10:16.000Z | // Copyright 2022 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// 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 BooleanWaitHandler.cpp
*
*/
#include <ddsrouter_utils/Log.hpp>
#include <ddsrouter_event/wait/BooleanWaitHandler.hpp>
namespace eprosima {
namespace ddsrouter {
namespace event {
BooleanWaitHandler::BooleanWaitHandler(
bool opened /* = false */,
bool enabled /* = true */)
: WaitHandler<bool>(opened, enabled)
{
}
BooleanWaitHandler::~BooleanWaitHandler()
{
}
AwakeReason BooleanWaitHandler::wait(
const utils::Duration_ms& timeout /* = 0 */)
{
return WaitHandler<bool>::wait(
std::function<bool(const bool&)>([](const bool& value)
{
return value;
}),
timeout);
}
void BooleanWaitHandler::open() noexcept
{
// Change value and do notify
set_value(true, true);
}
void BooleanWaitHandler::close() noexcept
{
// Change value and do not notify
set_value(false, false);
}
bool BooleanWaitHandler::is_open() const noexcept
{
return get_value();
}
} /* namespace event */
} /* namespace ddsrouter */
} /* namespace eprosima */
| 23.871429 | 75 | 0.689408 | eProsima |
bfde7de1ca20fb0c77ea0b9dc6d8de9cdf2afce1 | 2,137 | hpp | C++ | src/common/minhook.hpp | PragmaTwice/proxinject | 3de394b110301c2d04eb4bc83c1f7bbabc214531 | [
"Apache-2.0"
] | null | null | null | src/common/minhook.hpp | PragmaTwice/proxinject | 3de394b110301c2d04eb4bc83c1f7bbabc214531 | [
"Apache-2.0"
] | null | null | null | src/common/minhook.hpp | PragmaTwice/proxinject | 3de394b110301c2d04eb4bc83c1f7bbabc214531 | [
"Apache-2.0"
] | null | null | null | // Copyright 2022 PragmaTwice
//
// Licensed under the Apache License,
// Version 2.0(the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef PROXINJECT_COMMON_MINHOOK
#define PROXINJECT_COMMON_MINHOOK
#include <minhook.h>
struct minhook {
struct status {
MH_STATUS v;
status(MH_STATUS v) : v(v) {}
operator MH_STATUS() const { return v; }
bool ok() const { return v == MH_OK; }
bool error() const { return v != MH_OK; }
};
static status init() { return MH_Initialize(); }
static status deinit() { return MH_Uninitialize(); }
template <typename F> static status enable(F *api) {
return MH_EnableHook(reinterpret_cast<LPVOID>(api));
}
template <typename F> static status disable(F *api) {
return MH_DisableHook(reinterpret_cast<LPVOID>(api));
}
static constexpr inline void *all_hooks = MH_ALL_HOOKS;
static status enable() { return enable(all_hooks); }
static status disable() { return disable(all_hooks); }
template <typename F>
static status create(F *target, F *detour, F *&original) {
return MH_CreateHook(reinterpret_cast<LPVOID>(target),
reinterpret_cast<LPVOID>(detour),
reinterpret_cast<LPVOID *>(&original));
}
template <typename F> static status remove(F *target) {
return MH_RemoveHook(reinterpret_cast<LPVOID>(target));
}
template <auto syscall, typename derived> struct api {
using F = decltype(syscall);
static inline F original = nullptr;
static status create() {
return minhook::create(syscall, derived::detour, original);
}
static status remove() { return minhook::remove(syscall); }
};
};
#endif
| 28.493333 | 75 | 0.689752 | PragmaTwice |
bfdfe590b733a58fd999394f876eaacce78bb14f | 1,828 | hpp | C++ | MultiDimensionalArray.hpp | astrowar/SuperNovaeOpenCL | 7fd322d289f642feb4e4b8d8a09e92086c76f5e7 | [
"MIT"
] | null | null | null | MultiDimensionalArray.hpp | astrowar/SuperNovaeOpenCL | 7fd322d289f642feb4e4b8d8a09e92086c76f5e7 | [
"MIT"
] | null | null | null | MultiDimensionalArray.hpp | astrowar/SuperNovaeOpenCL | 7fd322d289f642feb4e4b8d8a09e92086c76f5e7 | [
"MIT"
] | null | null | null |
#ifndef MULTIDIMENSIONALARRAY_HPP
#define MULTIDIMENSIONALARRAY_HPP
#include <utility>
#include <vector>
template < typename N>
class Interval
{
const double start;
const double end;
const double delta;
const size_t num_divs;
Interval(double _start, double _end , double _delta): start(_start),end(_end), delta(_delta), num_divs(size_t(fabs(end - start) / delta))
{
}
int i(double x )
{
int ii = (x - start) / delta;
if (ii < 0) return 0;
if (ii > num_divs-1) return num_divs-1;
return ii;
}
};
template < int N>
class MultiDimensionalArray
{
public:
std::vector< MultiDimensionalArray< N - 1> > data;
std::vector< double> x;
MultiDimensionalArray(std::vector<double> _x ) : x(std::move(_x))
{
}
};
template< > class MultiDimensionalArray<1>
{
public:
std::vector<double> data;
std::vector< double> x;
MultiDimensionalArray(std::vector<double> _x) : x(std::move(_x))
{
data.resize(x.size(), 0.0);
}
};
template < int N ,typename... Rest>
MultiDimensionalArray<N> make_mdarray(std::vector< double> x, Rest... rest)
{
if constexpr (sizeof...(rest) > 0)
{
auto m = MultiDimensionalArray<N>(x);
//m.data.reserve(x.size());
for (auto _x : x)
{
m.data.push_back(make_mdarray<N - 1>(rest...));
}
return m;
}
else
{
return MultiDimensionalArray<1>(x);
}
}
template <typename F, int N, typename... Rest>
void iterator_function( F func, MultiDimensionalArray<N> &m , Rest... rest)
{
if constexpr (N > 1)
{
for(int i =0;i<m.x.size();++i)
{
double x = m.x[i];
iterator_function(func,m.data[i], rest..., x);
}
}
else
{
for (auto x : m.x)
{
func( rest... , x );
}
}
}
//MultiDimensionalArray<1> make_mdarray(std::vector< double> x )
//{
// return MultiDimensionalArray<1>(x);
//}
#endif // MULTIDIMENSIONALARRAY_HPP
| 17.245283 | 138 | 0.640044 | astrowar |
bfdffb4899ad724bc8b51b47528bd63999f9b2b5 | 2,500 | cpp | C++ | cpp/library/boost/program_options.cpp | KaiserLancelot/Cpp-Primer | a4791a6765f0b6c864e8881e6a5328e2a3d68974 | [
"MIT"
] | 2 | 2019-12-21T00:53:47.000Z | 2020-01-01T10:36:30.000Z | cpp/library/boost/program_options.cpp | KaiserLancelot/Cpp-Primer | a4791a6765f0b6c864e8881e6a5328e2a3d68974 | [
"MIT"
] | null | null | null | cpp/library/boost/program_options.cpp | KaiserLancelot/Cpp-Primer | a4791a6765f0b6c864e8881e6a5328e2a3d68974 | [
"MIT"
] | null | null | null | //
// Created by kaiser on 2020/4/27.
//
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/positional_options.hpp>
#include <boost/program_options/variables_map.hpp>
int main(int argc, char* argv[]) {
try {
std::int32_t opt;
boost::program_options::options_description generic("Generic options");
generic.add_options()("version,v", "print version string")(
"help,h", "produce help message");
boost::program_options::options_description config("Configuration");
config.add_options()(
"optimization,O",
boost::program_options::value<std::int32_t>(&opt)->default_value(0),
"optimization level")(
"include-path,I",
// composing() 告诉库将来自不同位置的值合并到一起
boost::program_options::value<std::vector<std::string>>()->composing(),
"include path");
boost::program_options::options_description hidden("Hidden options");
hidden.add_options()(
"input-file", boost::program_options::value<std::vector<std::string>>(),
"input file");
boost::program_options::options_description cmdline_options;
cmdline_options.add(generic).add(config).add(hidden);
boost::program_options::options_description visible("Allowed options");
visible.add(generic).add(config);
boost::program_options::positional_options_description p;
p.add("input-file", -1);
boost::program_options::variables_map vm;
store(boost::program_options::command_line_parser(argc, argv)
.options(cmdline_options)
.positional(p)
.run(),
vm);
notify(vm);
if (vm.contains("help")) {
std::cout << visible << "\n";
return EXIT_SUCCESS;
}
if (opt != 0) {
std::cout << "optimization: " << opt << '\n';
}
if (vm.contains("include-path")) {
std::cout << "include-path: " << '\n';
for (const auto& item :
vm["include-path"].as<std::vector<std::string>>()) {
std::cout << item << '\n';
}
}
if (vm.contains("input-file")) {
std::cout << "input-file: " << '\n';
for (const auto& item : vm["input-file"].as<std::vector<std::string>>()) {
std::cout << item << '\n';
}
}
} catch (const std::exception& err) {
std::cerr << err.what() << "\n";
return EXIT_FAILURE;
}
}
| 29.761905 | 80 | 0.6184 | KaiserLancelot |
bfe45fd63a66c1ac3be272ee6f9f09ae0e0892a0 | 4,413 | cpp | C++ | dev/Gems/CloudGemMetric/v1/Code/Source/MetricsPriority.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 8 | 2019-10-07T16:33:47.000Z | 2020-12-07T03:59:58.000Z | dev/Gems/CloudGemMetric/v1/Code/Source/MetricsPriority.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | null | null | null | dev/Gems/CloudGemMetric/v1/Code/Source/MetricsPriority.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 5 | 2020-08-27T20:44:18.000Z | 2021-08-21T22:54:11.000Z | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "StdAfx.h"
#include "CloudGemMetric/MetricsPriority.h"
#include "AWS/ServiceAPI/CloudGemMetricClientComponent.h"
#include <AzCore/std/sort.h>
namespace CloudGemMetric
{
MetricsPriority::MetricsPriority()
{
}
MetricsPriority::~MetricsPriority()
{
}
void MetricsPriority::SetEventPriority(const char* eventName, int priority)
{
m_eventNameToPriorityMap[eventName] = priority;
}
int MetricsPriority::CompareMetrics(const AZStd::pair<const MetricsAggregator*, int>& p1, const AZStd::pair<const MetricsAggregator*, int>& p2)
{
if (p1.second < p2.second)
{
return -1;
}
else if (p1.second > p2.second)
{
return 1;
}
else
{
return 0;
}
}
void MetricsPriority::FilterByPriority(AZStd::vector<MetricsAggregator>& metrics, int maxSizeInBytes, AZStd::vector<MetricsAggregator>& out) const
{
if (metrics.size() == 0)
{
return;
}
AZStd::vector<AZStd::pair<const MetricsAggregator*, int>> sortedMetrics;
for (int i = 0; i < metrics.size(); i++)
{
auto it = m_eventNameToPriorityMap.find(metrics[i].GetEventName());
if (it != m_eventNameToPriorityMap.end())
{
sortedMetrics.emplace_back(AZStd::make_pair(&(metrics[i]), it->second));
}
}
AZStd::sort(sortedMetrics.begin(), sortedMetrics.end(), CompareMetrics);
int curSize = 0;
for (auto& p : sortedMetrics)
{
curSize += p.first->GetSizeInBytes();
if (curSize <= maxSizeInBytes)
{
out.emplace_back(AZStd::move(*(p.first)));
}
else
{
break;
}
}
}
void MetricsPriority::SerializeToJson(rapidjson::Document& doc) const
{
rapidjson::Value precedenceArrayVal(rapidjson::kArrayType);
auto it = m_eventNameToPriorityMap.begin();
for (; it != m_eventNameToPriorityMap.end(); ++it)
{
rapidjson::Value eventPrecedenceObjVal(rapidjson::kObjectType);
eventPrecedenceObjVal.AddMember("event", rapidjson::StringRef(it->first.c_str()), doc.GetAllocator());
eventPrecedenceObjVal.AddMember("precedence", it->second, doc.GetAllocator());
precedenceArrayVal.PushBack(eventPrecedenceObjVal, doc.GetAllocator());
}
doc.AddMember("priority", precedenceArrayVal, doc.GetAllocator());
}
bool MetricsPriority::ReadFromJson(const rapidjson::Document& doc)
{
if (!RAPIDJSON_IS_VALID_MEMBER(doc, "priority", IsArray))
{
return false;
}
AZStd::unordered_map<AZStd::string, int> eventNameToPriorityMap;
const rapidjson::Value& precedenceArrayVal = doc["priority"];
for (int i = 0; i < precedenceArrayVal.Size(); i++)
{
const rapidjson::Value& eventPrecedenceObjVal = precedenceArrayVal[i];
if (!RAPIDJSON_IS_VALID_MEMBER(eventPrecedenceObjVal, "event", IsString) ||
!RAPIDJSON_IS_VALID_MEMBER(eventPrecedenceObjVal, "precedence", IsInt))
{
return false;
}
eventNameToPriorityMap[eventPrecedenceObjVal["event"].GetString()] = eventPrecedenceObjVal["precedence"].GetInt();
}
m_eventNameToPriorityMap = AZStd::move(eventNameToPriorityMap);
return true;
}
void MetricsPriority::InitFromBackend(const AZStd::vector<CloudGemMetric::ServiceAPI::Priority>& priorities)
{
m_eventNameToPriorityMap.clear();
for (const auto& p : priorities)
{
m_eventNameToPriorityMap[p.event] = p.precedence;
}
}
} | 32.448529 | 150 | 0.612055 | jeikabu |
bfe4e9a9a2ba8972e8dbeed2523c105f49d0bef8 | 21,357 | cc | C++ | ompi/contrib/vt/vt/tools/vtunify/vt_unify_markers.cc | bringhurst/ompi | 7da12594dc72085162265188b505aca0d0cfe811 | [
"BSD-3-Clause-Open-MPI"
] | 1 | 2016-05-01T09:37:07.000Z | 2016-05-01T09:37:07.000Z | ompi/contrib/vt/vt/tools/vtunify/vt_unify_markers.cc | bringhurst/ompi | 7da12594dc72085162265188b505aca0d0cfe811 | [
"BSD-3-Clause-Open-MPI"
] | null | null | null | ompi/contrib/vt/vt/tools/vtunify/vt_unify_markers.cc | bringhurst/ompi | 7da12594dc72085162265188b505aca0d0cfe811 | [
"BSD-3-Clause-Open-MPI"
] | null | null | null | /**
* VampirTrace
* http://www.tu-dresden.de/zih/vampirtrace
*
* Copyright (c) 2005-2011, ZIH, TU Dresden, Federal Republic of Germany
*
* Copyright (c) 1998-2005, Forschungszentrum Juelich, Juelich Supercomputing
* Centre, Federal Republic of Germany
*
* See the file COPYING in the package base directory for details
**/
#include "vt_unify_handlers.h"
#include "vt_unify_hooks.h"
#include "vt_unify_markers.h"
#include "vt_unify_sync.h"
#include "otf.h"
#include <algorithm>
#include <iostream>
#include <assert.h>
MarkersC * theMarkers = 0; // instance of class MarkersC
//////////////////// class MarkersC ////////////////////
// public methods
//
MarkersC::MarkersC() : m_tkfacScope( 0 )
{
assert( theTokenFactory );
MASTER
{
// create token factory scope for marker definitions
//
m_tkfacScope =
new TokenFactoryScopeC<DefRec_DefMarkerS>( &m_globDefs );
assert( m_tkfacScope );
theTokenFactory->addScope( DEF_REC_TYPE__DefMarker, m_tkfacScope );
}
}
MarkersC::~MarkersC()
{
assert( theTokenFactory );
MASTER
{
// delete token factory scope of def. marker records
//
theTokenFactory->deleteScope( DEF_REC_TYPE__DefMarker );
}
}
bool
MarkersC::run()
{
bool error = false;
#ifdef VT_MPI
// block until all ranks have reached this point
if( NumRanks > 1 )
CALL_MPI( MPI_Barrier( MPI_COMM_WORLD ) );
#endif // VT_MPI
VPrint( 1, "Unifying markers\n" );
// trigger phase pre hook
theHooks->triggerPhaseHook( HooksC::Phase_UnifyMarkers_pre );
do
{
// read local markers
//
error = !readLocal();
if( SyncError( &error ) )
break;
MASTER
{
// write global markers, if present
if( !m_globDefs.empty() || !m_globSpots.empty() )
error = !writeGlobal();
}
SyncError( &error );
} while( false );
// show an error message, if necessary
//
MASTER
{
if( error )
{
std::cerr << ExeName << ": "
<< "An error occurred during unifying markers. Aborting."
<< std::endl;
}
}
// trigger phase post hook, if no error occurred
//
if( !error )
theHooks->triggerPhaseHook( HooksC::Phase_UnifyMarkers_post );
return !error;
}
bool
MarkersC::cleanUp()
{
bool error = false;
char filename1[STRBUFSIZE];
char filename2[STRBUFSIZE];
MASTER
{
// rename temporary marker output file
//
// get temporary output file prefix
const std::string tmp_out_file_prefix =
Params.out_file_prefix + TmpFileSuffix;
// get output file type
const OTF_FileType out_file_type = OTF_FILETYPE_MARKER |
( Params.docompress ? OTF_FILECOMPRESSION_COMPRESSED : 0 );
// get temporary file name
OTF_getFilename( tmp_out_file_prefix.c_str(), 0, out_file_type,
STRBUFSIZE, filename1 );
// get new file name
OTF_getFilename( Params.out_file_prefix.c_str(), 0, out_file_type,
STRBUFSIZE, filename2 );
// rename file
if( rename( filename1, filename2 ) == 0 )
VPrint( 3, " Renamed %s to %s\n", filename1, filename2 );
}
// remove local marker files, if necessary
//
if( Params.doclean )
{
int streams_num = (int)MyStreamIds.size();
int i;
#if defined(HAVE_OMP) && HAVE_OMP
# pragma omp parallel for private(i, filename1)
#endif // HAVE_OMP
for( i = 0; i < streams_num; i++ )
{
const uint32_t & streamid = MyStreamIds[i];
bool removed = false;
// get file name without compression suffix
OTF_getFilename( Params.in_file_prefix.c_str(), streamid,
OTF_FILETYPE_MARKER, STRBUFSIZE, filename1 );
// try to remove file
if( !( removed = ( remove( filename1 ) == 0 ) ) )
{
// if failed, get file name with compression suffix
OTF_getFilename( Params.in_file_prefix.c_str(), streamid,
OTF_FILETYPE_MARKER | OTF_FILECOMPRESSION_COMPRESSED,
STRBUFSIZE, filename1 );
// try to remove file again
removed = ( remove( filename1 ) == 0 );
}
if( removed )
PVPrint( 3, " Removed %s\n", filename1 );
}
}
return !error;
}
// private methods
//
bool
MarkersC::readLocal()
{
bool error = false;
VPrint( 2, " Reading local markers\n" );
// vector of local marker definitions
LargeVectorC<DefRec_DefMarkerS*> loc_defs;
// vector of local marker spots
LargeVectorC<MarkerSpotS*> loc_spots;
do
{
// TODO: parallelize this loop with OpenMP
for( uint32_t i = 0; i < MyStreamIds.size(); i++ )
{
const uint32_t & streamid = MyStreamIds[i];
// read local markers of stream
if( (error = !readLocal( streamid, loc_defs, loc_spots )) )
break;
}
if( SyncError( &error ) )
break;
// process local marker definitions
//
#ifdef VT_MPI
if( NumRanks > 1 )
{
// gather local marker definitions from all ranks
//
error = !gatherLocal( GATHER_TYPE_DEFS, &loc_defs );
// if( SyncError( &error ) )
// break;
// local marker definitions not needed anymore on slave ranks;
// delete them
//
SLAVE
{
for( uint32_t i = 0; i < loc_defs.size(); i++ )
delete loc_defs[i];
loc_defs.clear();
}
}
#endif // VT_MPI
MASTER
{
// create global marker definitions
//
for( uint32_t i = 0; i < loc_defs.size(); i++ )
{
// create global definition
m_tkfacScope->create( loc_defs[i] );
// delete local definition
delete loc_defs[i];
}
// clear vector of local marker definitions
loc_defs.clear();
}
// process local marker spots
//
#ifdef VT_MPI
if( NumRanks > 1 )
{
// gather local marker spots from all ranks
//
error = !gatherLocal( GATHER_TYPE_SPOTS, &loc_spots );
if( SyncError( &error ) )
break;
// local marker spots not needed anymore on slave ranks;
// delete them
//
SLAVE
{
for( uint32_t i = 0; i < loc_spots.size(); i++ )
delete loc_spots[i];
loc_spots.clear();
}
}
#endif // VT_MPI
MASTER
{
// create global marker spots
//
for( uint32_t i = 0; i < loc_spots.size(); i++ )
{
MarkerSpotS new_glob_spot = *(loc_spots[i]);
// correct time
new_glob_spot.time =
theTimeSync->correctTime( new_glob_spot.proc,
new_glob_spot.time );
// correct marker token
new_glob_spot.marker =
m_tkfacScope->translate
( new_glob_spot.proc, new_glob_spot.marker );
assert( new_glob_spot.marker != 0 );
// add new global marker spot to vector
m_globSpots.push_back( new_glob_spot );
// delete local spot
delete loc_spots[i];
}
// clear vector of local marker spots
loc_spots.clear();
// sort global marker spots
std::stable_sort( m_globSpots.begin(), m_globSpots.end(),
std::less<MarkerSpotS>() );
}
} while( false );
return !error;
}
bool
MarkersC::readLocal( const uint32_t & streamId,
LargeVectorC<DefRec_DefMarkerS*> & locDefs,
LargeVectorC<MarkerSpotS*> & locSpots )
{
bool error = false;
// open file manager for reader stream
//
OTF_FileManager * manager = OTF_FileManager_open( 1 );
assert( manager );
// open stream for reading
//
OTF_RStream * rstream =
OTF_RStream_open( Params.in_file_prefix.c_str(), streamId, manager );
assert( rstream );
PVPrint( 3, " Opened OTF reader stream [namestub %s id %x]\n",
Params.in_file_prefix.c_str(), streamId );
do
{
// try to get markers buffer
//
if( !OTF_RStream_getMarkerBuffer( rstream ) )
{
PVPrint( 3, " No markers found in this OTF reader stream "
"- Ignored\n" );
break;
}
// close markers buffer
OTF_RStream_closeMarkerBuffer( rstream );
// create record handler and set defs./spots vector as
// first handler argument for ...
//
OTF_HandlerArray * handler_array = OTF_HandlerArray_open();
assert( handler_array );
// ... OTF_DEFMARKER_RECORD
OTF_HandlerArray_setHandler( handler_array,
(OTF_FunctionPointer*)Handle_DefMarker,
OTF_DEFMARKER_RECORD );
OTF_HandlerArray_setFirstHandlerArg( handler_array,
&locDefs,
OTF_DEFMARKER_RECORD );
// ... OTF_MARKER_RECORD
OTF_HandlerArray_setHandler( handler_array,
(OTF_FunctionPointer*)Handle_MarkerSpot,
OTF_MARKER_RECORD );
OTF_HandlerArray_setFirstHandlerArg( handler_array,
&locSpots,
OTF_MARKER_RECORD );
// read local markers
//
if( OTF_RStream_readMarker( rstream, handler_array ) ==
OTF_READ_ERROR )
{
std::cerr << ExeName << ": Error: "
<< "Could not read markers of OTF stream [namestub "
<< Params.in_file_prefix << " id "
<< std::hex << streamId << "]"
<< std::dec << std::endl;
error = true;
}
// close record handler
OTF_HandlerArray_close( handler_array );
} while( false );
// close reader stream
OTF_RStream_close( rstream );
// close file manager for reader stream
OTF_FileManager_close( manager );
PVPrint( 3, " Closed OTF reader stream [namestub %s id %x]\n",
Params.in_file_prefix.c_str(), streamId );
return !error;
}
bool
MarkersC::writeGlobal()
{
bool error = false;
VPrint( 2, " Writing global markers\n" );
// get temporary output file prefix
const std::string tmp_out_file_prefix =
Params.out_file_prefix + TmpFileSuffix;
// open file manager for writer stream
//
OTF_FileManager * manager = OTF_FileManager_open( 1 );
assert( manager );
// open stream for writing (stream id = 0)
//
OTF_WStream * wstream =
OTF_WStream_open( tmp_out_file_prefix.c_str(), 0, manager );
assert( wstream );
VPrint( 3, " Opened OTF writer stream [namestub %s id 0]\n",
tmp_out_file_prefix.c_str() );
// set file compression
if( Params.docompress )
OTF_WStream_setCompression( wstream, OTF_FILECOMPRESSION_COMPRESSED );
do
{
// resort marker definitions
//
typedef
std::set<const DefRec_DefMarkerS*, DefRec_DefMarkerS::SortS>
resorted_markers_t;
resorted_markers_t resorted_markers;
for( std::set<DefRec_DefMarkerS>::const_iterator it =
m_globDefs.begin(); it != m_globDefs.end(); it++ )
{
resorted_markers.insert( &(*it) );
}
// write global marker definition records
//
// iterate over all marker definitions
for( resorted_markers_t::const_iterator it = resorted_markers.begin();
it != resorted_markers.end(); it++ )
{
bool do_write = true;
// get copy of marker def. record in order that hook(s) can
// modify it
DefRec_DefMarkerS record = **it;
// trigger write record hook
theHooks->triggerWriteRecordHook( HooksC::Record_DefMarker, 5,
&wstream, &(record.deftoken), &(record.type), &(record.name),
&do_write );
// write record
if( do_write )
error = ( OTF_WStream_writeDefMarker( wstream, record.deftoken,
record.name.c_str(), record.type ) == 0 );
}
// write global marker spot records
//
for( uint32_t i = 0; i < m_globSpots.size() && !error; i++ )
{
bool do_write = true;
// reference to marker spot record
MarkerSpotS & record = m_globSpots[i];
// trigger write record hook
theHooks->triggerWriteRecordHook( HooksC::Record_MarkerSpot, 6,
&wstream, &(record.time), &(record.proc), &(record.marker),
&(record.text), &do_write );
// write record
if( do_write )
error = ( OTF_WStream_writeMarker( wstream, record.time, record.proc,
record.marker, record.text.c_str() ) == 0 );
}
} while( false );
// show an error message, if necessary
//
if( error )
{
std::cerr << ExeName << ": Error: "
<< "Could not write global markers to OTF stream [namestub "
<< tmp_out_file_prefix.c_str() << " id 0]" << std::endl;
}
// close writer stream
OTF_WStream_close( wstream );
// close file manager for writer stream
OTF_FileManager_close( manager );
VPrint( 3, " Closed OTF writer stream [namestub %s id 0]\n",
tmp_out_file_prefix.c_str() );
return !error;
}
#ifdef VT_MPI
bool
MarkersC::gatherLocal( const GatherTypeT & type, void * locRecs )
{
bool error = false;
assert( NumRanks > 1 );
// block until all ranks have reached this point
CALL_MPI( MPI_Barrier( MPI_COMM_WORLD ) );
// cast input vector for more convenient access
//
LargeVectorC<DefRec_DefMarkerS*> * loc_defs = 0;
LargeVectorC<MarkerSpotS*> * loc_spots = 0;
if( type == GATHER_TYPE_DEFS )
{
loc_defs = static_cast<LargeVectorC<DefRec_DefMarkerS*>*>( locRecs );
VPrint( 2, " Gathering local marker definitions\n" );
}
else // type == GATHER_TYPE_SPOTS
{
loc_spots = static_cast<LargeVectorC<MarkerSpotS*>*>( locRecs );
VPrint( 2, " Gathering local marker spots\n" );
}
uint32_t loc_recs_size;
char * send_buffer;
VT_MPI_INT send_buffer_size;
VT_MPI_INT send_buffer_pos;
// get size needed for the send buffer
//
// locRecs.size()
CALL_MPI( MPI_Pack_size( 1, MPI_UNSIGNED, MPI_COMM_WORLD,
&send_buffer_size ) );
SLAVE
{
// locRecs (loc_defs/loc_spots)
//
if( type == GATHER_TYPE_DEFS )
{
for( uint32_t i = 0; i < loc_defs->size(); i++ )
send_buffer_size += (*loc_defs)[i]->getPackSize();
}
else // type == GATHER_TYPE_SPOTS
{
for( uint32_t i = 0; i < loc_spots->size(); i++ )
send_buffer_size += (*loc_spots)[i]->getPackSize();
}
}
// allocate memory for the send buffer
//
send_buffer = new char[send_buffer_size];
assert( send_buffer );
// pack send buffer
//
send_buffer_pos = 0;
// locRecs.size()
//
if( type == GATHER_TYPE_DEFS )
{
loc_recs_size = loc_defs->size();
}
else // type == GATHER_TYPE_SPOTS
{
loc_recs_size = loc_spots->size();
}
CALL_MPI( MPI_Pack( &loc_recs_size, 1, MPI_UNSIGNED, send_buffer,
send_buffer_size, &send_buffer_pos, MPI_COMM_WORLD ) );
SLAVE
{
// locRecs (loc_defs/loc_spots)
//
if( type == GATHER_TYPE_DEFS )
{
for( uint32_t i = 0; i < loc_defs->size(); i++ )
(*loc_defs)[i]->pack( send_buffer, send_buffer_size,
send_buffer_pos );
}
else // type == GATHER_TYPE_SPOTS
{
for( uint32_t i = 0; i < loc_spots->size(); i++ )
(*loc_spots)[i]->pack( send_buffer, send_buffer_size,
send_buffer_pos );
}
}
char * recv_buffer = 0;
VT_MPI_INT recv_buffer_size = 0;
VT_MPI_INT * recv_buffer_sizes = 0;
VT_MPI_INT * recv_buffer_displs = 0;
MASTER
{
// allocate memory for the receive buffer sizes
//
recv_buffer_sizes = new VT_MPI_INT[NumRanks];
assert( recv_buffer_sizes );
}
// gather buffer sizes
CALL_MPI( MPI_Gather( &send_buffer_size, 1, MPI_INT, recv_buffer_sizes, 1,
MPI_INT, 0, MPI_COMM_WORLD ) );
MASTER
{
// allocate memory for displacements
//
recv_buffer_displs = new VT_MPI_INT[NumRanks];
assert( recv_buffer_displs );
// compute displacements and receive buffer size
//
for( VT_MPI_INT i = 0; i < NumRanks; i++ )
{
recv_buffer_size += recv_buffer_sizes[i];
recv_buffer_displs[i] = 0;
if( i > 0 )
{
recv_buffer_displs[i] =
recv_buffer_displs[i-1] + recv_buffer_sizes[i-1];
}
}
// allocate memory for the receive buffer
//
recv_buffer = new char[recv_buffer_size];
assert( recv_buffer );
}
// gather packed local marker definitions
CALL_MPI( MPI_Gatherv( send_buffer, send_buffer_size, MPI_PACKED,
recv_buffer, recv_buffer_sizes, recv_buffer_displs,
MPI_PACKED, 0, MPI_COMM_WORLD ) );
// free memory of send buffer
delete [] send_buffer;
MASTER
{
// unpack receive buffer
//
for( VT_MPI_INT i = 1; i < NumRanks; i++ )
{
char * buffer = recv_buffer + recv_buffer_displs[i];
VT_MPI_INT buffer_size = recv_buffer_sizes[i];
VT_MPI_INT buffer_pos = 0;
// locDefs.size()
CALL_MPI( MPI_Unpack( buffer, buffer_size, &buffer_pos,
&loc_recs_size, 1, MPI_UNSIGNED,
MPI_COMM_WORLD ) );
// locDefs
//
for( uint32_t j = 0; j < loc_recs_size; j++ )
{
if( type == GATHER_TYPE_DEFS )
{
DefRec_DefMarkerS * new_def = new DefRec_DefMarkerS();
new_def->unpack( buffer, buffer_size, buffer_pos );
loc_defs->push_back( new_def );
}
else // type == GATHER_TYPE_SPOTS
{
MarkerSpotS * new_spot = new MarkerSpotS();
new_spot->unpack( buffer, buffer_size, buffer_pos );
loc_spots->push_back( new_spot );
}
}
}
// free some memory
delete [] recv_buffer;
delete [] recv_buffer_sizes;
delete [] recv_buffer_displs;
}
return !error;
}
#endif // VT_MPI
//////////////////// struct MarkersC::MarkerSpotS ////////////////////
#ifdef VT_MPI
VT_MPI_INT
MarkersC::MarkerSpotS::getPackSize()
{
VT_MPI_INT buffer_size = 0;
VT_MPI_INT size;
// proc + marker
CALL_MPI( MPI_Pack_size( 2, MPI_UNSIGNED, MPI_COMM_WORLD, &size ) );
buffer_size += size;
// time
CALL_MPI( MPI_Pack_size( 1, MPI_LONG_LONG_INT, MPI_COMM_WORLD, &size ) );
buffer_size += size;
// text.length()
uint32_t text_length = text.length();
CALL_MPI( MPI_Pack_size( 1, MPI_UNSIGNED, MPI_COMM_WORLD, &size ) );
buffer_size += size;
// text
CALL_MPI( MPI_Pack_size( text_length + 1, MPI_CHAR, MPI_COMM_WORLD,
&size ) );
buffer_size += size;
return buffer_size;
}
void
MarkersC::MarkerSpotS::pack( char *& buffer, const VT_MPI_INT & bufferSize,
VT_MPI_INT & bufferPos )
{
// proc
CALL_MPI( MPI_Pack( &proc, 1, MPI_UNSIGNED, buffer, bufferSize, &bufferPos,
MPI_COMM_WORLD ) );
// time
CALL_MPI( MPI_Pack( &time, 1, MPI_LONG_LONG_INT, buffer, bufferSize,
&bufferPos, MPI_COMM_WORLD ) );
// marker
CALL_MPI( MPI_Pack( &marker, 1, MPI_UNSIGNED, buffer, bufferSize,
&bufferPos, MPI_COMM_WORLD ) );
// text.length()
uint32_t text_length = text.length();
CALL_MPI( MPI_Pack( &text_length, 1, MPI_UNSIGNED, buffer, bufferSize,
&bufferPos, MPI_COMM_WORLD ) );
// text
char * c_text = new char[text_length+1];
strcpy( c_text, text.c_str() );
CALL_MPI( MPI_Pack( c_text, text_length + 1, MPI_CHAR, buffer,
bufferSize, &bufferPos, MPI_COMM_WORLD ) );
delete [] c_text;
}
void
MarkersC::MarkerSpotS::unpack( char *& buffer, const VT_MPI_INT & bufferSize,
VT_MPI_INT & bufferPos )
{
// proc
CALL_MPI( MPI_Unpack( buffer, bufferSize, &bufferPos, &proc, 1,
MPI_UNSIGNED, MPI_COMM_WORLD ) );
// time
CALL_MPI( MPI_Unpack( buffer, bufferSize, &bufferPos, &time, 1,
MPI_LONG_LONG_INT, MPI_COMM_WORLD ) );
// marker
CALL_MPI( MPI_Unpack( buffer, bufferSize, &bufferPos, &marker, 1,
MPI_UNSIGNED, MPI_COMM_WORLD ) );
// text.length()
uint32_t text_length;
CALL_MPI( MPI_Unpack( buffer, bufferSize, &bufferPos, &text_length, 1,
MPI_UNSIGNED, MPI_COMM_WORLD ) );
// text
char * c_text = new char[text_length+1];
CALL_MPI( MPI_Unpack( buffer, bufferSize, &bufferPos, c_text,
text_length + 1, MPI_CHAR, MPI_COMM_WORLD ) );
text = c_text;
delete [] c_text;
}
#endif // VT_MPI
| 26.563433 | 81 | 0.576298 | bringhurst |
bfe5d64bcf1ad3b32a9d06e5260bf4592f089e62 | 5,325 | cpp | C++ | src/coreclr/src/ToolBox/superpmi/superpmi-shared/hash.cpp | swaroop-sridhar/runtime | d0efddd932f6fb94c3e9436ab393fc390c7b2da9 | [
"MIT"
] | 28 | 2021-02-08T01:22:52.000Z | 2022-01-19T08:01:48.000Z | src/coreclr/src/ToolBox/superpmi/superpmi-shared/hash.cpp | swaroop-sridhar/runtime | d0efddd932f6fb94c3e9436ab393fc390c7b2da9 | [
"MIT"
] | 2 | 2020-06-06T09:07:48.000Z | 2020-06-06T09:13:07.000Z | src/coreclr/src/ToolBox/superpmi/superpmi-shared/hash.cpp | swaroop-sridhar/runtime | d0efddd932f6fb94c3e9436ab393fc390c7b2da9 | [
"MIT"
] | 4 | 2021-05-27T08:39:33.000Z | 2021-06-24T09:17:05.000Z | //
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
//----------------------------------------------------------
// hash.cpp - Class for hashing a text stream using MD5 hashing
//
// Note that on Windows, acquiring the Crypto hash provider is expensive, so
// only do that once and cache it.
//----------------------------------------------------------
#include "standardpch.h"
#include "runtimedetails.h"
#include "errorhandling.h"
#include "md5.h"
#include "hash.h"
Hash::Hash()
#ifndef TARGET_UNIX
: m_Initialized(false)
, m_hCryptProv(NULL)
#endif // !TARGET_UNIX
{
}
Hash::~Hash()
{
Destroy(); // Ignoring return code.
}
// static
bool Hash::Initialize()
{
#ifdef TARGET_UNIX
// No initialization necessary.
return true;
#else // !TARGET_UNIX
if (m_Initialized)
{
LogError("Hash class has already been initialized");
return false;
}
// Get handle to the crypto provider
if (!CryptAcquireContextA(&m_hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
goto OnError;
m_Initialized = true;
return true;
OnError:
LogError("Failed to create a hash using the Crypto API (Error 0x%X)", GetLastError());
if (m_hCryptProv != NULL)
CryptReleaseContext(m_hCryptProv, 0);
m_Initialized = false;
return false;
#endif // !TARGET_UNIX
}
// static
bool Hash::Destroy()
{
#ifdef TARGET_UNIX
// No destruction necessary.
return true;
#else // !TARGET_UNIX
// Should probably check Crypt() function return codes.
if (m_hCryptProv != NULL)
{
CryptReleaseContext(m_hCryptProv, 0);
m_hCryptProv = NULL;
}
m_Initialized = false;
return true;
#endif // !TARGET_UNIX
}
// Hash::WriteHashValueAsText - Take a binary hash value in the array of bytes pointed to by
// 'pHash' (size in bytes 'cbHash'), and write an ASCII hexadecimal representation of it in the buffer
// 'hashTextBuffer' (size in bytes 'hashTextBufferLen').
//
// Returns true on success, false on failure (only if the arguments are bad).
bool Hash::WriteHashValueAsText(const BYTE* pHash, size_t cbHash, char* hashTextBuffer, size_t hashTextBufferLen)
{
// This could be:
//
// for (DWORD i = 0; i < MD5_HASH_BYTE_SIZE; i++)
// {
// sprintf_s(hash + i * 2, hashLen - i * 2, "%02X", bHash[i]);
// }
//
// But this function is hot, and sprintf_s is too slow. This is a specialized function to speed it up.
if (hashTextBufferLen < 2 * cbHash + 1) // 2 characters for each byte, plus null terminator
{
LogError("WriteHashValueAsText doesn't have enough space to write the output");
return false;
}
static const char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
char* pCur = hashTextBuffer;
for (size_t i = 0; i < cbHash; i++)
{
unsigned digit = pHash[i];
unsigned lowNibble = digit & 0xF;
unsigned highNibble = digit >> 4;
*pCur++ = hexDigits[highNibble];
*pCur++ = hexDigits[lowNibble];
}
*pCur++ = '\0';
return true;
}
// Hash::HashBuffer - Compute an MD5 hash of the data pointed to by 'pBuffer', of 'bufLen' bytes,
// writing the hexadecimal ASCII text representation of the hash to the buffer pointed to by 'hash',
// of 'hashLen' bytes in size, which must be at least MD5_HASH_BUFFER_SIZE bytes.
//
// Returns the number of bytes written, or -1 on error.
int Hash::HashBuffer(BYTE* pBuffer, size_t bufLen, char* hash, size_t hashLen)
{
#ifdef TARGET_UNIX
MD5HASHDATA md5_hashdata;
MD5 md5_hasher;
if (hashLen < MD5_HASH_BUFFER_SIZE)
return -1;
md5_hasher.Hash(pBuffer, (ULONG)bufLen, &md5_hashdata);
DWORD md5_hashdata_size = sizeof(md5_hashdata.rgb) / sizeof(BYTE);
Assert(md5_hashdata_size == MD5_HASH_BYTE_SIZE);
if (!WriteHashValueAsText(md5_hashdata.rgb, md5_hashdata_size, hash, hashLen))
return -1;
return MD5_HASH_BUFFER_SIZE; // if we had success we wrote MD5_HASH_BUFFER_SIZE bytes to the buffer
#else // !TARGET_UNIX
if (!m_Initialized)
{
LogError("Hash class not initialized");
return -1;
}
HCRYPTHASH hCryptHash;
BYTE bHash[MD5_HASH_BYTE_SIZE];
DWORD cbHash = MD5_HASH_BYTE_SIZE;
if (hashLen < MD5_HASH_BUFFER_SIZE)
return -1;
if (!CryptCreateHash(m_hCryptProv, CALG_MD5, 0, 0, &hCryptHash))
goto OnError;
if (!CryptHashData(hCryptHash, pBuffer, (DWORD)bufLen, 0))
goto OnError;
if (!CryptGetHashParam(hCryptHash, HP_HASHVAL, bHash, &cbHash, 0))
goto OnError;
if (cbHash != MD5_HASH_BYTE_SIZE)
goto OnError;
if (!WriteHashValueAsText(bHash, cbHash, hash, hashLen))
return -1;
// Clean up.
CryptDestroyHash(hCryptHash);
hCryptHash = NULL;
return MD5_HASH_BUFFER_SIZE; // if we had success we wrote MD5_HASH_BUFFER_SIZE bytes to the buffer
OnError:
LogError("Failed to create a hash using the Crypto API (Error 0x%X)", GetLastError());
if (hCryptHash != NULL)
{
CryptDestroyHash(hCryptHash);
hCryptHash = NULL;
}
return -1;
#endif // !TARGET_UNIX
}
| 26.625 | 119 | 0.640376 | swaroop-sridhar |
bfe83a3d96efd98022609b07edab58555d56eb30 | 1,470 | cpp | C++ | cpp/extras/benchmarks/hash.cpp | tenzir/libfilter | d0d23243f841cc625588afc16f2cacdfeb1cae56 | [
"Apache-2.0"
] | 22 | 2020-08-04T15:13:52.000Z | 2022-02-08T18:51:09.000Z | cpp/extras/benchmarks/hash.cpp | tenzir/libfilter | d0d23243f841cc625588afc16f2cacdfeb1cae56 | [
"Apache-2.0"
] | 3 | 2021-10-09T00:38:05.000Z | 2022-01-24T02:27:16.000Z | cpp/extras/benchmarks/hash.cpp | tenzir/libfilter | d0d23243f841cc625588afc16f2cacdfeb1cae56 | [
"Apache-2.0"
] | 2 | 2021-03-31T04:34:54.000Z | 2021-06-22T19:30:34.000Z | // Benchmarks number of hash collisions when hashing a full filter
#include <limits.h> // for CHAR_BIT
#include <cstdint> // for uint64_t
#include <iostream> // for operator<<, endl, basic_ostream, basi...
#include <unordered_set>
using namespace std;
#include "filter/block.hpp" // for BlockFilter, ScalarBlockFilter, Scala...
#include "util.hpp" // for Rand
using namespace filter;
template<typename Filter>
uint64_t experimental_hash_collisions(double ndv, double bytes) {
Filter f = Filter::CreateWithBytes(bytes);
Rand r;
uint64_t result = 0;
unordered_set<uint32_t> hashes;
vector<uint64_t> entropy(libfilter_hash_tabulate_entropy_bytes / sizeof(uint64_t));
for (unsigned i = 0; i < entropy.size(); ++i) {
entropy[i] = r();
}
hashes.insert(f.SaltedHash(entropy.data()));
while (ndv --> 0) {
const auto it = r();
auto hashed = f.SaltedHash(entropy.data());
// cout << hashed << endl;
result += !hashes.insert(hashed).second;
f.InsertHash(it);
if (0 == (hashes.size() & (hashes.size() - 1))) {
Filter g = f;
if (g.SaltedHash(entropy.data()) != f.SaltedHash(entropy.data())) exit(1);
}
}
return result;
}
int main() {
const double ndv = 1e4;
const double m_over_n = 8 / log(2);
const double bytes = m_over_n * ndv / CHAR_BIT;
cout << BlockFilter::Name() << "\t\t"
<< experimental_hash_collisions<BlockFilter>(ndv, bytes) / ndv << endl;
}
| 28.823529 | 85 | 0.644898 | tenzir |
bfe8b1290d38879883f56ee573a3b7f9fb042472 | 555 | hpp | C++ | RaiderEngine/timing.hpp | rystills/RaiderEngine | 5a5bce4b3eca2f2f8c166e3a6296b07309af0d8a | [
"MIT"
] | 4 | 2019-07-20T08:41:04.000Z | 2022-03-04T01:53:38.000Z | RaiderEngine/timing.hpp | rystills/RaiderEngine | 5a5bce4b3eca2f2f8c166e3a6296b07309af0d8a | [
"MIT"
] | null | null | null | RaiderEngine/timing.hpp | rystills/RaiderEngine | 5a5bce4b3eca2f2f8c166e3a6296b07309af0d8a | [
"MIT"
] | null | null | null | #pragma once
#include "stdafx.h"
// this file is responsible for maintaining timing information within the main game loop
inline double totalTime = 0.0;
inline float deltaTime = 0.0f;
inline double lastFrame = 0.0;
inline int framesThisSecond = 0;
inline double frameRenderTime = 0, avgRenderTime = 0, secondAvgRenderTime = 0;
inline double frameUpdateTime = 0, avgUpdateTime = 0, secondAvgUpdateTime = 0;
inline int fps = 0;
inline int lastTime = 0;
/*
update deltaTime based on the amount of time elapsed since the previous frame
*/
void updateTime(); | 32.647059 | 88 | 0.767568 | rystills |
bfe9a939b966c7677c5019f394277245eb2da825 | 2,261 | cc | C++ | paddle/fluid/distributed/fleet_executor/task_loop.cc | zmxdream/Paddle | 04f042a5d507ad98f7f2cfc3cbc44b06d7a7f45c | [
"Apache-2.0"
] | 11 | 2016-08-29T07:43:26.000Z | 2016-08-29T07:51:24.000Z | paddle/fluid/distributed/fleet_executor/task_loop.cc | zmxdream/Paddle | 04f042a5d507ad98f7f2cfc3cbc44b06d7a7f45c | [
"Apache-2.0"
] | 1 | 2022-01-28T07:23:22.000Z | 2022-01-28T07:23:22.000Z | paddle/fluid/distributed/fleet_executor/task_loop.cc | zmxdream/Paddle | 04f042a5d507ad98f7f2cfc3cbc44b06d7a7f45c | [
"Apache-2.0"
] | 1 | 2021-12-09T08:59:17.000Z | 2021-12-09T08:59:17.000Z | // Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "paddle/fluid/distributed/fleet_executor/task_loop.h"
#include "paddle/fluid/platform/enforce.h"
#include "paddle/fluid/platform/errors.h"
namespace paddle {
namespace distributed {
thread_local TaskLoop* TaskLoop::thread_local_loop_ = nullptr;
TaskLoop* TaskLoop::GetTaskLoopOfCurrentThread() { return thread_local_loop_; }
TaskLoop::TaskLoop()
: looping_(false), quit_(false), thread_id_(std::this_thread::get_id()) {
PADDLE_ENFORCE_EQ(
thread_local_loop_, nullptr,
platform::errors::AlreadyExists("Another TaskLoop is already init."));
thread_local_loop_ = this;
}
TaskLoop::~TaskLoop() { thread_local_loop_ = nullptr; }
void TaskLoop::Loop() {
PADDLE_ENFORCE_EQ(looping_, false,
platform::errors::PreconditionNotMet(
"Loop can only execute in one loop thread"));
AssertInLoopThread();
looping_ = true;
quit_ = false;
while (!quit_) {
auto tasks = tasks_.PopAll();
for (auto& task : tasks) {
task();
}
}
looping_ = false;
}
void TaskLoop::Quit() {
quit_ = true;
if (!IsInLoopThread()) WakeUp();
}
void TaskLoop::RunInLoop(Functor cb) {
if (IsInLoopThread()) {
cb();
} else {
QueueInLoop(cb);
}
}
void TaskLoop::QueueInLoop(Functor cb) { tasks_.Push(cb); }
void TaskLoop::WakeUp() {
Functor task([] {});
QueueInLoop(task);
}
void TaskLoop::AbortNotInLoopThread() {
PADDLE_THROW(platform::errors::PreconditionNotMet(
"This TaskLoop was created in thread %d, but current thread is %d",
thread_id_, std::this_thread::get_id()));
}
} // namespace distributed
} // namespace paddle
| 27.240964 | 79 | 0.696594 | zmxdream |
bfed30eb3fcd79467864bbd129d8632444fe54bc | 906 | cpp | C++ | 1_gestion_proyectos/src/central.cpp | antcc/practicas-mp | 20496b899bdb2af87aa3fbef2f972d3bd1989c1c | [
"MIT"
] | 2 | 2017-03-19T22:33:44.000Z | 2018-01-30T20:25:12.000Z | 1_gestion_proyectos/src/central.cpp | antcc/practicas-mp | 20496b899bdb2af87aa3fbef2f972d3bd1989c1c | [
"MIT"
] | 6 | 2016-03-15T14:46:39.000Z | 2016-04-13T17:50:17.000Z | 1_gestion_proyectos/src/central.cpp | antcc/practicas-mp | 20496b899bdb2af87aa3fbef2f972d3bd1989c1c | [
"MIT"
] | 3 | 2016-03-11T15:54:31.000Z | 2019-11-06T01:56:30.000Z | /**
* @file central.cpp
* @brief Calcula círculo con centro en medio de dos círculos y radio la mitad de la distancia
* @author Agarrido
*
* Un ejemplo de ejecución es:
* Introduzca un circulo en formato radio-(x,y): 3-(0,0)
* Introduzca otro circulo: 4-(5,0)
* El círculo que pasa por los dos centros es: 2.5-(2.5,0)
*/
#include <iostream>
#include "circle.h"
using namespace std;
int main()
{
Circle c1,c2;
do
{
cout << "Introduzca un circulo en formato radio-(x,y): ";
c1 = ReadCircle();
cout << "Introduzca otro circulo: ";
c2 = ReadCircle();
} while ( Distance( GetCenter( c1 ), GetCenter( c2 ) ) == 0 );
Circle res;
InitCircle( res, MiddlePoint( GetCenter( c1 ), GetCenter( c2 ) ),
Distance( GetCenter( c1 ), GetCenter( c2 ) ) / 2 );
cout << "El círculo que pasa por los dos centros es: ";
WriteCircle( res );
cout << endl;
}
| 24.486486 | 95 | 0.618102 | antcc |
bfed9448d265f2b453f58869b659b3270cc6b1c1 | 44 | cpp | C++ | SRC/GekkoCore/JitcX86/JitcInteger.cpp | ogamespec/dolwin | 7aaa864f9070ec14193f39f2e387087ccd5d0a93 | [
"CC0-1.0"
] | 107 | 2015-09-07T21:28:32.000Z | 2022-02-14T03:13:01.000Z | SRC/GekkoCore/JitcX86/JitcInteger.cpp | emu-russia/dolwin | 7aaa864f9070ec14193f39f2e387087ccd5d0a93 | [
"CC0-1.0"
] | 116 | 2020-03-11T16:42:02.000Z | 2021-05-27T17:05:40.000Z | SRC/GekkoCore/JitcX86/JitcInteger.cpp | ogamespec/dolwin | 7aaa864f9070ec14193f39f2e387087ccd5d0a93 | [
"CC0-1.0"
] | 8 | 2017-05-18T21:01:19.000Z | 2021-04-30T11:28:14.000Z | // Integer Instructions
#include "../pch.h"
| 14.666667 | 23 | 0.681818 | ogamespec |
bfef2e950f0dd234a9e947041efd41525a4daa62 | 1,945 | cpp | C++ | trainingregional2018/training1/H.cpp | Victoralin10/ACMSolutions | 6d6e50da87b2bc455e953629737215b74b10269c | [
"MIT"
] | null | null | null | trainingregional2018/training1/H.cpp | Victoralin10/ACMSolutions | 6d6e50da87b2bc455e953629737215b74b10269c | [
"MIT"
] | null | null | null | trainingregional2018/training1/H.cpp | Victoralin10/ACMSolutions | 6d6e50da87b2bc455e953629737215b74b10269c | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define REP(i, n) for(int i = 0; i < n; i++)
#define FOR(i, a, b) for (int i = a; i < b; i++)
#define CLR(t, value) memset(t, value, sizeof(t))
#define ALL(v) v.begin(), v.end()
#define SZ(v) ((int)(v).size())
#define TEST(x) cerr << "test " << #x << " " << x << endl;
#define sc(x) scanf("%d", &x)
using namespace std;
typedef long long Long;
typedef vector<int> vInt;
typedef pair<int,int> Pair;
const int N = 1e5 + 2;
const int INF = 1e9 + 7;
const int MOD = 1e9 + 7;
const double EPS = 1e-8;
void fast_io() {
ios_base::sync_with_stdio(0);
cin.tie(NULL);
cout.tie(NULL);
}
/************************************/
void smod(int &a, int v) {
a += v;
if (a>= MOD) a -= MOD;
}
vector<Pair> G[N];
int A[N], C[N], S[N], SS[N];
void pre(int node, int parent, int w) {
C[node] = 1;
for (auto &p: G[node]) {
if (p.first == parent) continue;
pre(p.first, node, p.second);
C[node] += C[p.first];
}
S[node] = ((Long)w*C[node])%MOD;
SS[node] = S[node];
for (auto &p: G[node]) {
if (p.first == parent) continue;
smod(SS[node], SS[p.first]);
}
}
void solve(int node, int parent) {
A[node] = 0;
for (auto &p: G[node]) {
if (p.first == parent) continue;
solve(p.first, node);
smod(A[node], A[p.first]);
smod(A[node], ((Long)SS[p.first]*(C[node] - C[p.first])) % MOD);
}
}
int main() {
fast_io();
int t, n=0, u, v, w;
cin>>t;
REP(caso, t) {
REP(i,n+1) G[i].clear();
cin>>n;
FOR(i,1,n) {
cin>>u>>v>>w;
G[u].push_back({v, w});
G[v].push_back({u, w});
}
pre(1, -1, 0);
solve(1, -1);
int ans=0;
REP(i,n) {
smod(ans, A[i+1]);
//cerr<<A[i+1]<<" ";
}
//cerr<<endl;
cout << "Case "<<caso+1<<": "<<ans<<endl;
}
return 0 ;
}
| 20.913978 | 72 | 0.462725 | Victoralin10 |
bffc22fa97a3105c5c606529d88d6839cbb1532b | 9,339 | cpp | C++ | src/EquationSet.cpp | gjo11/causaloptim | 81155ff1aeef5cd2618f2498ba6b779d5a944cff | [
"MIT"
] | 13 | 2019-11-28T16:33:10.000Z | 2021-12-10T12:03:35.000Z | src/EquationSet.cpp | gjo11/causaloptim | 81155ff1aeef5cd2618f2498ba6b779d5a944cff | [
"MIT"
] | 8 | 2020-05-04T14:32:49.000Z | 2021-12-09T13:10:07.000Z | src/EquationSet.cpp | gjo11/causaloptim | 81155ff1aeef5cd2618f2498ba6b779d5a944cff | [
"MIT"
] | 3 | 2020-04-22T23:18:06.000Z | 2020-12-10T09:32:05.000Z | //#include <afx.h>
#include <windows.h>
#include <stdio.h>
#include <math.h>
#include "CustomFormat.h"
#include "SymbolSet.h"
#include "Equation.h"
#include "EquationSet.h"
#define VAR_NOT_ELIMINATED ((WORD) 0xFFFF)
#define VAR_ELIMINATED ((WORD) 0xFFFE)
CEquationSet_ :: CEquationSet_
(
CSymbolSet_ * p_pVariables,
CSymbolSet_ * p_pParameters,
WORD p_EqnCount
)
{
WORD nEqn;
m_Count = p_EqnCount;
m_pVariables = p_pVariables;
m_pParameters = p_pParameters;
m_pEquations = new CEquation_ [m_Count];
for (nEqn = 0; nEqn < m_Count; nEqn++)
m_pEquations [nEqn]. Initialize (m_pVariables, m_pParameters);
} /* CEquationSet_ :: CEquationSet_ () */
CEquationSet_ :: ~CEquationSet_ ()
{
if (m_pEquations)
{
delete [] m_pEquations;
m_pEquations = NULL;
}
} /* CEquationSet_ :: ~CEquationSet_ () */
CEquationSet_ * CEquationSet_ :: Duplicate ()
{
CEquationSet_ * pEquationSet;
WORD nEqn;
pEquationSet = new CEquationSet_ (m_pVariables,
m_pParameters,
m_Count);
for (nEqn = 0; nEqn < m_Count; nEqn++)
pEquationSet-> m_pEquations [nEqn]. Copy (& m_pEquations [nEqn]);
return pEquationSet;
} /* CEquationSet_ :: Duplicate () */
#ifdef JUNK
CSymbolSet_ * CEquationSet_ :: EliminateVariables ()
{
WORD nEqn;
// Index of the current equation set.
WORD EqualityCnt;
// Number of equations of type equality;
WORD nEquality;
// Index into the equality equation set.
WORD nInequality;
// Index into the inequality equation set.
WORD nRemainingVar;
// Index into the remaining-variable symbol set.
WORD nVar;
// Index into the variable symbol set.
WORD Rank;
// Rank of the set of equalities.
WORD * pElimVarToEquality;
// Array that maps eliminated variables to the
// equality used to substitute out that
// variable. Allocated.
// A value of VAR_NOT_ELIMINATED if a variable
// is not to be eliminated.
CSymbolSet_ * pRemainingVariables;
// Set of all variables not eliminated.
// Allocated.
CEquationSet_ * pEqualitySet;
// Equation set consisting of only equalities.
// Allocated.
CEquationSet_ * pInequalitySet;
// Final equation set that contains only
// inequalities. Allocated.
CEquation_ * pWorkEqn;
// Copy of original equation for performing
// linear operations. Allocated.
CEquation_ * pEquality;
// Reference to equation within the equality set.
CEquation_ * pInequality;
// Reference to equation within the inequality set.
CEquation_ * pEquation;
// Reference to equation within the original equation set.
/****************************************************
* Create a set of equations consisting only of those
* equations in the current set that are equalities.
***************************************************/
/*
* Determine how many equalities exist.
*/
EqualityCnt = 0;
for (nEqn = 0; nEqn < m_Count; nEqn++)
{
pEquation = & m_pEquations [nEqn];
if (pEquation-> m_RelationToZero == RTZ_Equal)
EqualityCnt++;
}
/*
* Create a new equation set consisting of the equality
* equations.
*/
pEqualitySet = new CEquationSet_ (m_pVariables,
m_pParameters,
EqualityCnt);
nEquality = 0;
for (nEqn = 0; nEqn < m_Count; nEqn++)
{
pEquation = & m_pEquations [nEqn];
if (pEquation-> m_RelationToZero == RTZ_Equal)
{
pEquality = & pEqualitySet-> m_pEquations [nEquality];
pEquality-> Copy (pEquation);
nEquality++;
}
}
if (! pEqualitySet-> GaussianElimination ())
return NULL;
/*
* Set up the relationship between variables to be eliminated
* and the equality used to substitute out those variables.
*/
pElimVarToEquality = new WORD [m_pVariables-> Count ()];
for (nVar = 0; nVar < m_pVariables-> Count (); nVar++)
pElimVarToEquality [nVar] = VAR_NOT_ELIMINATED;
nEquality = 0;
for (nVar = 0; nVar < m_pVariables-> Count (); nVar++)
{
if (nEquality >= pEqualitySet-> m_Count)
break;
pEquality = & pEqualitySet-> m_pEquations [nEquality];
if (Approx(pEquality-> m_pVarCoefs [nVar],
1.0, LEEWAY))
{
pElimVarToEquality [nVar] = nEquality;
nEquality++;
}
}
Rank = nEquality;
/*****************************************************************
* Build a new symbol set for all variables that were not
* eliminated.
****************************************************************/
pRemainingVariables = new CSymbolSet_ (
m_pVariables-> Count () - Rank);
nRemainingVar = 0;
for (nVar = 0; nVar < m_pVariables-> Count (); nVar++)
{
if (pElimVarToEquality [nVar] == VAR_NOT_ELIMINATED)
{
pRemainingVariables-> Assign (nRemainingVar,
m_pVariables-> GetName (nVar));
nRemainingVar++;
}
}
/*****************************************************************
* Build a new equation set by (1) eliminating all equalities from
* the original set, and (2) substituting out all eliminated
* variables (Because all variables are implicitly >= 0, add new
* inequalities for each removed variable corresponding to this
* constraint).
****************************************************************/
pInequalitySet = new CEquationSet_ (pRemainingVariables,
m_pParameters,
m_Count - EqualityCnt + Rank);
/*
* Copy the old inequalities, substituting out the eliminated variables.
*/
pWorkEqn = new CEquation_ (m_pVariables, m_pParameters);
nInequality = 0;
for (nEqn = 0; nEqn < m_Count; nEqn++)
{
pEquation = & m_pEquations [nEqn];
if (pEquation-> m_RelationToZero != RTZ_Equal)
{
pWorkEqn-> Copy (pEquation);
for (nVar = 0; nVar < m_pVariables-> Count (); nVar++)
{
if (pElimVarToEquality [nVar] != VAR_NOT_ELIMINATED)
{
nEquality = pElimVarToEquality [nVar];
pEquality = & pEqualitySet-> m_pEquations [nEquality];
pWorkEqn-> FactorAdd (pEquality,
- pWorkEqn-> m_pVarCoefs [nVar]);
}
}
/*
* Copy the reduced equation into the inequality set.
*/
pInequality = & pInequalitySet-> m_pEquations [nInequality];
if (pInequality-> Projection (pWorkEqn) == ProjectDataLoss)
Rprintf ("ERROR: non-zero coefficient for an eliminated variable.\n");
nInequality++;
}
}
/*
* Create inequalities corresponding to the implicit constraint that all
* eliminated variables must have been greater than or equal to zero.
*/
for (nVar = 0; nVar < m_pVariables-> Count (); nVar++)
{
nEquality = pElimVarToEquality [nVar];
if (nEquality != VAR_NOT_ELIMINATED)
{
pEquality = & pEqualitySet-> m_pEquations [nEquality];
pInequality = & pInequalitySet-> m_pEquations [nInequality];
/*
* Projection will drop the coefficient of the eliminated variable.
* Since that variable was >= 0, the rest of the equality must be
* <= 0;
*/
pInequality-> Projection (pEquality);
pInequality-> m_RelationToZero = RTZ_EqualOrLess;
nInequality++;
}
}
if (pWorkEqn)
{
delete pWorkEqn;
pWorkEqn = NULL;
}
if (pEqualitySet)
{
delete pEqualitySet;
pEqualitySet = NULL;
}
if (pElimVarToEquality)
{
delete [] pElimVarToEquality;
pElimVarToEquality = NULL;
}
/*
* The original array of equations for this set will be replaced
* by the generated set of inequalities.
*/
if (m_pEquations)
{
delete m_pEquations;
m_pEquations = NULL;
}
m_pEquations = pInequalitySet-> m_pEquations;
pInequalitySet-> m_pEquations = NULL;
if (pInequalitySet)
{
delete pInequalitySet;
pInequalitySet = NULL;
}
return pRemainingVariables;
} /* CEquationSet_ :: EliminateVariables () */
BOOL CEquationSet_ :: GaussianElimination ()
{
int nRow;
int nEqn;
int nVar;
int MaxRow;
double MaxAbs;
double FTemp;
/****************************************************
* All equations must be equalities.
***************************************************/
for (nEqn = 0; nEqn < m_Count; nEqn++)
if (m_pEquations [nEqn]. m_RelationToZero != RTZ_Equal)
return FALSE;
/****************************************************
* Diagonalize over all columns representing the
* variable symbol coefficients.
***************************************************/
nVar = 0;
for (nEqn = 0; nEqn < m_Count; nEqn++)
{
if (Approx (m_pEquations [nEqn]. m_pVarCoefs [nVar],
0.0, LEEWAY))
{
/*******************************************
* Make sure the pivot element is not zero.
******************************************/
MaxRow = -1;
while (MaxRow < 0)
{
MaxAbs = 0.0;
for (nRow = nEqn; nRow < m_Count; nRow++)
{
FTemp = m_pEquations [nRow]. m_pVarCoefs [nVar];
FTemp = fabs (FTemp);
if (FTemp > MaxAbs)
{
MaxRow = nRow;
MaxAbs = FTemp;
}
}
if (MaxRow < 0)
{
nVar++;
if (nVar >= m_pVariables-> Count ())
return TRUE;
continue;
}
}
m_pEquations [nEqn]. FactorAdd (& m_pEquations [MaxRow], 1.0);
}
m_pEquations [nEqn]. Divide (m_pEquations [nEqn]. m_pVarCoefs [nVar]);
for (nRow = 0; nRow < m_Count; nRow++)
{
if (nRow != nEqn)
m_pEquations [nRow]. FactorAdd (
& m_pEquations [nEqn],
- m_pEquations [nRow]. m_pVarCoefs [nVar]);
}
nVar++;
}
return TRUE;
} /* CEquationSet_ :: GaussianElimination () */
#endif // JUNK
| 24.641161 | 74 | 0.613663 | gjo11 |
bffc7f61b0d4c6bd983d572494bcd2ca97dec9eb | 2,489 | inl | C++ | archive/game/advanced_math.inl | brettonw/Two | 5cd121c94388f4465157c770bde7ec369f1f5f97 | [
"MIT"
] | null | null | null | archive/game/advanced_math.inl | brettonw/Two | 5cd121c94388f4465157c770bde7ec369f1f5f97 | [
"MIT"
] | null | null | null | archive/game/advanced_math.inl | brettonw/Two | 5cd121c94388f4465157c770bde7ec369f1f5f97 | [
"MIT"
] | null | null | null | //-----------------------------------------------------------------------------
// Copyright (C) 1997-2006 Bretton Wade
// All Rights Reserved
//-----------------------------------------------------------------------------
#ifndef _ADVANCED_MATH_INL_
#define _ADVANCED_MATH_INL_
//-----------------------------------------------------------------------------
// include files
//-----------------------------------------------------------------------------
#ifndef _ADVANCED_MATH_H_
#include "advanced_math.h"
#endif // _ADVANCED_MATH_H_
//-----------------------------------------------------------------------------
// useful vector operator definitions
//-----------------------------------------------------------------------------
inline
float
operator dot (const D3DXVECTOR2& lhs, const D3DXVECTOR2& rhs)
{
return D3DXVec2Dot (&lhs, &rhs);
}
//-----------------------------------------------------------------------------
inline
float
operator cross (const D3DXVECTOR2& lhs, const D3DXVECTOR2& rhs)
{
return (lhs.x * rhs.y) - (lhs.y * rhs.x);
}
//-----------------------------------------------------------------------------
// generally useful routines
//-----------------------------------------------------------------------------
inline
float
Sign (float fValue)
{
return (fValue > 0.0f) ? 1.0f : ((fValue < 0.0f) ? -1.0f : 0.0f);
}
//-----------------------------------------------------------------------------
// fuzzy comparisons for floats
//-----------------------------------------------------------------------------
inline
bool
CloseMatch (float a, float b)
{
#if 1
float delta = fabsf (a - b);
bool result = delta <= g_fEpsilon;
return result;
#else
float fa = fabsf (a);
float fb = fabsf (b);
float delta = (fa > fb) ? (fa / fb) - 1.0f : (fb / fa) - 1.0f;
bool result = delta < 1.0e-2f;
return result;
#endif
}
//-----------------------------------------------------------------------------
inline
bool
CloseMatch (const D3DXVECTOR2& A, const D3DXVECTOR2& B)
{
return CloseMatch (A.x, B.x) and CloseMatch (A.y, B.y);
}
//-----------------------------------------------------------------------------
inline
bool
CloseMatch (const D3DXVECTOR3& A, const D3DXVECTOR3& B)
{
return CloseMatch (A.x, B.x) and CloseMatch (A.y, B.y) and CloseMatch (A.z, B.z);
}
//-----------------------------------------------------------------------------
#endif // _ADVANCED_MATH_INL_
| 29.987952 | 85 | 0.355966 | brettonw |
bffe4a9cb95f40aaf3031addca697e5da918be28 | 3,213 | cpp | C++ | semana1/E.cpp | AllanNozomu/MC521 | 92e44eaee36b6adf4c4655e3b32d3ca2948ee03a | [
"MIT"
] | null | null | null | semana1/E.cpp | AllanNozomu/MC521 | 92e44eaee36b6adf4c4655e3b32d3ca2948ee03a | [
"MIT"
] | null | null | null | semana1/E.cpp | AllanNozomu/MC521 | 92e44eaee36b6adf4c4655e3b32d3ca2948ee03a | [
"MIT"
] | null | null | null | bool debug = false;
#include<vector>
#include<stack>
#include<queue>
#include<deque>
#include<bitset>
#include<set>
#include<string>
#include<iostream>
#include<algorithm>
#include<map>
#include<unordered_map>
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
#include<math.h>
#include<time.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll, ll> pll;
typedef vector<int> vi;
typedef vector<pii> vii;
typedef vector<ll> vl;
typedef vector<vector<int>> vvi;
typedef unordered_map<int, int> umap_ii;
typedef unordered_map<int, pii> umap_ipii;
typedef unordered_map<int, string> umap_is;
#define mkp(a,b) make_pair(a,b)
#define spc " "
#define all(container) container.begin(), container.end()
void print_pair(const pii & par){
cout << "(" << par.first << spc << par.second << ")" << spc;
}
template <typename C>
void print_array(const C &data, int n){
if (!debug) return;
cout << "[DEBUG] " << endl;
for (int i = 0; i < n; ++i){
cout << data[i] << spc;
}
cout << endl;
}
template <typename C>
void print_container(const C &data){
if (!debug) return;
cout << "[DEBUG] " << endl;
for (const auto &v : data){
cout << v << spc;
}
cout << endl;
}
template <typename C>
void print_pairs(const C &data){
if (!debug) return;
cout << "[DEBUG] " << endl;
for (const auto &v : data){
print_pair(v);
}
cout << endl;
}
template <typename C>
void print_matrix(const C &data){
if (!debug) return;
cout << "[DEBUG] " << endl;
for (const auto &row : data){
for (const auto &v : row){
cout << v << spc;
} cout << endl;
}
cout << endl;
}
#define MAX 100000
#define LOGMAX 18
int query(const int matrix[MAX][LOGMAX], const ll data[MAX], int qs, int qe){
int k = (int)log2(qe - qs + 1);
if (data[matrix[qs][k]] < data[matrix[qe - (1 << k) + 1][k]])
return matrix[qs][k];
return matrix[qe - (1 << k) + 1][k];
}
void pre_process(int matrix[MAX][LOGMAX], const ll data[MAX], int n){
for (int i = 0 ; i < n; ++i){
matrix[i][0] = i;
}
for (int j = 1; (1 << j) <= n; ++j){
for (int i = 0; i + (1 << j) - 1 < n; ++i){
if (data[matrix[i][j-1]] < data[matrix[i + (1 << j - 1)][j-1]]){
matrix[i][j] = matrix[i][j-1];
} else {
matrix[i][j] = matrix[i + (1 << j - 1)][j-1];
}
}
}
}
ll process(int matrix[MAX][LOGMAX], const ll data[MAX], int qs, int qe){
if (qs > qe){
return 0;
}
if (qs == qe){
return data[qs];
}
int mid = query(matrix, data, qs, qe);
ll now = data[mid] * (qe - qs + 1);
ll esq = process(matrix, data, qs, mid - 1);
ll dir = process(matrix, data, mid + 1, qe);
return max({now, dir, esq});
}
int main()
{
std::ios::sync_with_stdio(false);
cin.tie(NULL);
ll data[MAX];
int matrix[MAX][LOGMAX];
int n;
cin >> n;
while(n > 0){
for (int i = 0 ; i < n; ++i){
cin >> data[i];
}
pre_process(matrix, data, n);
cout << process(matrix, data, 0, n - 1) << endl;
cin >> n;
}
} | 22.3125 | 77 | 0.540305 | AllanNozomu |
8700a75d7725b91ba46ff1f6be19a7e88575bff5 | 704 | cpp | C++ | Code/Engine/Renderer/IndexBuffer.cpp | yixuan-wei/PersonalEngine | 6f3b1df3ddeb662fbf65ca8b3ea7ddb446ef5a20 | [
"MIT"
] | 1 | 2021-06-11T06:41:29.000Z | 2021-06-11T06:41:29.000Z | Code/Engine/Renderer/IndexBuffer.cpp | yixuan-wei/PersonalEngine | 6f3b1df3ddeb662fbf65ca8b3ea7ddb446ef5a20 | [
"MIT"
] | 1 | 2022-02-25T07:46:54.000Z | 2022-02-25T07:46:54.000Z | Code/Engine/Renderer/IndexBuffer.cpp | yixuan-wei/PersonalEngine | 6f3b1df3ddeb662fbf65ca8b3ea7ddb446ef5a20 | [
"MIT"
] | null | null | null | #include "Engine/Renderer/IndexBuffer.hpp"
//////////////////////////////////////////////////////////////////////////
IndexBuffer::IndexBuffer(RenderContext* ctx, eRenderMemoryHint hint)
:RenderBuffer(ctx,INDEX_BUFFER_BIT,hint)
{
}
//////////////////////////////////////////////////////////////////////////
void IndexBuffer::Update(std::vector<unsigned int> const& indices)
{
Update((unsigned int)indices.size(), &indices[0]);
}
//////////////////////////////////////////////////////////////////////////
void IndexBuffer::Update(unsigned int iCount, unsigned int const* indices)
{
m_count = iCount;
RenderBuffer::Update(indices, iCount * sizeof(unsigned int), sizeof(unsigned int));
}
| 33.52381 | 87 | 0.507102 | yixuan-wei |
8705d72188746b0da700667aba31019b9e06b6b2 | 12,087 | cpp | C++ | Engine/Source/ThirdParty/IntelTBB/IntelTBB-4.0/src/tbb/governor.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | Engine/Source/ThirdParty/IntelTBB/IntelTBB-4.0/src/tbb/governor.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 2 | 2015-06-21T17:38:11.000Z | 2015-06-22T20:54:42.000Z | Engine/Source/ThirdParty/IntelTBB/IntelTBB-4.0/src/tbb/governor.cpp | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | /*
Copyright 2005-2012 Intel Corporation. All Rights Reserved.
The source code contained or described herein and all documents related
to the source code ("Material") are owned by Intel Corporation or its
suppliers or licensors. Title to the Material remains with Intel
Corporation or its suppliers and licensors. The Material is protected
by worldwide copyright laws and treaty provisions. No part of the
Material may be used, copied, reproduced, modified, published, uploaded,
posted, transmitted, distributed, or disclosed in any way without
Intel's prior express written permission.
No license under any patent, copyright, trade secret or other
intellectual property right is granted to or conferred upon you by
disclosure or delivery of the Materials, either expressly, by
implication, inducement, estoppel or otherwise. Any license under such
intellectual property rights must be express and approved by Intel in
writing.
*/
#include "governor.h"
#include "tbb_main.h"
#include "scheduler.h"
#include "market.h"
#include "arena.h"
#include "tbb/task_scheduler_init.h"
#include "dynamic_link.h"
namespace tbb {
namespace internal {
//------------------------------------------------------------------------
// governor
//------------------------------------------------------------------------
#if __TBB_SURVIVE_THREAD_SWITCH
// Support for interoperability with Intel(R) Cilk(tm) Plus.
#if _WIN32
#define CILKLIB_NAME "cilkrts20.dll"
#else
#define CILKLIB_NAME "libcilkrts.so"
#endif
//! Handler for interoperation with cilkrts library.
static __cilk_tbb_retcode (*watch_stack_handler)(struct __cilk_tbb_unwatch_thunk* u,
struct __cilk_tbb_stack_op_thunk o);
#if __TBB_WEAK_SYMBOLS
#pragma weak __cilkrts_watch_stack
#endif
//! Table describing how to link the handlers.
static const dynamic_link_descriptor CilkLinkTable[] = {
DLD(__cilkrts_watch_stack, watch_stack_handler)
};
static atomic<do_once_state> cilkrts_load_state;
bool initialize_cilk_interop() {
// Pinning can fail. This is a normal situation, and means that the current
// thread does not use cilkrts and consequently does not need interop.
return dynamic_link( CILKLIB_NAME, CilkLinkTable, 1 );
}
#endif /* __TBB_SURVIVE_THREAD_SWITCH */
namespace rml {
tbb_server* make_private_server( tbb_client& client );
}
void governor::acquire_resources () {
#if USE_PTHREAD
int status = theTLS.create(auto_terminate);
#else
int status = theTLS.create();
#endif
if( status )
handle_perror(status, "TBB failed to initialize task scheduler TLS\n");
}
void governor::release_resources () {
theRMLServerFactory.close();
#if TBB_USE_ASSERT
if( __TBB_InitOnce::initialization_done() && theTLS.get() )
runtime_warning( "TBB is unloaded while tbb::task_scheduler_init object is alive?" );
#endif
int status = theTLS.destroy();
if( status )
handle_perror(status, "TBB failed to destroy task scheduler TLS");
dynamic_unlink_all();
}
rml::tbb_server* governor::create_rml_server ( rml::tbb_client& client ) {
rml::tbb_server* server = NULL;
if( !UsePrivateRML ) {
::rml::factory::status_type status = theRMLServerFactory.make_server( server, client );
if( status != ::rml::factory::st_success ) {
UsePrivateRML = true;
runtime_warning( "rml::tbb_factory::make_server failed with status %x, falling back on private rml", status );
}
}
if ( !server ) {
__TBB_ASSERT( UsePrivateRML, NULL );
server = rml::make_private_server( client );
}
__TBB_ASSERT( server, "Failed to create RML server" );
return server;
}
void governor::sign_on(generic_scheduler* s) {
__TBB_ASSERT( !theTLS.get(), NULL );
theTLS.set(s);
#if __TBB_SURVIVE_THREAD_SWITCH
if( watch_stack_handler ) {
__cilk_tbb_stack_op_thunk o;
o.routine = &stack_op_handler;
o.data = s;
if( (*watch_stack_handler)(&s->my_cilk_unwatch_thunk, o) ) {
// Failed to register with cilkrts, make sure we are clean
s->my_cilk_unwatch_thunk.routine = NULL;
}
#if TBB_USE_ASSERT
else
s->my_cilk_state = generic_scheduler::cs_running;
#endif /* TBB_USE_ASSERT */
}
#endif /* __TBB_SURVIVE_THREAD_SWITCH */
}
void governor::sign_off(generic_scheduler* s) {
suppress_unused_warning(s);
__TBB_ASSERT( theTLS.get()==s, "attempt to unregister a wrong scheduler instance" );
theTLS.set(NULL);
#if __TBB_SURVIVE_THREAD_SWITCH
__cilk_tbb_unwatch_thunk &ut = s->my_cilk_unwatch_thunk;
if ( ut.routine )
(*ut.routine)(ut.data);
#endif /* __TBB_SURVIVE_THREAD_SWITCH */
}
generic_scheduler* governor::init_scheduler( unsigned num_threads, stack_size_type stack_size, bool auto_init ) {
if( !__TBB_InitOnce::initialization_done() )
DoOneTimeInitializations();
generic_scheduler* s = theTLS.get();
if( s ) {
s->my_ref_count += 1;
return s;
}
#if __TBB_SURVIVE_THREAD_SWITCH
atomic_do_once( &initialize_cilk_interop, cilkrts_load_state );
#endif /* __TBB_SURVIVE_THREAD_SWITCH */
if( (int)num_threads == task_scheduler_init::automatic )
num_threads = default_num_threads();
s = generic_scheduler::create_master(
market::create_arena( num_threads - 1, stack_size ? stack_size : ThreadStackSize ) );
__TBB_ASSERT(s, "Somehow a local scheduler creation for a master thread failed");
s->my_auto_initialized = auto_init;
return s;
}
void governor::terminate_scheduler( generic_scheduler* s ) {
__TBB_ASSERT( s == theTLS.get(), "Attempt to terminate non-local scheduler instance" );
if( !--(s->my_ref_count) )
s->cleanup_master();
}
void governor::auto_terminate(void* arg){
generic_scheduler* s = static_cast<generic_scheduler*>(arg);
if( s && s->my_auto_initialized ) {
if( !--(s->my_ref_count) ) {
// If the TLS slot is already cleared by OS or underlying concurrency
// runtime, restore its value.
if ( !theTLS.get() )
theTLS.set(s);
else __TBB_ASSERT( s == theTLS.get(), NULL );
s->cleanup_master();
__TBB_ASSERT( !theTLS.get(), "cleanup_master has not cleared its TLS slot" );
}
}
}
void governor::print_version_info () {
if ( UsePrivateRML )
PrintExtraVersionInfo( "RML", "private" );
else {
PrintExtraVersionInfo( "RML", "shared" );
theRMLServerFactory.call_with_server_info( PrintRMLVersionInfo, (void*)"" );
}
#if __TBB_SURVIVE_THREAD_SWITCH
if( watch_stack_handler )
PrintExtraVersionInfo( "CILK", CILKLIB_NAME );
#endif /* __TBB_SURVIVE_THREAD_SWITCH */
}
void governor::initialize_rml_factory () {
::rml::factory::status_type res = theRMLServerFactory.open();
UsePrivateRML = res != ::rml::factory::st_success;
}
#if __TBB_SURVIVE_THREAD_SWITCH
__cilk_tbb_retcode governor::stack_op_handler( __cilk_tbb_stack_op op, void* data ) {
__TBB_ASSERT(data,NULL);
generic_scheduler* s = static_cast<generic_scheduler*>(data);
#if TBB_USE_ASSERT
void* current = theTLS.get();
#if _WIN32||_WIN64
uintptr_t thread_id = GetCurrentThreadId();
#else
uintptr_t thread_id = uintptr_t(pthread_self());
#endif
#endif /* TBB_USE_ASSERT */
switch( op ) {
default:
__TBB_ASSERT( 0, "invalid op" );
case CILK_TBB_STACK_ADOPT: {
__TBB_ASSERT( !current && s->my_cilk_state==generic_scheduler::cs_limbo ||
current==s && s->my_cilk_state==generic_scheduler::cs_running, "invalid adoption" );
#if TBB_USE_ASSERT
if( current==s )
runtime_warning( "redundant adoption of %p by thread %p\n", s, (void*)thread_id );
s->my_cilk_state = generic_scheduler::cs_running;
#endif /* TBB_USE_ASSERT */
theTLS.set(s);
break;
}
case CILK_TBB_STACK_ORPHAN: {
__TBB_ASSERT( current==s && s->my_cilk_state==generic_scheduler::cs_running, "invalid orphaning" );
#if TBB_USE_ASSERT
s->my_cilk_state = generic_scheduler::cs_limbo;
#endif /* TBB_USE_ASSERT */
theTLS.set(NULL);
break;
}
case CILK_TBB_STACK_RELEASE: {
__TBB_ASSERT( !current && s->my_cilk_state==generic_scheduler::cs_limbo ||
current==s && s->my_cilk_state==generic_scheduler::cs_running, "invalid release" );
#if TBB_USE_ASSERT
s->my_cilk_state = generic_scheduler::cs_freed;
#endif /* TBB_USE_ASSERT */
s->my_cilk_unwatch_thunk.routine = NULL;
auto_terminate( s );
}
}
return 0;
}
#endif /* __TBB_SURVIVE_THREAD_SWITCH */
} // namespace internal
//------------------------------------------------------------------------
// task_scheduler_init
//------------------------------------------------------------------------
using namespace internal;
/** Left out-of-line for the sake of the backward binary compatibility **/
void task_scheduler_init::initialize( int number_of_threads ) {
initialize( number_of_threads, 0 );
}
void task_scheduler_init::initialize( int number_of_threads, stack_size_type thread_stack_size ) {
#if __TBB_TASK_GROUP_CONTEXT && TBB_USE_EXCEPTIONS
uintptr_t new_mode = thread_stack_size & propagation_mode_mask;
#endif
thread_stack_size &= ~(stack_size_type)propagation_mode_mask;
if( number_of_threads!=deferred ) {
__TBB_ASSERT( !my_scheduler, "task_scheduler_init already initialized" );
__TBB_ASSERT( number_of_threads==-1 || number_of_threads>=1,
"number_of_threads for task_scheduler_init must be -1 or positive" );
internal::generic_scheduler *s = governor::init_scheduler( number_of_threads, thread_stack_size );
#if __TBB_TASK_GROUP_CONTEXT && TBB_USE_EXCEPTIONS
if ( s->master_outermost_level() ) {
uintptr_t &vt = s->default_context()->my_version_and_traits;
uintptr_t prev_mode = vt & task_group_context::exact_exception ? propagation_mode_exact : 0;
vt = new_mode & propagation_mode_exact ? vt | task_group_context::exact_exception
: new_mode & propagation_mode_captured ? vt & ~task_group_context::exact_exception : vt;
// Use least significant bit of the scheduler pointer to store previous mode.
// This is necessary when components compiled with different compilers and/or
// TBB versions initialize the
my_scheduler = static_cast<scheduler*>((generic_scheduler*)((uintptr_t)s | prev_mode));
}
else
#endif /* __TBB_TASK_GROUP_CONTEXT && TBB_USE_EXCEPTIONS */
my_scheduler = s;
} else {
__TBB_ASSERT( !thread_stack_size, "deferred initialization ignores stack size setting" );
}
}
void task_scheduler_init::terminate() {
#if __TBB_TASK_GROUP_CONTEXT && TBB_USE_EXCEPTIONS
uintptr_t prev_mode = (uintptr_t)my_scheduler & propagation_mode_exact;
my_scheduler = (scheduler*)((uintptr_t)my_scheduler & ~(uintptr_t)propagation_mode_exact);
#endif /* __TBB_TASK_GROUP_CONTEXT && TBB_USE_EXCEPTIONS */
generic_scheduler* s = static_cast<generic_scheduler*>(my_scheduler);
my_scheduler = NULL;
__TBB_ASSERT( s, "task_scheduler_init::terminate without corresponding task_scheduler_init::initialize()");
#if __TBB_TASK_GROUP_CONTEXT && TBB_USE_EXCEPTIONS
if ( s->master_outermost_level() ) {
uintptr_t &vt = s->default_context()->my_version_and_traits;
vt = prev_mode & propagation_mode_exact ? vt | task_group_context::exact_exception
: vt & ~task_group_context::exact_exception;
}
#endif /* __TBB_TASK_GROUP_CONTEXT && TBB_USE_EXCEPTIONS */
governor::terminate_scheduler(s);
}
int task_scheduler_init::default_num_threads() {
return governor::default_num_threads();
}
} // namespace tbb
| 38.25 | 122 | 0.672044 | windystrife |
870a743b82f419eefe98753770e83478cdbc8ce4 | 668 | cc | C++ | vos/gui/sub/gui/histcommands/SetVertHistGraphCmd.cc | NASA-AMMOS/VICAR | 4504c1f558855d9c6eaef89f4460217aa4909f8e | [
"BSD-3-Clause"
] | 16 | 2020-10-21T05:56:26.000Z | 2022-03-31T10:02:01.000Z | vos/gui/sub/gui/histcommands/SetVertHistGraphCmd.cc | NASA-AMMOS/VICAR | 4504c1f558855d9c6eaef89f4460217aa4909f8e | [
"BSD-3-Clause"
] | null | null | null | vos/gui/sub/gui/histcommands/SetVertHistGraphCmd.cc | NASA-AMMOS/VICAR | 4504c1f558855d9c6eaef89f4460217aa4909f8e | [
"BSD-3-Clause"
] | 2 | 2021-03-09T01:51:08.000Z | 2021-03-23T00:23:24.000Z | ///////////////////////////////////////////////////////////
// SetVertHistGraphCmd.C: Example, dummy command class
//////////////////////////////////////////////////////////
#include "SetVertHistGraphCmd.h"
#include "Histogram.h"
#include "HistBox.h"
#include <iostream>
SetVertHistGraphCmd::SetVertHistGraphCmd ( const char *name, int active, HistBox *obj, CmdList *list=NULL ) : RadioCmd ( name, active, list )
{
_menuView = obj;
if (_menuView->getOrientType() == HORIZONTAL) {
_value = (CmdValue) TRUE;
newValue ();
}
}
void SetVertHistGraphCmd::doit()
{
if (_value) {
_menuView->setOrientType( HORIZONTAL );
}
}
| 24.740741 | 141 | 0.54491 | NASA-AMMOS |
870fe268a7302179531faf63d726107929c090f0 | 7,843 | hpp | C++ | src/open_viii/graphics/Ppm.hpp | Sebanisu/VIIIcppTest | 59565ae2d32ea302401402544a70d3b37fab7351 | [
"MIT"
] | 2 | 2020-04-30T22:12:06.000Z | 2020-05-01T07:06:26.000Z | src/open_viii/graphics/Ppm.hpp | Sebanisu/VIIIcppTest | 59565ae2d32ea302401402544a70d3b37fab7351 | [
"MIT"
] | 9 | 2020-04-26T01:52:21.000Z | 2020-05-20T21:10:28.000Z | src/open_viii/graphics/Ppm.hpp | Sebanisu/VIIIcppTest | 59565ae2d32ea302401402544a70d3b37fab7351 | [
"MIT"
] | null | null | null | // This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef VIIIARCHIVE_PPM_HPP
#define VIIIARCHIVE_PPM_HPP
#include "Color.hpp"
#include "open_viii/Concepts.hpp"
#include "open_viii/tools/Tools.hpp"
#include "Point.hpp"
#include <execution>
namespace open_viii::graphics {
struct Ppm
{
private:
std::filesystem::path m_path{};
Point<std::uint16_t> m_width_height{};
std::vector<Color24<ColorLayoutT::RGB>> m_colors{};
Point<std::uint16_t>
get_width_height(const std::string &buffer)
{
Point<std::uint16_t> point{};
// the support is mostly limited to the same type that is made by the save
// function. I can't use span because span_stream does not exist yet it
// missed cpp20... so this will need to be a string stream? I know not to
// use std::regex but i'm feeling like that's better than what I'm doing
// here. heh.
// sample header ss << "P6\n# THIS IS A COMMENT\n" << width << " " << height
// << "\n255\n"; sample header ss << "P6\n# THIS IS A COMMENT\n" << width <<
// " " << height << " 255\n";
auto ss = std::stringstream(buffer);
std::string line{};
std::string type{};
std::string comment{};
std::string w_h{};
std::string bytesize{};
while ((std::ranges::empty(bytesize) || std::ranges::empty(w_h))
&& std::getline(ss, line)) {
if (line == "P6") {
type = line;
continue;
}
if (line[0] == '#') {
comment += line;
continue;
}
if (line == "255") {
bytesize = line;
continue;
}
if ([&line, &point, &bytesize]() -> bool {
const auto count = std::ranges::count(line, ' ');
std::uint16_t width{};
std::uint16_t height{};
if (count == 1) {// 000 000\n000
auto lss = std::stringstream(line);
lss >> width;
lss >> height;
}
else if (count == 2) {// 000 000 000
auto lss = std::stringstream(line);
lss >> width;
lss >> height;
lss >> bytesize;
}
point.x(width);
point.y(height);
return width > 0 || height > 0;
}()) {
w_h = line;
continue;
}
}
const auto start = ss.tellg();
ss.seekg(0, std::ios::end);
const auto end = ss.tellg();
const auto sz = static_cast<std::size_t>(end - start)
/ sizeof(Color24<ColorLayoutT::RGB>);
if (sz != point.area()) {
std::cerr << m_path << "\n\t" << sz << " != area of " << point
<< std::endl;
// assert(sz == m_width_height.area());
return {};// instead of throwing reset the value and quit.
}
return point;
}
auto
get_colors(std::span<const char> buffer_span)
{
std::vector<Color24<ColorLayoutT::RGB>> colors{};
const auto area = m_width_height.area();
static constexpr auto color_size = sizeof(Color24<ColorLayoutT::RGB>);
const auto size_of_bytes = area * color_size;
if (area > 0 && std::ranges::size(buffer_span) > size_of_bytes) {
buffer_span = buffer_span.subspan(
std::ranges::size(buffer_span) - size_of_bytes,
size_of_bytes);
colors.resize(area);
std::memcpy(
std::ranges::data(colors),
std::ranges::data(buffer_span),
size_of_bytes);
}
return colors;
}
public:
Ppm() = default;
explicit Ppm(const std::filesystem::path &path)
: Ppm(tools::read_entire_file<std::string>(path), path)
{}
explicit Ppm(const std::string &buffer, std::filesystem::path path = {})
: m_path(std::move(path)), m_width_height(get_width_height(buffer)),
m_colors(get_colors(buffer))
{}
bool
empty() const noexcept
{
return std::ranges::empty(m_colors) || m_width_height.x() <= 0
|| m_width_height.y() <= 0;
}
template<std::ranges::contiguous_range cT>
static void
save(
const cT &data,
std::size_t width,
std::size_t height,
const std::string_view &input,
bool skip_check = false)
{// how do i make the concept reject ranges that aren't of Colors? I'm at
// least checking for Color down below.
if (!skip_check) {
bool are_colors_all_black = check_if_colors_are_black(data);
if (
width == 0 || height == 0 || std::ranges::empty(data)
|| are_colors_all_black) {
return;
}
}
const std::string filename = [&]() {
if (!open_viii::tools::i_ends_with(input, ".ppm")) {
auto tmp = std::filesystem::path(input);
std::string local_filename{ (tmp.parent_path() / tmp.stem()).string() };
if (tmp.has_extension()) {
local_filename += "_" + tmp.extension().string().substr(1);
}
local_filename += ".ppm";
return local_filename;
}
return std::string{ input };
}();
if (std::ranges::size(data) < width * height) {
std::cout << std::ranges::size(data) << ", " << width << '*' << height
<< '=' << width * height << '\n';
return;
}
tools::write_buffer(
[&data, &width, &height](std::ostream &ss) {
ss << "P6\n# THIS IS A COMMENT\n"
<< width << " " << height << "\n255\n";
for (const Color auto &color :
data) {// organize the data in ram first then write all at once.
ss << color.r();
ss << color.g();
ss << color.b();
}
},
filename);
}
static bool
check_if_colors_are_black(const auto &data)
{
return std::all_of(
std::execution::par_unseq,
data.begin(),
data.end(),
[](const Color auto &color) -> bool {
return color.a() == 0U
|| (color.b() == 0U && color.g() == 0U && color.r() == 0U);
});
}
[[nodiscard]] const std::vector<Color24<ColorLayoutT::RGB>> &
colors() const noexcept
{
return m_colors;
}
[[nodiscard]] constexpr auto
width() const noexcept
{
return m_width_height.x();
}
[[nodiscard]] constexpr auto
height() const noexcept
{
return m_width_height.y();
}
[[nodiscard]] const auto &
width_height() const noexcept
{
return m_width_height;
}
[[nodiscard]] const Color24<ColorLayoutT::RGB> &
color(const std::size_t &x, const std::size_t &y) const noexcept
{
return at(x + (y * static_cast<std::size_t>(m_width_height.x())));
}
[[nodiscard]] const Color24<ColorLayoutT::RGB> &
at(const size_t i) const noexcept
{
static constexpr Color24<ColorLayoutT::RGB> black{};
if (i < std::ranges::size(m_colors)) {
return m_colors[i];
}
return black;
}
[[nodiscard]] const std::filesystem::path &
path() const noexcept
{
return m_path;
}
};
inline std::ostream &
operator<<(std::ostream &os, const Ppm &ppm)
{
return os << "(Width, Height): " << ppm.width_height() << "\t" << ppm.path()
<< '\n';
}
}// namespace open_viii::graphics
#endif// VIIIARCHIVE_PPM_HPP
| 32.8159 | 80 | 0.563687 | Sebanisu |
8710f2c2d2d282fdd1ff8231c80279a8f57c0cd1 | 1,889 | hpp | C++ | Engine/Events/EventSource.hpp | ryanvanrooyen/GameFramework | 56ec1fe66964b2963cbdb2ba04640be47de59cc7 | [
"Apache-2.0"
] | null | null | null | Engine/Events/EventSource.hpp | ryanvanrooyen/GameFramework | 56ec1fe66964b2963cbdb2ba04640be47de59cc7 | [
"Apache-2.0"
] | null | null | null | Engine/Events/EventSource.hpp | ryanvanrooyen/GameFramework | 56ec1fe66964b2963cbdb2ba04640be47de59cc7 | [
"Apache-2.0"
] | null | null | null |
#pragma once
#include "EngineCommon.h"
#include "Listeners.hpp"
namespace Game
{
class Window;
class EventSource
{
public:
virtual ~EventSource() = default;
void PushListener(WindowListener* listener);
void PushListener(MouseListener* listener);
void PushListener(KeyboardListener* listener);
void PushListener(EventListener* listener)
{
PushListener((WindowListener*)listener);
PushListener((MouseListener*)listener);
PushListener((KeyboardListener*)listener);
}
void PopListener(WindowListener* listener);
void PopListener(MouseListener* listener);
void PopListener(KeyboardListener* listener);
void PopListener(EventListener* listener)
{
PopListener((WindowListener*)listener);
PopListener((MouseListener*)listener);
PopListener((KeyboardListener*)listener);
}
protected:
bool DispatchWindowClose(Window& window);
bool DispatchWindowResize(Window& window);
bool DispatchWindowScroll(Window& window, double xOffset, double yOffset);
bool DispatchWindowMonitor(Window& window, int monitorEventType);
bool DispatchMouseMove(Window& window, double xPos, double yPos);
bool DispatchMousePress(Window& window, MouseCode button);
bool DispatchMouseRelease(Window& window, MouseCode button);
bool DispatchKeyPress(Window& window, KeyCode key);
bool DispatchKeyRelease(Window& window, KeyCode key);
bool DispatchKeyRepeat(Window& window, KeyCode key);
bool DispatchCharTyped(Window& window, unsigned int character);
private:
std::vector<WindowListener*> windowListeners;
std::vector<MouseListener*> mouseListeners;
std::vector<KeyboardListener*> keyboardListeners;
};
} | 33.732143 | 82 | 0.677078 | ryanvanrooyen |
8713fa7a6b4895b12f501e015478608f65f2734a | 226 | hpp | C++ | PP/get_std.hpp | Petkr/PP | 646cc156603a6a9461e74d8f54786c0d5a9c32d2 | [
"MIT"
] | 3 | 2019-07-12T23:12:24.000Z | 2019-09-05T07:57:45.000Z | PP/get_std.hpp | Petkr/PP | 646cc156603a6a9461e74d8f54786c0d5a9c32d2 | [
"MIT"
] | null | null | null | PP/get_std.hpp | Petkr/PP | 646cc156603a6a9461e74d8f54786c0d5a9c32d2 | [
"MIT"
] | null | null | null | #pragma once
#include <PP/size_t.hpp>
#include <PP/tuple/concept.hpp>
namespace PP
{
namespace tuple
{
template <size_t I>
constexpr decltype(auto) get(concepts::tuple auto&& t) noexcept
{
return PP_F(t)[value<I>];
}
}
}
| 14.125 | 63 | 0.70354 | Petkr |
871511482876f2d602815e0bc6d7b7f31641152c | 21,772 | cc | C++ | src/chrome/browser/shell_integration_unittest.cc | jxjnjjn/chromium | 435c1d02fd1b99001dc9e1e831632c894523580d | [
"Apache-2.0"
] | 9 | 2018-09-21T05:36:12.000Z | 2021-11-15T15:14:36.000Z | src/chrome/browser/shell_integration_unittest.cc | jxjnjjn/chromium | 435c1d02fd1b99001dc9e1e831632c894523580d | [
"Apache-2.0"
] | null | null | null | src/chrome/browser/shell_integration_unittest.cc | jxjnjjn/chromium | 435c1d02fd1b99001dc9e1e831632c894523580d | [
"Apache-2.0"
] | 3 | 2018-11-28T14:54:13.000Z | 2020-07-02T07:36:07.000Z | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/shell_integration.h"
#include <cstdlib>
#include <map>
#include "base/file_util.h"
#include "base/files/file_path.h"
#include "base/files/scoped_temp_dir.h"
#include "base/message_loop.h"
#include "base/stl_util.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/web_applications/web_app.h"
#include "chrome/common/chrome_constants.h"
#include "content/public/test/test_browser_thread.h"
#include "googleurl/src/gurl.h"
#include "testing/gtest/include/gtest/gtest.h"
#if defined(OS_POSIX) && !defined(OS_MACOSX)
#include "base/environment.h"
#include "chrome/browser/shell_integration_linux.h"
#endif
#define FPL FILE_PATH_LITERAL
using content::BrowserThread;
#if defined(OS_POSIX) && !defined(OS_MACOSX)
namespace {
// Provides mock environment variables values based on a stored map.
class MockEnvironment : public base::Environment {
public:
MockEnvironment() {}
void Set(const std::string& name, const std::string& value) {
variables_[name] = value;
}
virtual bool GetVar(const char* variable_name, std::string* result) OVERRIDE {
if (ContainsKey(variables_, variable_name)) {
*result = variables_[variable_name];
return true;
}
return false;
}
virtual bool SetVar(const char* variable_name,
const std::string& new_value) OVERRIDE {
ADD_FAILURE();
return false;
}
virtual bool UnSetVar(const char* variable_name) OVERRIDE {
ADD_FAILURE();
return false;
}
private:
std::map<std::string, std::string> variables_;
DISALLOW_COPY_AND_ASSIGN(MockEnvironment);
};
// Allows you to change the real environment, but reverts changes upon
// destruction.
class ScopedEnvironment {
public:
ScopedEnvironment() {}
~ScopedEnvironment() {
for (std::map<std::string, std::string>::const_iterator
it = old_variables_.begin(); it != old_variables_.end(); ++it) {
if (it->second.empty()) {
unsetenv(it->first.c_str());
} else {
setenv(it->first.c_str(), it->second.c_str(), 1);
}
}
}
void Set(const std::string& name, const std::string& value) {
if (!ContainsKey(old_variables_, name)) {
const char* value = getenv(name.c_str());
if (value != NULL) {
old_variables_[name] = value;
} else {
old_variables_[name] = std::string();
}
}
setenv(name.c_str(), value.c_str(), 1);
}
private:
// Map from name to original value, or the empty string if there was no
// previous value.
std::map<std::string, std::string> old_variables_;
DISALLOW_COPY_AND_ASSIGN(ScopedEnvironment);
};
} // namespace
TEST(ShellIntegrationTest, GetExistingShortcutLocations) {
base::FilePath kProfilePath("Default");
const char kExtensionId[] = "test_extension";
const char kTemplateFilename[] = "chrome-test_extension-Default.desktop";
base::FilePath kTemplateFilepath(kTemplateFilename);
const char kNoDisplayDesktopFile[] = "[Desktop Entry]\nNoDisplay=true";
MessageLoop message_loop;
content::TestBrowserThread file_thread(BrowserThread::FILE, &message_loop);
// No existing shortcuts.
{
MockEnvironment env;
ShellIntegration::ShortcutLocations result =
ShellIntegrationLinux::GetExistingShortcutLocations(
&env, kProfilePath, kExtensionId);
EXPECT_FALSE(result.on_desktop);
EXPECT_FALSE(result.in_applications_menu);
EXPECT_FALSE(result.in_quick_launch_bar);
EXPECT_FALSE(result.hidden);
}
// Shortcut on desktop.
{
base::ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
base::FilePath desktop_path = temp_dir.path();
MockEnvironment env;
ASSERT_TRUE(file_util::CreateDirectory(desktop_path));
ASSERT_FALSE(file_util::WriteFile(
desktop_path.AppendASCII(kTemplateFilename),
"", 0));
ShellIntegration::ShortcutLocations result =
ShellIntegrationLinux::GetExistingShortcutLocations(
&env, kProfilePath, kExtensionId, desktop_path);
EXPECT_TRUE(result.on_desktop);
EXPECT_FALSE(result.in_applications_menu);
EXPECT_FALSE(result.in_quick_launch_bar);
EXPECT_FALSE(result.hidden);
}
// Shortcut in applications directory.
{
base::ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
base::FilePath apps_path = temp_dir.path().AppendASCII("applications");
MockEnvironment env;
env.Set("XDG_DATA_HOME", temp_dir.path().value());
ASSERT_TRUE(file_util::CreateDirectory(apps_path));
ASSERT_FALSE(file_util::WriteFile(
apps_path.AppendASCII(kTemplateFilename),
"", 0));
ShellIntegration::ShortcutLocations result =
ShellIntegrationLinux::GetExistingShortcutLocations(
&env, kProfilePath, kExtensionId);
EXPECT_FALSE(result.on_desktop);
EXPECT_TRUE(result.in_applications_menu);
EXPECT_FALSE(result.in_quick_launch_bar);
EXPECT_FALSE(result.hidden);
}
// Shortcut in applications directory with NoDisplay=true.
{
base::ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
base::FilePath apps_path = temp_dir.path().AppendASCII("applications");
MockEnvironment env;
env.Set("XDG_DATA_HOME", temp_dir.path().value());
ASSERT_TRUE(file_util::CreateDirectory(apps_path));
ASSERT_TRUE(file_util::WriteFile(
apps_path.AppendASCII(kTemplateFilename),
kNoDisplayDesktopFile, strlen(kNoDisplayDesktopFile)));
ShellIntegration::ShortcutLocations result =
ShellIntegrationLinux::GetExistingShortcutLocations(
&env, kProfilePath, kExtensionId);
// Doesn't count as being in applications menu.
EXPECT_FALSE(result.on_desktop);
EXPECT_FALSE(result.in_applications_menu);
EXPECT_FALSE(result.in_quick_launch_bar);
EXPECT_TRUE(result.hidden);
}
// Shortcut on desktop and in applications directory.
{
base::ScopedTempDir temp_dir1;
ASSERT_TRUE(temp_dir1.CreateUniqueTempDir());
base::FilePath desktop_path = temp_dir1.path();
base::ScopedTempDir temp_dir2;
ASSERT_TRUE(temp_dir2.CreateUniqueTempDir());
base::FilePath apps_path = temp_dir2.path().AppendASCII("applications");
MockEnvironment env;
ASSERT_TRUE(file_util::CreateDirectory(desktop_path));
ASSERT_FALSE(file_util::WriteFile(
desktop_path.AppendASCII(kTemplateFilename),
"", 0));
env.Set("XDG_DATA_HOME", temp_dir2.path().value());
ASSERT_TRUE(file_util::CreateDirectory(apps_path));
ASSERT_FALSE(file_util::WriteFile(
apps_path.AppendASCII(kTemplateFilename),
"", 0));
ShellIntegration::ShortcutLocations result =
ShellIntegrationLinux::GetExistingShortcutLocations(
&env, kProfilePath, kExtensionId, desktop_path);
EXPECT_TRUE(result.on_desktop);
EXPECT_TRUE(result.in_applications_menu);
EXPECT_FALSE(result.in_quick_launch_bar);
EXPECT_FALSE(result.hidden);
}
}
TEST(ShellIntegrationTest, GetExistingShortcutContents) {
const char kTemplateFilename[] = "shortcut-test.desktop";
base::FilePath kTemplateFilepath(kTemplateFilename);
const char kTestData1[] = "a magical testing string";
const char kTestData2[] = "a different testing string";
MessageLoop message_loop;
content::TestBrowserThread file_thread(BrowserThread::FILE, &message_loop);
// Test that it searches $XDG_DATA_HOME/applications.
{
base::ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
MockEnvironment env;
env.Set("XDG_DATA_HOME", temp_dir.path().value());
// Create a file in a non-applications directory. This should be ignored.
ASSERT_TRUE(file_util::WriteFile(
temp_dir.path().AppendASCII(kTemplateFilename),
kTestData2, strlen(kTestData2)));
ASSERT_TRUE(file_util::CreateDirectory(
temp_dir.path().AppendASCII("applications")));
ASSERT_TRUE(file_util::WriteFile(
temp_dir.path().AppendASCII("applications")
.AppendASCII(kTemplateFilename),
kTestData1, strlen(kTestData1)));
std::string contents;
ASSERT_TRUE(
ShellIntegrationLinux::GetExistingShortcutContents(
&env, kTemplateFilepath, &contents));
EXPECT_EQ(kTestData1, contents);
}
// Test that it falls back to $HOME/.local/share/applications.
{
base::ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
MockEnvironment env;
env.Set("HOME", temp_dir.path().value());
ASSERT_TRUE(file_util::CreateDirectory(
temp_dir.path().AppendASCII(".local/share/applications")));
ASSERT_TRUE(file_util::WriteFile(
temp_dir.path().AppendASCII(".local/share/applications")
.AppendASCII(kTemplateFilename),
kTestData1, strlen(kTestData1)));
std::string contents;
ASSERT_TRUE(
ShellIntegrationLinux::GetExistingShortcutContents(
&env, kTemplateFilepath, &contents));
EXPECT_EQ(kTestData1, contents);
}
// Test that it searches $XDG_DATA_DIRS/applications.
{
base::ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
MockEnvironment env;
env.Set("XDG_DATA_DIRS", temp_dir.path().value());
ASSERT_TRUE(file_util::CreateDirectory(
temp_dir.path().AppendASCII("applications")));
ASSERT_TRUE(file_util::WriteFile(
temp_dir.path().AppendASCII("applications")
.AppendASCII(kTemplateFilename),
kTestData2, strlen(kTestData2)));
std::string contents;
ASSERT_TRUE(
ShellIntegrationLinux::GetExistingShortcutContents(
&env, kTemplateFilepath, &contents));
EXPECT_EQ(kTestData2, contents);
}
// Test that it searches $X/applications for each X in $XDG_DATA_DIRS.
{
base::ScopedTempDir temp_dir1;
ASSERT_TRUE(temp_dir1.CreateUniqueTempDir());
base::ScopedTempDir temp_dir2;
ASSERT_TRUE(temp_dir2.CreateUniqueTempDir());
MockEnvironment env;
env.Set("XDG_DATA_DIRS", temp_dir1.path().value() + ":" +
temp_dir2.path().value());
// Create a file in a non-applications directory. This should be ignored.
ASSERT_TRUE(file_util::WriteFile(
temp_dir1.path().AppendASCII(kTemplateFilename),
kTestData1, strlen(kTestData1)));
// Only create a findable desktop file in the second path.
ASSERT_TRUE(file_util::CreateDirectory(
temp_dir2.path().AppendASCII("applications")));
ASSERT_TRUE(file_util::WriteFile(
temp_dir2.path().AppendASCII("applications")
.AppendASCII(kTemplateFilename),
kTestData2, strlen(kTestData2)));
std::string contents;
ASSERT_TRUE(
ShellIntegrationLinux::GetExistingShortcutContents(
&env, kTemplateFilepath, &contents));
EXPECT_EQ(kTestData2, contents);
}
}
TEST(ShellIntegrationTest, GetDesktopShortcutTemplate) {
#if defined(GOOGLE_CHROME_BUILD)
const char kTemplateFilename[] = "google-chrome.desktop";
#else // CHROMIUM_BUILD
const char kTemplateFilename[] = "chromium-browser.desktop";
#endif
const char kTestData[] = "a magical testing string";
MessageLoop message_loop;
content::TestBrowserThread file_thread(BrowserThread::FILE, &message_loop);
// Just do a simple test. The details are covered by
// GetExistingShortcutContents test.
{
base::ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
MockEnvironment env;
env.Set("XDG_DATA_HOME", temp_dir.path().value());
ASSERT_TRUE(file_util::CreateDirectory(
temp_dir.path().AppendASCII("applications")));
ASSERT_TRUE(file_util::WriteFile(
temp_dir.path().AppendASCII("applications")
.AppendASCII(kTemplateFilename),
kTestData, strlen(kTestData)));
std::string contents;
ASSERT_TRUE(ShellIntegrationLinux::GetDesktopShortcutTemplate(&env,
&contents));
EXPECT_EQ(kTestData, contents);
}
}
TEST(ShellIntegrationTest, GetWebShortcutFilename) {
const struct {
const base::FilePath::CharType* path;
const char* url;
} test_cases[] = {
{ FPL("http___foo_.desktop"), "http://foo" },
{ FPL("http___foo_bar_.desktop"), "http://foo/bar/" },
{ FPL("http___foo_bar_a=b&c=d.desktop"), "http://foo/bar?a=b&c=d" },
// Now we're starting to be more evil...
{ FPL("http___foo_.desktop"), "http://foo/bar/baz/../../../../../" },
{ FPL("http___foo_.desktop"), "http://foo/bar/././../baz/././../" },
{ FPL("http___.._.desktop"), "http://../../../../" },
};
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_cases); i++) {
EXPECT_EQ(std::string(chrome::kBrowserProcessExecutableName) + "-" +
test_cases[i].path,
ShellIntegrationLinux::GetWebShortcutFilename(
GURL(test_cases[i].url)).value()) <<
" while testing " << test_cases[i].url;
}
}
TEST(ShellIntegrationTest, GetDesktopFileContents) {
const struct {
const char* url;
const char* title;
const char* icon_name;
bool nodisplay;
const char* template_contents;
const char* expected_output;
} test_cases[] = {
// Dumb case.
{ "ignored", "ignored", "ignored", false, "", "#!/usr/bin/env xdg-open\n" },
// Invalid desktop file.
{ "ignored", "ignored", "ignored", false, "[Desktop\n",
"#!/usr/bin/env xdg-open\n" },
// Non-empty file without [Desktop Entry].
// This tests a different code path to the above.
{ "http://gmail.com",
"GMail",
"chrome-http__gmail.com",
false,
"\n",
// The resulting shortcut is not useful, but we just want to make sure
// this doesn't crash.
"#!/usr/bin/env xdg-open\n"
"[Desktop Entry]\n"
"Name=GMail\n"
"Icon=chrome-http__gmail.com\n"
#if !defined(USE_AURA)
// Aura Chrome does not (yet) set WMClass, so we only expect
// StartupWMClass on non-Aura builds.
"StartupWMClass=gmail.com\n"
#endif
},
// Real-world case.
{ "http://gmail.com",
"GMail",
"chrome-http__gmail.com",
false,
"[Desktop Entry]\n"
"Version=1.0\n"
"Encoding=UTF-8\n"
"Name=Google Chrome\n"
"GenericName=Web Browser\n"
"Comment=The web browser from Google\n"
"Exec=/opt/google/chrome/google-chrome %U\n"
"Terminal=false\n"
"Icon=/opt/google/chrome/product_logo_48.png\n"
"Type=Application\n"
"Categories=Application;Network;WebBrowser;\n"
"MimeType=text/html;text/xml;application/xhtml_xml;\n"
"X-Ayatana-Desktop-Shortcuts=NewWindow;\n"
"\n"
"[NewWindow Shortcut Group]\n"
"Name=Open New Window\n"
"Exec=/opt/google/chrome/google-chrome\n"
"TargetEnvironment=Unity\n",
"#!/usr/bin/env xdg-open\n"
"[Desktop Entry]\n"
"Version=1.0\n"
"Encoding=UTF-8\n"
"Name=GMail\n"
"Exec=/opt/google/chrome/google-chrome --app=http://gmail.com/\n"
"Terminal=false\n"
"Icon=chrome-http__gmail.com\n"
"Type=Application\n"
"Categories=Application;Network;WebBrowser;\n"
#if !defined(USE_AURA)
// Aura Chrome does not (yet) set WMClass, so we only expect
// StartupWMClass on non-Aura builds.
"StartupWMClass=gmail.com\n"
#endif
},
// Make sure we don't insert duplicate shebangs.
{ "http://gmail.com",
"GMail",
"chrome-http__gmail.com",
false,
"#!/some/shebang\n"
"[Desktop Entry]\n"
"Name=Google Chrome\n"
"Exec=/opt/google/chrome/google-chrome %U\n",
"#!/usr/bin/env xdg-open\n"
"[Desktop Entry]\n"
"Name=GMail\n"
"Exec=/opt/google/chrome/google-chrome --app=http://gmail.com/\n"
"Icon=chrome-http__gmail.com\n"
#if !defined(USE_AURA)
// Aura Chrome does not (yet) set WMClass, so we only expect
// StartupWMClass on non-Aura builds.
"StartupWMClass=gmail.com\n"
#endif
},
// Make sure i18n-ed names and other fields are removed.
{ "http://gmail.com",
"GMail",
"chrome-http__gmail.com",
false,
"[Desktop Entry]\n"
"Name=Google Chrome\n"
"Name[en_AU]=Google Chrome\n"
"Name[pl]=Google Chrome\n"
"GenericName=Web Browser\n"
"GenericName[en_AU]=Web Browser\n"
"GenericName[pl]=Navegador Web\n"
"Exec=/opt/google/chrome/google-chrome %U\n"
"Comment[en_AU]=Some comment.\n"
"Comment[pl]=Jakis komentarz.\n",
"#!/usr/bin/env xdg-open\n"
"[Desktop Entry]\n"
"Name=GMail\n"
"Exec=/opt/google/chrome/google-chrome --app=http://gmail.com/\n"
"Icon=chrome-http__gmail.com\n"
#if !defined(USE_AURA)
// Aura Chrome does not (yet) set WMClass, so we only expect
// StartupWMClass on non-Aura builds.
"StartupWMClass=gmail.com\n"
#endif
},
// Make sure that empty icons are replaced by the chrome icon.
{ "http://gmail.com",
"GMail",
"",
false,
"[Desktop Entry]\n"
"Name=Google Chrome\n"
"Exec=/opt/google/chrome/google-chrome %U\n"
"Comment[pl]=Jakis komentarz.\n"
"Icon=/opt/google/chrome/product_logo_48.png\n",
"#!/usr/bin/env xdg-open\n"
"[Desktop Entry]\n"
"Name=GMail\n"
"Exec=/opt/google/chrome/google-chrome --app=http://gmail.com/\n"
"Icon=/opt/google/chrome/product_logo_48.png\n"
#if !defined(USE_AURA)
// Aura Chrome does not (yet) set WMClass, so we only expect
// StartupWMClass on non-Aura builds.
"StartupWMClass=gmail.com\n"
#endif
},
// Test adding NoDisplay=true.
{ "http://gmail.com",
"GMail",
"chrome-http__gmail.com",
true,
"[Desktop Entry]\n"
"Name=Google Chrome\n"
"Exec=/opt/google/chrome/google-chrome %U\n",
"#!/usr/bin/env xdg-open\n"
"[Desktop Entry]\n"
"Name=GMail\n"
"Exec=/opt/google/chrome/google-chrome --app=http://gmail.com/\n"
"Icon=chrome-http__gmail.com\n"
"NoDisplay=true\n"
#if !defined(USE_AURA)
// Aura Chrome does not (yet) set WMClass, so we only expect
// StartupWMClass on non-Aura builds.
"StartupWMClass=gmail.com\n"
#endif
},
// Now we're starting to be more evil...
{ "http://evil.com/evil --join-the-b0tnet",
"Ownz0red\nExec=rm -rf /",
"chrome-http__evil.com_evil",
false,
"[Desktop Entry]\n"
"Name=Google Chrome\n"
"Exec=/opt/google/chrome/google-chrome %U\n",
"#!/usr/bin/env xdg-open\n"
"[Desktop Entry]\n"
"Name=http://evil.com/evil%20--join-the-b0tnet\n"
"Exec=/opt/google/chrome/google-chrome "
"--app=http://evil.com/evil%20--join-the-b0tnet\n"
"Icon=chrome-http__evil.com_evil\n"
#if !defined(USE_AURA)
// Aura Chrome does not (yet) set WMClass, so we only expect
// StartupWMClass on non-Aura builds.
"StartupWMClass=evil.com__evil%20--join-the-b0tnet\n"
#endif
},
{ "http://evil.com/evil; rm -rf /; \"; rm -rf $HOME >ownz0red",
"Innocent Title",
"chrome-http__evil.com_evil",
false,
"[Desktop Entry]\n"
"Name=Google Chrome\n"
"Exec=/opt/google/chrome/google-chrome %U\n",
"#!/usr/bin/env xdg-open\n"
"[Desktop Entry]\n"
"Name=Innocent Title\n"
"Exec=/opt/google/chrome/google-chrome "
"\"--app=http://evil.com/evil;%20rm%20-rf%20/;%20%22;%20rm%20"
// Note: $ is escaped as \$ within an arg to Exec, and then
// the \ is escaped as \\ as all strings in a Desktop file should
// be; finally, \\ becomes \\\\ when represented in a C++ string!
"-rf%20\\\\$HOME%20%3Eownz0red\"\n"
"Icon=chrome-http__evil.com_evil\n"
#if !defined(USE_AURA)
// Aura Chrome does not (yet) set WMClass, so we only expect
// StartupWMClass on non-Aura builds.
"StartupWMClass=evil.com__evil;%20rm%20-rf%20_;%20%22;%20"
"rm%20-rf%20$HOME%20%3Eownz0red\n"
#endif
},
{ "http://evil.com/evil | cat `echo ownz0red` >/dev/null",
"Innocent Title",
"chrome-http__evil.com_evil",
false,
"[Desktop Entry]\n"
"Name=Google Chrome\n"
"Exec=/opt/google/chrome/google-chrome %U\n",
"#!/usr/bin/env xdg-open\n"
"[Desktop Entry]\n"
"Name=Innocent Title\n"
"Exec=/opt/google/chrome/google-chrome "
"--app=http://evil.com/evil%20%7C%20cat%20%60echo%20ownz0red"
"%60%20%3E/dev/null\n"
"Icon=chrome-http__evil.com_evil\n"
#if !defined(USE_AURA)
// Aura Chrome does not (yet) set WMClass, so we only expect
// StartupWMClass on non-Aura builds.
"StartupWMClass=evil.com__evil%20%7C%20cat%20%60echo%20ownz0red"
"%60%20%3E_dev_null\n"
#endif
},
};
// Set the language to en_AU. This causes glib to copy the en_AU localized
// strings into the shortcut file. (We want to test that they are removed.)
ScopedEnvironment env;
env.Set("LC_ALL", "en_AU.UTF-8");
env.Set("LANGUAGE", "en_AU.UTF-8");
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_cases); i++) {
SCOPED_TRACE(i);
EXPECT_EQ(
test_cases[i].expected_output,
ShellIntegrationLinux::GetDesktopFileContents(
test_cases[i].template_contents,
web_app::GenerateApplicationNameFromURL(GURL(test_cases[i].url)),
GURL(test_cases[i].url),
std::string(),
base::FilePath(),
ASCIIToUTF16(test_cases[i].title),
test_cases[i].icon_name,
base::FilePath(),
test_cases[i].nodisplay));
}
}
#endif
| 33.138508 | 80 | 0.661078 | jxjnjjn |
87165bdd762ebcc49d346f43ddd68e4476e22fca | 8,073 | cpp | C++ | Source/Player.cpp | nolancs/OrangeMUD | 3db3ddf73855bb76110d7a6a8e67271c36652b04 | [
"MIT"
] | 4 | 2020-01-25T04:20:07.000Z | 2022-01-14T02:59:28.000Z | Source/Player.cpp | nolancs/OrangeMUD | 3db3ddf73855bb76110d7a6a8e67271c36652b04 | [
"MIT"
] | null | null | null | Source/Player.cpp | nolancs/OrangeMUD | 3db3ddf73855bb76110d7a6a8e67271c36652b04 | [
"MIT"
] | 1 | 2020-04-01T04:36:48.000Z | 2020-04-01T04:36:48.000Z | /******************************************************************************
Author: Matthew Nolan OrangeMUD Codebase
Date: January 2001 [Crossplatform]
License: MIT 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.
Copyright 2000-2019 Matthew Nolan, All Rights Reserved
******************************************************************************/
#include "CommonTypes.h"
#include "Act.h"
#include "ANSI.h"
#include "Area.h"
#include "Channel.h"
#include "MUD.h"
#include "Player.h"
#include "RoomIndex.h"
#include "StringMagic.h"
#include "StringUtils.h"
#include "Tables.h"
#include "XMLFile.h"
Player::Player()
//Runtime Data
: isImm(NULL)
, mDamRoll(0)
, mHitRoll(0)
, mFlagsStatus(0)
//Persistant Data
, mUID(0)
, mLastLogin(0)
, mTimePlayed(0)
, mTrust(0)
, mScroll(20)
, mInvisLevel(0)
, mFlagsOptions(0)
, mFlagsInfo(0)
{
isPlayer = this;
isMobile = NULL;
for(LONG i = 0; i < kCondMax; ++i)
mCondition[i] = 0;
for(LONG i = 0; i < kColorPrefMax; ++i)
mColorPref[i] = 0;
}
Player::~Player()
{
}
#if 0
//***************************************************************************//
///////////////////////////////////////////////////////////////////////////////
//***************************************************************************//
#pragma mark -
#endif
void Player::PlaceInGame(PersonHolder* hTo, bool hLoggingIn)
{
ASSERT(hTo != NULL);
ASSERT(mSession != NULL);
ASSERT(mUID != 0);
mSession->mColorPrefStrs.clear();
for(LONG i = 0; i < kColorPrefMax; ++i)
mSession->mColorPrefStrs.AddBack(gANSIPrefTable.BuildANSICode(mColorPref[i]));
if(mKeywords.Empty())
mKeywords = mName;
MUD::Get()->PlaceInGame(this);
Person::PlaceInGame(hTo, hLoggingIn);
if(hLoggingIn)
{
Channel::Broadcast(-1, NULL,
kInfoConnect, "^]Info || ", "$n has connected.^x",
this, NULL, NULL, kActWorld|kActNoChar|kActOnlySeeChar);
}
}
void Player::RemoveFromGame(bool hLoggingOut)
{
Person::RemoveFromGame(hLoggingOut);
if(hLoggingOut)
{
//Show To World
Channel::Broadcast(-1, NULL,
kInfoQuit, "^]Info || ", "$n has left our reality.^x",
this, NULL, NULL, kActWorld|kActNoChar);
}
MUD::Get()->RemoveFromGame(this);
}
void Player::PlaceIn(PersonHolder* hTo)
{
Person::PlaceIn(hTo);
if(mInRoom)
{
++mInRoom->mNumPlayers;
++mInRoom->mInArea->mNumPlayers;
}
}
void Player::RemoveFrom()
{
if(mInRoom)
{
--mInRoom->mNumPlayers;
--mInRoom->mInArea->mNumPlayers;
}
Person::RemoveFrom();
}
bool Player::GetRoundAttacks(AttackArray& hAttacks)
{
return false;
}
void Player::StatTo(Person* hTo)
{
SHORT nBStr, nBDex, nBInt, nBWis, nBCon;
SHORT nStr, nDex, nInt, nWis, nCon;
LONG nHits, nHitsMax, nEnergy, nEnergyMax, nMoves, nMovesMax;
CHAR nResCold, nResFire, nResAcid, nResElec, nResPois, nResMind;
float nHR, nDR, nHitRegen, nEnergyRegen, nMoveRegen;
LONG nCopperBank, nCopperHere, nExpTNL;
STRINGCW nCondBuf;
nStr = GetStr();
nDex = GetDex();
nInt = GetInt();
nWis = GetWis();
nCon = GetCon();
nBStr = GetBaseStr();
nBDex = GetBaseDex();
nBInt = GetBaseInt();
nBWis = GetBaseWis();
nBCon = GetBaseCon();
nHits = GetHits();
nHitsMax = GetMaxHits();
nEnergy = GetEnergy();
nEnergyMax = GetMaxEnergy();
nMoves = GetMoves();
nMovesMax = GetMaxMoves();
nResCold = GetColdRes();
nResFire = GetFireRes();
nResAcid = GetAcidRes();
nResElec = GetElecRes();
nResPois = GetPoisRes();
nResMind = GetMindRes();
nHR = 0;
nDR = 0;
nHitRegen = 0;
nEnergyRegen = 0;
nMoveRegen = 0;
nCopperBank = 0;
nCopperHere = 0;
nExpTNL = 0;
//Conditions
if(mCondition[kCondThirst] >= kNowThirsty)
{
nCondBuf += ", thirsty";
if(hTo->IsImm()) nCondBuf += QBuf("(%d)", mCondition[kCondThirst]);
}
if(mCondition[kCondHunger] >= kNowHungry)
{
nCondBuf += ", hungry";
if(hTo->IsImm()) nCondBuf += QBuf("(%d)", mCondition[kCondHunger]);
}
if(mCondition[kCondDrunk] > 0)
{
nCondBuf += ", drunk";
if(hTo->IsImm()) nCondBuf += QBuf("(%d)", mCondition[kCondDrunk]);
}
if(mCondition[kCondHigh] > 0)
{
nCondBuf += ", high";
if(hTo->IsImm()) nCondBuf += QBuf("(%d)", mCondition[kCondHigh]);
}
//Setup Some Work Buffers
STRINGCW nTitleBuf, nHBuf, nEBuf, nMBuf;
nTitleBuf.SPrintF("%s the %s %s", *GetNameTo(hTo), *GetRaceNameTo(hTo), *GetClassNameTo(hTo));
nHBuf.SPrintF("%ld/%ld", nHits , nHitsMax);
nEBuf.SPrintF("%ld/%ld", nEnergy, nEnergyMax);
nMBuf.SPrintF("%ld/%ld", nMoves , nMovesMax);
STRINGCW nBuf;
nBuf.SPrintF(
////////////////////////////////// Score Template //////////////////////////////////////
"-==============================================================================-\n"
"^!%s^x\n"
"\n"
" Hits: %-11s Energy: %-11s Moves: %-11s\n"
"\n",
///////////////////////////////////////////////////////////////////////////////////////
CenterLine(nTitleBuf, 80),
*nHBuf, *nEBuf, *nMBuf);
hTo->Send(nBuf);
if(nCondBuf.Empty() == false)
{
hTo->Send("[ ");
hTo->Send(&nCondBuf[2]);
hTo->Send(" ]\n\n");
}
nBuf.SPrintF(
////////////////////////////////// Score Template //////////////////////////////////////
" Str:%2d(%2d) Dex:%2d(%2d) Int:%2d(%2d) Wis:%2d(%2d) Con:%2d(%2d)\n"
"\n"
" ^bCold^x:%4d%% ^cElec^x:%4d%% ^yPoison^x:%4d%%\n"
" ^rFire^x:%4d%% ^gAcid^x:%4d%% ^mMental^x:%4d%%\n"
"\n"
" Level: %-4d Focus: %-7s Sex: %s\n"
" Hit Regen: %+-7.1f Hitroll: %+-7.1f Align: %s\n"
" Energy Regen: %+-7.1f Damroll: %+-7.1f In Bank: %ldcp\n"
" Movement Regen: %+-7.1f Experience: %-12ld Carried: %ldcp\n"
"-==============================================================================-\n",
///////////////////////////////////////////////////////////////////////////////////////
nBStr, nStr, nBDex, nDex, nBInt, nInt, nBWis, nWis, nBCon, nCon,
nResCold , nResElec , nResPois ,
nResFire , nResAcid , nResMind ,
mLevel , "" , gSexTable[mSex].mName ,
nHitRegen , nHR , "gone" ,
nEnergyRegen , nDR , nCopperBank ,
nMoveRegen , nExpTNL , nCopperHere);
hTo->Send(nBuf);
}
| 30.123134 | 98 | 0.50799 | nolancs |
8716c7cb8cc02338de1bacf526833b346fb525d6 | 1,525 | cpp | C++ | src/programs/pthreads/pthreads.cpp | isaaclimdc/cachemulator | bcd0d330431df4dae9a7e1c61d2a61c4a0b3ffec | [
"MIT"
] | 1 | 2022-03-06T08:31:11.000Z | 2022-03-06T08:31:11.000Z | src/programs/pthreads/pthreads.cpp | isaaclimdc/cachemulator | bcd0d330431df4dae9a7e1c61d2a61c4a0b3ffec | [
"MIT"
] | null | null | null | src/programs/pthreads/pthreads.cpp | isaaclimdc/cachemulator | bcd0d330431df4dae9a7e1c61d2a61c4a0b3ffec | [
"MIT"
] | null | null | null | #include <sched.h>
#include <sys/types.h>
#include <signal.h>
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#define MAXTHREADS 1000
void *threadFunc(void *arg) {
// for (int i=0; i<100; i++) {
int *p = (int *)arg;
// printf("p is %p\n", p);
*p = 20;
int x = *p;
(void)x;
// }
return NULL;
}
int fib(int n) {
if (n == 0 || n == 1) return 1;
return fib(n-1) + fib(n-2);
}
void fibMemStack(int n, int *f) {
if (n == 0 || n == 1) {
*f = 1;
}
else {
int f1, f2 = 0;
fibMemStack(n-1, &f1);
fibMemStack(n-2, &f2);
*f = f1 + f2;
}
}
void fibMemHeap(int n, int *f) {
if (n == 0 || n == 1) {
*f = 1;
}
else {
int *f1 = (int *)malloc(sizeof(int));
int *f2 = (int *)malloc(sizeof(int));
fibMemHeap(n-1, f1);
fibMemHeap(n-2, f2);
*f = *f1 + *f2;
free(f1); free(f2);
}
}
int main(int argc, char *argv[]) {
pthread_t threads[MAXTHREADS];
int numthreads = 20;
for (int i = 0; i< numthreads; i++) {
int *p = (int *)malloc(sizeof(int));
*p = 42;
pthread_create(&threads[i], 0, threadFunc, p);
}
for (int i = 0; i < numthreads; i++) {
pthread_join(threads[i], 0);
}
// Other stuff
int n1 = 20;
int f1 = fib(n1);
printf("Fib %d is: %d\n", n1, f1);
// int f2 = 0;
// fibMemStack(n1, &f2);
// printf("Fib %d is: %d\n", n1, f2);
int *f3 = (int *)malloc(sizeof(int));
*f3 = 0;
fibMemHeap(n1, f3);
printf("Fib %d is: %d\n", n1, *f3);
free(f3);
return 0;
}
| 18.154762 | 50 | 0.510164 | isaaclimdc |
871a64882c43829827e0c64911606a13cce4fc94 | 1,510 | cpp | C++ | ADT-SET-MULTIset/Sort-AlgoAcedemy-Oct2015-RTF2-byMAP.cpp | kilarionov/cppTopics | 94461d25832b53e6c40c374fb2ff1695b3dfe3c7 | [
"MIT"
] | null | null | null | ADT-SET-MULTIset/Sort-AlgoAcedemy-Oct2015-RTF2-byMAP.cpp | kilarionov/cppTopics | 94461d25832b53e6c40c374fb2ff1695b3dfe3c7 | [
"MIT"
] | null | null | null | ADT-SET-MULTIset/Sort-AlgoAcedemy-Oct2015-RTF2-byMAP.cpp | kilarionov/cppTopics | 94461d25832b53e6c40c374fb2ff1695b3dfe3c7 | [
"MIT"
] | 1 | 2019-05-24T03:44:06.000Z | 2019-05-24T03:44:06.000Z | // http://bgcoder.com/Contests/268/Telerik-Algo-Academy-October-2015
// https://github.com/TelerikAcademy/AlgoAcademy/tree/master/2015-10-Algorithms-on-String/Problems
#include <iostream>
//#include <set>
#include <map>
const int D = (int)('a'-'A') ;
using namespace std ;
int main ()
{
long n, k;
int asciiCode;
char c;
//set<char> myGoodChars ;
//set<char>::iterator go;
//pair<set<char>::iterator, bool> retCode ;
map<char, int> myGoodChars ;
map<char,int>::iterator it;
myGoodChars.clear();
cin >>n;
for (k=0; k<n; k++)
{
cin >>asciiCode;
if (asciiCode>=32 && asciiCode<=126)
{
c=(char)asciiCode;
if (c!='x' &&
((c>='a' && c<='z') ||
(c>='A' && c<='Z') ||
(c>='0' && c<='9')))
{
it = myGoodChars.find(c);
if (it == myGoodChars.end())
myGoodChars.insert(make_pair(c, 1)) ;
else
myGoodChars[c]++ ; // to count that char here
}
}
} ;
// if (myGoodChars.find('x') != myGoodChars.end())
// myGoodChars.erase ('x') ;
for (char ch='A'; ch<='Z'; ch++)
{
if (myGoodChars.find(ch) != myGoodChars.end())
for ( ; myGoodChars[ch]-- ; )
cout <<ch;
if (myGoodChars.find((char)(ch+D)) != myGoodChars.end())
for ( ; myGoodChars[(char)(ch+D)]-- ; )
cout <<(char)(ch+D) ;
} ;
for (char ch='1'; ch<='9'; ch++)
{
if (myGoodChars.find(ch) != myGoodChars.end())
for ( ; myGoodChars[ch]-- ; )
cout <<ch;
} ;
if (myGoodChars.find('0') != myGoodChars.end())
for ( ; myGoodChars['0']-- ; )
cout <<'0';
cout <<endl;
return 0;
}
| 24.354839 | 98 | 0.56755 | kilarionov |
26b4326687678413e4bc24225bfcb5071dccddb6 | 6,897 | cpp | C++ | hphp/util/embedded-data.cpp | simonwelsh/hhvm | d4f2f960f29fc66e0ed615b8fa7746a42aafb173 | [
"PHP-3.01",
"Zend-2.0"
] | 1 | 2016-10-08T12:13:09.000Z | 2016-10-08T12:13:09.000Z | hphp/util/embedded-data.cpp | simonwelsh/hhvm | d4f2f960f29fc66e0ed615b8fa7746a42aafb173 | [
"PHP-3.01",
"Zend-2.0"
] | null | null | null | hphp/util/embedded-data.cpp | simonwelsh/hhvm | d4f2f960f29fc66e0ed615b8fa7746a42aafb173 | [
"PHP-3.01",
"Zend-2.0"
] | null | null | null | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/util/embedded-data.h"
#include "hphp/util/current-executable.h"
#include "hphp/util/logger.h"
#include <folly/FileUtil.h>
#include <folly/ScopeGuard.h>
#include <folly/String.h>
#include <folly/portability/Unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <cstdio>
#include <cstring>
#include <dlfcn.h>
#include <fcntl.h>
#include <fstream>
#include <memory>
#include <vector>
#ifdef __APPLE__
#include <mach-o/getsect.h>
#elif defined(_MSC_VER)
#include <windows.h>
#include <winuser.h>
#else
#include <folly/experimental/symbolizer/Elf.h>
#endif
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
namespace {
/*
* /tmp files created by dlopen_embedded_data().
*/
std::vector<std::string> s_tmp_files;
/*
* Lock around accesses to s_tmp_files.
*/
std::mutex s_tmp_files_lock;
}
///////////////////////////////////////////////////////////////////////////////
bool get_embedded_data(const char* section, embedded_data* desc,
const std::string& filename /*= "" */) {
auto const fname = filename.empty() ? current_executable_path() : filename;
#ifdef _MSC_VER
HMODULE moduleHandle = GetModuleHandleA(fname.data());
HGLOBAL loadedResource;
HRSRC resourceInfo;
DWORD resourceSize;
resourceInfo = FindResource(moduleHandle, section, RT_RCDATA);
if (!resourceInfo) {
return false;
}
loadedResource = LoadResource(moduleHandle, resourceInfo);
if (!loadedResource) {
return false;
}
resourceSize = SizeofResource(moduleHandle, resourceInfo);
desc->m_filename = fname;
desc->m_handle = loadedResource;
desc->m_len = resourceSize;
return true;
#elif !defined(__APPLE__) // LINUX/ELF
folly::symbolizer::ElfFile file;
if (file.openNoThrow(fname.c_str()) != 0) return false;
auto const shdr = file.getSectionByName(section);
if (shdr == nullptr) return false;
desc->m_filename = fname;
desc->m_start = shdr->sh_offset;
desc->m_len = shdr->sh_size;
return true;
#else // __APPLE__
const struct section_64 *sect = getsectbyname("__text", section);
if (sect) {
desc->m_filename = fname;
desc->m_start = sect->offset;
desc->m_len = sect->size;
return !desc->m_filename.empty();
}
#endif // __APPLE__
return false;
}
#ifdef _MSC_VER
std::string read_embedded_data(const embedded_data& desc) {
return std::string((const char*)LockResource(desc.m_handle), desc.m_len);
}
void* dlopen_embedded_data(const embedded_data&, char*) {
return nullptr;
}
#else
std::string read_embedded_data(const embedded_data& desc) {
std::ifstream ifs(desc.m_filename);
if (!ifs.good()) return "";
ifs.seekg(desc.m_start, std::ios::beg);
std::unique_ptr<char[]> data(new char[desc.m_len]);
ifs.read(data.get(), desc.m_len);
return std::string(data.get(), desc.m_len);
}
void* dlopen_embedded_data(const embedded_data& desc, char* tmp_filename) {
auto const source_file = ::open(desc.m_filename.c_str(), O_RDONLY);
if (source_file < 0) {
Logger::Error("dlopen_embedded_data: Unable to open '%s': %s",
desc.m_filename.c_str(), folly::errnoStr(errno).c_str());
return nullptr;
}
SCOPE_EXIT { ::close(source_file); };
if (::lseek(source_file, desc.m_start, SEEK_SET) < 0) {
Logger::Error("dlopen_embedded_data: Unable to seek to section: %s",
folly::errnoStr(errno).c_str());
return nullptr;
}
auto const dest_file = ::mkstemp(tmp_filename);
if (dest_file < 0) {
Logger::Error("dlopen_embedded_data: Unable to create temporary file: %s",
folly::errnoStr(errno).c_str());
return nullptr;
}
{ // We don't unlink these files here because doing so can cause gdb to
// segfault or fail in other mysterious ways. Some bug reports suggest
// that to work around this, we need to use some sort of JIT extension
// live, which we don't want to do:
// - https://sourceware.org/ml/gdb-prs/2014-q1/msg00178.html
// - https://gcc.gnu.org/bugzilla/show_bug.cgi?id=64206
//
// So instead, we just hope that HHVM shuts down gracefully and that when
// it doesn't, some external job will clear /tmp out for us.
std::lock_guard<std::mutex> l(s_tmp_files_lock);
s_tmp_files.push_back(tmp_filename);
}
SCOPE_EXIT { ::close(dest_file); };
char buffer[64*1024];
std::size_t to_read = desc.m_len;
while (to_read > 0) {
auto const read = folly::readNoInt(source_file, buffer,
std::min(sizeof(buffer), to_read));
if (read <= 0) {
Logger::Error("dlopen_embedded_data: Error reading from section: %s",
folly::errnoStr(errno).c_str());
return nullptr;
}
if (folly::writeFull(dest_file, buffer, read) <= 0) {
Logger::Error("dlopen_embedded_data: Error writing to temporary file: %s",
folly::errnoStr(errno).c_str());
return nullptr;
}
to_read -= read;
}
// Finished copying the file; now load it.
auto const handle = dlopen(tmp_filename, RTLD_NOW);
if (!handle) {
Logger::Error("dlopen_embedded_data: dlopen failed: %s", dlerror());
return nullptr;
}
return handle;
}
#endif
void embedded_data_cleanup() {
std::lock_guard<std::mutex> l(s_tmp_files_lock);
for (auto const& filename : s_tmp_files) {
::unlink(filename.c_str());
}
}
///////////////////////////////////////////////////////////////////////////////
extern "C" {
ssize_t hphp_read_embedded_data(const char* section, char* buf, size_t len) {
embedded_data data;
if (get_embedded_data(section, &data)) {
auto str = read_embedded_data(data);
auto data_len = str.length();
auto real_len = data_len < len ? data_len : len;
memcpy(buf, str.data(), real_len * sizeof(char));
return real_len;
} else {
return -1;
}
}
}
} // namespace HPHP
| 29.857143 | 80 | 0.605046 | simonwelsh |
26b5a05d6e863f6b2dd1301fd01f508c7480d495 | 9,733 | cc | C++ | cc/chart/v3/grid-test.cc | skepner/ae | d53336a561df1a46a39debb143c9f9496b222a46 | [
"MIT"
] | null | null | null | cc/chart/v3/grid-test.cc | skepner/ae | d53336a561df1a46a39debb143c9f9496b222a46 | [
"MIT"
] | null | null | null | cc/chart/v3/grid-test.cc | skepner/ae | d53336a561df1a46a39debb143c9f9496b222a46 | [
"MIT"
] | null | null | null | #include "ext/omp.hh"
#include "chart/v3/grid-test.hh"
#include "chart/v3/chart.hh"
#include "chart/v3/stress.hh"
#include "chart/v3/area.hh"
// ----------------------------------------------------------------------
namespace ae::chart::v3::grid_test
{
static void test(result_t& result, const Projection& projection, const Stress& stress, const settings_t& settings);
static Area area_for(const Stress::TableDistancesForPoint& table_distances_for_point, const Layout& layout);
}
// ----------------------------------------------------------------------
ae::chart::v3::grid_test::results_t ae::chart::v3::grid_test::test(const Chart& chart, projection_index projection_no, const settings_t& settings)
{
const auto& projection = chart.projections()[projection_no];
results_t results(projection);
const auto stress = stress_factory(chart, projection, optimization_options{}.mult);
#ifdef _OPENMP
const int num_threads = settings.threads <= 0 ? omp_get_max_threads() : settings.threads;
const int slot_size = chart.antigens().size() < antigen_index{1000} ? 4 : 1;
#endif
#pragma omp parallel for default(shared) num_threads(num_threads) schedule(static, slot_size)
for (size_t entry_no = 0; entry_no < results.size(); ++entry_no)
test(results[entry_no], projection, stress, settings);
return results;
} // ae::chart::v3::grid_test::test
// ----------------------------------------------------------------------
void ae::chart::v3::grid_test::test(result_t& result, const Projection& projection, const Stress& stress, const settings_t& settings)
{
if (result.diagnosis == result_t::not_tested) {
const double hemisphering_distance_threshold = 1.0; // from acmacs-c2 hemi-local test: 1.0
const double hemisphering_stress_threshold = 0.25; // stress diff within threshold -> hemisphering, from acmacs-c2 hemi-local test: 0.25
const optimization_options options;
const auto table_distances_for_point = stress.table_distances_for(result.point_no);
if (table_distances_for_point.empty()) { // no table distances, cannot test
result.diagnosis = result_t::excluded;
return;
}
result.diagnosis = result_t::normal;
Layout layout{projection.layout()};
const auto target_contribution = stress.contribution(result.point_no, table_distances_for_point, layout);
const point_coordinates original_pos{layout[result.point_no]};
auto best_contribution = target_contribution;
point_coordinates best_coord, hemisphering_coord;
const auto hemisphering_stress_thresholdrough = hemisphering_stress_threshold * 2;
auto hemisphering_contribution = target_contribution + hemisphering_stress_thresholdrough;
const auto area = area_for(table_distances_for_point, layout);
for (auto it = area.begin(settings.step), last = area.end(); it != last; ++it) {
// AD_DEBUG("grid_test iter {}", *it);
layout.update(result.point_no, *it);
const auto contribution = stress.contribution(result.point_no, table_distances_for_point, layout);
if (contribution < best_contribution) {
best_contribution = contribution;
best_coord = *it;
}
else if (!best_coord.exists() && contribution < hemisphering_contribution && distance(original_pos, *it) > hemisphering_distance_threshold) {
hemisphering_contribution = contribution;
hemisphering_coord = *it;
}
}
if (best_coord.exists()) {
layout.update(result.point_no, best_coord);
const auto status = optimize(options.method, stress, layout.span(), optimization_precision::rough);
result.pos = layout[result.point_no];
result.distance = distance(original_pos, result.pos);
result.contribution_diff = status.final_stress - projection.stress();
result.diagnosis = std::abs(result.contribution_diff) > hemisphering_stress_threshold ? result_t::trapped : result_t::hemisphering;
}
else if (hemisphering_coord.exists()) {
// relax to find real contribution
layout.update(result.point_no, hemisphering_coord);
auto status = optimize(options.method, stress, layout.span(), optimization_precision::rough);
result.pos = layout[result.point_no];
result.distance = distance(original_pos, result.pos);
if (result.distance > hemisphering_distance_threshold && result.distance < (hemisphering_distance_threshold * 1.2)) {
status = optimize(options.method, stress, layout.span(), optimization_precision::fine);
result.pos = layout[result.point_no];
result.distance = distance(original_pos, result.pos);
}
result.contribution_diff = status.final_stress - projection.stress();
if (result.distance > hemisphering_distance_threshold) {
// if (const auto real_contribution_diff = stress.contribution(result.point_no, table_distances_for_point, layout.data()) - target_contribution;
// real_contribution_diff < hemisphering_stress_threshold) {
if (std::abs(result.contribution_diff) < hemisphering_stress_threshold) {
// result.contribution_diff = real_contribution_diff;
result.diagnosis = result_t::hemisphering;
}
}
}
// AD_DEBUG("GridTest {} area: {:8.1f} units^{} grid-step: {:5.3f}", result.report(chart_), area.area(), area.num_dim(), grid_step_);
}
} // ae::chart::v3::grid_test::test
// ----------------------------------------------------------------------
ae::chart::v3::Area ae::chart::v3::grid_test::area_for(const Stress::TableDistancesForPoint& table_distances_for_point, const Layout& layout)
{
point_index another_point;
if (!table_distances_for_point.regular.empty())
another_point = table_distances_for_point.regular.front().another_point;
else if (!table_distances_for_point.less_than.empty())
another_point = table_distances_for_point.less_than.front().another_point;
else
throw std::runtime_error("ae::chart::v3::grid_test::::area_for: table_distances_for_point has neither regulr nor less_than entries");
Area area(layout[another_point]);
auto extend = [&area, &layout](const auto& entry) {
const auto coord = layout[entry.another_point];
const auto radius = entry.distance; // + 1;
area.extend(coord - radius);
area.extend(coord + radius);
};
std::for_each(table_distances_for_point.regular.begin(), table_distances_for_point.regular.end(), extend);
std::for_each(table_distances_for_point.less_than.begin(), table_distances_for_point.less_than.end(), extend);
return area;
} // ae::chart::v3::grid_test::area_for
// ----------------------------------------------------------------------
ae::chart::v3::grid_test::results_t::results_t(const Projection& projection)
: data_(*projection.number_of_points(), result_t{point_index{0}, projection.number_of_dimensions()})
{
point_index point_no{0};
for (auto& res : data_)
res.point_no = point_no++;
exclude_disconnected(projection);
} // ae::chart::v3::grid_test::results_t::results_t
// ----------------------------------------------------------------------
void ae::chart::v3::grid_test::results_t::exclude_disconnected(const Projection& projection)
{
const auto exclude = [this](point_index point_no) {
if (auto* found = find(point_no); found)
found->diagnosis = result_t::excluded;
};
for (auto unmovable : projection.unmovable())
exclude(unmovable);
for (auto disconnected : projection.disconnected())
exclude(disconnected);
data_.erase(std::remove_if(data_.begin(), data_.end(), [](const auto& entry) { return entry.diagnosis == result_t::excluded; }), data_.end());
} // ae::chart::v3::grid_test::results_t::exclude_disconnected
// ----------------------------------------------------------------------
ae::chart::v3::grid_test::result_t* ae::chart::v3::grid_test::results_t::find(point_index point_no)
{
if (const auto found = std::find_if(data_.begin(), data_.end(), [point_no](const auto& en) { return en.point_no == point_no; }); found != data_.end())
return &*found;
else
return nullptr;
} // ae::chart::v3::grid_test::results_t::find
// ----------------------------------------------------------------------
std::vector<ae::chart::v3::grid_test::result_t> ae::chart::v3::grid_test::results_t::trapped_hemisphering() const
{
std::vector<result_t> th;
for (const auto& en : data_) {
if (en.diagnosis == result_t::trapped || en.diagnosis == result_t::hemisphering)
th.push_back(en);
}
return th;
} // ae::chart::v3::grid_test::trapped_hemisphering
// ----------------------------------------------------------------------
void ae::chart::v3::grid_test::results_t::apply(Layout& layout) const
{
for (const auto& result : data_) {
if (result.pos.exists() && result.contribution_diff < 0.0)
layout.update(result.point_no, result.pos);
}
} // ae::chart::v3::grid_test::results_t::apply
// ----------------------------------------------------------------------
void ae::chart::v3::grid_test::results_t::apply(Projection& projection) const // move points to their better locations
{
apply(projection.layout());
} // ae::chart::v3::grid_test::results_t::apply
// ----------------------------------------------------------------------
| 47.710784 | 160 | 0.624062 | skepner |
26b6b9f70aa3b5219751fdafead728446179389b | 1,813 | cpp | C++ | applications/MultilevelMonteCarloApplication/custom_python/add_custom_strategies_to_python.cpp | clazaro/Kratos | b947b82c90dfcbf13d60511427f85990d36b90be | [
"BSD-4-Clause"
] | 778 | 2017-01-27T16:29:17.000Z | 2022-03-30T03:01:51.000Z | applications/MultilevelMonteCarloApplication/custom_python/add_custom_strategies_to_python.cpp | clazaro/Kratos | b947b82c90dfcbf13d60511427f85990d36b90be | [
"BSD-4-Clause"
] | 6,634 | 2017-01-15T22:56:13.000Z | 2022-03-31T15:03:36.000Z | applications/MultilevelMonteCarloApplication/custom_python/add_custom_strategies_to_python.cpp | clazaro/Kratos | b947b82c90dfcbf13d60511427f85990d36b90be | [
"BSD-4-Clause"
] | 224 | 2017-02-07T14:12:49.000Z | 2022-03-06T23:09:34.000Z | // | / |
// ' / __| _` | __| _ \ __|
// . \ | ( | | ( |\__ `
// _|\_\_| \__,_|\__|\___/ ____/
// Multi-Physics
//
// License: BSD License
// Kratos default license: kratos/license.txt
//
// Main authors: Riccardo Tosi
//
// System includes
// External includes
#include <pybind11/pybind11.h>
// Project includes
#include "includes/define_python.h"
#include "custom_python/add_custom_strategies_to_python.h"
#include "spaces/ublas_space.h"
//strategies
#include "solving_strategies/strategies/implicit_solving_strategy.h"
//linear solvers
#include "linear_solvers/linear_solver.h"
namespace Kratos {
namespace Python {
void AddCustomStrategiesToPython(pybind11::module& m)
{
namespace py = pybind11;
typedef UblasSpace<double, CompressedMatrix, Vector> SparseSpaceType;
typedef UblasSpace<double, Matrix, Vector> LocalSpaceType;
typedef LinearSolver<SparseSpaceType, LocalSpaceType > LinearSolverType;
typedef ImplicitSolvingStrategy< SparseSpaceType, LocalSpaceType, LinearSolverType > BaseSolvingStrategyType;
typedef Scheme< SparseSpaceType, LocalSpaceType > BaseSchemeType;
//********************************************************************
//********************************************************************
// py::class_< TestStrategy< SparseSpaceType, LocalSpaceType, LinearSolverType>,
// TestStrategy< SparseSpaceType, LocalSpaceType, LinearSolverType>::Pointer,
// BaseSolvingStrategyType>(m, "TestStrategy")
// .def(py::init<ModelPart&, LinearSolverType::Pointer, int, int, bool >() )
// .def("MoveNodes",&TestStrategy< SparseSpaceType, LocalSpaceType, LinearSolverType >::MoveNodes)
// ;
}
} // namespace Python.
} // Namespace Kratos
| 29.721311 | 113 | 0.635962 | clazaro |
26b8d7ce0bad5125fa05a5e446346c0c7481f98a | 3,053 | cpp | C++ | decrypt/decryptor.cpp | NunoEdgarGFlowHub/SRVB-Cryptography | 631dea89f712bbecf8be2cae268314c21a011160 | [
"MIT"
] | null | null | null | decrypt/decryptor.cpp | NunoEdgarGFlowHub/SRVB-Cryptography | 631dea89f712bbecf8be2cae268314c21a011160 | [
"MIT"
] | null | null | null | decrypt/decryptor.cpp | NunoEdgarGFlowHub/SRVB-Cryptography | 631dea89f712bbecf8be2cae268314c21a011160 | [
"MIT"
] | null | null | null | #if !defined(__DECRYPTOR_CPP__)
#define __DECRYPTOR_CPP__
#include "decryptor.hpp"
#include <fstream>
#include <string>
#include <sstream>
Decryptor::Decryptor(const std::string& file_name) :
_pri_k(),
_key_name(file_name.substr(0,file_name.find('.')))
{
YSVB_TIMED_PUT("BUILDING DECRYPTOR OBJECT")
std::ifstream key_file(file_name);
key_file >> _pri_k;
YSVB_TIMED_PUT("DECRYPTOR OBJECT BUILDING COMPLETE")
}
/*
WARNING: THERE IS ONE CASE IN WICH THIS ALGORITHM FAILS. NAMELY A FILE WITH 0 BYTES.
*/
Decryptor::~Decryptor() {}
void Decryptor::decrypt(
const std::string input_file_name,
const std::string decryptet_file_name
) const {
YSVB_TIMED_PUT("BEGINNING SRVB DECRYPTION")
std::ifstream in(input_file_name);
std::ofstream out;
if (decryptet_file_name == default_output_file_name_flag() ) {
out.open(input_file_name.substr(0, input_file_name.find('_')), std::ios::binary | std::ios::out);
} else {
out.open(decryptet_file_name, std::ios::binary | std::ios::out);
}
if (in.good() && out.good()) {
t_meta_int N = (_pri_k.g_k() * _pri_k.g_m() - _pri_k.g_p()) / 8, i = N-1;
char lbb, lb, lf; //last block's byte, last byte, loop flag
std::stringstream last_block_str_stream;
char last_block_c_str[N];
char SAMPLE_FILE_BYTE, SAMPLE_PADDING_BYTE;
t_meta_int ENCRYPTING_BLOCK_NUMBER;
t_public_msg public_node_buffer(_pri_k.g_k()+1);
t_private_data buffer(_pri_k.g_k() * _pri_k.g_m(), _pri_k.g_k() * _pri_k.g_m() - _pri_k.g_p());
in.close();
in.open(input_file_name);
for (
in >> public_node_buffer, lf = 1, ENCRYPTING_BLOCK_NUMBER = 0;
lf;
ENCRYPTING_BLOCK_NUMBER++
) {
YSVB_TIMED_SHOW(ENCRYPTING_BLOCK_NUMBER)
*(static_cast<std::vector<bool> *>(&buffer)) = _pri_k.decode(public_node_buffer);
buffer.padding_hash();
in >> public_node_buffer;
if (!in) {
YSVB_CHECK_1(in.gcount(), ==, 0, "encrypted file must have an integer number of blocks, and nothing more but its header")
for (
lb = buffer.get_byte(buffer.set_size(buffer.get_size() - 8));
lb != (buffer.get_size()>0?buffer.get_byte(buffer.get_size() - 8):lbb) &&
buffer.get_size() >= 0;
buffer.less_eight(),
lb = (buffer.get_size()>0?buffer.get_byte(buffer.get_size()):lbb)
) {}
YSVB_CHECK_2(buffer.get_size(), >=, 0, buffer.get_size(), ==, -8, "Size must be multiple of 8 and the last byte of one before last block is the only possible end byte if it is not one of the last block's.")
YSVB_CHECK_1(lf, ==, 1, "it must be 1 until here")
lf = 0;
} else {
lbb = buffer.get_byte(buffer.get_size()-8);
}
#if defined(__SHOW__)
SAMPLE_FILE_BYTE = buffer.get_byte(0);
YSVB_TIMED_SHOW(SAMPLE_FILE_BYTE)
SAMPLE_PADDING_BYTE = buffer.get_byte(buffer.get_size());
YSVB_TIMED_SHOW(SAMPLE_PADDING_BYTE)
#endif
out << buffer;
}
YSVB_TIMED_PUT("CLOSING FILES")
in.close();
out.close();
YSVB_TIMED_PUT("SRVB ENCRYPTION FINISHED")
} else {
YSVB_TIMED_PUT("ERROR: COULD NOT ACCESS FILE TO BE DECRYPTED")
}
}
#endif | 33.184783 | 210 | 0.691451 | NunoEdgarGFlowHub |
26bb2b988cc1c098f20659b0d69cc4e9be331446 | 2,454 | cpp | C++ | tech/Game/DebugMeshRenderStep.cpp | nbtdev/teardrop | fa9cc8faba03a901d1d14f655a04167e14cd08ee | [
"MIT"
] | null | null | null | tech/Game/DebugMeshRenderStep.cpp | nbtdev/teardrop | fa9cc8faba03a901d1d14f655a04167e14cd08ee | [
"MIT"
] | null | null | null | tech/Game/DebugMeshRenderStep.cpp | nbtdev/teardrop | fa9cc8faba03a901d1d14f655a04167e14cd08ee | [
"MIT"
] | null | null | null | /******************************************************************************
Copyright (c) 2015 Teardrop Games
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 "DebugMeshRenderStep.h"
#include "Component_Physics.h"
#include "ZoneObject.h"
#include "Gfx/Renderer.h"
#include "Gfx/Viewport.h"
#include "Gfx/RenderTarget.h"
using namespace Teardrop;
//---------------------------------------------------------------------------
DebugMeshRenderStep::DebugMeshRenderStep()
{
m_bEnabled = false;
}
//---------------------------------------------------------------------------
DebugMeshRenderStep::~DebugMeshRenderStep()
{
}
//---------------------------------------------------------------------------
void DebugMeshRenderStep::render(
const VisibleObjects& objects, Gfx::Renderer* pRenderer, Scene* /*pScene*/)
{
if (!m_bEnabled)
return;
// since we are rendering into a scene that is already set up with the proper
// camera and viewport, we do not need beginScene() here; endScene() however
// is what actually renders so we want that
for (size_t i=0; i<objects.size(); ++i)
{
ZoneObject* pObject = objects[i];
PhysicsComponent* pComp;
if (!pObject->findComponents(PhysicsComponent::getClassDef(), (Component**)&pComp,1, true))
continue;
// allow dynamic updates to meshes
// pRenderer->queueForRendering(pComp->getDebugMesh());
}
pRenderer->endScene();
}
| 37.753846 | 93 | 0.645884 | nbtdev |
26bc26648f90f85257140905192ca7b2dbd91cb4 | 2,026 | cpp | C++ | example/miniping.cpp | oskarirauta/pingcpp | f521de4d024d644cefc88e115b5c8457ecc900bf | [
"MIT"
] | null | null | null | example/miniping.cpp | oskarirauta/pingcpp | f521de4d024d644cefc88e115b5c8457ecc900bf | [
"MIT"
] | null | null | null | example/miniping.cpp | oskarirauta/pingcpp | f521de4d024d644cefc88e115b5c8457ecc900bf | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include "example/report.hpp"
#include "network.hpp"
#include "ping.hpp"
#define PING_HOST "google.com"
#ifdef __IPV6__
# define TITLE "miniping(+IPV6), by Oskari Rauta\nMIT License\n"
#else
# define TITLE "miniping, by Oskari Rauta\nMIT License\n"
#endif
int main(int argc, char *argv[]) {
std::cout << TITLE << std::endl;
std::string arg = argc > 1 ? std::string(argv[1]) : "";
network::protocol proto =
arg == "-6" ? network::protocol::IPV6 :
( arg == "-4" ? network::protocol::IPV4 :
network::protocol::ANY );
std::string host = PING_HOST;
std::cout << TITLE << std::endl;
std::cout << "Attempting to ping host " << host << " using ";
std::cout << ( proto == network::protocol::IPV6 ? "IPv6" : (
proto == network::protocol::IPV4 ? "IPv4" : "ANY" ));
std::cout << " protocol" << std::endl;
network::ping_t ping(host, proto);
if ( ping.connection -> protocol == network::protocol::ANY ) {
std::cout << "error: IP address failure, or unsupported protocol for host " << host << std::endl;
return -1;
} else if ( ping.address_error()) {
std::cout << "error: address information for host " << host << " is not available" << std::endl;
return -1;
}
ping.packetsize = 56; // standard icmp packet size
ping.delay = std::chrono::milliseconds(500);
ping.timeout = std::chrono::seconds(15);
ping.count_min = 10;
ping.count_max = 99;
ping.report = report;
std::cout << "Host's ip address is " << ping.connection -> ipaddr << " on ";
std::cout << ( ping.connection -> protocol == network::protocol::IPV6 ? "IPv6" : "IPv4" );
std::cout << " network.\nICMP packet size: " << ping.packetsize << " bytes +";
std::cout << "\n\ticmp header size " << ICMP_HEADER_LENGTH << " bytes = ";
std::cout << ping.packetsize + ICMP_HEADER_LENGTH << " bytes\n";
std::cout << std::endl;
ping.execute();
std::cout << std::endl;
if ( ping.summary -> aborted ) std::cout << "Exited because of error" << std::endl;
return ping.summary -> aborted ? -1 : 0;
}
| 31.169231 | 99 | 0.631787 | oskarirauta |
26bc382621bcfec8958270649fd407da9b245e72 | 2,807 | hpp | C++ | Extensions/Gameplay/SplineParticles.hpp | RachelWilSingh/ZeroCore | e9a2f82d395e5c89fb98eceac44ce60d016dbff3 | [
"MIT"
] | 52 | 2018-09-11T17:18:35.000Z | 2022-03-13T15:28:21.000Z | Extensions/Gameplay/SplineParticles.hpp | RachelWilSingh/ZeroCore | e9a2f82d395e5c89fb98eceac44ce60d016dbff3 | [
"MIT"
] | 1,409 | 2018-09-19T18:03:43.000Z | 2021-06-09T08:33:33.000Z | Extensions/Gameplay/SplineParticles.hpp | RachelWilSingh/ZeroCore | e9a2f82d395e5c89fb98eceac44ce60d016dbff3 | [
"MIT"
] | 26 | 2018-09-11T17:16:32.000Z | 2021-11-22T06:21:19.000Z | ///////////////////////////////////////////////////////////////////////////////
///
/// \file ParticleEmitters.hpp
/// Declaration of the Particle emitters.
///
/// Authors: Chris Peters
/// Copyright 2010-2012, DigiPen Institute of Technology
///
///////////////////////////////////////////////////////////////////////////////
#pragma once
namespace Zero
{
//------------------------------------------------------ Spline Particle Emitter
class SplineParticleEmitter : public ParticleEmitterShared
{
public:
/// Meta Initialization.
ZilchDeclareType(TypeCopyMode::ReferenceType);
/// Component Interface.
void Serialize(Serializer& stream) override;
void Initialize(CogInitializer& initializer) override;
void OnAllObjectsCreated(CogInitializer& initializer) override;
void OnTargetSplineCogPathChanged(Event* e);
void FindSpline();
/// ParticleEmitter Interface.
int EmitParticles(ParticleList* particleList, float dt,
Mat4Ref transform, Vec3Param velocity, float timeAlive) override;
/// The current spline being emitted along
Spline* GetSpline() const;
void SetSpline(Spline* spline);
/// Path to an object to query for a spline
CogPath mTargetSplineCog;
/// Particles will be created along this spline
HandleOf<Spline> mSpline;
float mEmitRadius;
float mSpawnT, mSpawnTVariance;
bool mClampT;
};
//----------------------------------------------------- Spline Particle Animator
DeclareEnum2(SplineAnimatorMode, Exact, Spring);
class SplineParticleAnimator : public ParticleAnimator
{
public:
/// Meta Initialization.
ZilchDeclareType(TypeCopyMode::ReferenceType);
~SplineParticleAnimator();
/// Component Interface.
void Serialize(Serializer& stream) override;
void Initialize(CogInitializer& initializer) override;
/// ParticleAnimator Interface.
void Animate(ParticleList* particleList, float dt, Mat4Ref transform) override;
/// Speed setter / getter.
void SetSpeed(float speed);
float GetSpeed();
///
SplineParticleEmitter* mEmitter;
/// The speed at which the particles move in meters / second.
float mSpeed;
/// If checked, the lifetime on the SplineParticleEmitter will be updated
/// to the time it would take to travel the entire path at the current speed.
bool mAutoCalculateLifetime;
bool mHelix;
/// The radius of the helix.
float mHelixRadius;
/// How fast the helix rotates in radians / second.
float mHelixWaveLength;
/// Offset in radians for where the helix starts.
float mHelixOffset;
/// The current animate mode.
SplineAnimatorMode::Enum mMode;
/// Spring properties.
float mSpringFrequencyHz;
float mSpringDampingRatio;
};
}//namespace Zero
| 28.353535 | 86 | 0.646242 | RachelWilSingh |
26bfb69c0adfc8d5e94b03e09915e26d9ead7a9b | 4,603 | cc | C++ | crc32.cc | bisqwit/viewnes | 57a06b36b7a599e976a20459cb929786d506b84b | [
"Zlib"
] | 12 | 2017-04-27T18:50:31.000Z | 2022-02-18T04:13:13.000Z | crc32.cc | bisqwit/viewnes | 57a06b36b7a599e976a20459cb929786d506b84b | [
"Zlib"
] | null | null | null | crc32.cc | bisqwit/viewnes | 57a06b36b7a599e976a20459cb929786d506b84b | [
"Zlib"
] | 3 | 2017-04-28T13:23:23.000Z | 2020-05-15T10:56:11.000Z | /*** CRC32 calculation (CRC::update) ***/
#include "crc32.h"
#ifdef __GNUC__
# define likely(x) __builtin_expect(!!(x), 1)
# define unlikely(x) __builtin_expect(!!(x), 0)
#else
# define likely(x) (x)
# define unlikely(x) (x)
#endif
namespace {
/* This code constructs the CRC32 table at compile-time,
* avoiding the need for a huge explicitly written table of magical numbers. */
static const uint_least32_t crc32_poly = 0xEDB88320UL;
/*
template<uint_fast32_t crc> // One bit of a CRC32:
struct b1 { enum { res = (crc >> 1) ^ (( crc&1) ? crc32_poly : 0UL) }; };
template<uint_fast32_t i> // One byte of a CRC32 (eight bits):
struct b8 { enum { res = b1<b1<b1<b1< b1<b1<b1<b1<i
>::res>::res>::res>::res>::res>::res>::res>::res }; };
*/
template<uint_fast32_t crc> // One byte of a CRC32 (eight bits):
struct b8
{
enum { b1 = (crc & 1) ? (crc32_poly ^ (crc >> 1)) : (crc >> 1),
b2 = (b1 & 1) ? (crc32_poly ^ (b1 >> 1)) : (b1 >> 1),
b3 = (b2 & 1) ? (crc32_poly ^ (b2 >> 1)) : (b2 >> 1),
b4 = (b3 & 1) ? (crc32_poly ^ (b3 >> 1)) : (b3 >> 1),
b5 = (b4 & 1) ? (crc32_poly ^ (b4 >> 1)) : (b4 >> 1),
b6 = (b5 & 1) ? (crc32_poly ^ (b5 >> 1)) : (b5 >> 1),
b7 = (b6 & 1) ? (crc32_poly ^ (b6 >> 1)) : (b6 >> 1),
res= (b7 & 1) ? (crc32_poly ^ (b7 >> 1)) : (b7 >> 1) };
/*
enum { b1 = (crc>> 1) ^ ((crc&1) ? crc32_poly : 0UL),
b2 = (b1 >> 1) ^ (( b1&1) ? crc32_poly : 0UL),
b3 = (b2 >> 1) ^ (( b2&1) ? crc32_poly : 0UL),
b4 = (b3 >> 1) ^ (( b3&1) ? crc32_poly : 0UL),
b5 = (b4 >> 1) ^ (( b4&1) ? crc32_poly : 0UL),
b6 = (b5 >> 1) ^ (( b5&1) ? crc32_poly : 0UL),
b7 = (b6 >> 1) ^ (( b6&1) ? crc32_poly : 0UL),
res= (b7 >> 1) ^ (( b7&1) ? crc32_poly : 0UL),
};*/
};/**/
// Four values of the table
#define B4(n) b8<n>::res,b8<n+1>::res,b8<n+2>::res,b8<n+3>::res
// Sixteen values of the table
#define R(n) B4(n),B4(n+4),B4(n+8),B4(n+12)
// The whole table, index by steps of 16
static const uint_least32_t crctable[256] =
{ R(0x00),R(0x10),R(0x20),R(0x30), R(0x40),R(0x50),R(0x60),R(0x70),
R(0x80),R(0x90),R(0xA0),R(0xB0), R(0xC0),R(0xD0),R(0xE0),R(0xF0) };
#undef R
#undef B4
}
uint_fast32_t crc32_update(uint_fast32_t crc, unsigned/* char */b) // __attribute__((pure))
{
return ((crc >> 8) /* & 0x00FFFFFF*/) ^ crctable[/*(unsigned char)*/(crc^b)&0xFF];
}
crc32_t crc32_calc(const unsigned char* buf, unsigned long size)
{
return crc32_calc_upd(crc32_startvalue, buf, size);
}
crc32_t crc32_calc_upd(crc32_t c, const unsigned char* buf, unsigned long size)
{
uint_fast32_t value = c;
#if 0
unsigned long pos = 0;
while(size-- > 0) value = crc32_update(value, buf[pos++]);
#endif
#if 1
for(unsigned long p=0; p<size; ++p) value = crc32_update(value, buf[p]);
#endif
#if 0
unsigned unaligned_length = (4 - (unsigned long)(buf)) & 3;
if(size < unaligned_length) unaligned_length = size;
switch(unaligned_length)
{
case 3: value = crc32_update(value, *buf++);
case 2: value = crc32_update(value, *buf++);
case 1: value = crc32_update(value, *buf++);
size -= unaligned_length;
case 0: break;
}
for(; size >= 4; size -= 4, buf += 4)
value = crc32_update(
crc32_update(
crc32_update(
crc32_update(value, buf[0]),
buf[1]),
buf[2]),
buf[3]);
switch(size)
{
case 3: value = crc32_update(value, *buf++);
case 2: value = crc32_update(value, *buf++);
case 1: value = crc32_update(value, *buf++);
case 0: break;
}
#endif
#if 0 /* duff's device -- no gains observed over the simple loop above */
if(__builtin_expect( (size!=0), 1l ))
{
{ if(__builtin_expect( !(size&1), 1l )) goto case_0;
--buf; goto case_1;
}
//switch(size % 2)
{
//default:
do { size -= 2; buf += 2;
case_0: value = crc32_update(value, buf[0]);
case_1: value = crc32_update(value, buf[1]);
} while(size > 2);
}
}
#endif
#if 0
while(size-- > 0) value = crc32_update(value, *buf++);
#endif
return value;
}
| 35.137405 | 91 | 0.499022 | bisqwit |
26c0ab11e8a0f7adf9ac4038fc44c7d6120e7d7f | 232 | hxx | C++ | src/sdp_solve.hxx | ChrisPattison/sdpb | 4668f72c935e7feba705dd8247d9aacb23185f1c | [
"MIT"
] | 45 | 2015-02-10T15:45:22.000Z | 2022-02-24T07:45:01.000Z | src/sdp_solve.hxx | ChrisPattison/sdpb | 4668f72c935e7feba705dd8247d9aacb23185f1c | [
"MIT"
] | 58 | 2015-02-27T10:03:18.000Z | 2021-08-10T04:21:42.000Z | src/sdp_solve.hxx | ChrisPattison/sdpb | 4668f72c935e7feba705dd8247d9aacb23185f1c | [
"MIT"
] | 38 | 2015-02-10T11:11:27.000Z | 2022-02-11T20:59:42.000Z | #pragma once
#include "sdp_solve/Block_Info.hxx"
#include "sdp_solve/SDP_Solver.hxx"
#include "sdp_solve/Write_Solution.hxx"
#include "sdp_solve/read_text_block.hxx"
El::BigFloat dot(const Block_Vector &A, const Block_Vector &B);
| 25.777778 | 63 | 0.793103 | ChrisPattison |
26c11d4769736abe92dd9be916a8e4c5fe2ca2b3 | 815 | cpp | C++ | week4_divide_and_conquer/2_majority_element/majority_element.cpp | balajimohan80/Algorithm_Toolbox | e10e5ed811e2d5179d760e25ca82c29df2a879db | [
"MIT"
] | null | null | null | week4_divide_and_conquer/2_majority_element/majority_element.cpp | balajimohan80/Algorithm_Toolbox | e10e5ed811e2d5179d760e25ca82c29df2a879db | [
"MIT"
] | null | null | null | week4_divide_and_conquer/2_majority_element/majority_element.cpp | balajimohan80/Algorithm_Toolbox | e10e5ed811e2d5179d760e25ca82c29df2a879db | [
"MIT"
] | null | null | null | #include <algorithm>
#include <iostream>
#include <vector>
using std::vector;
int get_majority_element(vector<int> &a, int left, int right) {
if (left == right) return -1;
if (left+1 == right) return -1;
//if (left + 1 == right) return a[left];
//write your code here
std::sort(a.begin(), a.end(), [](int a, int b) {return a < b; });
int Mid = a.size() >> 1;
int Count = 0;
while (Mid-1 >= 0 && a[Mid] == a[Mid-1]) {
++Count;
--Mid;
}
Mid = a.size() >> 1;
while (Mid + 1 < a.size() && a[Mid] == a[Mid + 1]) {
++Count;
++Mid;
}
return (Count >= (a.size() >> 1)) ? 1 : -1;
}
int main() {
int n;
std::cin >> n;
vector<int> a(n);
for (size_t i = 0; i < a.size(); ++i) {
std::cin >> a[i];
}
std::cout << (get_majority_element(a, 0, a.size()) != -1) << '\n';
}
| 20.897436 | 68 | 0.507975 | balajimohan80 |
26c78b77ce1bb48d251db287731d261b49d6d024 | 1,025 | hpp | C++ | include/core/initialization.hpp | ida-zrt/thermalvis | 36a6ba0d12ab91097435630586e3eb760130582c | [
"BSD-3-Clause"
] | 109 | 2015-02-03T23:30:59.000Z | 2022-02-22T03:24:36.000Z | include/core/initialization.hpp | adaniy/thermalvis | 782f71b5fbde033d226d11b8d0c994fc83d10d98 | [
"BSD-3-Clause"
] | 9 | 2015-02-19T05:46:36.000Z | 2021-11-02T14:00:49.000Z | include/core/initialization.hpp | adaniy/thermalvis | 782f71b5fbde033d226d11b8d0c994fc83d10d98 | [
"BSD-3-Clause"
] | 59 | 2015-11-05T11:51:55.000Z | 2022-03-11T06:36:57.000Z | /*! \file initialization.hpp
* \brief (probably an obsolete file)
*/
#ifndef _THERMALVIS_INITIALIZATION_H_
#define _THERMALVIS_INITIALIZATION_H_
#ifdef _BUILD_FOR_ROS_
#include "core/general_resources.hpp"
#include "core/ros_resources.hpp"
#include "core/features.hpp"
#define MAXIMUM_FRAMES_TO_STORE 2000 // careful about setting this too high for memory
#define MAXIMUM_FEATURES_PER_DETECTOR 5000
#define DEFAULT_MAX_FRAMES 100
/// \brief (probably obsolete..)
struct initializationData {
string video_stream;
int max_frame_count;
bool debugMode;
string detector[MAX_DETECTORS], descriptor[MAX_DETECTORS];
double sensitivity[MAX_DETECTORS];
string method[MAX_DETECTORS];
bool method_match[MAX_DETECTORS];
unsigned int numDetectors;
string intrinsics;
bool obtainStartingData(ros::NodeHandle& nh);
void initializeDetectors(cv::Ptr<cv::FeatureDetector> *det);
void initializeDescriptors(cv::Ptr<cv::DescriptorExtractor> *desc);
};
#endif
#endif // _THERMALVIS_INITIALIZATION_H_
| 24.404762 | 88 | 0.782439 | ida-zrt |
26c859b46a25a7d04be90b4f4c2639c50b239922 | 721 | hpp | C++ | header/friedrichdb/fake_file_storage.hpp | jinncrafters/friedrichdb | 313180fee8f230b2a406000b948210c77c4253a3 | [
"BSD-3-Clause"
] | 1 | 2018-01-26T09:15:01.000Z | 2018-01-26T09:15:01.000Z | header/friedrichdb/fake_file_storage.hpp | duckstax/friedrichdb | 313180fee8f230b2a406000b948210c77c4253a3 | [
"BSD-3-Clause"
] | 1 | 2018-06-21T07:41:38.000Z | 2018-06-21T07:41:38.000Z | header/friedrichdb/fake_file_storage.hpp | duckstax/friedrichdb | 313180fee8f230b2a406000b948210c77c4253a3 | [
"BSD-3-Clause"
] | null | null | null | #ifndef FILE_STORAGE_HPP
#define FILE_STORAGE_HPP
#include "abstract_database.hpp"
#include <vector>
#include <functional>
namespace friedrichdb {
class file_storage_fake final : public abstract_database {
public:
file_storage_fake():abstract_database(storge_t::disk){}
~file_storage_fake(){}
abstract_table *table(const std::string &name) {
return nullptr;
}
abstract_table *table(const std::string &name) const {
return nullptr;
}
bool table(const std::string &, abstract_table *) {
return true;
}
bool table(schema&&){
return true;
}
};
}
#endif //VERSIONS_FILE_STORAGE_HPP
| 24.033333 | 63 | 0.619972 | jinncrafters |
26c90714f4d0f01f1fc49c305badaefcfcd4e9f8 | 14,236 | cc | C++ | chrome/browser/metrics/variations/variations_safe_mode_browsertest.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | chrome/browser/metrics/variations/variations_safe_mode_browsertest.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | chrome/browser/metrics/variations/variations_safe_mode_browsertest.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2021 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.
// The tests in this file verify the behavior of variations safe mode. The tests
// should be kept in sync with those in ios/chrome/browser/variations/
// variations_safe_mode_egtest.mm.
#include <string>
#include "base/base_switches.h"
#include "base/containers/contains.h"
#include "base/files/file_util.h"
#include "base/metrics/field_trial.h"
#include "base/path_service.h"
#include "base/ranges/ranges.h"
#include "base/strings/strcat.h"
#include "base/strings/stringprintf.h"
#include "base/test/launcher/test_launcher.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/task_environment.h"
#include "base/test/test_switches.h"
#include "chrome/browser/browser_process.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "components/metrics/clean_exit_beacon.h"
#include "components/metrics/metrics_service.h"
#include "components/prefs/json_pref_store.h"
#include "components/prefs/pref_service.h"
#include "components/prefs/pref_service_factory.h"
#include "components/variations/metrics.h"
#include "components/variations/pref_names.h"
#include "components/variations/service/variations_field_trial_creator.h"
#include "components/variations/service/variations_safe_mode_constants.h"
#include "components/variations/service/variations_service.h"
#include "components/variations/variations_switches.h"
#include "components/variations/variations_test_utils.h"
#include "components/version_info/channel.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/browser_test.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace variations {
class VariationsSafeModeBrowserTest : public InProcessBrowserTest {
public:
VariationsSafeModeBrowserTest() { DisableTestingConfig(); }
~VariationsSafeModeBrowserTest() override = default;
protected:
base::HistogramTester histogram_tester_;
};
IN_PROC_BROWSER_TEST_F(VariationsSafeModeBrowserTest,
PRE_PRE_PRE_ThreeCrashesTriggerSafeMode) {
// The PRE test mechanism is used to set prefs in the local state file before
// the next browser test runs. No InProcessBrowserTest functions allow this
// pref to be set early enough to be read by the variations code, which runs
// very early during startup.
PrefService* local_state = g_browser_process->local_state();
WriteSeedData(local_state, kTestSeedData, kSafeSeedPrefKeys);
SimulateCrash(local_state);
}
IN_PROC_BROWSER_TEST_F(VariationsSafeModeBrowserTest,
PRE_PRE_ThreeCrashesTriggerSafeMode) {
SimulateCrash(g_browser_process->local_state());
}
IN_PROC_BROWSER_TEST_F(VariationsSafeModeBrowserTest,
PRE_ThreeCrashesTriggerSafeMode) {
SimulateCrash(g_browser_process->local_state());
}
IN_PROC_BROWSER_TEST_F(VariationsSafeModeBrowserTest,
ThreeCrashesTriggerSafeMode) {
EXPECT_EQ(g_browser_process->local_state()->GetInteger(
prefs::kVariationsCrashStreak),
3);
histogram_tester_.ExpectUniqueSample("Variations.SafeMode.Streak.Crashes", 3,
1);
// Verify that Chrome fell back to a safe seed, which happens during browser
// test setup.
histogram_tester_.ExpectUniqueSample(
"Variations.SafeMode.LoadSafeSeed.Result", LoadSeedResult::kSuccess, 1);
histogram_tester_.ExpectUniqueSample("Variations.SeedUsage",
SeedUsage::kSafeSeedUsed, 1);
// Verify that |kTestSeedData| has been applied.
EXPECT_TRUE(FieldTrialListHasAllStudiesFrom(kTestSeedData));
}
IN_PROC_BROWSER_TEST_F(VariationsSafeModeBrowserTest,
PRE_FetchFailuresTriggerSafeMode) {
// The PRE test mechanism is used to set prefs in the local state file before
// the next browser test runs. No InProcessBrowserTest functions allow this
// pref to be set early enough to be read by the variations code, which runs
// very early during startup.
PrefService* local_state = g_browser_process->local_state();
local_state->SetInteger(prefs::kVariationsFailedToFetchSeedStreak, 25);
WriteSeedData(local_state, kTestSeedData, kSafeSeedPrefKeys);
}
IN_PROC_BROWSER_TEST_F(VariationsSafeModeBrowserTest,
FetchFailuresTriggerSafeMode) {
histogram_tester_.ExpectUniqueSample(
"Variations.SafeMode.Streak.FetchFailures", 25, 1);
// Verify that Chrome fell back to a safe seed, which happens during browser
// test setup.
histogram_tester_.ExpectUniqueSample(
"Variations.SafeMode.LoadSafeSeed.Result", LoadSeedResult::kSuccess, 1);
histogram_tester_.ExpectUniqueSample("Variations.SeedUsage",
SeedUsage::kSafeSeedUsed, 1);
// Verify that |kTestSeedData| has been applied.
EXPECT_TRUE(FieldTrialListHasAllStudiesFrom(kTestSeedData));
}
IN_PROC_BROWSER_TEST_F(VariationsSafeModeBrowserTest,
PRE_DoNotTriggerSafeMode) {
// The PRE test mechanism is used to set prefs in the local state file before
// the next browser test runs. No InProcessBrowserTest functions allow this
// pref to be set early enough to be read by the variations code, which runs
// very early during startup.
PrefService* local_state = g_browser_process->local_state();
local_state->SetInteger(prefs::kVariationsCrashStreak, 2);
local_state->SetInteger(prefs::kVariationsFailedToFetchSeedStreak, 24);
WriteSeedData(local_state, kTestSeedData, kRegularSeedPrefKeys);
}
IN_PROC_BROWSER_TEST_F(VariationsSafeModeBrowserTest, DoNotTriggerSafeMode) {
histogram_tester_.ExpectUniqueSample("Variations.SafeMode.Streak.Crashes", 2,
1);
histogram_tester_.ExpectUniqueSample(
"Variations.SafeMode.Streak.FetchFailures", 24, 1);
// Verify that Chrome applied the regular seed.
histogram_tester_.ExpectUniqueSample("Variations.SeedLoadResult",
LoadSeedResult::kSuccess, 1);
histogram_tester_.ExpectUniqueSample("Variations.SeedUsage",
SeedUsage::kRegularSeedUsed, 1);
}
// This test code is programmatically launched by the SafeModeEndToEnd
// test below. Its primary purpose is to provide an entry-point by
// which the SafeModeEndToEnd test can cause the Field Trial Setup
// code to be exercised. For some launches, the setup code is expected
// to crash before reaching the test body; the test body simply verifies
// that the test is using the user-data-dir configured on the command-line.
//
// The MANUAL_ prefix prevents the test from running unless explicitly
// invoked.
IN_PROC_BROWSER_TEST_F(VariationsSafeModeBrowserTest, MANUAL_SubTest) {
// Validate that Chrome is running with the user-data-dir specified on the
// command-line.
base::FilePath expected_user_data_dir =
base::CommandLine::ForCurrentProcess()->GetSwitchValuePath(
::switches::kUserDataDir);
base::FilePath actual_user_data_dir;
ASSERT_TRUE(
base::PathService::Get(chrome::DIR_USER_DATA, &actual_user_data_dir));
ASSERT_FALSE(expected_user_data_dir.empty());
ASSERT_FALSE(actual_user_data_dir.empty());
ASSERT_EQ(actual_user_data_dir, expected_user_data_dir);
// If the test makes it this far, then either it's the first run of the
// test, or the safe seed was used.
const int crash_streak = g_browser_process->local_state()->GetInteger(
prefs::kVariationsCrashStreak);
const bool is_first_run = (crash_streak == 0);
const bool safe_seed_was_used =
FieldTrialListHasAllStudiesFrom(kTestSeedData);
EXPECT_NE(is_first_run, safe_seed_was_used) // ==> XOR
<< "crash_streak=" << crash_streak;
}
namespace {
class FieldTrialTest : public ::testing::Test {
public:
void SetUp() override {
::testing::Test::SetUp();
metrics::CleanExitBeacon::SkipCleanShutdownStepsForTesting();
pref_registry_ = base::MakeRefCounted<PrefRegistrySimple>();
metrics::MetricsService::RegisterPrefs(pref_registry_.get());
variations::VariationsService::RegisterPrefs(pref_registry_.get());
base::ScopedAllowBlockingForTesting allow_blocking;
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
user_data_dir_ = temp_dir_.GetPath().AppendASCII("user-data-dir");
local_state_file_ = user_data_dir_.AppendASCII("Local State");
}
protected:
const base::FilePath& user_data_dir() const { return user_data_dir_; }
const base::FilePath& local_state_file() const { return local_state_file_; }
const base::FilePath CopyOfLocalStateFile(int suffix) const {
base::FilePath copy_of_local_state_file = temp_dir_.GetPath().AppendASCII(
base::StringPrintf("local-state-copy-%d.json", suffix));
base::CopyFile(local_state_file(), copy_of_local_state_file);
return copy_of_local_state_file;
}
bool IsSuccessfulSubTestOutput(const std::string& output) {
static const char* const kSubTestSuccessStrings[] = {
"Running 1 test from 1 test suite",
"OK ] VariationsSafeModeBrowserTest.MANUAL_SubTest",
"1 test from VariationsSafeModeBrowserTest",
"1 test from 1 test suite ran",
};
auto is_in_output = [&](const char* s) {
return base::Contains(output, s);
};
return base::ranges::all_of(kSubTestSuccessStrings, is_in_output);
}
bool IsCrashingSubTestOutput(const std::string& output) {
const char* const kSubTestCrashStrings[] = {
"Running 1 test from 1 test suite",
"VariationsSafeModeBrowserTest.MANUAL_SubTest",
"crash_for_testing",
};
auto is_in_output = [&](const char* s) {
return base::Contains(output, s);
};
return base::ranges::all_of(kSubTestCrashStrings, is_in_output);
}
void RunAndExpectSuccessfulSubTest(
const base::CommandLine& sub_test_command) {
std::string output;
base::GetAppOutputAndError(sub_test_command, &output);
EXPECT_TRUE(IsSuccessfulSubTestOutput(output))
<< "Did not find success signals in output:\n"
<< output;
}
void RunAndExpectCrashingSubTest(const base::CommandLine& sub_test_command) {
std::string output;
base::GetAppOutputAndError(sub_test_command, &output);
EXPECT_FALSE(IsSuccessfulSubTestOutput(output))
<< "Expected crash but found success signals in output:\n"
<< output;
EXPECT_TRUE(IsCrashingSubTestOutput(output))
<< "Did not find crash signals in output:\n"
<< output;
}
std::unique_ptr<PrefService> LoadLocalState(const base::FilePath& path) {
PrefServiceFactory pref_service_factory;
pref_service_factory.set_async(false);
pref_service_factory.set_user_prefs(
base::MakeRefCounted<JsonPrefStore>(path));
return pref_service_factory.Create(pref_registry_);
}
std::unique_ptr<metrics::CleanExitBeacon> LoadCleanExitBeacon(
PrefService* pref_service) {
static constexpr wchar_t kDummyWindowsRegistryKey[] = L"";
auto clean_exit_beacon = std::make_unique<metrics::CleanExitBeacon>(
kDummyWindowsRegistryKey, user_data_dir(), pref_service,
version_info::Channel::UNKNOWN);
clean_exit_beacon->Initialize();
return clean_exit_beacon;
}
private:
base::test::TaskEnvironment task_environment_;
scoped_refptr<PrefRegistrySimple> pref_registry_;
base::ScopedTempDir temp_dir_;
base::FilePath user_data_dir_;
base::FilePath local_state_file_;
};
} // namespace
TEST_F(FieldTrialTest, ExtendedSafeModeEndToEnd) {
// Reuse the browser_tests binary (i.e., that this test code is in), to
// manually run the sub-test.
base::CommandLine sub_test =
base::CommandLine(base::CommandLine::ForCurrentProcess()->GetProgram());
// Run the manual sub-test in the |user_data_dir()| allocated for this test.
sub_test.AppendSwitchASCII(base::kGTestFilterFlag,
"VariationsSafeModeBrowserTest.MANUAL_SubTest");
sub_test.AppendSwitch(::switches::kRunManualTestsFlag);
sub_test.AppendSwitch(::switches::kSingleProcessTests);
sub_test.AppendSwitchPath(::switches::kUserDataDir, user_data_dir());
const std::string group_name = kSignalAndWriteViaFileUtilGroup;
// Select the extended variations safe mode field trial group. The "*"
// prefix forces the experiment/trial state to "active" at startup.
sub_test.AppendSwitchASCII(
::switches::kForceFieldTrials,
base::StrCat({"*", kExtendedSafeModeTrial, "/", group_name, "/"}));
// Assign the test environment to be on the "Dev" channel. This ensures
// compatibility with both the extended safe mode trial and the crashing
// study in the seed.
sub_test.AppendSwitchASCII(switches::kFakeVariationsChannel, "dev");
// Explicitly avoid any terminal control characters in the output.
sub_test.AppendSwitchASCII("gtest_color", "no");
// Initial sub-test run should be successful.
RunAndExpectSuccessfulSubTest(sub_test);
// Inject the safe and crashing seeds into the Local State of |sub_test|.
{
auto local_state = LoadLocalState(local_state_file());
WriteSeedData(local_state.get(), kTestSeedData, kSafeSeedPrefKeys);
WriteSeedData(local_state.get(), kCrashingSeedData, kRegularSeedPrefKeys);
}
SetUpExtendedSafeModeExperiment(group_name);
// The next |kCrashStreakThreshold| runs of the sub-test should crash...
for (int run_count = 1; run_count <= kCrashStreakThreshold; ++run_count) {
SCOPED_TRACE(base::StringPrintf("Run #%d with crashing seed", run_count));
RunAndExpectCrashingSubTest(sub_test);
auto local_state = LoadLocalState(CopyOfLocalStateFile(run_count));
auto clean_exit_beacon = LoadCleanExitBeacon(local_state.get());
ASSERT_TRUE(clean_exit_beacon != nullptr);
ASSERT_FALSE(clean_exit_beacon->exited_cleanly());
ASSERT_EQ(run_count,
local_state->GetInteger(prefs::kVariationsCrashStreak));
}
// Do another run and verify that safe mode kicks in, preventing the crash.
RunAndExpectSuccessfulSubTest(sub_test);
}
} // namespace variations
| 41.9941 | 80 | 0.74431 | zealoussnow |
26c9c3a27b15384bc70a19d1089b93514861ff79 | 21,272 | cpp | C++ | ShadowMapping/CascadedShadowMappingRenderer.cpp | LYP951018/EasyDX | 10b5a04c13af1fc6c3b405e309dc754a42530011 | [
"Apache-2.0"
] | 3 | 2017-03-12T07:26:56.000Z | 2017-11-20T13:01:46.000Z | ShadowMapping/CascadedShadowMappingRenderer.cpp | LYP951018/EasyDX | 10b5a04c13af1fc6c3b405e309dc754a42530011 | [
"Apache-2.0"
] | 9 | 2019-04-27T08:36:01.000Z | 2021-11-25T16:36:02.000Z | ShadowMapping/CascadedShadowMappingRenderer.cpp | LYP951018/EasyDX | 10b5a04c13af1fc6c3b405e309dc754a42530011 | [
"Apache-2.0"
] | 2 | 2018-04-16T09:41:56.000Z | 2021-11-01T06:17:58.000Z | #include "Pch.hpp"
#if 1
#include "CascadedShadowMappingRenderer.hpp"
#include <DirectXColors.h>
using namespace DirectX;
using namespace dx;
CascadedShadowMappingRenderer::CascadedShadowMappingRenderer(
ID3D11Device& device3D, const CascadedShadowMapConfig& shadowMapConfig)
: m_config{shadowMapConfig}, m_partitions{shadowMapConfig.Intervals}
{
CreateDepthGenerationResources(device3D);
CreateCsmGenerationResources(device3D, shadowMapConfig.ShadowMapSize);
CreateSssmRt(device3D, shadowMapConfig.ScreenSpaceTexSize);
}
XMMATRIX OrthographicFromBoundingBox(const BoundingBox& box)
{
XMFLOAT3 corners[8];
box.GetCorners(corners);
const XMFLOAT3& minPoint = corners[2];
const XMFLOAT3& maxPoint = corners[4];
return XMMatrixOrthographicOffCenterLH(minPoint.x, maxPoint.x, minPoint.y,
maxPoint.y, minPoint.z, maxPoint.z);
}
DirectX::BoundingBox BoxFromFrutum(const BoundingFrustum& frustum)
{
XMFLOAT3 corners[8];
frustum.GetCorners(corners);
DirectX::BoundingBox box;
BoundingBox::CreateFromPoints(box, 8, corners, sizeof(XMFLOAT3));
return box;
}
void CascadedShadowMappingRenderer::GenerateShadowMap(
const dx::GlobalGraphicsContext& gfxContext, const dx::Camera& camera,
gsl::span<const dx::Light> lights, gsl::span<const RenderNode> renderNodes,
const dx::GlobalShaderContext& shaderContext)
{
ID3D11DeviceContext& context3D = gfxContext.Context3D();
// first pass: collect depth in view space
// 为了从 screen space 还原到 world space。
std::array<ID3D11RenderTargetView* const, 1> nullView = {};
context3D.OMSetRenderTargets(1, nullView.data(), m_worldDepthView.Get());
// context3D.ClearRenderTargetView(rt, color.data());
context3D.ClearDepthStencilView(m_worldDepthView.Get(), D3D11_CLEAR_DEPTH, 1.0f, 0);
RunShadowCaster(renderNodes, shaderContext, context3D);
BoundingBox viewSpaceSceneAabb;
BoundingBox::CreateFromPoints(viewSpaceSceneAabb, g_XMNegInfinity,
g_XMInfinity);
for (const RenderNode& renderNode : renderNodes)
{
const BoundingBox& localBoundingBox = renderNode.mesh.GetBoundingBox();
BoundingBox worldBoundingBox;
localBoundingBox.Transform(worldBoundingBox,
renderNode.World * camera.GetView());
BoundingBox::CreateMerged(viewSpaceSceneAabb, viewSpaceSceneAabb,
worldBoundingBox);
}
// m_viewSpaceDepthMap contains what we want
// second pass: CSM
BoundingFrustum frustum = camera.Frustum();
const dx::Light& mainLight = lights[0];
BoundingFrustum lightSpaceFrustum;
XMMATRIX lightSpaceViewMatrix;
XMMATRIX lightSpaceProjMatrix;
XMMATRIX viewToLight;
switch (mainLight.index())
{
case dx::kDirectionalLight:
{
auto& directionalLight = std::get<DirectionalLight>(mainLight);
lightSpaceViewMatrix = XMMatrixLookToLH(
XMVectorZero(), Load(directionalLight.Direction),
XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f));
viewToLight =
XMMatrixInverse({}, camera.GetView()) * lightSpaceViewMatrix;
BoundingBox lightSpaceAabb;
viewSpaceSceneAabb.Transform(lightSpaceAabb, viewToLight);
lightSpaceProjMatrix = OrthographicFromBoundingBox(lightSpaceAabb);
}
}
frustum.Transform(lightSpaceFrustum, viewToLight);
// BoundingBox lightSpaceFrustumBox = BoxFromFrutum(lightSpaceFrustum);
// lightSpaceProjMatrix =
// OrthographicFromBoundingBox(lightSpaceFrustumBox);
const std::uint32_t partitionCount = kCascadedCount;
dx::GlobalShaderContext shaderContextForShadowMapping = shaderContext;
shaderContextForShadowMapping.ViewMatrix = lightSpaceViewMatrix;
const float nearZ =
std::max(frustum.Near,
viewSpaceSceneAabb.Center.z - viewSpaceSceneAabb.Extents.z);
const float farZ =
viewSpaceSceneAabb.Center.z + viewSpaceSceneAabb.Extents.z;
const float nearFarDistance = farZ - nearZ;
const XMFLOAT4 colors[] = {
XMFLOAT4{1.0f, 0.0f, 0.0f, 1.0f},
XMFLOAT4{0.0f, 1.0f, 0.0f, 1.0f},
XMFLOAT4{0.0f, 0.0f, 1.0f, 1.0f},
XMFLOAT4{1.0f, 1.0f, 0.0f, 1.0f},
};
D3D11_VIEWPORT viewport{
0.0f, 0.0f, m_config.ShadowMapSize.Width, m_config.ShadowMapSize.Height, 0, 1
};;
context3D.RSSetViewports(1, &viewport);
for (std::uint32_t i = 0; i < partitionCount; ++i)
{
const float low = nearZ + m_partitions[i] * nearFarDistance;
const float high = nearZ + m_partitions[i + 1] * nearFarDistance;
m_intervals[i] = low;
XMMATRIX projMatrix = CalcLightProjMatrix(
mainLight, frustum, low, high, lightSpaceProjMatrix,
viewSpaceSceneAabb, viewToLight);
shaderContextForShadowMapping.ProjMatrix =
lightSpaceProjMatrix * projMatrix;
if (!m_lightSpaceFrustum[i])
{
m_lightSpaceFrustum[i] = MeshFromFrustum(
gfxContext.Device3D(), lightSpaceFrustum, colors[i]);
}
shaderContextForShadowMapping.ViewProjMatrix =
shaderContextForShadowMapping.ViewMatrix *
shaderContextForShadowMapping.ProjMatrix;
m_lightViewProjs[i] = viewToLight * shaderContextForShadowMapping.ProjMatrix;
ID3D11RenderTargetView* rt = m_shadowMapRtViews[i].Get();
context3D.OMSetRenderTargets(1, &rt, m_shadowMapRtDepthStencil.View());
std::array<float, 4> color = {};
context3D.ClearRenderTargetView(rt, color.data());
m_shadowMapRtDepthStencil.ClearBoth(context3D);
ShaderInputs inputs;
for (const RenderNode& renderNode : renderNodes)
{
// FIXME:如何避免上一个对象设置的 buffer 遗留的问题?
FillUpShaders(context3D, renderNode.material.shadowCasterPass,
renderNode.World, nullptr,
shaderContextForShadowMapping);
DrawMesh(context3D, renderNode.mesh,
*renderNode.material.shadowCasterPass.pass);
}
}
/*if (!m_cubePass)
{
const auto mappedCso =
MemoryMappedCso{fs::current_path() / L"CubeVS.cso"};
m_cubePass = std::make_shared<Pass>(Pass{MakeShaderCollection(
Shader{gfxContext.Device3D(), mappedCso.Bytes()},
dx::Shader::FromCompiledCso(gfxContext.Device3D(),
fs::current_path() / L"CubePS.cso"))});
InputLayoutAllocator::Register(
gfxContext.Device3D(),
m_lightSpaceFrustum[0]->GetFullInputElementDesces(),
mappedCso.Bytes());
}
std::array<ID3D11RenderTargetView* const, 1> views = {gfxContext.MainRt()};
context3D.OMSetRenderTargets(1, views.data(),
gfxContext.GetDepthStencil().View());
for (const std::shared_ptr<dx::Mesh>& mesh : m_lightSpaceFrustum)
{
FillUpShaders(context3D, dx::PassWithShaderInputs{m_cubePass},
XMMatrixIdentity(), nullptr, shaderContext);
DrawMesh(context3D, *mesh, *m_cubePass);
}*/
ID3D11RenderTargetView* rts[] = { m_sssmRt.Get() };
context3D.OMSetRenderTargets(1, rts, nullptr);
D3D11_VIEWPORT viewport2{
0.0f, 0.0f, m_config.ScreenSpaceTexSize.Width, m_config.ScreenSpaceTexSize.Height, 0, 1
};;
context3D.RSSetViewports(1, &viewport2);
float color[4] = {};
context3D.ClearRenderTargetView(m_sssmRt.Get(), color);
ShaderInputs& inputs = m_collectPass.inputs;
const XMMATRIX invProj = XMMatrixInverse({}, camera.GetProjection());
inputs.SetField("InvProj", invProj);
inputs.SetField("lightSpaceProjs", m_lightViewProjs);
inputs.SetField("Intervals", m_intervals);
inputs.Bind("DepthMap", m_depthSrv);
inputs.Bind("ShadowMapArray", m_shadowMapTexArraySrv);
inputs.Bind("NearestPointSampler", m_nearestPointSampler);
FillUpShaders(context3D, m_collectPass,
DirectX::XMMatrixIdentity(), nullptr,
shaderContextForShadowMapping);
DrawMesh(context3D, *m_screenSpaceQuad,
m_collectPass.pass, &gfxContext.Device3D());
ID3D11ShaderResourceView* srvs[] = { nullptr, nullptr };
context3D.PSSetShaderResources(0, 2, srvs);
context3D.VSSetShaderResources(0, 2, srvs);
// m_depthTexArray has been filled.
// last pass: generate screen space shadowmap
// auto invViewProj = XMMatrixInverse({},
// XMMatrixTranspose(shaderContext.ViewProjMatrix));
// dx::ShaderInputs additionalInputs;
//// viewspace
// additionalInputs.SetField("lightSpaceProjs", m_lightViewProjs);
// additionalInputs.SetField("InvProj", m_lightViewProjs);
// additionalInputs.Bind("DepthTex", m_shadowMapTexArraySrv);
// additionalInputs.Bind("DepthTexSampler", m_nearestPointSampler);
// DrawMesh(context3D, *m_quad, m_collectPass);
}
wrl::ComPtr<ID3D11ShaderResourceView>
CascadedShadowMappingRenderer::GetCsmTexArray() const
{
return m_shadowMapTexArraySrv;
}
void CascadedShadowMappingRenderer::RunShadowCaster(
gsl::span<const dx::RenderNode>& renderNodes,
const dx::GlobalShaderContext& shaderContextForShadowMapping,
ID3D11DeviceContext& context3D)
{
for (const RenderNode& renderNode : renderNodes)
{
const Material& material = renderNode.material;
if (material.shadowCasterPass.pass)
{
FillUpShaders(context3D, material.shadowCasterPass,
renderNode.World, nullptr,
shaderContextForShadowMapping);
DrawMesh(context3D, renderNode.mesh,
*material.shadowCasterPass.pass);
}
}
}
void CascadedShadowMappingRenderer::DrawCube(
gsl::span<const DirectX::XMFLOAT3> points)
{}
std::shared_ptr<dx::Mesh> CascadedShadowMappingRenderer::MeshFromFrustum(
ID3D11Device& device3D, const DirectX::BoundingFrustum& frustum,
const XMFLOAT4& color)
{
XMFLOAT3 corners[8];
frustum.GetCorners(corners);
const ShortIndex indices[] = {3, 0, 1, 1, 2, 3, 7, 4, 5, 5, 6, 7,
7, 4, 0, 0, 3, 7, 2, 1, 5, 5, 6, 2,
4, 0, 1, 0, 1, 5, 7, 3, 2, 3, 2, 6};
const XMFLOAT4 colors[] = {color, color, color, color,
color, color, color, color};
const VSSemantics semantics[] = {VSSemantics::kPosition,
VSSemantics::kColor};
const DxgiFormat formats[] = {DxgiFormat::R32G32B32Float,
DxgiFormat::R32G32B32A32Float};
const std::uint32_t semanticsIndices[] = {0, 0};
/*
4 0
7 3
*/
std::vector<D3D11_INPUT_ELEMENT_DESC> inputDesc;
dx::FillInputElementsDesc(inputDesc, gsl::make_span(semantics),
gsl::make_span(formats),
gsl::make_span(semanticsIndices));
return Mesh::CreateImmutable(device3D, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST,
gsl::make_span(indices), semantics, 8,
std::move(inputDesc), corners, colors);
}
DirectX::XMMATRIX CascadedShadowMappingRenderer::CalcLightProjMatrix(
const dx::Light& light, DirectX::BoundingFrustum& existingFrustum,
float low, float high, const XMMATRIX& lightProjMatrix,
const DirectX::BoundingBox& viewSpaceAabb, const XMMATRIX& viewToLight)
{
switch (light.index())
{
case kDirectionalLight:
{
// BUG:
//上面的 viewSpaceSceneAabb 是物体求出的
// AABB,视锥角落的点可能不在这里面,导致变换到 homo space
//外面。
existingFrustum.Near = low;
existingFrustum.Far = high;
XMFLOAT3 frustumCorners[8];
XMFLOAT3 boxCorners[8];
XMFLOAT3 corners[8];
BoundingBox frustumBox;
existingFrustum.GetCorners(frustumCorners);
BoundingBox::CreateFromPoints(frustumBox, 8, frustumCorners,
sizeof(XMFLOAT3));
frustumBox.GetCorners(frustumCorners);
viewSpaceAabb.GetCorners(boxCorners);
/*
const auto select = [&](int index) {
const XMFLOAT3& boxCorner = boxCorners[index];
const XMFLOAT3& frustumCorner = frustumCorners[index];
const XMVECTOR minBox = XMLoadFloat3(&boxCorner);
const XMVECTOR minFrustum = XMLoadFloat3(&frustumCorner);
return XMVectorMin(g_BoxOffset[index] * minBox,
g_BoxOffset[index] * minFrustum);
};
BoundingBox newBox;
BoundingBox::CreateFromPoints(newBox, select(2), select(4));
newBox.GetCorners(corners);*/
for (int i = 0; i < 8; ++i)
{
const float* offset = g_BoxOffset[i];
const XMFLOAT3& boxCorner = boxCorners[i];
const XMFLOAT3& frustumCorner = frustumCorners[i];
const auto select = [&](int index) {
const float selector = offset[index];
return selector *
std::min(selector * (&boxCorner.x)[index],
selector * (&frustumCorner.x)[index]);
};
corners[i] = {select(0), select(1), select(2)};
}
BoundingBox newBox;
BoundingBox::CreateFromPoints(newBox, 8, corners, sizeof(XMFLOAT3));
newBox.Transform(newBox, viewToLight);
newBox.GetCorners(corners);
// for (int i = 0; i < 8; ++i)
//{
// const XMFLOAT3& frustumCorner = frustumCorners[i];
// const XMFLOAT3& boxCorner = boxCorners[i];
// const XMVECTOR minimum =
//XMVectorMin(XMLoadFloat3(&frustumCorner),
//XMLoadFloat3(&boxCorner)); XMStoreFloat3(corners + i, minimum);
//}
// Then, each corner point p of the camera’s
// frustum slice is projected into p h = PMp in the light’s
// homogeneous space.
for (XMFLOAT3& corner : corners)
{
XMFLOAT4 position = {corner.x, corner.y, corner.z, 1.0f};
XMVECTOR loaded = XMLoadFloat4(&position);
loaded = XMVector4Transform(loaded, lightProjMatrix);
loaded /= XMVectorGetW(loaded);
XMStoreFloat3(&corner, loaded);
}
BoundingBox lightHomoBox;
BoundingBox::CreateFromPoints(lightHomoBox, 8, corners,
sizeof(XMFLOAT3));
lightHomoBox.GetCorners(corners);
const XMFLOAT3& minPoint = corners[2];
const XMFLOAT3& maxPoint = corners[4];
return XMMatrixOrthographicOffCenterLH(minPoint.x, maxPoint.x,
minPoint.y, maxPoint.y,
minPoint.z, maxPoint.z);
}
default:
break;
}
}
void CascadedShadowMappingRenderer::CreateCsmGenerationResources(
ID3D11Device& device3D, dx::Size size)
{
D3D11_TEXTURE2D_DESC depthTexArrayDesc{};
depthTexArrayDesc.ArraySize = kCascadedCount;
depthTexArrayDesc.Width = size.Width;
depthTexArrayDesc.Height = size.Height;
depthTexArrayDesc.Usage = D3D11_USAGE_DEFAULT;
depthTexArrayDesc.BindFlags =
D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
depthTexArrayDesc.Format = DXGI_FORMAT_R32_FLOAT;
depthTexArrayDesc.MipLevels = 1;
depthTexArrayDesc.SampleDesc.Count = 1;
TryHR(device3D.CreateTexture2D(&depthTexArrayDesc, nullptr,
m_depthTexArray.GetAddressOf()));
D3D11_SHADER_RESOURCE_VIEW_DESC rsvDesc{};
rsvDesc.Format = DXGI_FORMAT_R32_FLOAT;
rsvDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE2DARRAY;
D3D11_TEX2D_ARRAY_SRV& tex2DArray = rsvDesc.Texture2DArray;
tex2DArray.ArraySize = kCascadedCount;
tex2DArray.MipLevels = 1;
tex2DArray.MostDetailedMip = 0;
tex2DArray.FirstArraySlice = 0;
TryHR(device3D.CreateShaderResourceView(
m_depthTexArray.Get(), &rsvDesc,
m_shadowMapTexArraySrv.GetAddressOf()));
D3D11_RENDER_TARGET_VIEW_DESC rtViewDesc{};
rtViewDesc.Format = DXGI_FORMAT_R32_FLOAT;
rtViewDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DARRAY;
D3D11_TEX2D_ARRAY_RTV& rtTexArray = rtViewDesc.Texture2DArray;
rtTexArray.MipSlice = 0;
rtTexArray.ArraySize = 1;
for (unsigned i = 0; i < kCascadedCount; ++i)
{
rtViewDesc.Texture2DArray.FirstArraySlice =
D3D11CalcSubresource(0, i, 1);
TryHR(device3D.CreateRenderTargetView(
m_depthTexArray.Get(), &rtViewDesc,
m_shadowMapRtViews[i].GetAddressOf()));
}
m_shadowMapRtDepthStencil = DepthStencil{device3D, size};
}
void CascadedShadowMappingRenderer::CreateSssmRt(ID3D11Device& device3D,
dx::Size size)
{
D3D11_TEXTURE2D_DESC texDesc{};
texDesc.Width = size.Width;
texDesc.Height = size.Height;
texDesc.MipLevels = 1;
texDesc.ArraySize = 1;
texDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
texDesc.Usage = D3D11_USAGE_DEFAULT;
texDesc.BindFlags = D3D11_BIND_RENDER_TARGET;
texDesc.SampleDesc.Count = 1;
TryHR(device3D.CreateTexture2D(&texDesc, nullptr,
m_screenSpaceShadowMap.GetAddressOf()));
D3D11_RENDER_TARGET_VIEW_DESC rtDesc{};
rtDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
rtDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
TryHR(device3D.CreateRenderTargetView(m_screenSpaceShadowMap.Get(), &rtDesc,
m_sssmRt.GetAddressOf()));
const ShortIndex quadIndices[] = {0, 1, 2, 2, 1, 3};
const PositionType quadPositions[] = {
MakePosition(-1.0f, 1.0f, 1.0f),
MakePosition(1.0f, 1.0f, 1.0f),
MakePosition(-1.0f, -1.0f, 1.0f),
MakePosition(1.0f, -1.0f, 1.0f),
};
const TexCoordType quadTexCoords[] = {
MakeTexCoord(0.0f, 0.0f), MakeTexCoord(1.0f, 0.0f),
MakeTexCoord(0.0f, 1.0f), MakeTexCoord(1.0f, 1.0f)};
VSSemantics semantics[] = {
VSSemantics::kPosition, VSSemantics::kTexCoord
};
DxgiFormat formats[] = {
DxgiFormat::R32G32B32A32Float,
DxgiFormat::R32G32Float
};
std::uint32_t indices[] = { 0, 0 };
std::vector<D3D11_INPUT_ELEMENT_DESC> inputElementsDesces;
FillInputElementsDesc(inputElementsDesces, semantics, formats,
indices);
m_screenSpaceQuad = Mesh::CreateImmutable(
device3D, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, gsl::span(quadIndices),
semantics, 4, std::move(inputElementsDesces),
quadPositions, quadTexCoords);
m_collectPass.pass = std::make_shared<dx::Pass>(dx::Pass
{
MakeShaderCollection(
dx::Shader::FromCompiledCso(device3D, fs::current_path() /
"ShadowCollectVS.cso"),
dx::Shader::FromCompiledCso(device3D, fs::current_path() /
L"ShadowCollectPS.cso"))
});
CD3D11_SAMPLER_DESC samplerDesc{ CD3D11_DEFAULT{} };
samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT;
TryHR(device3D.CreateSamplerState(&samplerDesc, m_nearestPointSampler.GetAddressOf()));
}
void CascadedShadowMappingRenderer::CreateDepthGenerationResources(
ID3D11Device& device3D)
{
// first pass: collect depth
CD3D11_TEXTURE2D_DESC depthTexDesc{DXGI_FORMAT_R32G8X24_TYPELESS,
m_config.ScreenSpaceTexSize.Width,
m_config.ScreenSpaceTexSize.Height, 1, 1};
depthTexDesc.BindFlags |= D3D11_BIND_FLAG::D3D11_BIND_DEPTH_STENCIL;
TryHR(device3D.CreateTexture2D(&depthTexDesc, nullptr,
m_worldSpaceDepthMap.GetAddressOf()));
CD3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc{
D3D11_DSV_DIMENSION_TEXTURE2D, DXGI_FORMAT_D32_FLOAT_S8X24_UINT};
TryHR(device3D.CreateDepthStencilView(m_worldSpaceDepthMap.Get(),
&depthStencilViewDesc,
m_worldDepthView.GetAddressOf()));
CD3D11_SHADER_RESOURCE_VIEW_DESC srvDesc{
D3D11_SRV_DIMENSION_TEXTURE2D, DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS};
TryHR(device3D.CreateShaderResourceView(
m_worldSpaceDepthMap.Get(), &srvDesc, m_depthSrv.GetAddressOf()));
}
dx::Pass
CascadedShadowMappingRenderer::MakeCollectionPass(ID3D11Device& device3D)
{
throw std::runtime_error{"fuck"};
/*using namespace dx;
return Pass{ShaderCollection{
Shader::FromCompiledCso(device3D, fs::current_path() /
"SecondPassVS.hlsl"), Shader::FromCompiledCso(device3D,
fs::current_path() / "SecondPassPS.hlsl")}};*/
}
#endif | 43.235772 | 95 | 0.639667 | LYP951018 |
26cdc8571d8beeb922fc266aee09dd8770f8347e | 2,633 | cpp | C++ | crypto_sign/bls/ref/ecn.cpp | iadgov/simon-speck-supercop | 5bba85c3094029eb73b7077441e5c6ea2f2cb1c6 | [
"CC0-1.0"
] | 21 | 2016-12-03T14:19:01.000Z | 2018-03-09T14:52:25.000Z | crypto_sign/bls/ref/ecn.cpp | iadgov/simon-speck-supercop | 5bba85c3094029eb73b7077441e5c6ea2f2cb1c6 | [
"CC0-1.0"
] | null | null | null | crypto_sign/bls/ref/ecn.cpp | iadgov/simon-speck-supercop | 5bba85c3094029eb73b7077441e5c6ea2f2cb1c6 | [
"CC0-1.0"
] | 11 | 2017-03-06T17:21:42.000Z | 2018-03-18T03:52:58.000Z | /*
* MIRACL C++ functions ecn.cpp
*
* AUTHOR : M. Scott
*
* PURPOSE : Implementation of class ECn functions using Montgomery
* representation
* NOTE : Must be used in conjunction with big.h and big.cpp
*
* Copyright (c) 1988-2004 Shamus Software Ltd.
*/
#include "ecn.h"
int ECn::get(Big& x,Big& y) const
{return epoint_get(p,x.getbig(),y.getbig());}
int ECn::get(Big& x) const
{return epoint_get(p,x.getbig(),x.getbig());}
void ECn::getx(Big &x) const
{epoint_getxyz(p,x.getbig(),NULL,NULL);}
void ECn::getxy(Big &x,Big &y) const
{epoint_getxyz(p,x.getbig(),y.getbig(),NULL);}
void ECn::getxyz(Big &x,Big &y, Big &z) const
{epoint_getxyz(p,x.getbig(),y.getbig(),z.getbig());}
BOOL ECn::iszero() const
{if (p->marker==MR_EPOINT_INFINITY) return TRUE; return FALSE;}
epoint * ECn::get_point() const
{ return p; }
ECn operator-(const ECn& e)
{ ECn t=e; epoint_negate(t.p); return t;}
ECn mul(const Big& e1,const ECn& p1,const Big& e2,const ECn& p2)
{
ECn t;
ecurve_mult2(e1.getbig(),p1.get_point(),e2.getbig(),p2.get_point(),t.get_point());
return t;
}
ECn operator*(const Big& e,const ECn& b)
{
ECn t;
ecurve_mult(e.getbig(),b.p,t.p);
return t;
}
#ifndef MR_STATIC
ECn mul(int n,const Big *y,ECn *x)
{
ECn w;
int i;
big *a=(big *)mr_alloc(n,sizeof(big));
epoint **b=(epoint **)mr_alloc(n,sizeof(epoint *));
for (i=0;i<n;i++)
{
a[i]=y[i].getbig();
b[i]=x[i].p;
}
ecurve_multn(n,a,b,w.p);
mr_free(b);
mr_free(a);
return w;
}
void multi_add(int m,ECn *x, ECn *w)
{
int i;
epoint **xp=(epoint **)mr_alloc(m,sizeof(epoint *));
epoint **wp=(epoint **)mr_alloc(m,sizeof(epoint *));
for (i=0;i<m;i++)
{
xp[i]=x[i].p;
wp[i]=w[i].p;
}
ecurve_multi_add(m,xp,wp);
mr_free(wp);
mr_free(xp);
}
#endif
void double_add(ECn& A,ECn& B,ECn& C,ECn& D,big& s1,big& s2)
{
ecurve_double_add(A.p,B.p,C.p,D.p,&s1,&s2);
}
#ifndef MR_NO_STANDARD_IO
ostream& operator<<(ostream& s,const ECn& b)
{
Big x,y;
if (b.iszero())
s << "(Infinity)";
else
{
b.get(x,y);
s << "(" << x << "," << y << ")";
}
return s;
}
#endif
void ecurve(const Big& a,const Big& b,const Big& p,int t)
{
ecurve_init(a.fn,b.fn,p.fn,t);
}
#ifndef MR_NOSUPPORT_COMPRESSION
BOOL is_on_curve(const Big& a)
{ return epoint_x(a.fn);}
#endif
| 21.941667 | 87 | 0.542727 | iadgov |
26ce3919b248d63aa4e81588360fa96dbb9b7b57 | 966 | hpp | C++ | include/bdlearn/BatchBlas.hpp | billythedummy/bdlearn | bdb7b22c326f8057ec3ec06a701d00885e801bfd | [
"MIT"
] | 2 | 2019-12-04T08:24:17.000Z | 2020-01-31T23:29:52.000Z | include/bdlearn/BatchBlas.hpp | billythedummy/bdlearn | bdb7b22c326f8057ec3ec06a701d00885e801bfd | [
"MIT"
] | null | null | null | include/bdlearn/BatchBlas.hpp | billythedummy/bdlearn | bdb7b22c326f8057ec3ec06a701d00885e801bfd | [
"MIT"
] | null | null | null | #ifndef _BDLEARN_BATCHBLAS_H_
#define _BDLEARN_BATCHBLAS_H_
#include "Halide.h"
namespace bdlearn {
void BatchMatMul(Halide::Buffer<float> out, Halide::Buffer<float> A, Halide::Buffer<float> B);
void BatchMatMul_BT(Halide::Buffer<float> out, Halide::Buffer<float> A, Halide::Buffer<float> BT);
// A broadcasted, transposed
void BatchMatMul_ATBr(Halide::Buffer<float> out, Halide::Buffer<float> AT, Halide::Buffer<float> B);
// A broadcasted
//void BatchMatMul_ABr(Halide::Buffer<float> out, Halide::Buffer<float> A, Halide::Buffer<float> B);
/*
void BatchIm2Col(Halide::Buffer<float> out, Halide::Buffer<float> in,
const int p, const int s, const int k, const int out_width, const int out_height);*/
/*
void BatchCol2ImAccum(Halide::Buffer<float> out, Halide::Buffer<float> in,
const int p, const int s, const int k, const int out_width, const int out_height);*/
}
#endif | 46 | 112 | 0.681159 | billythedummy |
26cebadcb187d85f53733297d3a33190785e624a | 2,202 | cpp | C++ | ELOSystem/ELOcalculations.cpp | pablogalve/ELO-System | e99c558b462b6d44020c5d789b11fce647d3dbe0 | [
"Apache-2.0"
] | 1 | 2021-05-01T00:50:18.000Z | 2021-05-01T00:50:18.000Z | ELOSystem/ELOcalculations.cpp | pablogalve/ELO-System | e99c558b462b6d44020c5d789b11fce647d3dbe0 | [
"Apache-2.0"
] | null | null | null | ELOSystem/ELOcalculations.cpp | pablogalve/ELO-System | e99c558b462b6d44020c5d789b11fce647d3dbe0 | [
"Apache-2.0"
] | null | null | null | #include "users.h"
void ELOManager::calculateELO(user* myself, float theirELO, float result) {
float changeELO;
float adjust;
bool change;
if (theirELO == 0) //To avoid not updating ELO
theirELO = 1;
changeELO = (result - getProbWin(myself->ELO, theirELO)) * K;
//Change ELO balances to make sure that there are not negative ELOs and to create inflation on users with low ELO
if (result == 1) {
change = true;
myself->exp += 3;
}
else {
change = true;
adjust = changeELO + myself->ELO;
if (adjust < 0) { //Players can't have negative ELO
myself->ELO = 0;
change = false;
}
}
if(change)
myself->ELO += changeELO;
}
void ELOManager::calculateScore() {
//This must be changed at a later stage
float avg; // average ELO of other users
float probWinUp;
float probWinDown=0;
user* index = first;
while (index != nullptr) {
avg = getAvgUp(index);
//Probabilities of beating the user before you
if(index->next!=nullptr)
probWinUp = getProbWin(index->ELO, index->next->ELO);
//Probabilities of beating the user after you
/*if(index->previous !=nullptr) {
probWinDown=getProbWin(index->ELO, index->previous->ELO);
}*/
index->score = index->ELO / 3 + index->exp + static_cast <float> (rand()) / (static_cast <float> (200 / (probWinUp+probWinDown)));
//index->score = index->ELO+7;
//avg = getAvgDown(index);
//probWin = getProbWin(index->ELO, avg) * 100;
//index->score -= index->ELO + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / probWin));
//Finish loop
index = index->next;
}
}
float ELOManager::getAvgUp(user* myself) {
float ELOsum = 0, i = 0;
if (first == myself)
return NULL;
else {
for (user* index = first; index->next != myself; index = index->next) {
ELOsum += index->ELO;
i++;
}
return ELOsum / i;
}
}
float ELOManager::getAvgDown(user* myself) {
float ELOsum = 0, i = 0;
if (last == myself)
return NULL;
else {
for (user* index = last; index->previous != myself; index = index->previous) {
ELOsum += index->ELO;
i++;
}
return ELOsum / i;
}
}
float ELOManager::getProbWin(float myELO, float theirELO) {
return (1 / (1 + pow(10, (theirELO - myELO) / 400)));
}
| 25.905882 | 132 | 0.647139 | pablogalve |
26d9cce2051a4d4011dc367b9d511f6c5f400871 | 1,382 | hpp | C++ | MRedisConfig.hpp | MrMoose/mredis | 5a60cc57c6193bd68eab9c0f6a9938c9530b8665 | [
"BSL-1.0"
] | 4 | 2018-10-31T14:31:30.000Z | 2019-07-31T11:45:57.000Z | MRedisConfig.hpp | MrMoose/mredis | 5a60cc57c6193bd68eab9c0f6a9938c9530b8665 | [
"BSL-1.0"
] | null | null | null | MRedisConfig.hpp | MrMoose/mredis | 5a60cc57c6193bd68eab9c0f6a9938c9530b8665 | [
"BSL-1.0"
] | null | null | null | // Copyright 2018 Stephan Menzel. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#pragma once
// see https://gcc.gnu.org/wiki/Visibility
// Generic helper definitions for shared library support
#if defined _WIN32 || defined __CYGWIN__
#define MREDIS_DLL_IMPORT __declspec(dllimport)
#define MREDIS_DLL_EXPORT __declspec(dllexport)
#define MREDIS_DLL_LOCAL
#ifndef NOMINMAX
#define NOMINMAX
#endif
#else
#if __GNUC__ >= 4
#define MREDIS_DLL_IMPORT __attribute__ ((visibility ("default")))
#define MREDIS_DLL_EXPORT __attribute__ ((visibility ("default")))
#define MREDIS_DLL_LOCAL __attribute__ ((visibility ("hidden")))
#else
#define MREDIS_DLL_IMPORT
#define MREDIS_DLL_EXPORT
#define MREDIS_DLL_LOCAL
#endif
#endif
#ifdef MREDIS_DLL // defined if is compiled as a DLL
#ifdef mredis_EXPORTS // defined if we are building the DLL (instead of using it)
#define MREDIS_API MREDIS_DLL_EXPORT
#else
#define MREDIS_API MREDIS_DLL_IMPORT
#endif // mredis_EXPORTS
#define MREDIS_LOCAL MREDIS_DLL_LOCAL
#else // MREDIS_DLL is not defined: this means it is a static lib.
#define MREDIS_API
#define MREDIS_LOCAL
#endif // MREDIS_DLL
#ifdef _MSC_VER
#pragma warning (disable : 4996) // Function call with parameters that may be unsafe.
#endif
| 29.404255 | 85 | 0.769899 | MrMoose |
26dc23fd0a6e7be3d02ec8fcd83019ef4b74e5ea | 1,870 | cpp | C++ | hw/1,2/1.cpp | rgeorgiev583/FMI-DSP | 7fac5ad4373bbcb8494b7675c21ad0458176a3d3 | [
"MIT"
] | 1 | 2017-11-08T13:24:14.000Z | 2017-11-08T13:24:14.000Z | hw/1,2/1.cpp | rgeorgiev583/FMI-DSP | 7fac5ad4373bbcb8494b7675c21ad0458176a3d3 | [
"MIT"
] | null | null | null | hw/1,2/1.cpp | rgeorgiev583/FMI-DSP | 7fac5ad4373bbcb8494b7675c21ad0458176a3d3 | [
"MIT"
] | null | null | null | #include <iostream>
#include "stack.cpp"
#include <stack>
#include <queue>
using namespace std;
void print(queue<stack<size_t> > qs)
{
size_t i = 1;
while (!qs.empty())
{
cout << "Купчина " << i << ": ";
stack<size_t> sn = qs.front();
while (!sn.empty())
{
cout << sn.top() << " ";
sn.pop();
}
cout << endl;
i++;
qs.pop();
}
}
int main()
{
queue<size_t> q;
size_t d;
cin >> d;
while (d)
{
q.push(d);
cin >> d;
}
if (q.empty())
return 0;
queue<stack<size_t> > qs;
stack<size_t> s;
s.push(q.front());
q.pop();
while (!q.empty())
{
size_t dn = q.front();
if (s.top() > dn)
{
stack<size_t> sr;
pour(sr, s);
qs.push(sr);
destroy(s);
}
s.push(dn);
q.pop();
}
stack<size_t> sr;
pour(sr, s);
qs.push(sr);
destroy(s);
size_t fixed_stack_count = 0;
bool was_stack_moved = false;
while (fixed_stack_count < qs.size())
{
stack<size_t> sn;
copy(sn, qs.front());
if (sn.empty() && was_stack_moved)
was_stack_moved = false;
else if (s.empty())
{
pour(s, sn);
qs.push(stack<size_t>()); // sentinel stack
}
else
{
if (sn.empty())
fixed_stack_count++;
else if (sn.top() > s.top())
{
was_stack_moved = true;
fixed_stack_count = 0;
}
if (sn.empty() || sn.top() > s.top())
{
pour(sn, s);
destroy(s);
}
qs.push(sn);
}
qs.pop();
}
print(qs);
return 0;
}
| 16.548673 | 55 | 0.400535 | rgeorgiev583 |
26ddb3d7d9833632e7517e021ef67c9f2a975b3f | 15,200 | cc | C++ | Archive/Stroika_FINAL_for_STERL_1992/Library/Framework/Sources/FocusItem.cc | SophistSolutions/Stroika | f4e5d84767903a054fba0a6b9c7c4bd1aaefd105 | [
"MIT"
] | 28 | 2015-09-22T21:43:32.000Z | 2022-02-28T01:35:01.000Z | Archive/Stroika_FINAL_for_STERL_1992/Library/Framework/Sources/FocusItem.cc | SophistSolutions/Stroika | f4e5d84767903a054fba0a6b9c7c4bd1aaefd105 | [
"MIT"
] | 98 | 2015-01-22T03:21:27.000Z | 2022-03-02T01:47:00.000Z | Archive/Stroika_FINAL_for_STERL_1992/Library/Framework/Sources/FocusItem.cc | SophistSolutions/Stroika | f4e5d84767903a054fba0a6b9c7c4bd1aaefd105 | [
"MIT"
] | 4 | 2019-02-21T16:45:25.000Z | 2022-02-18T13:40:04.000Z | /* Copyright(c) Sophist Solutions Inc. 1990-1992. All rights reserved */
/*
* $Header: /fuji/lewis/RCS/FocusItem.cc,v 1.6 1992/09/08 15:34:00 lewis Exp $
*
* TODO:
*
* Should do FocusOwner::DTOR which asserts all items removed...
*
*
* Changes:
* $Log: FocusItem.cc,v $
* Revision 1.6 1992/09/08 15:34:00 lewis
* Renamed NULL -> Nil.
*
* Revision 1.5 1992/09/01 15:46:50 sterling
* Lots of Foundation changes.
*
* Revision 1.4 1992/07/21 21:29:31 sterling
* Use Sequence instead of obsolete SequencePtr.
*
* Revision 1.3 1992/07/03 00:25:14 lewis
* Use Panel:: to scope access to nested UpdateMode enum.
* And, general cleanups - shorten lines.
*
* Revision 1.2 1992/07/02 04:52:31 lewis
* Renamed Sequence_DoublyLLOfPointers->SequencePtr.
*
* Revision 1.1 1992/06/20 17:30:04 lewis
* Initial revision
*
* Revision 1.30 1992/05/18 17:22:20 lewis
* Dont call SetCurrentFocus (Nil) in AbstractFocusItem::DTOR since many of items
* may already be destroyed - in fact this happens often. Probably should assert
* already nil - for now, just check when debug on, and print message.
*
* Revision 1.29 92/04/15 13:42:50 13:42:50 sterling (Sterling Wight)
* changed from Option to Shift key for backwards tab
*
* Revision 1.28 92/03/26 15:15:20 15:15:20 lewis (Lewis Pringle)
* Changed EffectiveFocusedChanged () to EffectiveFocusChanged(), and got rid of
* oldFocused first argument.
*
* Revision 1.27 1992/03/13 16:36:23 lewis
* Moved FocusView to User.
*
* Revision 1.24 1992/03/10 00:30:34 lewis
* Use new HandleKeyStroke interface, and change GetTab interface to use KeyStroike
* rather than KeyBoard.
*
* Revision 1.23 1992/03/06 22:17:32 lewis
* Minor cleanups like getting rid of ifdefs out stuff, and unneeded dtors.
* Also, undid a patch sterl had done but seemed unwise - in TrackPress for FocusView...
*
* Revision 1.22 1992/02/24 06:46:26 lewis
* Added if macui around focusitem stuff as hack for sterls/simones demo til we
* clean things up a bit - sterl - lewis says: FocusItemView bad idea to begin with...
*
* Revision 1.19 1992/02/17 16:36:04 lewis
* Worked around assert for focusitem differently than before since that change broke things.
* Just comment out the assert. Must revisit the issue soon!!!
*
* Revision 1.18 1992/02/16 18:06:39 lewis
* Change definition of FocusItem::GetEffectiveFocused ().... Discuss with sterl...
*
* Revision 1.17 1992/02/15 05:32:34 sterling
* many changes, includeng adding EffectiveFocusedChanged
*
* Revision 1.16 1992/01/31 21:11:03 lewis
* In FocusItem::CanBeFocused(), we add GetFocusOwner()!=Nil to conjunction.
* And in AbstractFocusOwner we just call GetLive() in CanBeFocused () instead
* of inherited::CanBeFocusued.
*
* Revision 1.15 1992/01/31 16:43:17 sterling
* added grabfocus
*
* Revision 1.14 1992/01/22 15:18:29 sterling
* fixed tabs
*
* Revision 1.11 1992/01/08 06:25:13 lewis
* Sterl- lots of changes - mostly tabbing related.
*
*
*
*/
#include "Debug.hh"
#include "StreamUtils.hh"
#include "Shape.hh"
#include "Adornment.hh"
#include "Dialog.hh"
#include "MenuOwner.hh"
#include "View.hh"
#include "FocusItem.hh"
#if !qRealTemplatesAvailable
Implement (Iterator, FocusItemPtr);
Implement (Collection, FocusItemPtr);
Implement (AbSequence, FocusItemPtr);
Implement (Array, FocusItemPtr);
Implement (Sequence_Array, FocusItemPtr);
Implement (Sequence, FocusItemPtr);
#endif
/*
********************************************************************************
******************************* FocusException *********************************
********************************************************************************
*/
FocusException::FocusException ():
fMessage (kEmptyString)
{
}
void FocusException::Raise ()
{
if (Exception::GetCurrent () != this) { // if were not the current exception
fMessage = kEmptyString;
}
Exception::Raise ();
}
void FocusException::Raise (const String& message)
{
fMessage = message;
Exception::Raise ();
}
String FocusException::GetMessage () const
{
return (fMessage);
}
/*
********************************************************************************
********************************* FocusItem ************************************
********************************************************************************
*/
const Boolean FocusItem::kFocused = True;
const Boolean FocusItem::kValidate = True;
FocusItem::FocusItem ():
KeyHandler (),
MenuCommandHandler (),
LiveItem (),
fFocused (not kFocused),
fOwner (Nil)
{
}
void FocusItem::SetFocused (Boolean focused, Panel::UpdateMode updateMode, Boolean validate)
{
if (GetFocused () != focused) {
SetFocused_ (focused, updateMode, validate);
}
Ensure (GetFocused () == focused);
}
Boolean FocusItem::GetFocused_ () const
{
return (fFocused);
}
void FocusItem::SetFocused_ (Boolean focused, Panel::UpdateMode updateMode, Boolean validate)
{
Require (focused != fFocused);
Boolean oldFocused = GetEffectiveFocused ();
if (validate and (not focused)) {
Validate ();
}
fFocused = focused;
if (oldFocused != GetEffectiveFocused ()) {
EffectiveFocusChanged (not oldFocused, updateMode);
}
}
Boolean FocusItem::GetEffectiveFocused () const
{
AbstractFocusOwner* owner = GetFocusOwner ();
return (Boolean (GetFocused () and ((owner == Nil) or (owner->GetEffectiveFocused ()))));
}
void FocusItem::EffectiveFocusChanged (Boolean /*newFocused*/, Panel::UpdateMode /*updateMode*/)
{
MenuOwner::SetMenusOutOfDate ();
}
AbstractFocusOwner* FocusItem::GetFocusOwner () const
{
return (fOwner);
}
void FocusItem::SetFocusOwner (AbstractFocusOwner* focusOwner)
{
Require ((fOwner == Nil) or (focusOwner == Nil));
fOwner = focusOwner;
}
Boolean FocusItem::CanBeFocused ()
{
/*
* By default, focus items can be focused if they are live.
*/
return (GetEffectiveLive ());
}
void FocusItem::GrabFocus (Panel::UpdateMode updateMode, Boolean validate)
{
AbstractFocusOwner* owner = GetFocusOwner ();
if (owner == Nil) {
SetFocused (kFocused, updateMode);
}
else {
if (validate) {
// set owners focus to Nil first to ensure validates get called early on
owner->SetCurrentFocus ((FocusItem*)Nil, updateMode, validate);
}
owner->GrabFocus (updateMode, validate);
owner->SetCurrentFocus (this, updateMode, validate);
}
}
void FocusItem::TabbingFocus (SequenceDirection /*d*/,
Panel::UpdateMode updateMode)
{
GrabFocus (updateMode, kValidate);
}
Boolean FocusItem::HandleTab (SequenceDirection /*d*/,
Boolean /*wrapping*/)
{
return (False);
}
void FocusItem::Validate ()
{
}
/*
********************************************************************************
***************************** AbstractFocusOwner *******************************
********************************************************************************
*/
const Boolean AbstractFocusOwner::kWrap = True;
AbstractFocusOwner::AbstractFocusOwner ():
fFocus (Nil)
{
}
AbstractFocusOwner::~AbstractFocusOwner ()
{
// Require (GetCurrentFocus () == Nil);
#if qDebug
if (GetCurrentFocus () != Nil) {
gDebugStream << "destroying abstract focus ownerwith current focus set!!!" << newline;
}
#endif
#if 0
// LGP May 18, 1992 - if anything, assert that current focus is Nil - when we are being destroyed, our children
// may well be already!!! In fact, that should be quite common!!!
SetCurrentFocus ((FocusItem*)Nil, Panel::eNoUpdate, False);
#endif
}
void AbstractFocusOwner::EffectiveFocusChanged (Boolean newFocused, Panel::UpdateMode updateMode)
{
FocusItem::EffectiveFocusChanged (newFocused, updateMode);
if (GetCurrentFocus () != Nil) {
GetCurrentFocus ()->EffectiveFocusChanged (newFocused, updateMode);
}
}
void AbstractFocusOwner::Validate ()
{
if (GetCurrentFocus () != Nil) {
GetCurrentFocus ()->Validate ();
}
}
Boolean AbstractFocusOwner::CanBeFocused ()
{
if (GetEffectiveLive ()) {
ForEach (FocusItemPtr, it, MakeFocusIterator ()) {
AssertNotNil (it.Current ());
if (it.Current ()->CanBeFocused ()) {
return (True);
}
}
}
return (False);
}
void AbstractFocusOwner::DoSetupMenus ()
{
if (GetCurrentFocus () != Nil) {
GetCurrentFocus ()->DoSetupMenus ();
}
}
Boolean AbstractFocusOwner::DoCommand (const CommandSelection& selection)
{
if (GetCurrentFocus () != Nil) {
return (GetCurrentFocus ()->DoCommand (selection));
}
return (False);
}
void AbstractFocusOwner::TabbingFocus (SequenceDirection d,
Panel::UpdateMode updateMode)
{
SetCurrentFocus ((FocusItem*)Nil, updateMode, kValidate);
FocusItem* nextFocus = CalcNextFocus (d, True);
if (nextFocus == Nil) {
FocusItem::TabbingFocus (d, updateMode);
}
else {
nextFocus->TabbingFocus (d, updateMode);
}
}
Boolean AbstractFocusOwner::HandleTab (SequenceDirection d,
Boolean wrapping)
{
FocusItem* currentFocus = GetCurrentFocus ();
if (currentFocus != Nil) {
if (currentFocus->HandleTab (d, wrapping)) {
return (True);
}
}
FocusItem* nextFocus = CalcNextFocus (d, wrapping);
SetCurrentFocus ((FocusItem*)Nil, View::eDelayedUpdate, kValidate);
if (nextFocus != currentFocus) {
if (nextFocus != Nil) {
nextFocus->TabbingFocus (d, View::eDelayedUpdate);
}
return (True);
}
return (False);
}
Boolean AbstractFocusOwner::HandleKeyStroke (const KeyStroke& keyStroke)
{
SequenceDirection direction;
Boolean wrapping;
if (GetTab (keyStroke, direction, wrapping)) {
if (HandleTab (direction, wrapping)) {
return (True);
}
else if (not wrapping) {
return (HandleTab (direction, True));
}
}
return (False);
}
Boolean AbstractFocusOwner::DispatchKeyEvent (KeyBoard::KeyCode code, Boolean isUp,
const KeyBoard& keyBoardState,
KeyComposeState& composeState)
{
/*
* See if we handle it for tabbing purposes, otherwise pass to our focus.
*/
if (HandleKeyEvent (code, isUp, keyBoardState, composeState)) {
return (True);
}
else {
if (GetCurrentFocus () != Nil) {
return (GetCurrentFocus ()->DispatchKeyEvent (code, isUp, keyBoardState, composeState));
}
}
return (False);
}
Boolean AbstractFocusOwner::GetTab (const KeyStroke& keyStroke,
SequenceDirection& d,
Boolean& wrapping)
{
KeyStroke ks = keyStroke.GetCharacter ();
if (ks == KeyStroke::kTab) {
if (keyStroke.GetModifiers ().Contains (KeyStroke::eShiftKeyModifier)) {
d = eSequenceBackward;
}
else {
d = eSequenceForward;
}
wrapping = False;
return (True);
}
else if (ks == KeyStroke::kDownArrow) {
d = eSequenceForward;
wrapping = True;
return (True);
}
else if (ks == KeyStroke::kUpArrow) {
d = eSequenceBackward;
wrapping = True;
return (True);
}
return (False);
}
FocusItem* AbstractFocusOwner::GetCurrentFocus () const
{
return (fFocus);
}
void AbstractFocusOwner::SetCurrentFocus (FocusItem* newFocus,
Panel::UpdateMode updateMode, Boolean validate)
{
if (newFocus != GetCurrentFocus ()) {
SetCurrentFocus_ (newFocus, updateMode, validate);
}
Ensure (GetCurrentFocus () == newFocus);
}
void AbstractFocusOwner::SetCurrentFocus (SequenceDirection d,
Panel::UpdateMode updateMode, Boolean validate)
{
SetCurrentFocus (CalcNextFocus (d, True), updateMode, validate);
}
void AbstractFocusOwner::SetCurrentFocus_ (FocusItem* newFocus, Panel::UpdateMode updateMode,
Boolean validate)
{
Require (fFocus != newFocus);
if (GetCurrentFocus () != Nil) {
GetCurrentFocus ()->SetFocused (not kFocused, updateMode, validate);
}
fFocus = newFocus;
if (GetCurrentFocus () != Nil) {
GetCurrentFocus ()->SetFocused (kFocused, updateMode);
}
}
FocusItem* AbstractFocusOwner::CalcNextFocus (SequenceDirection d,
Boolean allowWrapAround)
{
Boolean matched = Boolean (fFocus == Nil);
{
ForEach (FocusItemPtr, it, MakeFocusIterator (d)) {
FocusItem* c = it.Current ();
AssertNotNil (c);
if (matched) {
Assert (c != fFocus);
if (c->CanBeFocused ()) {
return (c);
}
}
else {
matched = Boolean (c == fFocus);
}
}
}
if (matched and allowWrapAround) {
// wrap around search
ForEach (FocusItemPtr, it, MakeFocusIterator (d)) {
FocusItem* c = it.Current ();
AssertNotNil (c);
if (c == fFocus) {
// wrap around failed, could find no new candidate
break;
}
else {
if (c->CanBeFocused ()) {
return (c);
}
}
}
}
return (fFocus); // failed to find a new guy
}
void AbstractFocusOwner::SetOwnerOfFocusItem (FocusItem* focus, AbstractFocusOwner* owner)
{
Require ((owner == this) or (owner == Nil));
RequireNotNil (focus);
Require (focus->GetFocusOwner () != owner);
focus->SetFocusOwner (owner);
}
/*
********************************************************************************
********************************* FocusOwner ***********************************
********************************************************************************
*/
FocusOwner::FocusOwner ():
AbstractFocusOwner (),
fFocusList ()
{
}
void FocusOwner::AddFocus (FocusItem* focus, CollectionSize index)
{
RequireNotNil (focus);
Require (focus->GetFocusOwner () == Nil);
Require (not focus->GetFocused ());
if (index == eAppend) {
index = fFocusList.GetLength () + 1;
}
fFocusList.InsertAt (focus, index);
SetOwnerOfFocusItem (focus, this);
}
void FocusOwner::AddFocus (FocusItem* focus, FocusItem* neighborFocus, AddMode addMode)
{
RequireNotNil (neighborFocus);
CollectionSize index = fFocusList.IndexOf (neighborFocus);
Require (index != kBadSequenceIndex);
AddFocus (focus, (addMode == eAppend) ? index + 1 : index);
}
void FocusOwner::RemoveFocus (FocusItem* focus)
{
RequireNotNil (focus);
Require (focus->GetFocusOwner () == this);
if (focus == GetCurrentFocus ()) {
SetCurrentFocus ((FocusItem*)Nil, Panel::eDelayedUpdate, not kValidate);
}
fFocusList.Remove (focus);
SetOwnerOfFocusItem (focus, Nil);
}
void FocusOwner::ReorderFocus (FocusItem* focus, CollectionSize index)
{
RequireNotNil (focus);
if (index == eAppend) {
index = fFocusList.GetLength (); // not count + 1 cuz we will remove first,
// shrinking list temporarily
}
fFocusList.Remove (focus);
fFocusList.InsertAt (focus, index);
Ensure (fFocusList.IndexOf (focus) == index);
}
void FocusOwner::ReorderFocus (FocusItem* focus, FocusItem* neighborFocus, AddMode addMode)
{
RequireNotNil (neighborFocus);
Require (focus != neighborFocus);
CollectionSize index = fFocusList.IndexOf (neighborFocus);
CollectionSize oldIndex = fFocusList.IndexOf (focus);
Require (index != kBadSequenceIndex);
Require (oldIndex != kBadSequenceIndex);
if (oldIndex < index) {
index--;
}
ReorderFocus (focus, (addMode == eAppend) ? index + 1 : index);
}
SequenceIterator(FocusItemPtr)* FocusOwner::MakeFocusIterator (SequenceDirection
d)
{
return (fFocusList.MakeSequenceIterator (d));
}
Boolean FocusOwner::GetLive () const
{
return (True);
}
// For gnuemacs:
// Local Variables: ***
// mode:C++ ***
// tab-width:4 ***
// End: ***
| 24.32 | 112 | 0.649013 | SophistSolutions |
26e1232c1ee54e3539bbfb4e334302db9311aa40 | 736 | hpp | C++ | indexer/edits_migration.hpp | Barysman/omim | 469632c879027ec38278ebda699415c28dbd79e0 | [
"Apache-2.0"
] | null | null | null | indexer/edits_migration.hpp | Barysman/omim | 469632c879027ec38278ebda699415c28dbd79e0 | [
"Apache-2.0"
] | 1 | 2018-06-27T11:44:23.000Z | 2018-06-28T10:51:48.000Z | indexer/edits_migration.hpp | Barysman/omim | 469632c879027ec38278ebda699415c28dbd79e0 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "indexer/feature_decl.hpp"
#include "indexer/osm_editor.hpp"
#include "editor/xml_feature.hpp"
#include "base/exception.hpp"
#include "std/functional.hpp"
namespace editor
{
DECLARE_EXCEPTION(MigrationError, RootException);
using TGenerateIDFn = function<FeatureID()>;
/// Tries to match xml feature with one on a new mwm and retruns FeatrueID
/// of a found feature, thows MigrationError if migration fails.
FeatureID MigrateFeatureIndex(osm::Editor::ForEachFeaturesNearByFn & forEach,
XMLFeature const & xml,
osm::Editor::FeatureStatus const featureStatus,
TGenerateIDFn const & generateID);
} // namespace editor
| 29.44 | 77 | 0.690217 | Barysman |
26e27838aed2efaa0d5bd9092391796352379b44 | 13,642 | cpp | C++ | model/Event_attributes.cpp | ProcessMaker/pmio-sdk-cpprest | 4c8408571837995dceebbb119454b81cd2dff995 | [
"Apache-2.0"
] | null | null | null | model/Event_attributes.cpp | ProcessMaker/pmio-sdk-cpprest | 4c8408571837995dceebbb119454b81cd2dff995 | [
"Apache-2.0"
] | null | null | null | model/Event_attributes.cpp | ProcessMaker/pmio-sdk-cpprest | 4c8408571837995dceebbb119454b81cd2dff995 | [
"Apache-2.0"
] | 2 | 2017-08-06T12:56:32.000Z | 2018-09-06T05:09:47.000Z | /**
* ProcessMaker API
* This ProcessMaker I/O API provides access to a BPMN 2.0 compliant workflow engine api that is designed to be used as a microservice to support enterprise cloud applications. The current Alpha 1.0 version supports most of the descriptive class of the BPMN 2.0 specification.
*
* OpenAPI spec version: 1.0.0
* Contact: support@processmaker.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*
* 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 "Event_attributes.h"
namespace io {
namespace processmaker {
namespace pmio {
namespace model {
Event_attributes::Event_attributes()
{
m_Name = U("");
m_Description = U("");
m_DescriptionIsSet = false;
m_Process_id = U("");
m_Message_id = nullptr;
m_Message_idIsSet = false;
m_Type = U("");
m_Definition = U("");
m_Interrupting = false;
m_InterruptingIsSet = false;
m_Condition = U("");
m_ConditionIsSet = false;
m_Time = U("");
m_TimeIsSet = false;
m_Duration = U("");
m_DurationIsSet = false;
m_Cycle = U("");
m_CycleIsSet = false;
m_Attached_to_task_id = U("");
m_Attached_to_task_idIsSet = false;
m_Created_at = U("");
m_Created_atIsSet = false;
m_Updated_at = U("");
m_Updated_atIsSet = false;
}
Event_attributes::~Event_attributes()
{
}
void Event_attributes::validate()
{
// TODO: implement validation
}
web::json::value Event_attributes::toJson() const
{
web::json::value val = web::json::value::object();
val[U("name")] = ModelBase::toJson(m_Name);
if(m_DescriptionIsSet)
{
val[U("description")] = ModelBase::toJson(m_Description);
}
val[U("process_id")] = ModelBase::toJson(m_Process_id);
if(m_Message_idIsSet)
{
val[U("message_id")] = ModelBase::toJson(m_Message_id);
}
val[U("type")] = ModelBase::toJson(m_Type);
val[U("definition")] = ModelBase::toJson(m_Definition);
if(m_InterruptingIsSet)
{
val[U("interrupting")] = ModelBase::toJson(m_Interrupting);
}
if(m_ConditionIsSet)
{
val[U("condition")] = ModelBase::toJson(m_Condition);
}
if(m_TimeIsSet)
{
val[U("time")] = ModelBase::toJson(m_Time);
}
if(m_DurationIsSet)
{
val[U("duration")] = ModelBase::toJson(m_Duration);
}
if(m_CycleIsSet)
{
val[U("cycle")] = ModelBase::toJson(m_Cycle);
}
if(m_Attached_to_task_idIsSet)
{
val[U("attached_to_task_id")] = ModelBase::toJson(m_Attached_to_task_id);
}
if(m_Created_atIsSet)
{
val[U("created_at")] = ModelBase::toJson(m_Created_at);
}
if(m_Updated_atIsSet)
{
val[U("updated_at")] = ModelBase::toJson(m_Updated_at);
}
return val;
}
void Event_attributes::fromJson(web::json::value& val)
{
setName(ModelBase::stringFromJson(val[U("name")]));
if(val.has_field(U("description")))
{
setDescription(ModelBase::stringFromJson(val[U("description")]));
}
setProcessId(ModelBase::stringFromJson(val[U("process_id")]));
if(val.has_field(U("message_id")))
{
setMessageId(ModelBase::int32_tFromJson(val[U("message_id")]));
}
setType(ModelBase::stringFromJson(val[U("type")]));
setDefinition(ModelBase::stringFromJson(val[U("definition")]));
if(val.has_field(U("interrupting")))
{
setInterrupting(ModelBase::boolFromJson(val[U("interrupting")]));
}
if(val.has_field(U("condition")))
{
setCondition(ModelBase::stringFromJson(val[U("condition")]));
}
if(val.has_field(U("time")))
{
setTime(ModelBase::stringFromJson(val[U("time")]));
}
if(val.has_field(U("duration")))
{
setDuration(ModelBase::stringFromJson(val[U("duration")]));
}
if(val.has_field(U("cycle")))
{
setCycle(ModelBase::stringFromJson(val[U("cycle")]));
}
if(val.has_field(U("attached_to_task_id")))
{
setAttachedToTaskId(ModelBase::stringFromJson(val[U("attached_to_task_id")]));
}
if(val.has_field(U("created_at")))
{
setCreatedAt(ModelBase::stringFromJson(val[U("created_at")]));
}
if(val.has_field(U("updated_at")))
{
setUpdatedAt(ModelBase::stringFromJson(val[U("updated_at")]));
}
}
void Event_attributes::toMultipart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& prefix) const
{
utility::string_t namePrefix = prefix;
if(namePrefix.size() > 0 && namePrefix[namePrefix.size() - 1] != U('.'))
{
namePrefix += U(".");
}
multipart->add(ModelBase::toHttpContent(namePrefix + U("name"), m_Name));
if(m_DescriptionIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + U("description"), m_Description));
}
multipart->add(ModelBase::toHttpContent(namePrefix + U("process_id"), m_Process_id));
if(m_Message_idIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + U("message_id"), m_Message_id));
}
multipart->add(ModelBase::toHttpContent(namePrefix + U("type"), m_Type));
multipart->add(ModelBase::toHttpContent(namePrefix + U("definition"), m_Definition));
if(m_InterruptingIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + U("interrupting"), m_Interrupting));
}
if(m_ConditionIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + U("condition"), m_Condition));
}
if(m_TimeIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + U("time"), m_Time));
}
if(m_DurationIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + U("duration"), m_Duration));
}
if(m_CycleIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + U("cycle"), m_Cycle));
}
if(m_Attached_to_task_idIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + U("attached_to_task_id"), m_Attached_to_task_id));
}
if(m_Created_atIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + U("created_at"), m_Created_at));
}
if(m_Updated_atIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + U("updated_at"), m_Updated_at));
}
}
void Event_attributes::fromMultiPart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& prefix)
{
utility::string_t namePrefix = prefix;
if(namePrefix.size() > 0 && namePrefix[namePrefix.size() - 1] != U('.'))
{
namePrefix += U(".");
}
setName(ModelBase::stringFromHttpContent(multipart->getContent(U("name"))));
if(multipart->hasContent(U("description")))
{
setDescription(ModelBase::stringFromHttpContent(multipart->getContent(U("description"))));
}
setProcessId(ModelBase::stringFromHttpContent(multipart->getContent(U("process_id"))));
if(multipart->hasContent(U("message_id")))
{
setMessageId(ModelBase::int32_tFromHttpContent(multipart->getContent(U("message_id"))));
}
setType(ModelBase::stringFromHttpContent(multipart->getContent(U("type"))));
setDefinition(ModelBase::stringFromHttpContent(multipart->getContent(U("definition"))));
if(multipart->hasContent(U("interrupting")))
{
setInterrupting(ModelBase::boolFromHttpContent(multipart->getContent(U("interrupting"))));
}
if(multipart->hasContent(U("condition")))
{
setCondition(ModelBase::stringFromHttpContent(multipart->getContent(U("condition"))));
}
if(multipart->hasContent(U("time")))
{
setTime(ModelBase::stringFromHttpContent(multipart->getContent(U("time"))));
}
if(multipart->hasContent(U("duration")))
{
setDuration(ModelBase::stringFromHttpContent(multipart->getContent(U("duration"))));
}
if(multipart->hasContent(U("cycle")))
{
setCycle(ModelBase::stringFromHttpContent(multipart->getContent(U("cycle"))));
}
if(multipart->hasContent(U("attached_to_task_id")))
{
setAttachedToTaskId(ModelBase::stringFromHttpContent(multipart->getContent(U("attached_to_task_id"))));
}
if(multipart->hasContent(U("created_at")))
{
setCreatedAt(ModelBase::stringFromHttpContent(multipart->getContent(U("created_at"))));
}
if(multipart->hasContent(U("updated_at")))
{
setUpdatedAt(ModelBase::stringFromHttpContent(multipart->getContent(U("updated_at"))));
}
}
utility::string_t Event_attributes::getName() const
{
return m_Name;
}
void Event_attributes::setName(utility::string_t value)
{
m_Name = value;
}
utility::string_t Event_attributes::getDescription() const
{
return m_Description;
}
void Event_attributes::setDescription(utility::string_t value)
{
m_Description = value;
m_DescriptionIsSet = true;
}
bool Event_attributes::descriptionIsSet() const
{
return m_DescriptionIsSet;
}
void Event_attributes::unsetDescription()
{
m_DescriptionIsSet = false;
}
utility::string_t Event_attributes::getProcessId() const
{
return m_Process_id;
}
void Event_attributes::setProcessId(utility::string_t value)
{
m_Process_id = value;
}
int32_t Event_attributes::getMessageId() const
{
return m_Message_id;
}
void Event_attributes::setMessageId(int32_t value)
{
m_Message_id = value;
m_Message_idIsSet = true;
}
bool Event_attributes::message_idIsSet() const
{
return m_Message_idIsSet;
}
void Event_attributes::unsetMessage_id()
{
m_Message_idIsSet = false;
}
utility::string_t Event_attributes::getType() const
{
return m_Type;
}
void Event_attributes::setType(utility::string_t value)
{
m_Type = value;
}
utility::string_t Event_attributes::getDefinition() const
{
return m_Definition;
}
void Event_attributes::setDefinition(utility::string_t value)
{
m_Definition = value;
}
bool Event_attributes::getInterrupting() const
{
return m_Interrupting;
}
void Event_attributes::setInterrupting(bool value)
{
m_Interrupting = value;
m_InterruptingIsSet = true;
}
bool Event_attributes::interruptingIsSet() const
{
return m_InterruptingIsSet;
}
void Event_attributes::unsetInterrupting()
{
m_InterruptingIsSet = false;
}
utility::string_t Event_attributes::getCondition() const
{
return m_Condition;
}
void Event_attributes::setCondition(utility::string_t value)
{
m_Condition = value;
m_ConditionIsSet = true;
}
bool Event_attributes::conditionIsSet() const
{
return m_ConditionIsSet;
}
void Event_attributes::unsetCondition()
{
m_ConditionIsSet = false;
}
utility::string_t Event_attributes::getTime() const
{
return m_Time;
}
void Event_attributes::setTime(utility::string_t value)
{
m_Time = value;
m_TimeIsSet = true;
}
bool Event_attributes::timeIsSet() const
{
return m_TimeIsSet;
}
void Event_attributes::unsetTime()
{
m_TimeIsSet = false;
}
utility::string_t Event_attributes::getDuration() const
{
return m_Duration;
}
void Event_attributes::setDuration(utility::string_t value)
{
m_Duration = value;
m_DurationIsSet = true;
}
bool Event_attributes::durationIsSet() const
{
return m_DurationIsSet;
}
void Event_attributes::unsetDuration()
{
m_DurationIsSet = false;
}
utility::string_t Event_attributes::getCycle() const
{
return m_Cycle;
}
void Event_attributes::setCycle(utility::string_t value)
{
m_Cycle = value;
m_CycleIsSet = true;
}
bool Event_attributes::cycleIsSet() const
{
return m_CycleIsSet;
}
void Event_attributes::unsetCycle()
{
m_CycleIsSet = false;
}
utility::string_t Event_attributes::getAttachedToTaskId() const
{
return m_Attached_to_task_id;
}
void Event_attributes::setAttachedToTaskId(utility::string_t value)
{
m_Attached_to_task_id = value;
m_Attached_to_task_idIsSet = true;
}
bool Event_attributes::attached_to_task_idIsSet() const
{
return m_Attached_to_task_idIsSet;
}
void Event_attributes::unsetAttached_to_task_id()
{
m_Attached_to_task_idIsSet = false;
}
utility::string_t Event_attributes::getCreatedAt() const
{
return m_Created_at;
}
void Event_attributes::setCreatedAt(utility::string_t value)
{
m_Created_at = value;
m_Created_atIsSet = true;
}
bool Event_attributes::created_atIsSet() const
{
return m_Created_atIsSet;
}
void Event_attributes::unsetCreated_at()
{
m_Created_atIsSet = false;
}
utility::string_t Event_attributes::getUpdatedAt() const
{
return m_Updated_at;
}
void Event_attributes::setUpdatedAt(utility::string_t value)
{
m_Updated_at = value;
m_Updated_atIsSet = true;
}
bool Event_attributes::updated_atIsSet() const
{
return m_Updated_atIsSet;
}
void Event_attributes::unsetUpdated_at()
{
m_Updated_atIsSet = false;
}
}
}
}
}
| 26.184261 | 277 | 0.672555 | ProcessMaker |
26e643b953a6a51f89ecdfd216e622e75d0df6ae | 1,858 | cpp | C++ | HackerRank/Searching/A_-_Ice_Cream_Parlor.cpp | Sohelr360/my_codes | 9bdd28f62d3850aad8f8af2a253ba66138a7057c | [
"MIT"
] | null | null | null | HackerRank/Searching/A_-_Ice_Cream_Parlor.cpp | Sohelr360/my_codes | 9bdd28f62d3850aad8f8af2a253ba66138a7057c | [
"MIT"
] | null | null | null | HackerRank/Searching/A_-_Ice_Cream_Parlor.cpp | Sohelr360/my_codes | 9bdd28f62d3850aad8f8af2a253ba66138a7057c | [
"MIT"
] | null | null | null | /**
* Author: Sohel Rana
* Date: 2022-06-12 11:50:13
* Task: A_-_Ice_Cream_Parlor
**/
#include <bits/stdc++.h>
#define endl '\n'
#define sqr(x) (x) * (x)
#define gcd(x,y) __gcd(x, y)
#define lcm(x,y) ((x/gcd(x,y)) * y)
#define pf push_front
#define pb push_back
#define fi first
#define se second
#define mp make_pair
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define sz(x) (long long)x.size()
#define prec(x) fixed<<setprecision(x)
#define debug(x) cerr<<#x<<" = "<<(x)<< endl
#define debug2(x,y) cerr<<#x<<" = "<<(x)<<","<<#y<<" = "<<(y)<< endl
#define unsyncIO ios_base::sync_with_stdio(false); cin.tie(nullptr)
using ll = long long;
using db = double;
using ld = long double;
using ull = unsigned long long;
const ld pi = acos((ld)-1);
const int mod = 1e9+7;
const ll inf = 1e18;
const ld eps = 1e-9;
const int mx = 1e4+5;
using namespace std;
vector<int> TwoPointer(vector<pair<int,int> >& vp, int target, int n) {
int left = 0, right = n-1;
while(left < right) {
ll sum = vp[left].fi + vp[right].fi;
if(sum == target) {
return {vp[left].se, vp[right].se};
}
else if(sum < target)
left++;
else
right--;
}
return {};
}
int main()
{
//freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
unsyncIO;
int t;
cin>>t;
while(t--) {
int target, n;
cin>>target>>n;
vector<pair<int,int> > vp;
for(int i = 1; i <= n; i++){
int x; cin>>x;
vp.pb({x,i});
}
sort(all(vp));
vector<int> ans;
ans = TwoPointer(vp, target, n);
sort(all(ans));
cout<<ans[0] <<" "<<ans[1]<<endl;
}
return 0;
} | 24.773333 | 71 | 0.50592 | Sohelr360 |
26e87472aa034a1a5ddc92700c89d58663bcf06f | 46,263 | cpp | C++ | src/mame/video/konamigx.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 26 | 2015-03-31T06:25:51.000Z | 2021-12-14T09:29:04.000Z | src/mame/video/konamigx.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | null | null | null | src/mame/video/konamigx.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 10 | 2015-03-27T05:45:51.000Z | 2022-02-04T06:57:36.000Z | // license:BSD-3-Clause
// copyright-holders:R. Belmont, Acho A. Tang, Phil Stroffolino, Olivier Galibert
/*
* video/konamigx.cpp - Konami GX video hardware (here there be dragons, and achocode)
*
*/
#include "emu.h"
#include "video/k053250.h"
#include "includes/konamigx.h"
//#define GX_DEBUG
#define VERBOSE 0
static inline void set_color_555(palette_device &palette, pen_t color, int rshift, int gshift, int bshift, uint16_t data);
void konamigx_state::konamigx_precache_registers(void)
{
// (see sprite color coding scheme on p.46 & 47)
static const int coregmasks[5] = {0xf,0xe,0xc,0x8,0x0};
static const int coregshifts[5]= {4,5,6,7,8};
int i;
i = m_k055673->k053247_read_register(0x8/2);
m_k053247_vrcbk[0] = (i & 0x000f) << 14;
m_k053247_vrcbk[1] = (i & 0x0f00) << 6;
i = m_k055673->k053247_read_register(0xa/2);
m_k053247_vrcbk[2] = (i & 0x000f) << 14;
m_k053247_vrcbk[3] = (i & 0x0f00) << 6;
// COREG == OBJSET2+1C == bit8-11 of OPSET ??? (see p.50 last table, needs p.49 to confirm)
m_k053247_opset = m_k055673->k053247_read_register(0xc/2);
i = m_k053247_opset & 7; if (i > 4) i = 4;
m_k053247_coreg = m_k055673->k053247_read_register(0xc/2)>>8 & 0xf;
m_k053247_coreg =(m_k053247_coreg & coregmasks[i]) << 12;
m_k053247_coregshift = coregshifts[i];
m_opri = m_k055555->K055555_read_register(K55_PRIINP_8);
m_oinprion = m_k055555->K055555_read_register(K55_OINPRI_ON);
m_vcblk[0] = m_k055555->K055555_read_register(K55_PALBASE_A);
m_vcblk[1] = m_k055555->K055555_read_register(K55_PALBASE_B);
m_vcblk[2] = m_k055555->K055555_read_register(K55_PALBASE_C);
m_vcblk[3] = m_k055555->K055555_read_register(K55_PALBASE_D);
m_vcblk[4] = m_k055555->K055555_read_register(K55_PALBASE_SUB1);
m_vcblk[5] = m_k055555->K055555_read_register(K55_PALBASE_SUB2);
m_ocblk = m_k055555->K055555_read_register(K55_PALBASE_OBJ);
m_vinmix = m_k055555->K055555_read_register(K55_BLEND_ENABLES);
m_vmixon = m_k055555->K055555_read_register(K55_VINMIX_ON);
m_osinmix = m_k055555->K055555_read_register(K55_OSBLEND_ENABLES);
m_osmixon = m_k055555->K055555_read_register(K55_OSBLEND_ON);
}
inline int konamigx_state::K053247GX_combine_c18(int attrib) // (see p.46)
{
int c18;
c18 = (attrib & 0xff)<<m_k053247_coregshift | m_k053247_coreg;
if (m_gx_wrport2 & 4) c18 &= 0x3fff; else
if (!(m_gx_wrport2 & 8)) c18 = (c18 & 0x3fff) | (attrib<<6 & 0xc000);
return(c18);
}
inline int konamigx_state::K055555GX_decode_objcolor(int c18) // (see p.59 7.2.2)
{
int ocb, opon;
opon = m_oinprion<<8 | 0xff;
ocb = (m_ocblk & 7) << 10;
c18 &= opon;
ocb &=~opon;
return((ocb | c18) >> m_k053247_coregshift);
}
inline int konamigx_state::K055555GX_decode_inpri(int c18) // (see p.59 7.2.2)
{
int op = m_opri;
c18 >>= 8;
op &= m_oinprion;
c18 &=~m_oinprion;
return(c18 | op);
}
K055673_CB_MEMBER(konamigx_state::type2_sprite_callback)
{
int num = *code;
int c18 = *color;
*code = m_k053247_vrcbk[num>>14] | (num & 0x3fff);
c18 = K053247GX_combine_c18(c18);
*color = K055555GX_decode_objcolor(c18);
*priority_mask = K055555GX_decode_inpri(c18);
}
K055673_CB_MEMBER(konamigx_state::dragoonj_sprite_callback)
{
int num, op, pri, c18;
num = *code;
*code = m_k053247_vrcbk[num>>14] | (num & 0x3fff);
c18 = pri = *color;
op = m_opri;
pri = (pri & 0x200) ? 4 : pri>>4 & 0xf;
op &= m_oinprion;
pri &=~m_oinprion;
*priority_mask = pri | op;
c18 = K053247GX_combine_c18(c18);
*color = K055555GX_decode_objcolor(c18);
}
K055673_CB_MEMBER(konamigx_state::salmndr2_sprite_callback)
{
int num, op, pri, c18;
num = *code;
*code = m_k053247_vrcbk[num>>14] | (num & 0x3fff);
c18 = pri = *color;
op = m_opri;
pri = pri>>4 & 0x3f;
op &= m_oinprion;
pri &=~m_oinprion;
*priority_mask = pri | op;
c18 = K053247GX_combine_c18(c18);
*color = K055555GX_decode_objcolor(c18);
}
K055673_CB_MEMBER(konamigx_state::le2_sprite_callback)
{
int num, op, pri;
num = *code;
*code = m_k053247_vrcbk[num>>14] | (num & 0x3fff);
pri = *color;
*color &= 0x1f;
op = m_opri;
pri &= 0xf0;
op &= m_oinprion;
pri &=~m_oinprion;
*priority_mask = pri | op;
}
int konamigx_state::K055555GX_decode_vmixcolor(int layer, int *color) // (see p.62 7.2.6 and p.27 3.3)
{
int vcb, shift, pal, vmx, von, pl45, emx;
vcb = m_vcblk[layer]<<6;
shift = layer<<1;
pal = *color;
vmx = m_vinmix>>shift & 3;
von = m_vmixon>>shift & 3;
emx = pl45 = pal>>4 & 3;
pal &= 0xf;
pl45 &= von;
vmx &= von;
pl45 <<= 4;
emx &= ~von;
pal |= pl45;
emx |= vmx;
pal |= vcb;
//if (m_gx_le2_textcolour_hack)
// if (layer==0)
// pal |= 0x1c0;
if (von == 3) emx = -1; // invalidate external mix code if all bits are from internal
*color = pal;
return(emx);
}
int konamigx_state::K055555GX_decode_osmixcolor(int layer, int *color) // (see p.63, p.49-50 and p.27 3.3)
{
int scb, shift, pal, osmx, oson, pl45, emx;
shift = layer<<1;
pal = *color;
osmx = m_osinmix>>shift & 3;
oson = m_osmixon>>shift & 3;
if (layer)
{
// layer 1-3 are external tile layers
scb = m_vcblk[layer+3]<<6;
emx = pl45 = pal>>4 & 3;
pal &= 0xf;
pl45 &= oson;
osmx &= oson;
pl45 <<= 4;
emx &= ~oson;
pal |= pl45;
emx |= osmx;
pal |= scb;
if (oson == 3) emx = -1; // invalidate external mix code if all bits are from internal
*color = pal;
}
else
{
// layer 0 is the sprite layer with different attributes decode; detail on p.49 (missing)
emx = 0; // k053247_read_register(??)>>? & 3;
osmx &= oson;
emx &=~oson;
emx |= osmx;
}
return(emx);
}
void konamigx_state::wipezbuf(int noshadow)
{
const rectangle &visarea = m_screen->visible_area();
int w = visarea.width();
int h = visarea.height();
uint8_t *zptr = m_gx_objzbuf;
int ecx = h;
do { memset(zptr, -1, w); zptr += GX_ZBUFW; } while (--ecx);
if (!noshadow)
{
zptr = m_gx_shdzbuf.get();
w <<= 1;
ecx = h;
do { memset(zptr, -1, w); zptr += (GX_ZBUFW<<1); } while (--ecx);
}
}
/*
* Sprite Format
* ------------------
*
* Word | Bit(s) | Use
* -----+-fedcba9876543210-+----------------
* 0 | x--------------- | active (show this sprite)
* 0 | -x-------------- | maintain aspect ratio (when set, zoom y acts on both axis)
* 0 | --x------------- | flip y
* 0 | ---x------------ | flip x
* 0 | ----xxxx-------- | sprite size (see below)
* 0 | --------xxxxxxxx | zcode
* 1 | xxxxxxxxxxxxxxxx | sprite code
* 2 | ------xxxxxxxxxx | y position
* 3 | ------xxxxxxxxxx | x position
* 4 | xxxxxxxxxxxxxxxx | zoom y (0x40 = normal, <0x40 = enlarge, >0x40 = reduce)
* 5 | xxxxxxxxxxxxxxxx | zoom x (0x40 = normal, <0x40 = enlarge, >0x40 = reduce)
* 6 | x--------------- | mirror y (top half is drawn as mirror image of the bottom)
* 6 | -x-------------- | mirror x (right half is drawn as mirror image of the left)
* 6 | --xx------------ | reserved (sprites with these two bits set don't seem to be graphics data at all)
* 6 | ----xx---------- | shadow code: 0=off, 0x400=preset1, 0x800=preset2, 0xc00=preset3
* 6 | ------xx-------- | effect code: flicker, upper palette, full shadow...etc. (game dependent)
* 6 | --------xxxxxxxx | "color", but depends on external connections (implies priority)
* 7 | xxxxxxxxxxxxxxxx | game dependent
*
* shadow enables transparent shadows. Note that it applies to the last sprite pen ONLY.
* The rest of the sprite remains normal.
*/
#define GX_MAX_SPRITES 512*2
#define GX_MAX_LAYERS 6
#define GX_MAX_OBJECTS (GX_MAX_SPRITES + GX_MAX_LAYERS)
void konamigx_state::konamigx_mixer_init(screen_device &screen, int objdma)
{
m_gx_objdma = 0;
m_gx_primode = 0;
m_gx_objzbuf = &screen.priority().pix(0);
m_gx_shdzbuf = std::make_unique<uint8_t[]>(GX_ZBUFSIZE);
m_gx_objpool = std::make_unique<GX_OBJ[]>(GX_MAX_OBJECTS);
m_k054338->export_config(&m_K054338_shdRGB);
if (objdma)
{
m_gx_spriteram_alloc = std::make_unique<uint16_t[]>(0x2000/2);
m_gx_spriteram = m_gx_spriteram_alloc.get();
m_gx_objdma = 1;
}
else
m_k055673->k053247_get_ram(&m_gx_spriteram);
m_palette->set_shadow_dRGB32(3,-80,-80,-80, 0);
m_k054338->invert_alpha(1);
}
void konamigx_state::konamigx_mixer_primode(int mode)
{
m_gx_primode = mode;
}
void konamigx_state::konamigx_objdma(void)
{
uint16_t* k053247_ram;
m_k055673->k053247_get_ram(&k053247_ram);
if (m_gx_objdma && m_gx_spriteram && k053247_ram) memcpy(m_gx_spriteram, k053247_ram, 0x1000);
}
void konamigx_state::konamigx_mixer(screen_device &screen, bitmap_rgb32 &bitmap, const rectangle &cliprect,
tilemap_t *sub1, int sub1flags,
tilemap_t *sub2, int sub2flags,
int mixerflags, bitmap_ind16 *extra_bitmap, int rushingheroes_hack)
{
int objbuf[GX_MAX_OBJECTS];
int shadowon[3], shdpri[3], layerid[6], layerpri[6];
GX_OBJ *objpool, *objptr;
int cltc_shdpri, /*prflp,*/ disp;
// buffer can move when it's resized, so refresh the pointer
m_gx_objzbuf = &screen.priority().pix(0);
// abort if object database failed to initialize
objpool = m_gx_objpool.get();
if (!objpool) return;
// clear screen with backcolor and update flicker pulse
if (m_gx_wrport1_0 & 0x20)
m_k054338->fill_backcolor(bitmap,
cliprect,
m_palette->pens() + (m_k055555->K055555_read_register(0) << 9),
m_k055555->K055555_read_register(1));
else
m_k054338->fill_solid_bg(bitmap, cliprect);
// abort if video has been disabled
disp = m_k055555->K055555_read_register(K55_INPUT_ENABLES);
if (!disp) return;
cltc_shdpri = m_k054338->register_r(K338_REG_CONTROL);
if (!rushingheroes_hack) // Slam Dunk 2 never sets this. It's either part of the protection, or type4 doesn't use it
{
if (!(cltc_shdpri & K338_CTL_KILL)) return;
}
// demote shadows by one layer when this bit is set??? (see p.73 8.6)
cltc_shdpri &= K338_CTL_SHDPRI;
// wipe z-buffer
if (mixerflags & GXMIX_NOZBUF)
mixerflags |= GXMIX_NOSHADOW;
else
wipezbuf(mixerflags & GXMIX_NOSHADOW);
// cache global parameters
konamigx_precache_registers();
// init OBJSET2 and mixer parameters (see p.51 and chapter 7)
layerid[0] = 0; layerid[1] = 1; layerid[2] = 2; layerid[3] = 3; layerid[4] = 4; layerid[5] = 5;
// invert layer priority when this flag is set (not used by any GX game?)
//prflp = K055555_read_register(K55_CONTROL) & K55_CTL_FLIPPRI;
layerpri[0] = m_k055555->K055555_read_register(K55_PRIINP_0);
layerpri[1] = m_k055555->K055555_read_register(K55_PRIINP_3);
layerpri[3] = m_k055555->K055555_read_register(K55_PRIINP_7);
layerpri[4] = m_k055555->K055555_read_register(K55_PRIINP_9);
layerpri[5] = m_k055555->K055555_read_register(K55_PRIINP_10);
int shdprisel;
if (m_gx_primode == -1)
{
// Lethal Enforcer hack (requires pixel color comparison)
layerpri[2] = m_k055555->K055555_read_register(K55_PRIINP_3) + 0x20;
shdprisel = 0x3f;
}
else
{
layerpri[2] = m_k055555->K055555_read_register(K55_PRIINP_6);
shdprisel = m_k055555->K055555_read_register(K55_SHD_PRI_SEL);
}
// SHDPRISEL filters shadows by different priority comparison methods (UNIMPLEMENTED, see detail on p.66)
if (!(shdprisel & 0x03)) shadowon[0] = 0;
if (!(shdprisel & 0x0c)) shadowon[1] = 0;
if (!(shdprisel & 0x30)) shadowon[2] = 0;
shdpri[0] = m_k055555->K055555_read_register(K55_SHAD1_PRI);
shdpri[1] = m_k055555->K055555_read_register(K55_SHAD2_PRI);
shdpri[2] = m_k055555->K055555_read_register(K55_SHAD3_PRI);
int spri_min = 0;
shadowon[2] = shadowon[1] = shadowon[0] = 0;
int k = 0;
if (!(mixerflags & GXMIX_NOSHADOW))
{
int i,j;
// only enable shadows beyond a +/-7 RGB threshold
for (j=0,i=0; i<3; j+=3,i++)
{
k = m_K054338_shdRGB[j ]; if (k < -7 || k > 7) { shadowon[i] = 1; continue; }
k = m_K054338_shdRGB[j+1]; if (k < -7 || k > 7) { shadowon[i] = 1; continue; }
k = m_K054338_shdRGB[j+2]; if (k < -7 || k > 7) { shadowon[i] = 1; }
}
// SHDON specifies layers on which shadows can be projected (see detail on p.65 7.2.8)
int temp = m_k055555->K055555_read_register(K55_SHD_ON);
for (i=0; i<4; i++) if (!(temp>>i & 1) && spri_min < layerpri[i]) spri_min = layerpri[i]; // HACK
// update shadows status
m_k054338->update_all_shadows(rushingheroes_hack, *m_palette);
}
// pre-sort layers
for (int j=0; j<5; j++)
{
int temp1 = layerpri[j];
for (int i=j+1; i<6; i++)
{
int temp2 = layerpri[i];
if ((uint32_t)temp1 <= (uint32_t)temp2)
{
layerpri[i] = temp1; layerpri[j] = temp1 = temp2;
temp2 = layerid[i]; layerid[i] = layerid[j]; layerid[j] = temp2;
}
}
}
// build object database and create indices
objptr = objpool;
int nobj = 0;
for (int i=5; i>=0; i--)
{
int offs;
int code = layerid[i];
switch (code)
{
/*
Background layers are represented by negative offset values as follow:
0+ : normal sprites
-1 : tile layer A - D
-2 : K053936 ROZ+ layer 1
-3 : K053936 ROZ+ layer 2
-4 : K053250 LVC layer 1
-5 : K053250 LVC layer 2
*/
case 4 :
offs = -128;
if (sub1flags & 0xf) { if (sub1flags & GXSUB_K053250) offs = -4; else if (sub1) offs = -2; }
break;
case 5 :
offs = -128;
if (sub2flags & 0xf) { if (sub2flags & GXSUB_K053250) offs = -5; else if (sub2) offs = -3; }
if (extra_bitmap) offs = -3;
break;
default: offs = -1;
}
if (offs != -128)
{
objptr->order = layerpri[i]<<24;
objptr->code = code;
objptr->offs = offs;
objptr++;
objbuf[nobj] = nobj;
nobj++;
}
}
// i = j = 0xff;
int l = 0;
u32 start_addr = m_type3_spriteram_bank ? 0x800 : 0;
u32 end_addr = start_addr + 0x800;
for (int offs=start_addr; offs<end_addr; offs+=8)
{
int pri = 0;
if (!(m_gx_spriteram[offs] & 0x8000)) continue;
int zcode = m_gx_spriteram[offs] & 0xff;
// invert z-order when opset_pri is set (see p.51 OPSET PRI)
if (m_k053247_opset & 0x10) zcode = 0xff - zcode;
int code = m_gx_spriteram[offs+1];
int color = k = m_gx_spriteram[offs+6];
l = m_gx_spriteram[offs+7];
m_k055673->m_k053247_cb(&code, &color, &pri);
/*
shadow = shadow code
spri = shadow priority
temp1 = add solid object
temp2 = solid pens draw mode
temp3 = add shadow object
temp4 = shadow pens draw mode
*/
int temp4 = 0;
int temp3 = 0;
int temp2 = 0;
int temp1 = 0;
int spri = 0;
int shadow = 0;
if (color & K055555_FULLSHADOW)
{
shadow = 3; // use default intensity and color
spri = pri; // retain host priority
temp3 = 1; // add shadow
temp4 = 5; // draw full shadow
}
else
{
shadow = k>>10 & 3;
if (shadow) // object has shadow?
{
int k053246_objset1 = m_k055673->k053246_read_register(5);
if (shadow != 1 || k053246_objset1 & 0x20)
{
shadow--;
temp1 = 1; // add solid
temp2 = 1; // draw partial solid
if (shadowon[shadow])
{
temp3 = 1; // add shadow
temp4 = 4; // draw partial shadow
}
}
else
{
// drop the entire sprite to shadow if its shadow code is 1 and SD0EN is off (see p.48)
shadow = 0;
if (!shadowon[0]) continue;
temp3 = 1; // add shadow
temp4 = 5; // draw full shadow
}
}
else
{
temp1 = 1; // add solid
temp2 = 0; // draw full solid
}
if (temp1)
{
// tag sprite for alpha blending
if (color>>K055555_MIXSHIFT & 3) temp2 |= 2;
}
if (temp3)
{
// determine shadow priority
spri = (m_k053247_opset & 0x20) ? pri : shdpri[shadow]; // (see p.51 OPSET SDSEL)
}
}
switch (m_gx_primode & 0xf)
{
// Dadandarn zcode suppression
case 1:
zcode = 0;
break;
// Daisukiss bad shadow filter
case 4:
if (k & 0x3000 || k == 0x0800) continue;
[[fallthrough]];
// Tokkae shadow masking (INACCURATE)
case 5:
if (spri < spri_min) spri = spri_min;
break;
}
/*
default sort order:
fedcba9876543210fedcba9876543210
xxxxxxxx------------------------ (priority)
--------xxxxxxxx---------------- (zcode)
----------------xxxxxxxx-------- (offset)
------------------------xxxx---- (shadow mode)
----------------------------xxxx (shadow code)
*/
if (temp1)
{
// add objects with solid or alpha pens
int order = pri<<24 | zcode<<16 | offs<<(8-3) | temp2<<4;
objptr->order = order;
objptr->offs = offs;
objptr->code = code;
objptr->color = color;
objptr++;
objbuf[nobj] = nobj;
nobj++;
}
if (temp3 && !(color & K055555_SKIPSHADOW) && !(mixerflags & GXMIX_NOSHADOW))
{
// add objects with shadows if enabled
int order = spri<<24 | zcode<<16 | offs<<(8-3) | temp4<<4 | shadow;
objptr->order = order;
objptr->offs = offs;
objptr->code = code;
objptr->color = color;
objptr++;
objbuf[nobj] = nobj;
nobj++;
}
}
// sort objects in decending order (SLOW)
k = nobj;
l = nobj - 1;
for (int j=0; j<l; j++)
{
int temp1 = objbuf[j];
int temp2 = objpool[temp1].order;
for (int i=j+1; i<k; i++)
{
int temp3 = objbuf[i];
int temp4 = objpool[temp3].order;
if ((uint32_t)temp2 <= (uint32_t)temp4) { temp2 = temp4; objbuf[i] = temp1; objbuf[j] = temp1 = temp3; }
}
}
konamigx_mixer_draw(screen,bitmap,cliprect,sub1,sub1flags,sub2,sub2flags,mixerflags,extra_bitmap,rushingheroes_hack,
objpool,
objbuf,
nobj
);
}
void konamigx_state::gx_draw_basic_tilemaps(screen_device &screen, bitmap_rgb32 &bitmap, const rectangle &cliprect, int mixerflags, int code)
{
int temp1,temp2,temp3,temp4;
int i = code<<1;
int j = mixerflags>>i & 3;
int k = 0;
int disp = m_k055555->K055555_read_register(K55_INPUT_ENABLES);
if (disp & (1<<code))
{
if (j == GXMIX_BLEND_NONE) { temp1 = 0xff; temp2 = temp3 = 0; } else
if (j == GXMIX_BLEND_FORCE) { temp1 = 0x00; temp2 = mixerflags>>(i+16); temp3 = 3; }
else
{
temp1 = m_vinmix;
temp2 = m_vinmix>>i & 3;
temp3 = m_vmixon>>i & 3;
}
/* blend layer only when:
1) m_vinmix != 0xff
2) its internal mix code is set
3) all mix code bits are internal(overridden until tile blending has been implemented)
4) 0 > alpha < 255;
*/
if (temp1!=0xff && temp2 /*&& temp3==3*/)
{
temp4 = m_k054338->set_alpha_level(temp2);
if (temp4 <= 0) return;
if (temp4 < 255) k = TILEMAP_DRAW_ALPHA(temp4);
}
if (mixerflags & 1<<(code+12)) k |= K056382_DRAW_FLAG_FORCE_XYSCROLL;
m_k056832->m_tilemap_draw(screen, bitmap, cliprect, code, k, 0);
}
}
void konamigx_state::gx_draw_basic_extended_tilemaps_1(screen_device &screen, bitmap_rgb32 &bitmap, const rectangle &cliprect, int mixerflags, int code, tilemap_t *sub1, int sub1flags, int rushingheroes_hack, int offs)
{
int temp1,temp2,temp3,temp4;
int i = code<<1;
int j = mixerflags>>i & 3;
int k = 0;
int disp = m_k055555->K055555_read_register(K55_INPUT_ENABLES);
if ((disp & K55_INP_SUB1) || (rushingheroes_hack))
{
int alpha = 255;
if (j == GXMIX_BLEND_NONE) { temp1 = 0xff; temp2 = temp3 = 0; } else
if (j == GXMIX_BLEND_FORCE) { temp1 = 0x00; temp2 = mixerflags>>24; temp3 = 3; }
else
{
temp1 = m_osinmix;
temp2 = m_osinmix>>2 & 3;
temp3 = m_osmixon>>2 & 3;
}
if (temp1!=0xff && temp2 /*&& temp3==3*/)
{
alpha = temp4 = m_k054338->set_alpha_level(temp2);
if (temp4 <= 0) return;
if (temp4 < 255) k = 1;
}
int l = sub1flags & 0xf;
if (offs == -2)
{
int pixeldouble_output = 0;
const rectangle &visarea = screen.visible_area();
int width = visarea.width();
if (width>512) // vsnetscr case
pixeldouble_output = 1;
K053936GP_0_zoom_draw(machine(), bitmap, cliprect, sub1, l, k, alpha, pixeldouble_output, m_k053936_0_ctrl_16, m_k053936_0_linectrl_16, m_k053936_0_ctrl, m_k053936_0_linectrl, *m_palette);
}
else
{
m_k053250_1->draw(bitmap, cliprect, m_vcblk[4]<<l, 0, screen.priority(), 0);
}
}
}
void konamigx_state::gx_draw_basic_extended_tilemaps_2(screen_device &screen, bitmap_rgb32 &bitmap, const rectangle &cliprect, int mixerflags, int code, tilemap_t *sub2, int sub2flags, bitmap_ind16 *extra_bitmap, int offs)
{
int temp1,temp2,temp3,temp4;
int i = code<<1;
int j = mixerflags>>i & 3;
int disp = m_k055555->K055555_read_register(K55_INPUT_ENABLES);
if (disp & K55_INP_SUB2)
{
//int alpha = 255;
if (j == GXMIX_BLEND_NONE) { temp1 = 0xff; temp2 = temp3 = 0; } else
if (j == GXMIX_BLEND_FORCE) { temp1 = 0x00; temp2 = mixerflags>>26; temp3 = 3; }
else
{
temp1 = m_osinmix;
temp2 = m_osinmix>>4 & 3;
temp3 = m_osmixon>>4 & 3;
}
if (temp1!=0xff && temp2 /*&& temp3==3*/)
{
//alpha =
temp4 = m_k054338->set_alpha_level(temp2);
if (temp4 <= 0) return;
//if (temp4 < 255) k = 1;
}
int l = sub2flags & 0xf;
if (offs == -3)
{
if (extra_bitmap) // soccer superstars roz layer
{
int width = screen.width();
int height = screen.height();
pen_t const *const paldata = m_palette->pens();
// the output size of the roz layer has to be doubled horizontally
// so that it aligns with the sprites and normal tilemaps. This appears
// to be done as a post-processing / mixing step effect
//
// - todo, use the pixeldouble_output I just added for vsnet instead?
for (int yy=0;yy<height;yy++)
{
uint16_t const *const src = &extra_bitmap->pix(yy);
uint32_t *const dst = &bitmap.pix(yy);
int shiftpos = 0;
for (int xx=0;xx<width;xx+=2)
{
uint16_t dat = src[(((xx/2)+shiftpos))%width];
if (dat&0xff)
dst[xx+1] = dst[xx] = paldata[dat];
}
}
}
else
{
// int pixeldouble_output = 0;
// K053936GP_1_zoom_draw(machine, bitmap, cliprect, sub2, l, k, alpha, pixeldouble_output);
}
}
else
m_k053250_2->draw(bitmap, cliprect, m_vcblk[5]<<l, 0, screen.priority(), 0);
}
}
void konamigx_state::konamigx_mixer_draw(screen_device &screen, bitmap_rgb32 &bitmap, const rectangle &cliprect,
tilemap_t *sub1, int sub1flags,
tilemap_t *sub2, int sub2flags,
int mixerflags, bitmap_ind16 *extra_bitmap, int rushingheroes_hack,
/* passed from above function */
GX_OBJ *objpool,
int *objbuf,
int nobj
)
{
// traverse draw list
int disp = m_k055555->K055555_read_register(K55_INPUT_ENABLES);
for (int count=0; count<nobj; count++)
{
GX_OBJ *objptr = objpool + objbuf[count];
int order = objptr->order;
int offs = objptr->offs;
int code = objptr->code;
int color = objptr->color;
/* entries >=0 in our list are sprites */
if (offs >= 0)
{
if (!(disp & K55_INP_OBJ)) continue;
int drawmode = order>>4 & 0xf;
int alpha = 255;
int pri = 0;
int zcode = -1; // negative zcode values turn off z-buffering
if (drawmode & 2)
{
alpha = color>>K055555_MIXSHIFT & 3;
if (alpha) alpha = m_k054338->set_alpha_level(alpha);
if (alpha <= 0) continue;
}
color &= K055555_COLORMASK;
if (drawmode >= 4) m_palette->set_shadow_mode(order & 0x0f);
if (!(mixerflags & GXMIX_NOZBUF))
{
zcode = order>>16 & 0xff;
pri = order>>24 & 0xff;
}
m_k055673->k053247_draw_single_sprite_gxcore(bitmap, cliprect,
m_gx_objzbuf, m_gx_shdzbuf.get(), code, m_gx_spriteram, offs,
color, alpha, drawmode, zcode, pri,
/* non-gx only */
0,0,nullptr,nullptr,0
);
}
/* the rest are tilemaps of various kinda */
else
{
switch (offs)
{
case -1:
gx_draw_basic_tilemaps(screen, bitmap, cliprect, mixerflags, code);
continue;
case -2:
case -4:
gx_draw_basic_extended_tilemaps_1(screen, bitmap, cliprect, mixerflags, code, sub1, sub1flags, rushingheroes_hack, offs);
continue;
case -3:
case -5:
gx_draw_basic_extended_tilemaps_2(screen, bitmap, cliprect, mixerflags, code, sub2, sub2flags, extra_bitmap, offs);
continue;
}
continue;
}
}
}
/* Run and Gun 2 / Rushing Heroes */
TILE_GET_INFO_MEMBER(konamigx_state::get_gx_psac_tile_info)
{
int tileno, colour, col, flip = 0;
if (tile_index&1)
{
tileno = m_psacram[tile_index/2] & 0x00001fff;
col =(m_psacram[tile_index/2] & 0x00002000)>>13;
if (m_psacram[tile_index/2] & 0x00004000) flip |= TILE_FLIPX;
if (m_psacram[tile_index/2] & 0x00008000) flip |= TILE_FLIPY;
}
else
{
tileno = (m_psacram[tile_index/2] & 0x1fff0000)>>16;
col = (m_psacram[tile_index/2] & 0x20000000)>>29;
if (m_psacram[tile_index/2] & 0x40000000) flip |= TILE_FLIPX;
if (m_psacram[tile_index/2] & 0x80000000) flip |= TILE_FLIPY;
}
colour = (m_psac_colorbase << 4) + col;
tileinfo.set(0, tileno, colour, TILE_FLIPYX(flip));
}
void konamigx_state::type3_bank_w(offs_t offset, uint8_t data)
{
// other bits are used for something...
if (offset == 0)
{
m_type3_psac2_bank = (data & 0x10) >> 4;
// swap sprite display bank for left/right screens
// bit 6 works for soccerss, doesn't for type4 (where they never enable it)
// so the best candidate is bit 0
//m_type3_spriteram_bank = (data & 0x40) >> 6;
m_type3_spriteram_bank = (data & 0x01);
}
else
logerror("Write to type3 bank %02x address %02x\n",offset, data);
/* handle this by creating 2 roz tilemaps instead, otherwise performance dies completely on dual screen mode
if (m_konamigx_type3_psac2_actual_bank!=m_konamigx_type3_psac2_actual_last_bank)
{
m_gx_psac_tilemap->mark_all_dirty();
m_konamigx_type3_psac2_actual_last_bank = m_konamigx_type3_psac2_actual_bank;
}
*/
}
/* Soccer Superstars (tile and flip bits now TRUSTED) */
TILE_GET_INFO_MEMBER(konamigx_state::get_gx_psac3_tile_info)
{
int tileno, colour, flip;
uint8_t *tmap = memregion("gfx4")->base();
int base_index = tile_index;
// if (m_konamigx_type3_psac2_actual_bank)
// base_index+=0x20000/2;
tileno = tmap[base_index*2] | ((tmap[(base_index*2)+1] & 0x0f)<<8);
colour = (tmap[(base_index*2)+1]&0xc0)>>6;
flip = 0;
if (tmap[(base_index*2)+1] & 0x20) flip |= TILE_FLIPY;
if (tmap[(base_index*2)+1] & 0x10) flip |= TILE_FLIPX;
tileinfo.set(0, tileno, colour, flip);
}
TILE_GET_INFO_MEMBER(konamigx_state::get_gx_psac3_alt_tile_info)
{
int tileno, colour, flip;
uint8_t *tmap = memregion("gfx4")->base()+0x20000;
int base_index = tile_index;
// if (m_konamigx_type3_psac2_actual_bank)
// base_index+=0x20000/2;
tileno = tmap[base_index*2] | ((tmap[(base_index*2)+1] & 0x0f)<<8);
colour = (tmap[(base_index*2)+1]&0xc0)>>6;
flip = 0;
if (tmap[(base_index*2)+1] & 0x20) flip |= TILE_FLIPY;
if (tmap[(base_index*2)+1] & 0x10) flip |= TILE_FLIPX;
tileinfo.set(0, tileno, colour, flip);
}
/* PSAC4 */
/* these tilemaps are weird in both format and content, one of them
doesn't really look like it should be displayed? - it's height data */
TILE_GET_INFO_MEMBER(konamigx_state::get_gx_psac1a_tile_info)
{
int tileno, colour, flipx,flipy;
int flip;
flip=0;
colour = 0;
tileno = (m_psacram[tile_index*2] & 0x00003fff)>>0;
// scanrows
//flipx = (m_psacram[tile_index*2+1] & 0x00800000)>>23;
//flipy = (m_psacram[tile_index*2+1] & 0x00400000)>>22;
// scancols
flipy = (m_psacram[tile_index*2+1] & 0x00800000)>>23;
flipx = (m_psacram[tile_index*2+1] & 0x00400000)>>22;
if (flipx) flip |= TILE_FLIPX;
if (flipy) flip |= TILE_FLIPY;
tileinfo.set(1, tileno, colour, flip);
}
TILE_GET_INFO_MEMBER(konamigx_state::get_gx_psac1b_tile_info)
{
int tileno, colour, flipx,flipy;
int flip;
flip=0;
colour = 0;
tileno = (m_psacram[tile_index*2+1] & 0x00003fff)>>0;
// scanrows
//flipx = (m_psacram[tile_index*2+1] & 0x00800000)>>23;
//flipy = (m_psacram[tile_index*2+1] & 0x00400000)>>22;
// scancols
flipy = (m_psacram[tile_index*2+1] & 0x00200000)>>21;
flipx = (m_psacram[tile_index*2+1] & 0x00100000)>>20;
if (flipx) flip |= TILE_FLIPX;
if (flipy) flip |= TILE_FLIPY;
tileinfo.set(0, tileno, colour, flip);
}
K056832_CB_MEMBER(konamigx_state::type2_tile_callback)
{
int d = *code;
*code = (m_gx_tilebanks[(d & 0xe000)>>13]<<13) + (d & 0x1fff);
K055555GX_decode_vmixcolor(layer, color);
}
K056832_CB_MEMBER(konamigx_state::alpha_tile_callback)
{
int mixcode;
int d = *code;
mixcode = K055555GX_decode_vmixcolor(layer, color);
if (mixcode < 0)
*code = (m_gx_tilebanks[(d & 0xe000)>>13]<<13) + (d & 0x1fff);
else
{
/* save mixcode and mark tile alpha (unimplemented) */
// Daisu-Kiss stage presentation
// Sexy Parodius level 3b
*code = (m_gx_tilebanks[(d & 0xe000)>>13]<<13) + (d & 0x1fff);
if (VERBOSE)
popmessage("skipped alpha tile(layer=%d mix=%d)", layer, mixcode);
}
}
/*
> bits 8-13 are the low priority bits
> i.e. pri 0-5
> pri 6-7 can be either 1, bits 14,15 or bits 16,17
> contro.bit 2 being 0 forces the 1
> when control.bit 2 is 1, control.bit 3 selects between the two
> 0 selects 16,17
> that gives you the entire 8 bits of the sprite priority
> ok, lemme see if I've got this. bit2 = 0 means the top bits are 11, bit2=1 means the top bits are bits 14/15 (of the whatever word?) else
+16+17?
> bit3=1 for the second
* 6 | ---------xxxxxxx | "color", but depends on external connections
> there are 8 color lines entering the 5x5
> that means the palette is 4 bits, not 5 as you currently have
> the bits 4-9 are the low priority bits
> bits 10/11 or 12/13 are the two high priority bits, depending on the control word
> and bits 14/15 are the shadow bits
> mix0/1 and brit0/1 come from elsewhere
> they come from the '673 all right, but not from word 6
> and in fact the top address bits are highly suspect
> only 18 of the address bits go to the roms
> the next 2 go to cai0/1 and the next 4 to bk0-3
> (the '246 indexes the roms, the '673 reads the result)
> the roms are 64 bits wide
> so, well, the top bits of the code are suspicious
*/
void konamigx_state::common_init()
{
konamigx_mixer_init(*m_screen, 0);
for (int i = 0; i < 8; i++)
{
m_gx_tilebanks[i] = m_gx_oldbanks[i] = 0;
}
save_pointer(NAME(m_gx_spriteram), 0x800);
save_item(NAME(m_gx_tilebanks));
save_item(NAME(m_k053247_vrcbk));
save_item(NAME(m_k053247_coreg));
save_item(NAME(m_k053247_coregshift));
save_item(NAME(m_k053247_opset));
save_item(NAME(m_opri));
save_item(NAME(m_oinprion));
save_item(NAME(m_vcblk));
save_item(NAME(m_ocblk));
save_item(NAME(m_vinmix));
save_item(NAME(m_vmixon));
save_item(NAME(m_osinmix));
save_item(NAME(m_osmixon));
m_gx_tilemode = 0;
m_gx_rozenable = 0;
m_gx_specialrozenable = 0;
m_gx_rushingheroes_hack = 0;
// Documented relative offsets of non-flipped games are (-2, 0, 2, 3),(0, 0, 0, 0).
// (+ve values move layers to the right and -ve values move layers to the left)
// In most cases only a constant is needed to add to the X offsets to yield correct
// displacement. This should be done by the CCU but the CRT timings have not been
// figured out.
m_k056832->set_layer_offs(0, -2, 0);
m_k056832->set_layer_offs(1, 0, 0);
m_k056832->set_layer_offs(2, 2, 0);
m_k056832->set_layer_offs(3, 3, 0);
m_konamigx_has_dual_screen = 0;
m_konamigx_current_frame = 0;
}
VIDEO_START_MEMBER(konamigx_state, konamigx_5bpp)
{
common_init();
if (!strcmp(machine().system().name,"tbyahhoo"))
m_gx_tilemode = 1;
else if (!strcmp(machine().system().name,"crzcross") || !strcmp(machine().system().name,"puzldama"))
konamigx_mixer_primode(5);
else if (!strcmp(machine().system().name,"daiskiss"))
konamigx_mixer_primode(4);
}
VIDEO_START_MEMBER(konamigx_state, dragoonj)
{
common_init();
m_k056832->set_layer_offs(0, -2+1, 0);
m_k056832->set_layer_offs(1, 0+1, 0);
m_k056832->set_layer_offs(2, 2+1, 0);
m_k056832->set_layer_offs(3, 3+1, 0);
}
VIDEO_START_MEMBER(konamigx_state, le2)
{
common_init();
konamigx_mixer_primode(-1); // swapped layer B and C priorities?
}
VIDEO_START_MEMBER(konamigx_state, konamigx_6bpp)
{
common_init();
konamigx_mixer_primode(5);
}
VIDEO_START_MEMBER(konamigx_state, konamigx_type3)
{
int width = m_screen->width();
int height = m_screen->height();
m_dualscreen_left_tempbitmap = std::make_unique<bitmap_rgb32>( width, height);
m_dualscreen_right_tempbitmap = std::make_unique<bitmap_rgb32>( width, height);
common_init();
m_gx_psac_tilemap = &machine().tilemap().create(*m_gfxdecode, tilemap_get_info_delegate(*this, FUNC(konamigx_state::get_gx_psac3_tile_info)), TILEMAP_SCAN_COLS, 16, 16, 256, 256);
m_gx_psac_tilemap_alt = &machine().tilemap().create(*m_gfxdecode, tilemap_get_info_delegate(*this, FUNC(konamigx_state::get_gx_psac3_alt_tile_info)), TILEMAP_SCAN_COLS, 16, 16, 256, 256);
m_gx_rozenable = 0;
m_gx_specialrozenable = 2;
/* set up tile layers */
m_type3_roz_temp_bitmap = std::make_unique<bitmap_ind16>(width, height);
//m_gx_psac_tilemap->set_flip(TILEMAP_FLIPX| TILEMAP_FLIPY);
K053936_wraparound_enable(0, 1);
// K053936GP_set_offset(0, -30, -1);
K053936_set_offset(0, -30, +1);
m_k056832->set_layer_offs(0, -52, 0);
m_k056832->set_layer_offs(1, -48, 0);
m_k056832->set_layer_offs(2, -48, 0);
m_k056832->set_layer_offs(3, -48, 0);
m_konamigx_has_dual_screen = 1;
m_konamigx_palformat = 1;
}
VIDEO_START_MEMBER(konamigx_state, konamigx_type4)
{
int width = m_screen->width();
int height = m_screen->height();
m_dualscreen_left_tempbitmap = std::make_unique<bitmap_rgb32>( width, height);
m_dualscreen_right_tempbitmap = std::make_unique<bitmap_rgb32>( width, height);
common_init();
m_gx_psac_tilemap = &machine().tilemap().create(*m_gfxdecode, tilemap_get_info_delegate(*this, FUNC(konamigx_state::get_gx_psac_tile_info)), TILEMAP_SCAN_COLS, 16, 16, 128, 128);
m_gx_rozenable = 0;
m_gx_specialrozenable = 3;
m_k056832->set_layer_offs(0, -27, 0);
m_k056832->set_layer_offs(1, -25, 0);
m_k056832->set_layer_offs(2, -24, 0);
m_k056832->set_layer_offs(3, -22, 0);
K053936_wraparound_enable(0, 0);
K053936GP_set_offset(0, -36, 1);
m_gx_rushingheroes_hack = 1;
m_konamigx_has_dual_screen = 1;
m_konamigx_palformat = 0;
}
VIDEO_START_MEMBER(konamigx_state, konamigx_type4_vsn)
{
int width = m_screen->width();
int height = m_screen->height();
m_dualscreen_left_tempbitmap = std::make_unique<bitmap_rgb32>( width, height);
m_dualscreen_right_tempbitmap = std::make_unique<bitmap_rgb32>( width, height);
common_init();
m_gx_psac_tilemap = &machine().tilemap().create(*m_gfxdecode, tilemap_get_info_delegate(*this, FUNC(konamigx_state::get_gx_psac_tile_info)), TILEMAP_SCAN_COLS, 16, 16, 128, 128);
m_gx_rozenable = 0;
m_gx_specialrozenable = 3;
m_k056832->set_layer_offs(0, -52, 0);
m_k056832->set_layer_offs(1, -48, 0);
m_k056832->set_layer_offs(2, -48, 0);
m_k056832->set_layer_offs(3, -48, 0);
K053936_wraparound_enable(0, 1); // wraparound doesn't work properly with the custom drawing function anyway, see the crowd in vsnet and rushhero
K053936GP_set_offset(0, -30, 0);
m_gx_rushingheroes_hack = 1;
m_konamigx_has_dual_screen = 1;
m_konamigx_palformat = 0;
}
VIDEO_START_MEMBER(konamigx_state, konamigx_type4_sd2)
{
int width = m_screen->width();
int height = m_screen->height();
m_dualscreen_left_tempbitmap = std::make_unique<bitmap_rgb32>( width, height);
m_dualscreen_right_tempbitmap = std::make_unique<bitmap_rgb32>( width, height);
common_init();
m_gx_psac_tilemap = &machine().tilemap().create(*m_gfxdecode, tilemap_get_info_delegate(*this, FUNC(konamigx_state::get_gx_psac_tile_info)), TILEMAP_SCAN_COLS, 16, 16, 128, 128);
m_gx_rozenable = 0;
m_gx_specialrozenable = 3;
m_k056832->set_layer_offs(0, -29, -1);
m_k056832->set_layer_offs(1, -27, -1);
m_k056832->set_layer_offs(2, -26, -1);
m_k056832->set_layer_offs(3, -24, -1);
K053936_wraparound_enable(0, 0);
K053936GP_set_offset(0, -36, -1);
m_gx_rushingheroes_hack = 1;
m_konamigx_has_dual_screen = 1;
m_konamigx_palformat = 0;
}
VIDEO_START_MEMBER(konamigx_state, opengolf)
{
common_init();
m_k056832->set_layer_offs(0, -2+1, 0);
m_k056832->set_layer_offs(1, 0+1, 0);
m_k056832->set_layer_offs(2, 2+1, 0);
m_k056832->set_layer_offs(3, 3+1, 0);
m_gx_psac_tilemap = &machine().tilemap().create(*m_gfxdecode, tilemap_get_info_delegate(*this, FUNC(konamigx_state::get_gx_psac1a_tile_info)), TILEMAP_SCAN_COLS, 16, 16, 128, 128);
m_gx_psac_tilemap2 = &machine().tilemap().create(*m_gfxdecode, tilemap_get_info_delegate(*this, FUNC(konamigx_state::get_gx_psac1b_tile_info)), TILEMAP_SCAN_COLS, 16, 16, 128, 128);
// transparency will be handled manually in post-processing
//m_gx_psac_tilemap->set_transparent_pen(0);
//m_gx_psac_tilemap2->set_transparent_pen(0);
m_gx_rozenable = 0;
m_gx_specialrozenable = 1;
m_gxtype1_roz_dstbitmap = std::make_unique<bitmap_ind16>(512,512); // BITMAP_FORMAT_IND16 because we NEED the raw pen data for post-processing
m_gxtype1_roz_dstbitmap2 = std::make_unique<bitmap_ind16>(512,512); // BITMAP_FORMAT_IND16 because we NEED the raw pen data for post-processing
m_gxtype1_roz_dstbitmapclip.set(0, 512-1, 0, 512-1);
K053936_wraparound_enable(0, 1);
K053936GP_set_offset(0, 0, 0);
// urgh.. the priority bitmap is global, and because our temp bitmaps are bigger than the screen, this causes issues.. so just allocate something huge
// until there is a better solution, or priority bitmap can be specified manually.
m_screen->priority().allocate(2048,2048);
}
VIDEO_START_MEMBER(konamigx_state, racinfrc)
{
common_init();
m_k056832->set_layer_offs(0, -2+1, -16);
m_k056832->set_layer_offs(1, 0+1, -16);
m_k056832->set_layer_offs(2, 2+1, -16);
m_k056832->set_layer_offs(3, 3+1, -16);
m_gx_psac_tilemap = &machine().tilemap().create(*m_gfxdecode, tilemap_get_info_delegate(*this, FUNC(konamigx_state::get_gx_psac1a_tile_info)), TILEMAP_SCAN_COLS, 16, 16, 128, 128);
m_gx_psac_tilemap2 = &machine().tilemap().create(*m_gfxdecode, tilemap_get_info_delegate(*this, FUNC(konamigx_state::get_gx_psac1b_tile_info)), TILEMAP_SCAN_COLS, 16, 16, 128, 128);
// transparency will be handled manually in post-processing
//m_gx_psac_tilemap->set_transparent_pen(0);
//m_gx_psac_tilemap2->set_transparent_pen(0);
m_gx_rozenable = 0;
m_gx_specialrozenable = 1;
m_gxtype1_roz_dstbitmap = std::make_unique<bitmap_ind16>(512,512); // BITMAP_FORMAT_IND16 because we NEED the raw pen data for post-processing
m_gxtype1_roz_dstbitmap2 = std::make_unique<bitmap_ind16>(512,512); // BITMAP_FORMAT_IND16 because we NEED the raw pen data for post-processing
m_gxtype1_roz_dstbitmapclip.set(0, 512-1, 0, 512-1);
K053936_wraparound_enable(0, 1);
K053936GP_set_offset(0, 0, 0);
// urgh.. the priority bitmap is global, and because our temp bitmaps are bigger than the screen, this causes issues.. so just allocate something huge
// until there is a better solution, or priority bitmap can be specified manually.
m_screen->priority().allocate(2048,2048);
}
uint32_t konamigx_state::screen_update_konamigx(screen_device &screen, bitmap_rgb32 &bitmap, const rectangle &cliprect)
{
int i, newbank, newbase, dirty, unchained;
/* if any banks are different from last render, we need to flush the planes */
for (dirty = 0, i = 0; i < 8; i++)
{
newbank = m_gx_tilebanks[i];
if (m_gx_oldbanks[i] != newbank) { m_gx_oldbanks[i] = newbank; dirty = 1; }
}
if (m_gx_tilemode == 0)
{
// driver approximates tile update in mode 0 for speed
unchained = m_k056832->get_layer_association();
for (i=0; i<4; i++)
{
newbase = m_k055555->K055555_get_palette_index(i)<<6;
if (m_layer_colorbase[i] != newbase)
{
m_layer_colorbase[i] = newbase;
if (unchained)
m_k056832->mark_plane_dirty(i);
else
dirty = 1;
}
}
}
else
{
// altK056832 does all the tracking in mode 1 for accuracy (Twinbee needs this)
}
// sub2 is PSAC colorbase on GX
if (m_gx_rozenable)
{
m_last_psac_colorbase = m_psac_colorbase;
m_psac_colorbase = m_k055555->K055555_get_palette_index(6);
if (m_psac_colorbase != m_last_psac_colorbase)
{
m_gx_psac_tilemap->mark_all_dirty();
if (m_gx_rozenable == 3)
{
m_gx_psac_tilemap2->mark_all_dirty();
}
}
}
if (dirty) m_k056832->mark_all_tilemaps_dirty();
// Type-1
if (m_gx_specialrozenable == 1)
{
//K053936_0_zoom_draw(screen, *m_gxtype1_roz_dstbitmap, m_gxtype1_roz_dstbitmapclip,m_gx_psac_tilemap, 0,0,0); // height data
K053936_0_zoom_draw(screen, *m_gxtype1_roz_dstbitmap2,m_gxtype1_roz_dstbitmapclip,m_gx_psac_tilemap2,0,0,0); // colour data (+ some voxel height data?)
}
if (m_gx_specialrozenable==3)
{
konamigx_mixer(screen, bitmap, cliprect, m_gx_psac_tilemap, GXSUB_8BPP,nullptr,0, 0, nullptr, m_gx_rushingheroes_hack);
}
// todo: fix so that it works with the mixer without crashing(!)
else if (m_gx_specialrozenable == 2)
{
// we're going to throw half of this away anyway in post-process, so only render what's needed
rectangle temprect;
temprect = cliprect;
temprect.max_x = cliprect.min_x+320;
if (m_type3_psac2_bank == 1) K053936_0_zoom_draw(screen, *m_type3_roz_temp_bitmap, temprect,m_gx_psac_tilemap_alt, 0,0,0); // soccerss playfield
else K053936_0_zoom_draw(screen, *m_type3_roz_temp_bitmap, temprect,m_gx_psac_tilemap, 0,0,0); // soccerss playfield
konamigx_mixer(screen, bitmap, cliprect, nullptr, 0, nullptr, 0, 0, m_type3_roz_temp_bitmap.get(), m_gx_rushingheroes_hack);
}
else
{
konamigx_mixer(screen, bitmap, cliprect, nullptr, 0, nullptr, 0, 0, nullptr, m_gx_rushingheroes_hack);
}
/* Hack! draw type-1 roz layer here for testing purposes only */
if (m_gx_specialrozenable == 1)
{
pen_t const *const paldata = m_palette->pens();
// hack, draw the roz tilemap if W is held
if ( machine().input().code_pressed(KEYCODE_W) )
{
// make it flicker, to compare positioning
//if (screen.frame_number() & 1)
{
for (int y=0;y<256;y++)
{
//uint32_t *const dst = &bitmap.pix(y);
// ths K053936 rendering should probably just be flipped
// this is just kludged to align the racing force 2d logo
uint16_t const *const src = &m_gxtype1_roz_dstbitmap2->pix(y);
//uint16_t const *const src = &m_gxtype1_roz_dstbitmap->pix(y);
uint32_t *const dst = &bitmap.pix((256+16)-y);
for (int x=0;x<512;x++)
{
uint16_t const dat = src[x];
dst[x] = paldata[dat];
}
}
}
}
}
return 0;
}
uint32_t konamigx_state::screen_update_konamigx_left(screen_device &screen, bitmap_rgb32 &bitmap, const rectangle &cliprect)
{
/* the video gets demuxed by a board which plugs into the jamma connector */
m_konamigx_current_frame^=1;
if (m_konamigx_current_frame==1)
{
int offset=0;
if (m_konamigx_palformat==1)
{
for (offset=0;offset<0x4000/4;offset++)
{
uint32_t coldat = m_generic_paletteram_32[offset];
set_color_555(*m_palette, offset*2, 0, 5, 10,coldat >> 16);
set_color_555(*m_palette, offset*2+1, 0, 5, 10,coldat & 0xffff);
}
}
else
{
for (offset=0;offset<0x8000/4;offset++)
{
int r,g,b;
r = (m_generic_paletteram_32[offset] >>16) & 0xff;
g = (m_generic_paletteram_32[offset] >> 8) & 0xff;
b = (m_generic_paletteram_32[offset] >> 0) & 0xff;
m_palette->set_pen_color(offset,rgb_t(r,g,b));
}
}
screen_update_konamigx( screen, downcast<bitmap_rgb32 &>(*m_dualscreen_left_tempbitmap), cliprect);
copybitmap(bitmap, *m_dualscreen_left_tempbitmap, 0, 0, 0, 0, cliprect);
}
else
{
copybitmap(bitmap, *m_dualscreen_left_tempbitmap, 0, 0, 0, 0, cliprect);
}
return 0;
}
uint32_t konamigx_state::screen_update_konamigx_right(screen_device &screen, bitmap_rgb32 &bitmap, const rectangle &cliprect)
{
if (m_konamigx_current_frame==1)
{
copybitmap(bitmap, *m_dualscreen_right_tempbitmap, 0, 0, 0, 0, cliprect);
}
else
{
int offset=0;
if (m_konamigx_palformat==1)
{
for (offset=0;offset<0x4000/4;offset++)
{
uint32_t coldat = m_subpaletteram32[offset];
set_color_555(*m_palette, offset*2, 0, 5, 10,coldat >> 16);
set_color_555(*m_palette, offset*2+1, 0, 5, 10,coldat & 0xffff);
}
}
else
{
for (offset=0;offset<0x8000/4;offset++)
{
int r,g,b;
r = (m_subpaletteram32[offset] >>16) & 0xff;
g = (m_subpaletteram32[offset] >> 8) & 0xff;
b = (m_subpaletteram32[offset] >> 0) & 0xff;
m_palette->set_pen_color(offset,rgb_t(r,g,b));
}
}
screen_update_konamigx(screen, downcast<bitmap_rgb32 &>(*m_dualscreen_right_tempbitmap), cliprect);
copybitmap(bitmap, *m_dualscreen_right_tempbitmap, 0, 0, 0, 0, cliprect);
}
return 0;
}
static inline void set_color_555(palette_device &palette, pen_t color, int rshift, int gshift, int bshift, uint16_t data)
{
palette.set_pen_color(color, pal5bit(data >> rshift), pal5bit(data >> gshift), pal5bit(data >> bshift));
}
// main monitor for type 3
void konamigx_state::konamigx_555_palette_w(offs_t offset, uint32_t data, uint32_t mem_mask)
{
uint32_t coldat;
COMBINE_DATA(&m_generic_paletteram_32[offset]);
coldat = m_generic_paletteram_32[offset];
set_color_555(*m_palette, offset*2, 0, 5, 10,coldat >> 16);
set_color_555(*m_palette, offset*2+1, 0, 5, 10,coldat & 0xffff);
}
// sub monitor for type 3
void konamigx_state::konamigx_555_palette2_w(offs_t offset, uint32_t data, uint32_t mem_mask)
{
uint32_t coldat;
COMBINE_DATA(&m_subpaletteram32[offset]);
coldat = m_subpaletteram32[offset];
offset += (0x4000/4);
set_color_555(*m_palette, offset*2, 0, 5, 10,coldat >> 16);
set_color_555(*m_palette, offset*2+1, 0, 5, 10,coldat & 0xffff);
}
void konamigx_state::konamigx_tilebank_w(offs_t offset, uint32_t data, uint32_t mem_mask)
{
if (ACCESSING_BITS_24_31)
m_gx_tilebanks[offset*4] = (data>>24)&0xff;
if (ACCESSING_BITS_16_23)
m_gx_tilebanks[offset*4+1] = (data>>16)&0xff;
if (ACCESSING_BITS_8_15)
m_gx_tilebanks[offset*4+2] = (data>>8)&0xff;
if (ACCESSING_BITS_0_7)
m_gx_tilebanks[offset*4+3] = data&0xff;
}
// type 1 RAM-based PSAC tilemap
void konamigx_state::konamigx_t1_psacmap_w(offs_t offset, uint32_t data, uint32_t mem_mask)
{
COMBINE_DATA(&m_psacram[offset]);
m_gx_psac_tilemap->mark_tile_dirty(offset/2);
m_gx_psac_tilemap2->mark_tile_dirty(offset/2);
}
// type 4 RAM-based PSAC tilemap
void konamigx_state::konamigx_t4_psacmap_w(offs_t offset, uint32_t data, uint32_t mem_mask)
{
COMBINE_DATA(&m_psacram[offset]);
m_gx_psac_tilemap->mark_tile_dirty(offset*2);
m_gx_psac_tilemap->mark_tile_dirty((offset*2)+1);
}
| 28.24359 | 222 | 0.679744 | Robbbert |
26ea7e087772d178fc9cd06a7e3be116ab733699 | 2,534 | cc | C++ | src/Circuit/models/ideal/IdealCapacitor.cc | kwisniew/devsim | 3a7c1e9c4d28a8a6f9e7a43e5d5475ea2cdfe138 | [
"Apache-2.0"
] | null | null | null | src/Circuit/models/ideal/IdealCapacitor.cc | kwisniew/devsim | 3a7c1e9c4d28a8a6f9e7a43e5d5475ea2cdfe138 | [
"Apache-2.0"
] | null | null | null | src/Circuit/models/ideal/IdealCapacitor.cc | kwisniew/devsim | 3a7c1e9c4d28a8a6f9e7a43e5d5475ea2cdfe138 | [
"Apache-2.0"
] | null | null | null | #include "IdealCapacitor.hh"
#include <cmath>
IdealCapacitor::IdealCapacitor( NodeKeeper *nk, const char *name,
const char *n1,
const char *n2) : InstanceModel(nk, name)
{
node_ptr_vtop= this->AddCircuitNode(n1);
node_ptr_vbot= this->AddCircuitNode(n2);
//Parameter List
C = 1.000000e+00;
}
void IdealCapacitor::assembleDC(const NodeKeeper::Solution &sol, dsMath::RealRowColValueVec &mat, std::vector<std::pair<int, double> > &rhs)
{
}
void IdealCapacitor::assembleTran(const double scl, const NodeKeeper::Solution &sol, dsMath::RealRowColValueVec *mat, std::vector<std::pair<int, double> > &rhs)
{
const size_t node_num_vbot = node_ptr_vbot->getNumber();
const size_t node_num_vtop = node_ptr_vtop->getNumber();
const bool is_gnd_node_vbot = node_ptr_vbot->isGROUND();
const bool is_gnd_node_vtop = node_ptr_vtop->isGROUND();
const double vbot = (is_gnd_node_vbot) ? 0.0 : sol[node_num_vbot];
const double vtop = (is_gnd_node_vtop) ? 0.0 : sol[node_num_vtop];
const double iq = (C * (vtop - vbot));
const double evbot = scl *(-iq);
const double evtop = scl *iq;
if (!is_gnd_node_vbot)
rhs.push_back(std::make_pair(node_num_vbot, evbot));
if (!is_gnd_node_vtop)
rhs.push_back(std::make_pair(node_num_vtop, evtop));
if (mat == NULL)
return;
const double d_iq_d_vtop = C;
const double evbot_vtop = scl * (-d_iq_d_vtop);
const double d_iq_d_vbot = (-C);
const double evbot_vbot = scl * (-d_iq_d_vbot);
const double evtop_vtop = scl * d_iq_d_vtop;
const double evtop_vbot = scl * d_iq_d_vbot;
if (!is_gnd_node_vbot)
{
if (!is_gnd_node_vtop)
mat->push_back(dsMath::RealRowColVal(node_num_vbot,node_num_vtop, evbot_vtop));
mat->push_back(dsMath::RealRowColVal(node_num_vbot,node_num_vbot, evbot_vbot));
}
if (!is_gnd_node_vtop)
{
mat->push_back(dsMath::RealRowColVal(node_num_vtop,node_num_vtop, evtop_vtop));
if (!is_gnd_node_vbot)
mat->push_back(dsMath::RealRowColVal(node_num_vtop,node_num_vbot, evtop_vbot));
}
}
bool IdealCapacitor::addParam(const std::string &str, double val)
{
bool ret = false;
if (str == "C")
{
C = val;
ret = true;
}
return ret;
}
extern "C" InstanceModel *IdealCapacitor_create (NodeKeeper *nk, const std::string &name, const std::vector<std::string> &nodelist) {
return new IdealCapacitor(nk, name.c_str(), nodelist[0].c_str(), nodelist[1].c_str());
}
| 28.795455 | 160 | 0.676401 | kwisniew |
26f12b230f4963a779e950fe9c56e05c356300a5 | 1,538 | cpp | C++ | benchmarks/vote/novelsm/rocksdb_checkpoint.cpp | huangvincent170/cyclone | 737af617ab1472dfb16e6c20a079e88dccf85850 | [
"Apache-2.0"
] | 2 | 2019-04-16T01:33:36.000Z | 2021-02-23T08:34:38.000Z | benchmarks/vote/novelsm/rocksdb_checkpoint.cpp | huangvincent170/cyclone | 737af617ab1472dfb16e6c20a079e88dccf85850 | [
"Apache-2.0"
] | null | null | null | benchmarks/vote/novelsm/rocksdb_checkpoint.cpp | huangvincent170/cyclone | 737af617ab1472dfb16e6c20a079e88dccf85850 | [
"Apache-2.0"
] | 4 | 2020-03-27T18:06:33.000Z | 2021-03-24T09:56:17.000Z |
#include<assert.h>
#include<errno.h>
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
#include <time.h>
#include<unistd.h>
#include <leveldb/db.h>
#include <leveldb/options.h>
#include <leveldb/write_batch.h>
#include <leveldb/utilities/checkpoint.h>
#include "rocksdb.hpp"
#include "logging.hpp"
#include "clock.hpp"
// Rate measurement stuff
leveldb::DB* db = NULL;
void opendb(){
leveldb::Options options;
options.create_if_missing = true;
//options.error_if_exists = true;
auto env = leveldb::Env::Default();
//env->set_affinity(0, 10);
env->SetBackgroundThreads(2, leveldb::Env::LOW);
env->SetBackgroundThreads(1, leveldb::Env::HIGH);
options.env = env;
options.write_buffer_size = 1024 * 1024 * 256;
options.target_file_size_base = 1024 * 1024 * 512;
options.max_background_compactions = 2;
options.max_background_flushes = 1;
options.max_write_buffer_number = 3;
leveldb::Status s = leveldb::DB::Open(options, preload_dir, &db);
if (!s.ok()){
BOOST_LOG_TRIVIAL(fatal) << s.ToString().c_str();
exit(-1);
}
// Create checkpoint
leveldb::Checkpoint * checkpoint_ptr;
s = leveldb::Checkpoint::Create(db, &checkpoint_ptr);
if (!s.ok()){
BOOST_LOG_TRIVIAL(fatal) << s.ToString().c_str();
exit(-1);
}
s = checkpoint_ptr->CreateCheckpoint(data_dir);
if (!s.ok()){
BOOST_LOG_TRIVIAL(fatal) << s.ToString().c_str();
exit(-1);
}
delete checkpoint_ptr;
}
void closedb()
{
delete db;
}
int main(int argc, char *argv[])
{
opendb();
closedb();
}
| 22.955224 | 67 | 0.680104 | huangvincent170 |
26f2fc8f200d1d61e94ded94853dfe123552d29b | 1,372 | hpp | C++ | Runtime/MP1/CPauseScreenBlur.hpp | Jcw87/urde | fb9ea9092ad00facfe957ece282a86c194e9cbda | [
"MIT"
] | 267 | 2016-03-10T21:59:16.000Z | 2021-03-28T18:21:03.000Z | Runtime/MP1/CPauseScreenBlur.hpp | cobalt2727/metaforce | 3bb05c0ee5dd9b1b8eaa861fc49713aef62c844a | [
"MIT"
] | 129 | 2016-03-12T10:17:32.000Z | 2021-04-05T20:45:19.000Z | Runtime/MP1/CPauseScreenBlur.hpp | cobalt2727/metaforce | 3bb05c0ee5dd9b1b8eaa861fc49713aef62c844a | [
"MIT"
] | 31 | 2016-03-20T00:20:11.000Z | 2021-03-10T21:14:11.000Z | #pragma once
#include "Runtime/CToken.hpp"
#include "Runtime/Camera/CCameraFilter.hpp"
#include "Runtime/Graphics/CTexture.hpp"
#include "Runtime/Graphics/Shaders/CTexturedQuadFilter.hpp"
#include "Runtime/Graphics/Shaders/CScanLinesFilter.hpp"
#include "Runtime/MP1/CInGameGuiManagerCommon.hpp"
namespace metaforce {
class CStateManager;
namespace MP1 {
class CPauseScreenBlur {
enum class EState { InGame, MapScreen, SaveGame, HUDMessage, Pause };
TLockedToken<CTexture> x4_mapLightQuarter;
EState x10_prevState = EState::InGame;
EState x14_nextState = EState::InGame;
float x18_blurAmt = 0.f;
CCameraBlurPass x1c_camBlur;
bool x50_24_blurring : 1 = false;
bool x50_25_gameDraw : 1 = true;
CTexturedQuadFilter m_quarterFilter{EFilterType::Multiply, x4_mapLightQuarter};
CScanLinesFilterEven m_linesFilter{EFilterType::Multiply};
void OnBlurComplete(bool);
void SetState(EState state);
public:
CPauseScreenBlur();
void OnNewInGameGuiState(EInGameGuiState state, CStateManager& stateMgr);
bool IsGameDraw() const { return x50_25_gameDraw; }
void Update(float dt, const CStateManager& stateMgr, bool);
void Draw(const CStateManager& stateMgr);
float GetBlurAmt() const { return std::fabs(x18_blurAmt); }
bool IsNotTransitioning() const { return x10_prevState == x14_nextState; }
};
} // namespace MP1
} // namespace metaforce
| 31.181818 | 81 | 0.777697 | Jcw87 |
26f3836661aa3bedcaced716c016d8ce312579d3 | 2,578 | cpp | C++ | Edge/edgecomputerserver.cpp | Somoshree/serverlessonedge | 3d8e0dc7867146c9c177f814a3507d027adbb0a0 | [
"MIT"
] | 17 | 2020-07-27T08:28:29.000Z | 2022-03-19T09:17:21.000Z | Edge/edgecomputerserver.cpp | Somoshree/serverlessonedge | 3d8e0dc7867146c9c177f814a3507d027adbb0a0 | [
"MIT"
] | null | null | null | Edge/edgecomputerserver.cpp | Somoshree/serverlessonedge | 3d8e0dc7867146c9c177f814a3507d027adbb0a0 | [
"MIT"
] | 4 | 2021-02-23T09:29:32.000Z | 2022-01-18T07:24:19.000Z | /*
__ __ __
|__|__| | __
| | | ||__|
___ ___ __ | | | |
| | | || | | | Ubiquitous Internet @ IIT-CNR
| | | || | | | C++ edge computing libraries and tools
|_______|__||__|__|__| https://github.com/ccicconetti/serverlessonedge
Licensed under the MIT License <http://opensource.org/licenses/MIT>
Copyright (c) 2021 C. Cicconetti <https://ccicconetti.github.io/>
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 "edgecomputerserver.h"
namespace uiiit {
namespace edge {
EdgeComputerServer::EdgeComputerServerImpl::EdgeComputerServerImpl(
EdgeComputerServer& aParent)
: SimpleStreamingServerImpl(aParent) {
}
EdgeComputerServer::EdgeComputerServerImpl::~EdgeComputerServerImpl() {
}
grpc::Status EdgeComputerServer::EdgeComputerServerImpl::StreamUtil(
grpc::ServerContext* aContext,
const rpc::Void* aReq,
grpc::ServerWriter<rpc::Utilization>* aWriter) {
return handle(aContext, [&aWriter](const rpc::Utilization& aMsg) {
return aWriter->Write(aMsg);
});
}
EdgeComputerServer::EdgeComputerServer(const std::string& aServerEndpoint)
: SimpleStreamingServer(aServerEndpoint)
, theServerImpl(*this) {
}
void EdgeComputerServer::add(const std::map<std::string, double>& aUtil) {
auto myMsg = std::make_shared<rpc::Utilization>();
for (const auto& myPair : aUtil) {
(*myMsg->mutable_values())[myPair.first] = myPair.second;
}
push(myMsg);
}
} // namespace edge
} // end namespace uiiit
| 37.362319 | 78 | 0.706362 | Somoshree |
26f786487133949e213c1d83b6bcdba02d155a91 | 1,583 | cpp | C++ | qt/app/applicationpath.cpp | qbit-t/qb | c1fd82df3838f8526fc5e335254529ab6f953f78 | [
"MIT"
] | 1 | 2021-02-14T04:04:50.000Z | 2021-02-14T04:04:50.000Z | qt/app/applicationpath.cpp | qbit-t/qb | c1fd82df3838f8526fc5e335254529ab6f953f78 | [
"MIT"
] | null | null | null | qt/app/applicationpath.cpp | qbit-t/qb | c1fd82df3838f8526fc5e335254529ab6f953f78 | [
"MIT"
] | 1 | 2021-08-28T07:42:43.000Z | 2021-08-28T07:42:43.000Z | #include <QDir>
#include <QPluginLoader>
#include <QQmlExtensionPlugin>
#include <QDebug>
#include <QException>
#include <QStandardPaths>
#include <QStringList>
#include <QJsonDocument>
#include "applicationpath.h"
#include "error.h"
using namespace buzzer;
#ifdef Q_OS_ANDROID
std::wstring gProfile(L"android");
#else
std::wstring gProfile(L"desktop");
#endif
QString ApplicationPath::applicationDirPath()
{
#ifdef Q_OS_ANDROID
return QString("assets:");
#endif
return qApp->applicationDirPath();
}
QString ApplicationPath::logsDirPath()
{
#ifdef Q_OS_ANDROID
return QStandardPaths::writableLocation(QStandardPaths::DownloadLocation);
#endif
#ifdef Q_OS_IOS
return QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
#endif
return qApp->applicationDirPath() + "/logs";
}
QString ApplicationPath::tempFilesDir()
{
#ifdef Q_OS_ANDROID
return QStandardPaths::writableLocation(QStandardPaths::TempLocation);
#endif
#ifdef Q_OS_IOS
return QStandardPaths::writableLocation(QStandardPaths::TempLocation);
#endif
QString lGlobalDataPath = qApp->applicationDirPath() + "/data";
QDir lDataDir(lGlobalDataPath);
if (!lDataDir.exists()) {
lDataDir.setPath(qApp->applicationDirPath());
lDataDir.mkdir("data");
}
QString lCacheDataPath = lGlobalDataPath + "/cache";
QDir lCacheDir(lCacheDataPath);
if (!lCacheDir.exists()) {
lCacheDir.setPath(lGlobalDataPath);
lCacheDir.mkdir("cache");
}
#ifdef Q_OS_WINDOWS
lCacheDataPath.replace(0, 1, lCacheDataPath[0].toLower());
return lCacheDataPath;
#endif
return lCacheDataPath;
}
| 21.106667 | 79 | 0.765635 | qbit-t |
26f82b0ace9129df1404b4df35cf87c1bdd9c8cf | 2,958 | hxx | C++ | opencascade/AdvApp2Var_Data.hxx | valgur/OCP | 2f7d9da73a08e4ffe80883614aedacb27351134f | [
"Apache-2.0"
] | 117 | 2020-03-07T12:07:05.000Z | 2022-03-27T07:35:22.000Z | opencascade/AdvApp2Var_Data.hxx | CadQuery/cpp-py-bindgen | 66e7376d3a27444393fc99acbdbef40bbc7031ae | [
"Apache-2.0"
] | 66 | 2019-12-20T16:07:36.000Z | 2022-03-15T21:56:10.000Z | opencascade/AdvApp2Var_Data.hxx | CadQuery/cpp-py-bindgen | 66e7376d3a27444393fc99acbdbef40bbc7031ae | [
"Apache-2.0"
] | 76 | 2020-03-16T01:47:46.000Z | 2022-03-21T16:37:07.000Z | // Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef AdvApp2Var_Data_HeaderFile
#define AdvApp2Var_Data_HeaderFile
#include <Standard_Macro.hxx>
#include <AdvApp2Var_Data_f2c.hxx>
//
struct mdnombr_1_ {
doublereal pi,
deuxpi,
pisur2,
pis180,
c180pi,
zero,
one,
a180,
a360,
a90;
};
//
struct minombr_1_ {
integer nbr[1001];
};
//
struct maovpar_1_ {
doublereal r8und, r8ovr, x4und, x4ovr;
real r4und, r4ovr;
integer r4nbe, r8nbm, r8nbe, i4ovr, i4ovn, r4exp, r8exp, r4exn, r8exn,
r4ncs, r8ncs, r4nbm;
shortint i2ovr, i2ovn;
};
//
struct maovpch_1_ {
char cnmmac[16], frmr4[8], frmr8[8], cdcode[8];
};
//
struct mlgdrtl_1_ {
doublereal rootab[930],// was [465][2]
hiltab[930],// was [465][2]
hi0tab[31];
};
//
struct mmjcobi_1_ {
doublereal plgcan[3968];// was [496][2][4]
doublereal canjac[3968];// was [496][2][4]
};
//
struct mmcmcnp_1_ {
doublereal cnp[3721]; // was [61][61] ;
};
//
struct mmapgss_1_ {
doublereal gslxjs[5017],
gsl0js[52];
};
//
struct mmapgs0_1_ {
doublereal gslxj0[4761], gsl0j0[49];
};
//
struct mmapgs1_1_ {
doublereal gslxj1[4505], gsl0j1[46];
};
//
struct mmapgs2_1_ {
doublereal gslxj2[4249], gsl0j2[43];
};
////
class AdvApp2Var_Data {
public:
Standard_EXPORT static mdnombr_1_& Getmdnombr();
Standard_EXPORT static minombr_1_& Getminombr();
Standard_EXPORT static maovpar_1_& Getmaovpar();
Standard_EXPORT static maovpch_1_& Getmaovpch();
Standard_EXPORT static mlgdrtl_1_& Getmlgdrtl();
Standard_EXPORT static mmjcobi_1_& Getmmjcobi();
Standard_EXPORT static mmcmcnp_1_& Getmmcmcnp();
Standard_EXPORT static mmapgss_1_& Getmmapgss();
Standard_EXPORT static mmapgs0_1_& Getmmapgs0();
Standard_EXPORT static mmapgs1_1_& Getmmapgs1();
Standard_EXPORT static mmapgs2_1_& Getmmapgs2();
};
//
#define mdnombr_ AdvApp2Var_Data::Getmdnombr()
#define minombr_ AdvApp2Var_Data::Getminombr()
#define maovpar_ AdvApp2Var_Data::Getmaovpar()
#define maovpch_ AdvApp2Var_Data::Getmaovpch()
#define mlgdrtl_ AdvApp2Var_Data::Getmlgdrtl()
#define mmjcobi_ AdvApp2Var_Data::Getmmjcobi()
#define mmcmcnp_ AdvApp2Var_Data::Getmmcmcnp()
#define mmapgss_ AdvApp2Var_Data::Getmmapgss()
#define mmapgs0_ AdvApp2Var_Data::Getmmapgs0()
#define mmapgs1_ AdvApp2Var_Data::Getmmapgs1()
#define mmapgs2_ AdvApp2Var_Data::Getmmapgs2()
//
#endif
| 26.648649 | 81 | 0.734956 | valgur |
26fad1aa447d610467e3eeacb8632ded76b35948 | 590 | cpp | C++ | Game/src/Keyboard.cpp | rasmusrosengren/OpenGL3DGame | db6101d8aae97b8798a99ae458e62d2a8b407acb | [
"MIT"
] | null | null | null | Game/src/Keyboard.cpp | rasmusrosengren/OpenGL3DGame | db6101d8aae97b8798a99ae458e62d2a8b407acb | [
"MIT"
] | null | null | null | Game/src/Keyboard.cpp | rasmusrosengren/OpenGL3DGame | db6101d8aae97b8798a99ae458e62d2a8b407acb | [
"MIT"
] | null | null | null | #include "Keyboard.h"
std::array<bool, Keyboard::NUM_KEYS> Keyboard::m_lastKeys;
GLFWwindow* Keyboard::m_window = nullptr;
void Keyboard::init(GLFWwindow* window)
{
m_window = window;
}
void Keyboard::update() // Need to be called every frame
{
for (int i = 0; i < NUM_KEYS; i++)
{
m_lastKeys[i] = getKey(i);
}
}
bool Keyboard::getKey(int keyCode)
{
return glfwGetKey(m_window, keyCode);
}
bool Keyboard::getKeyDown(int keyCode)
{
return getKey(keyCode) && !m_lastKeys.at(keyCode);
}
bool Keyboard::getKeyUp(int keyCode)
{
return !getKey(keyCode) && m_lastKeys.at(keyCode);
} | 18.4375 | 58 | 0.705085 | rasmusrosengren |
26fc029492dd6f1cc022acd3eb315badcd4bef95 | 301 | hpp | C++ | header/conditions.hpp | jonathanmarp/dbmem | fa2d143758282fc28b00d36bcc5acfb859de1f74 | [
"MIT"
] | 2 | 2021-05-18T08:08:53.000Z | 2021-05-18T09:41:09.000Z | header/conditions.hpp | thekotekjournal/dbmem | 5fe1371167f5754e55dc84bd16278595dd5f9b38 | [
"MIT"
] | 1 | 2021-05-18T10:12:15.000Z | 2021-05-18T10:12:15.000Z | header/conditions.hpp | thekotekjournal/dbmem | 5fe1371167f5754e55dc84bd16278595dd5f9b38 | [
"MIT"
] | 1 | 2021-05-18T09:41:12.000Z | 2021-05-18T09:41:12.000Z | #ifndef DBMEM_CONDITIONS_HPP
#define DBMEM_CONDITIONS_HPP
namespace conditions {
enum CONDITIONS_STRUCT {
FALSE = 0x001,
TRUE = 0x002
};
typedef enum CONDITIONS_STRUCT Dconditions;
Dconditions Fconditions(bool conditions_boolean);
};
#endif // DBMEM_CONDITIONS_HPP | 20.066667 | 53 | 0.727575 | jonathanmarp |
26fe51326b37d5c846251f5cb710e7208fa12b56 | 1,115 | cpp | C++ | src/engine/GLUtils.cpp | Arkshine/PrototypeEngine | 6833b931ca02934dd5f68377fc8c486f01103841 | [
"Unlicense"
] | 2 | 2018-10-09T14:42:39.000Z | 2021-02-07T21:41:00.000Z | src/engine/GLUtils.cpp | Arkshine/PrototypeEngine | 6833b931ca02934dd5f68377fc8c486f01103841 | [
"Unlicense"
] | null | null | null | src/engine/GLUtils.cpp | Arkshine/PrototypeEngine | 6833b931ca02934dd5f68377fc8c486f01103841 | [
"Unlicense"
] | 1 | 2018-10-09T14:42:41.000Z | 2018-10-09T14:42:41.000Z | #include <sstream>
#include <string>
#include <GL/glew.h>
#include "Logging.h"
#include "GLUtils.h"
namespace gl
{
bool GetContextVersion( uint32_t& uiOutMajor, uint32_t& uiOutMinor )
{
uiOutMajor = 1;
uiOutMinor = 0;
const char* pszVersion = reinterpret_cast<const char*>( glGetString( GL_VERSION ) );
if( !pszVersion )
{
Msg( "gl::GetContextVersion: Couldn't query OpenGL version info\n" );
return false;
}
std::string szVersion( pszVersion );
//Vendor specific information follows after a space, so trim it. - Solokiller
const auto space = szVersion.find( ' ' );
if( space != std::string::npos )
szVersion = szVersion.substr( 0, space );
std::stringstream stream( szVersion );
std::string szToken;
if( !std::getline( stream, szToken, '.' ) )
{
Msg( "gl::GetContextVersion: Invalid version string\n" );
return false;
}
const uint32_t uiMajor = std::stoul( szToken );
if( !std::getline( stream, szToken, '.' ) )
{
Msg( "gl::GetContextVersion: Invalid version string\n" );
return false;
}
uiOutMajor = uiMajor;
uiOutMinor = std::stoul( szToken );
return true;
}
} | 19.910714 | 85 | 0.679821 | Arkshine |
f8015e1b149ec7f4c352449e6c234065bdde6ace | 2,892 | hpp | C++ | include/ast/IsConstantVisitor.hpp | wichtounet/eddic | 66398a493a499eab5d1f465f93f9f099a2140d59 | [
"MIT"
] | 24 | 2015-10-08T23:08:50.000Z | 2021-09-18T21:15:01.000Z | include/ast/IsConstantVisitor.hpp | wichtounet/eddic | 66398a493a499eab5d1f465f93f9f099a2140d59 | [
"MIT"
] | 1 | 2016-02-29T20:20:45.000Z | 2016-03-03T07:16:53.000Z | include/ast/IsConstantVisitor.hpp | wichtounet/eddic | 66398a493a499eab5d1f465f93f9f099a2140d59 | [
"MIT"
] | 5 | 2015-08-09T09:53:52.000Z | 2021-09-18T21:15:05.000Z | //=======================================================================
// Copyright Baptiste Wicht 2011-2016.
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#ifndef IS_CONSTANT_VISITOR_H
#define IS_CONSTANT_VISITOR_H
#include <boost/mpl/vector.hpp>
#include <boost/mpl/contains.hpp>
#include "variant.hpp"
#include "VisitorUtils.hpp"
#include "Type.hpp"
#include "ast/Value.hpp"
namespace eddic {
namespace ast {
/*!
* \struct IsConstantVisitor
* \brief AST Visitor to test if a node is constant.
*/
struct IsConstantVisitor : public boost::static_visitor<bool> {
typedef boost::mpl::vector<ast::Integer, ast::Literal, ast::CharLiteral, ast::IntegerSuffix, ast::Float, ast::Boolean, ast::Null> constant_types;
typedef boost::mpl::vector<ast::FunctionCall,
ast::BuiltinOperator, ast::Assignment, ast::Ternary, ast::New, ast::NewArray> non_constant_types;
template<typename T>
typename std::enable_if<boost::mpl::contains<constant_types, T>::value, bool>::type operator()(T&) const {
return true;
}
template<typename T>
typename std::enable_if<boost::mpl::contains<non_constant_types, T>::value, bool>::type operator()(T&) const {
return false;
}
bool operator()(ast::PrefixOperation& value) const {
auto op = value.op;
if(
op == ast::Operator::STAR || op == ast::Operator::ADDRESS || op == ast::Operator::CALL
|| op == ast::Operator::DOT || op == ast::Operator::INC || op == ast::Operator::DEC){
return false;
}
return visit(*this, value.left_value);
}
bool operator()(ast::Cast& cast) const {
return visit(*this, cast.value);
}
bool operator()(ast::VariableValue& variable) const {
return variable.var->type()->is_const();
}
bool operator()(ast::Expression& value) const {
if(visit(*this, value.first)){
for(auto& op : value.operations){
if(ast::has_operation_value(op)){
if(auto* ptr = boost::smart_get<ast::FunctionCall>(&op.get<1>())){
for(auto& v : ptr->values){
if(!visit(*this, v)){
return false;
}
}
} else {
if(!visit(*this, op.get<1>())){
return false;
}
}
}
}
return true;
}
return false;
}
template<typename T>
bool operator()(x3::forward_ast<T>& value) const {
return (*this)(value.get());
}
};
} //end of ast
} //end of eddic
#endif
| 29.510204 | 149 | 0.5287 | wichtounet |
f805448050d7b1c8e358ba00f476f98c4eb4f3aa | 1,610 | hpp | C++ | solver/modules/slide/include/slide/KurageHashFeature.hpp | taiheioki/procon2014_ut | 8199ff0a54220f1a0c51acece377f65b64db4863 | [
"MIT"
] | 2 | 2021-04-14T06:41:18.000Z | 2021-04-29T01:56:08.000Z | solver/modules/slide/include/slide/KurageHashFeature.hpp | taiheioki/procon2014_ut | 8199ff0a54220f1a0c51acece377f65b64db4863 | [
"MIT"
] | null | null | null | solver/modules/slide/include/slide/KurageHashFeature.hpp | taiheioki/procon2014_ut | 8199ff0a54220f1a0c51acece377f65b64db4863 | [
"MIT"
] | null | null | null | #ifndef SLIDE_KURAGE_HASH_FEATURE_HPP_
#define SLIDE_KURAGE_HASH_FEATURE_HPP_
#include <memory>
#include "PlayBoard.hpp"
#include "ZobristTable.hpp"
namespace slide
{
template<int H, int W>
class KurageHashFeature
{
private:
ull selHash;
ull hash;
public:
static std::unique_ptr<const ZobristTable<H, W>> table;
KurageHashFeature() = default;
KurageHashFeature(const PlayBoardBase<H, W>& board) {
init(board);
}
void init(const PlayBoardBase<H, W>& board)
{
hash = 0ull;
rep(i, board.height()) rep(j, board.width()) {
hash ^= table->look(board(i, j), Point(i, j));
}
if(board.isSelected()){
selHash = table->lookSelected(board(board.selected));
hash ^= selHash;
}
else{
selHash = 0ull;
}
}
ull operator()() const
{
return hash;
}
void move(const PlayBoardBase<H, W>& board, Direction dir)
{
const Point src1 = board.selected - Point::delta(dir);
const Point src2 = board.selected;
const uchar id1 = board(src2);
const uchar id2 = board(src1);
hash ^= table->look(id1, src1) ^ table->look(id1, src2) ^ table->look(id2, src1) ^ table->look(id2, src2);
}
void select(const PlayBoardBase<H, W>& board)
{
hash ^= selHash;
selHash = table->lookSelected(board(board.selected));
hash ^= selHash;
}
};
template<int H, int W>
std::unique_ptr<const ZobristTable<H, W>> KurageHashFeature<H, W>::table = nullptr;
} // end of namespace slide
#endif
| 21.756757 | 114 | 0.596273 | taiheioki |
f80dc8919f40eeff132b518031b932f72c2de488 | 279 | hpp | C++ | src/ast/array.hpp | shiroyasha/telegraph | 1735dc392cfa6651ce69ca98b18f6b631c01f231 | [
"MIT",
"Unlicense"
] | 1 | 2016-12-07T21:41:37.000Z | 2016-12-07T21:41:37.000Z | src/ast/array.hpp | shiroyasha/telegraph | 1735dc392cfa6651ce69ca98b18f6b631c01f231 | [
"MIT",
"Unlicense"
] | null | null | null | src/ast/array.hpp | shiroyasha/telegraph | 1735dc392cfa6651ce69ca98b18f6b631c01f231 | [
"MIT",
"Unlicense"
] | null | null | null | #pragma once
#include "ast/node.hpp"
#include "ast/identifier.hpp"
#include "ast/type.hpp"
namespace ast {
class Array : public Type {
public:
Array(Identifier* name) : Type(name) {}
std::string toString() {
return "[" + Type::toString() + "]";
}
};
}
| 16.411765 | 43 | 0.598566 | shiroyasha |
f8125ad1502af2014a7b21a0def4ab8d6961d315 | 1,653 | hpp | C++ | backend/inc/sim/components/capacitor.hpp | capstone-2019/capstone | b9212ad803c962dc4b03fe8505fe56bfd820aa8a | [
"MIT"
] | 1 | 2019-05-04T02:21:12.000Z | 2019-05-04T02:21:12.000Z | backend/inc/sim/components/capacitor.hpp | capstone-2019/capstone | b9212ad803c962dc4b03fe8505fe56bfd820aa8a | [
"MIT"
] | 2 | 2019-02-11T17:11:28.000Z | 2019-02-11T17:12:26.000Z | backend/inc/sim/components/capacitor.hpp | capstone-2019/capstone | b9212ad803c962dc4b03fe8505fe56bfd820aa8a | [
"MIT"
] | null | null | null | /**
*
* @file capacitor.hpp
*
* @data April 1, 2019
*
* @brief This file contains the interface to the capacitor, a type of
* energy storage component supported by our simulator.
*
* @author Matthew Kasper (mkasper@andrew.cmu.edu)
*
*/
#ifndef _CAPACITOR_H_
#define _CAPACITOR_H_
#include <vector>
#include <string>
#include <unordered_map>
/**
* @brief Class to represent capacitors - a passive energy storage device
* supported by our simulator.
*/
class Capacitor : public Component
{
public:
/** @brief String which denotes a new capacitor in a netlist file */
static constexpr const char *IDENTIFIER = "CAPACITOR";
/* create a capacitor */
Capacitor(const std::vector<std::string>& tokens);
/**
* @brief Destroys a capacitor.
*/
~Capacitor() { }
/* Convert a capacitor to its string representation */
std::string to_string() override;
/* get the unknown quantities for this component */
std::vector<std::string> unknowns() override;
/* map unknowns into matrix indices in a linear system */
void map_unknowns(std::unordered_map<std::string, int> mapping) override;
/* Adds resistor current contributions into system of KCL equations */
void add_contribution(LinearSystem& sys,
Eigen::VectorXd& soln,
Eigen::VectorXd& prev_soln,
double dt) override;
private:
int npos; /**< Positive terminal */
int nneg; /**< Negative terminal */
double capacitance; /**< Capacitance in farads */
int n1; /**< Matrix index for unknown npos voltage */
int n2; /**< Matrix index for unknown nneg voltage */
};
#endif /* _CAPACITOR_H_ */
| 25.430769 | 74 | 0.675136 | capstone-2019 |
f812838c96544be7500f7805882b01f983abc815 | 1,629 | cpp | C++ | advent-of-code/2021/day-10/problem-2.cpp | kpagacz/spoj | 8bff809c6c5227a6e85e9b12f808dd921f24e587 | [
"MIT"
] | 1 | 2021-12-06T16:01:55.000Z | 2021-12-06T16:01:55.000Z | advent-of-code/2021/day-10/problem-2.cpp | kpagacz/comp-programming | 15482d762ede4d3b7f8ff45a193f6e6bcd85672a | [
"MIT"
] | null | null | null | advent-of-code/2021/day-10/problem-2.cpp | kpagacz/comp-programming | 15482d762ede4d3b7f8ff45a193f6e6bcd85672a | [
"MIT"
] | null | null | null | #include<iostream>
#include<string>
#include<unordered_map>
#include<stack>
#include<set>
#include<vector>
#include<algorithm>
const std::unordered_map<char, int> points{{')', 3}, {']', 57}, {'}', 1197}, {'>', 25137}};
const std::unordered_map<char, char> closers{{'(', ')'}, {'[', ']'}, {'{', '}'}, {'<', '>'}};
const std::set<char> openings{'(', '{', '[', '<'};
const std::unordered_map<char, int> scores{{')', 1}, {']', 2}, {'}', 3}, {'>', 4}};
int main() {
std::vector < std::string> completions;
std::string line;
while(std::cin >> line) {
std::stack<char> line_stack;
bool corrupted = false;
for(const auto& c : line) {
if (line_stack.empty()) {
line_stack.push(c);
continue;
}
if (openings.find(c) != openings.end()) {
line_stack.push(c);
continue;
} else {
if (c != closers.at(line_stack.top())) {
corrupted = true;
break;
} else {
line_stack.pop();
}
}
}
if (!line_stack.empty() && !corrupted) {
std::string completion = "";
while(!line_stack.empty()) {
completion += closers.at(line_stack.top());
line_stack.pop();
}
completions.push_back(completion);
}
}
std::vector<uint64_t> lines_scores;
for(const auto& completion : completions) {
uint64_t score = 0;
for(auto c : completion) {
score *= 5;
score += scores.at(c);
}
lines_scores.push_back(score);
}
std::sort(lines_scores.begin(), lines_scores.end());
std::cout << "Middle score: " << lines_scores[lines_scores.size() / 2] << '\n';
}
| 26.704918 | 93 | 0.54205 | kpagacz |
f8166d2f7ac86c9e2cd49367715d50161e1c3373 | 1,280 | cpp | C++ | libs/spirit/test/qi/grammar_fail.cpp | mike-code/boost_1_38_0 | 7ff8b2069344ea6b0b757aa1f0778dfb8526df3c | [
"BSL-1.0"
] | 1 | 2019-08-22T17:17:41.000Z | 2019-08-22T17:17:41.000Z | libs/spirit/test/qi/grammar_fail.cpp | mike-code/boost_1_38_0 | 7ff8b2069344ea6b0b757aa1f0778dfb8526df3c | [
"BSL-1.0"
] | null | null | null | libs/spirit/test/qi/grammar_fail.cpp | mike-code/boost_1_38_0 | 7ff8b2069344ea6b0b757aa1f0778dfb8526df3c | [
"BSL-1.0"
] | 1 | 2021-03-07T05:20:43.000Z | 2021-03-07T05:20:43.000Z | /*=============================================================================
Copyright (c) 2001-2009 Hartmut Kaiser
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#include <boost/spirit/include/qi_operator.hpp>
#include <boost/spirit/include/qi_char.hpp>
#include <boost/spirit/include/qi_string.hpp>
#include <boost/spirit/include/qi_numeric.hpp>
#include <boost/spirit/include/qi_nonterminal.hpp>
#include <boost/spirit/include/qi_parse.hpp>
using namespace boost::spirit;
using namespace boost::spirit::qi;
using namespace boost::spirit::ascii;
struct num_list : grammar<char const*, rule<char const*> >
{
num_list() : base_type(start)
{
using boost::spirit::int_;
num = int_;
start = num >> *(',' >> num);
}
rule<char const*, rule<char const*> > start, num;
};
// this test must fail compiling
int main()
{
char const* input = "some input, it doesn't matter";
char const* end = &input[strlen(input)+1];
num_list g;
bool r = phrase_parse(input, end, g,
space | ('%' >> *~char_('\n') >> '\n'));
return 0;
}
| 29.767442 | 80 | 0.583594 | mike-code |
f8182d23cacbf23137987e06f7f772a982dba0d9 | 1,347 | cc | C++ | 3rdparty/pytorch/caffe2/operators/experimental/c10/cpu/relu_cpu.cc | WoodoLee/TorchCraft | 999f68aab9e7d50ed3ae138297226dc95fefc458 | [
"MIT"
] | null | null | null | 3rdparty/pytorch/caffe2/operators/experimental/c10/cpu/relu_cpu.cc | WoodoLee/TorchCraft | 999f68aab9e7d50ed3ae138297226dc95fefc458 | [
"MIT"
] | null | null | null | 3rdparty/pytorch/caffe2/operators/experimental/c10/cpu/relu_cpu.cc | WoodoLee/TorchCraft | 999f68aab9e7d50ed3ae138297226dc95fefc458 | [
"MIT"
] | null | null | null | #include <c10/core/dispatch/KernelRegistration.h>
#include "caffe2/operators/experimental/c10/schemas/relu.h"
#include "caffe2/utils/eigen_utils.h"
#include "caffe2/utils/math.h"
#include "caffe2/core/tensor.h"
using caffe2::Tensor;
namespace caffe2 {
namespace {
template <class DataType>
void relu_op_cpu_impl(
const C10Tensor& input_,
const C10Tensor& output_) {
Tensor input(input_);
Tensor output(output_);
output.ResizeLike(input);
#ifdef CAFFE2_USE_ACCELERATE
const float zero = 0.0f;
vDSP_vthres(
input.data<float>(),
1,
&zero,
output.mutable_data<float>(),
1,
input.size());
#else
caffe2::EigenVectorMap<float>(output.mutable_data<float>(), input.numel()) =
caffe2::ConstEigenVectorMap<float>(input.data<float>(), input.numel())
.cwiseMax(0.f);
#endif
/* Naive implementation
const float* input_data = input.data<float>();
float* output_data = output.mutable_data<float>();
for (int i = 0; i < input.size(); ++i) {
output_data[i] = std::max(input_data[i], 0.f);
}
*/
}
} // namespace
} // namespace caffe2
namespace c10 {
C10_REGISTER_KERNEL(caffe2::ops::Relu)
.kernel(&caffe2::relu_op_cpu_impl<float>)
.dispatchKey({DeviceTypeId::CPU,
LayoutId(0),
caffe2::TypeMeta::Id<float>()});
} // namespace c10
| 25.903846 | 78 | 0.664439 | WoodoLee |
f818c9b7c0053c2db06f0a5882f94d5d234c6efb | 402 | cpp | C++ | Simulation/src/SimulationCore/SimulationWindow.cpp | RubenB-1643541/MarblingSimulation | 7534d7bcc4952a85a2512d354569256f8129c2cd | [
"MIT"
] | null | null | null | Simulation/src/SimulationCore/SimulationWindow.cpp | RubenB-1643541/MarblingSimulation | 7534d7bcc4952a85a2512d354569256f8129c2cd | [
"MIT"
] | null | null | null | Simulation/src/SimulationCore/SimulationWindow.cpp | RubenB-1643541/MarblingSimulation | 7534d7bcc4952a85a2512d354569256f8129c2cd | [
"MIT"
] | null | null | null | #include "SimulationWindow.h"
#include "../SimUtils/Icon.h"
SimulationWindow::SimulationWindow() : RenderEngine::WindowBase("Marbling Simulation")
{
GLFWimage* icon = LoadGLFWimage("res/icons/Icon.png");
glfwSetWindowIcon(_window, 1, icon);
}
void SimulationWindow::OnDraw()
{
}
void SimulationWindow::OnCreate()
{
Maximize();
SetBackgroundColor(0.5f, 0.2f, 0.0f, 1.0f);
}
| 19.142857 | 87 | 0.691542 | RubenB-1643541 |
f81ccb181109bb2cdd86d930513e643e52392a41 | 6,212 | cpp | C++ | printscan/faxsrv/com/whistler/faxrecipients.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | printscan/faxsrv/com/whistler/faxrecipients.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | printscan/faxsrv/com/whistler/faxrecipients.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*++
Copyright (c) 2000 Microsoft Corporation
Module Name:
FaxRecipients.cpp
Abstract:
Implementation of Fax Recipients Collection
Author:
Iv Garber (IvG) Apr, 2000
Revision History:
--*/
#include "stdafx.h"
#include "FaxComEx.h"
#include "FaxRecipients.h"
//
//====================== ADD & REMOVE ==================================
//
STDMETHODIMP
CFaxRecipients::Add (
/*[in]*/ BSTR bstrFaxNumber,
/*[in,defaultvalue("")]*/ BSTR bstrName,
/*[out, retval]*/ IFaxRecipient **ppRecipient
)
/*++
Routine name : CFaxRecipients::Add
Routine description:
Add New Recipient to the Recipients Collection
Author:
Iv Garber (IvG), Apr, 2000
Arguments:
ppRecipient [out] - Ptr to the newly created Recipient
Return Value:
Standard HRESULT code
--*/
{
HRESULT hr = S_OK;
DBG_ENTER (_T("CFaxRecipients::Add"), hr);
//
// Check that we can write to the given pointer
//
if (::IsBadWritePtr(ppRecipient, sizeof(IFaxRecipient* )))
{
//
// Got a bad return pointer
//
hr = E_POINTER;
AtlReportError(CLSID_FaxRecipients,
IDS_ERROR_INVALID_ARGUMENT,
IID_IFaxRecipients,
hr);
CALL_FAIL(GENERAL_ERR, _T("::IsBadWritePtr()"), hr);
return hr;
}
//
// Fax Number should exist
//
if (::SysStringLen(bstrFaxNumber) < 1)
{
hr = E_INVALIDARG;
AtlReportError(CLSID_FaxRecipients,
IDS_ERROR_EMPTY_ARGUMENT,
IID_IFaxRecipients,
hr);
CALL_FAIL(GENERAL_ERR, _T("::SysStringLen(bstrFaxNumber) < 1"), hr);
return hr;
}
CComPtr<IFaxRecipient> pNewRecipient;
hr = CFaxRecipient::Create(&pNewRecipient);
if (FAILED(hr))
{
//
// Failed to create Recipient object
//
AtlReportError(CLSID_FaxRecipients,
IDS_ERROR_OPERATION_FAILED,
IID_IFaxRecipients,
hr);
CALL_FAIL(GENERAL_ERR, _T("CFaxRecipient::Create()"), hr);
return hr;
}
try
{
m_coll.push_back(pNewRecipient);
}
catch (exception &)
{
//
// Failed to add the Recipient to the Collection
//
hr = E_OUTOFMEMORY;
AtlReportError(CLSID_FaxRecipients,
IDS_ERROR_OUTOFMEMORY,
IID_IFaxRecipients,
hr);
CALL_FAIL(MEM_ERR, _T("m_coll.push_back()"), hr);
return hr;
}
//
// Put Fax Number
//
hr = pNewRecipient->put_FaxNumber(bstrFaxNumber);
if (FAILED(hr))
{
AtlReportError(CLSID_FaxRecipients,
IDS_ERROR_OPERATION_FAILED,
IID_IFaxRecipients,
hr);
CALL_FAIL(MEM_ERR, _T("pNewRecipient->put_FaxNumber(bstrFaxNumber)"), hr);
return hr;
}
//
// Put Recipient's Name
//
hr = pNewRecipient->put_Name(bstrName);
if (FAILED(hr))
{
AtlReportError(CLSID_FaxRecipients,
IDS_ERROR_OPERATION_FAILED,
IID_IFaxRecipients,
hr);
CALL_FAIL(MEM_ERR, _T("pNewRecipient->put_Name(bstrName)"), hr);
return hr;
}
//
// Additional AddRef() to prevent death of the Recipient
//
(*pNewRecipient).AddRef();
pNewRecipient.CopyTo(ppRecipient);
return hr;
};
STDMETHODIMP
CFaxRecipients::Remove (
/*[in]*/ long lIndex
)
/*++
Routine name : CFaxRecipients::Remove
Routine description:
Remove Recipient at given index from the Collection
Author:
Iv Garber (IvG), Apr, 2000
Arguments:
lIndex [in] - Index of the Recipient to Remove
Return Value:
Standard HRESULT code
--*/
{
HRESULT hr = S_OK;
DBG_ENTER (_T("CFaxRecipients::Remove"), hr, _T("%d"), lIndex);
if (lIndex < 1 || lIndex > m_coll.size())
{
//
// Invalid Index
//
hr = E_INVALIDARG;
AtlReportError(CLSID_FaxRecipients,
IDS_ERROR_OUTOFRANGE,
IID_IFaxRecipients,
hr);
CALL_FAIL(GENERAL_ERR, _T("lIndex > m_coll.size()"), hr);
return hr;
}
ContainerType::iterator it;
it = m_coll.begin() + lIndex - 1;
hr = (*it)->Release();
if (FAILED(hr))
{
//
// Failed to Release the Interface
//
AtlReportError(CLSID_FaxRecipients,
IDS_ERROR_OPERATION_FAILED,
IID_IFaxRecipients,
hr);
CALL_FAIL(GENERAL_ERR, _T("Release()"), hr);
return hr;
}
try
{
m_coll.erase(it);
}
catch(exception &)
{
//
// Failed to remove the Recipient from the Collection
//
hr = E_OUTOFMEMORY;
AtlReportError(CLSID_FaxRecipients,
IDS_ERROR_OUTOFMEMORY,
IID_IFaxRecipients,
hr);
CALL_FAIL(MEM_ERR, _T("m_coll.erase()"), hr);
return hr;
}
return hr;
};
//
//====================== CREATE ==================================
//
HRESULT
CFaxRecipients::Create (
IFaxRecipients **ppRecipients
)
/*++
Routine name : CFaxRecipients::Create
Routine description:
Static function to Create Recipients Collection
Author:
Iv Garber (IvG), Apr, 2000
Arguments:
ppRecipients [out] - the resulting collection
Return Value:
Standard HRESULT code
--*/
{
CComObject<CFaxRecipients> *pClass;
HRESULT hr;
DBG_ENTER (_T("CFaxRecipients::Create"), hr);
hr = CComObject<CFaxRecipients>::CreateInstance(&pClass);
if (FAILED(hr))
{
//
// Failed to create Instance
//
CALL_FAIL(GENERAL_ERR, _T("CComObject<CFaxRecipients>::CreateInstance()"), hr);
return hr;
}
hr = pClass->QueryInterface(__uuidof(IFaxRecipients), (void **) ppRecipients);
if (FAILED(hr))
{
//
// Failed to Query Fax Recipients Interface
//
CALL_FAIL(GENERAL_ERR, _T("QueryInterface()"), hr);
return hr;
}
return hr;
}
//
//==================== INTERFACE SUPPORT ERROR INFO =====================
//
STDMETHODIMP
CFaxRecipients::InterfaceSupportsErrorInfo (
REFIID riid
)
/*++
Routine name : CFaxRecipients::InterfaceSupportsErrorInfo
Routine description:
ATL's implementation of Support Error Info
Author:
Iv Garber (IvG), Apr, 2000
Arguments:
riid [in] - Interface ID
Return Value:
Standard HRESULT code
--*/
{
static const IID* arr[] =
{
&IID_IFaxRecipients
};
for (int i=0; i < sizeof(arr) / sizeof(arr[0]); i++)
{
if (InlineIsEqualGUID(*arr[i],riid))
return S_OK;
}
return S_FALSE;
}
| 18.163743 | 82 | 0.61671 | npocmaka |
f81d40d89f25fd1348ed725f9dc902a70b1889b6 | 2,995 | cpp | C++ | KatamariSphereController.cpp | catinapoke/directx-engine | b967eff417d170fce947066486b01a1003fa20ce | [
"MIT"
] | null | null | null | KatamariSphereController.cpp | catinapoke/directx-engine | b967eff417d170fce947066486b01a1003fa20ce | [
"MIT"
] | null | null | null | KatamariSphereController.cpp | catinapoke/directx-engine | b967eff417d170fce947066486b01a1003fa20ce | [
"MIT"
] | null | null | null | #include "KatamariSphereController.h"
#include <iostream>
#include "TransformComponent.h"
#include "Camera.h"
typedef DirectX::SimpleMath::Matrix Matrix;
KatamariSphereController::KatamariSphereController(std::shared_ptr<InputDevice> device, CameraComponent* camera)
: transform(nullptr), camera_(camera->GetActor()->GetComponent<TransformComponent>())
{
input_device = device;
}
void KatamariSphereController::Awake()
{
ComponentBase::Awake();
transform = GetActor()->GetComponent<TransformComponent>();
assert(transform != nullptr);
}
void RotateMatrix(TransformComponent* transform, const Vector3 rotation)
{
if (rotation == Vector3{ 0,0,0 }) return;
Matrix model = Matrix::CreateScale(transform->GetLocalScale());
model *= Matrix::CreateFromQuaternion(transform->GetLocalQuaternion());
//model *= Matrix::CreateFromQuaternion(Quaternion::CreateFromYawPitchRoll(rotation.z, rotation.y, rotation.x));
model *= Matrix::CreateRotationX(rotation.x);
model *= Matrix::CreateRotationY(rotation.y);
model *= Matrix::CreateRotationZ(rotation.z);
model *= Matrix::CreateTranslation(transform->GetLocalPosition());
transform->SetLocalMatrix(model);
Vector3 r = transform->GetLocalRotation();
std::cout << "R: " << r.x << " " << r.y << " " << r.z << std::endl;
}
void KatamariSphereController::Update(float deltaTime)
{
ComponentBase::Update(deltaTime);
Vector3 position = transform->GetLocalPosition();
Vector3 rotation = transform->GetLocalRotation();
const Vector3 move_direction = GetMoveDirection();
position += move_direction * direction_weight * deltaTime;
transform->SetLocalPosition(position);
rotation = CircleRotation(rotation + GetRotationOffset(move_direction) * rotation_weight * deltaTime);
transform->SetLocalRotation(rotation);
// RotateMatrix(transform, GetRotationOffset(move_direction) * rotation_weight * deltaTime);
}
Vector3 KatamariSphereController::GetMoveDirection() const
{
Vector3 direction(0, 0, 0);
if (input_device->IsKeyDown(Keys::D)) {
direction += Vector3(1.0f, 0.0f, 0.0f);
}
if (input_device->IsKeyDown(Keys::A)) {
direction += Vector3(-1.0f, 0.0f, 0.0f);
}
if (input_device->IsKeyDown(Keys::W)) {
direction += Vector3(0.0f, 0.0f, 1.0f);
}
if (input_device->IsKeyDown(Keys::S)) {
direction += Vector3(0.0f, 0.0f, -1.0f);
}
direction.Normalize();
Vector3 forward = transform->GetWorldPosition() - camera_->GetWorldPosition();
forward = (Matrix::CreateTranslation(forward) * transform->GetParentWorldModelMatrix().Invert()).Translation();
forward.y = 0;
forward.Normalize();
const Vector3 right = forward.Cross(Vector3(0, 1, 0));
return forward * direction.z + right * direction.x;
}
Vector3 KatamariSphereController::GetRotationOffset(Vector3 move_direction)
{
move_direction.Normalize();
return { -move_direction.x, move_direction.z, 0 };
}
| 32.554348 | 116 | 0.70384 | catinapoke |
f81f207532f53e6de14d7ea4ae35ad527b6f1aa9 | 9,596 | hpp | C++ | lib/fiber/collection_of_basis_transformations.hpp | nicolas-chaulet/bempp | 0f5cc72e0e542437e787db5704978456b0ad9e35 | [
"BSL-1.0"
] | 2 | 2021-07-22T13:34:28.000Z | 2021-07-22T13:35:20.000Z | lib/fiber/collection_of_basis_transformations.hpp | UCL/bempp | f768ec7d319c02d6e0142512fb61db0607cadf10 | [
"BSL-1.0"
] | null | null | null | lib/fiber/collection_of_basis_transformations.hpp | UCL/bempp | f768ec7d319c02d6e0142512fb61db0607cadf10 | [
"BSL-1.0"
] | 1 | 2021-05-17T09:46:44.000Z | 2021-05-17T09:46:44.000Z | // Copyright (C) 2011-2012 by the BEM++ 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.
#ifndef fiber_collection_of_basis_transformations_hpp
#define fiber_collection_of_basis_transformations_hpp
#include "../common/common.hpp"
#include "scalar_traits.hpp"
namespace Fiber
{
/** \cond FORWARD_DECL */
template <typename T> class CollectionOf3dArrays;
template <typename ValueType> class BasisData;
template <typename CoordinateType> class GeometricalData;
/** \endcond */
/** \ingroup weak_form_elements
* \brief Collection of basis function transformations.
*
* This class represents a collection of one or more basis function
* transformations. A basis function transformation is a function mapping a
* point \f$x\f$ located at an element of a grid to a scalar or vector
* of a fixed dimension, with real or complex elements. In addition to any
* geometrical data related to \f$x\f$, such as its global coordinates or the
* unit vectors normal to the grid at \f$x\f$, it can depend on the value
* and/or the first derivatives of a basis function defined on the reference
* element (e.g.\ the unit triangle or the unit square). Example basis
* function transformations include the mapping of basis functions to shape
* functions---expressed with the identity mapping for scalar basis functions
* or the Piola transform for vector basis function---and the mapping of basis
* functions to the surface curls of shape functions. All basis function
* transformations in a collection are evaluated together and hence may reuse
* results of any intermediate calculations.
*
* A basis function transformation is assumed to preserve the type of the
* values of basis functions, i.e. it should map real-valued basis functions
* to real-valued functions and complex-valued basis functions to
* complex-valued functions.
*
* \tparam CoordinateType_
* Type used to represent coordinates (either <tt>float</tt> or
* <tt>double</tt>). */
template <typename CoordinateType_>
class CollectionOfBasisTransformations
{
public:
typedef CoordinateType_ CoordinateType;
typedef typename ScalarTraits<CoordinateType>::ComplexType ComplexType;
/** \brief Destructor. */
virtual ~CollectionOfBasisTransformations()
{}
/** \brief Return the number of transformations belonging to the collection. */
virtual int transformationCount() const = 0;
/** \brief Return the number of components of basis functions acted upon.
*
* For instance, the implementation of this function for a collection of
* transformations operating on scalar basis functions should return 1; for
* a collection operating on vector-valued basis functions with three
* components, this function should return 3. */
virtual int argumentDimension() const = 0;
/** \brief Return the number of components of the result of i'th
* transformation.
*
* Transformation indices start from 0.
*
* For example, if the first transformation produces a scalar function,
* the implementation of this function should return 1 if \p i == 0.
*
* The behaviour of this function for \p i < 0 or \p >= transformationCount()
* is not specified. */
virtual int resultDimension(int i) const = 0;
/** \brief Retrieve the types of data on which the transformations depend.
*
* An implementation of this function should modify the \p basisDeps and
* \p geomDeps bitfields by adding to them, using the bitwise OR
* operation, an appropriate combination of the flags defined in the enums
* BasisDataType and GeometricalDataType.
*
* For example, a collection of transformations depending on the values
* and first derivatives of basis functions and the global coordinates of
* points at which the transformed functions are evaluated should modify
* the arguments as follows:
*
\code
basisDeps |= VALUES | DERIVATIVES;
geomDeps |= GLOBALS;
\endcode */
virtual void addDependencies(size_t& basisDeps, size_t& geomDeps) const = 0;
/** \brief Evaluate transformations of real-valued basis functions.
*
* \param[in] basisData
* Values and/or derivatives of \f$m \geq 0 \f$ basis functions at \f$n
* \geq 0\f$ points on an element. The number of points, \f$n\f$, can be
* obtained by calling <tt>basisData.pointCount()</tt>; the number of
* basis functions, \f$m\f$, can be obtained by calling
* <tt>basisData.functionCount()</tt>.
* \param[in] geomData
* Geometrical data related to the \f$n\f$ points at which the
* basis functions have been evaluated.
* \param[out] result
* A collection of 3-dimensional arrays intended to store the
* transformed basis function values. On output, <tt>result[i][(j, k,
* p)</tt> should contain the <em>j</em> element of the vector being the
* value of <em>i</em>th transformation of <em>k</em>th basis function
* at <em>p</em>th point.
*
* An implementation of this function may assume that \p basisData and \p
* geomData contain all the types of data specified in the implementation
* of addDependencies(). Before filling the arrays from \p result, this
* function must ensure that size of the array collection and the
* dimensions of the individual arrays are correct, calling
* <tt>CollectionOf3dArrays::set_size()</tt> and
* <tt>_3dArray::set_size()</tt> if necessary.
*/
void evaluate(
const BasisData<CoordinateType>& basisData,
const GeometricalData<CoordinateType>& geomData,
CollectionOf3dArrays<CoordinateType>& result) const {
evaluateImplReal(basisData, geomData, result);
}
/** \brief Evaluate transformations of complex-valued basis functions.
*
* See the documentation of the other overload for the description of
* function parameters.
*/
void evaluate(
const BasisData<ComplexType>& basisData,
const GeometricalData<CoordinateType>& geomData,
CollectionOf3dArrays<ComplexType>& result) const {
evaluateImplComplex(basisData, geomData, result);
}
private:
/** \brief Evaluate transformations of real-valued basis functions.
*
* \param[in] basisData
* Values and/or derivatives of \f$m \geq 0 \f$ basis functions at \f$n
* \geq 0\f$ points on an element. The number of points, \f$n\f$, can be
* obtained by calling <tt>basisData.pointCount()</tt>; the number of
* basis functions, \f$m\f$, can be obtained by calling
* <tt>basisData.functionCount()</tt>.
* \param[in] geomData
* Geometrical data related to the \f$n\f$ points at which the
* basis functions have been evaluated.
* \param[out] result
* A collection of 3-dimensional arrays intended to store the
* transformed basis function values. On output, <tt>result[i][(j, k,
* p)</tt> should contain the <em>j</em> element of the vector being the
* value of <em>i</em>th transformation of <em>k</em>th basis function
* at <em>p</em>th point.
*
* This is a pure virtual function that must be overridden in subclasses
* of CollectionOfBasisTransformations.
*
* An implementation of this function may assume that \p basisData and \p
* geomData contain all the types of data specified in the implementation
* of addDependencies(). Before filling the arrays from \p result, this
* function must ensure that size of the array collection and the
* dimensions of the individual arrays are correct, calling
* <tt>CollectionOf3dArrays::set_size()</tt> and
* <tt>_3dArray::set_size()</tt> if necessary.
*/
virtual void evaluateImplReal(
const BasisData<CoordinateType>& basisData,
const GeometricalData<CoordinateType>& geomData,
CollectionOf3dArrays<CoordinateType>& result) const = 0;
/** \brief Evaluate transformations of complex-valued basis functions.
*
* See the documentation of evaluateImplReal() for the description of
* function parameters. */
virtual void evaluateImplComplex(
const BasisData<ComplexType>& basisData,
const GeometricalData<CoordinateType>& geomData,
CollectionOf3dArrays<ComplexType>& result) const = 0;
};
} // namespace Fiber
#endif
| 45.913876 | 83 | 0.698833 | nicolas-chaulet |
f824518665a0ccd2d9fc19557a4ce29f38494a6b | 2,058 | cpp | C++ | src/libraries/thermophysicalModels/radiation/submodels/scatterModel/noScatter/noScatter.cpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | src/libraries/thermophysicalModels/radiation/submodels/scatterModel/noScatter/noScatter.cpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | src/libraries/thermophysicalModels/radiation/submodels/scatterModel/noScatter/noScatter.cpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | /*---------------------------------------------------------------------------*\
Copyright (C) 2012-2018 OpenFOAM Foundation
-------------------------------------------------------------------------------
License
This file is part of Caelus.
Caelus 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.
Caelus 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 Caelus. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include "noScatter.hpp"
#include "addToRunTimeSelectionTable.hpp"
// * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * //
namespace CML
{
namespace radiation
{
defineTypeNameAndDebug(noScatter, 0);
addToRunTimeSelectionTable(scatterModel, noScatter, dictionary);
}
}
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
CML::radiation::noScatter::noScatter
(
const dictionary& dict,
const fvMesh& mesh
)
:
scatterModel(dict, mesh)
{}
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
CML::tmp<CML::volScalarField> CML::radiation::noScatter::sigmaEff() const
{
return tmp<volScalarField>
(
new volScalarField
(
IOobject
(
"sigma",
mesh_.time().timeName(),
mesh_,
IOobject::NO_READ,
IOobject::NO_WRITE,
false
),
mesh_,
dimensionedScalar("zero", dimless/dimLength, 0.0)
)
);
}
| 28.985915 | 79 | 0.510204 | MrAwesomeRocks |
f824c6de8a75de55487bcacabf20b24e22ab5bef | 880 | hpp | C++ | escapee/Classes/v1/GameAct/Contours/KitExpert.hpp | 1pkg/dump | 0ee579cb6a97ae64d5367cc624b2407d7d4b1c7b | [
"MIT"
] | null | null | null | escapee/Classes/v1/GameAct/Contours/KitExpert.hpp | 1pkg/dump | 0ee579cb6a97ae64d5367cc624b2407d7d4b1c7b | [
"MIT"
] | 3 | 2020-12-11T10:01:27.000Z | 2022-02-13T22:12:05.000Z | escapee/Classes/v1/GameAct/Contours/KitExpert.hpp | 1pkg/dump | 0ee579cb6a97ae64d5367cc624b2407d7d4b1c7b | [
"MIT"
] | null | null | null | #ifndef __GAME_ACT_CONTOURS_KIT_EXPERT_HPP__
#define __GAME_ACT_CONTOURS_KIT_EXPERT_HPP__
#include "Interfaces/INoncopyable.hpp"
#include <cocos2d.h>
namespace GameAct
{
namespace Contours
{
class Kit;
class Segment;
class Line;
class KitExpert : public Interfaces::INoncopyable
{
public:
KitExpert(Kit * path);
Segment * getSegment(cocos2d::PhysicsBody * body) const;
bool intersect(cocos2d::Rect rect) const;
bool hasSegmentUnder(cocos2d::Vec2 point) const;
bool hasSegmentBellow(cocos2d::Vec2 point) const;
bool isEndOfSegment(cocos2d::Vec2 point, float delta) const;
cocos2d::Color4F getSegmentColor(cocos2d::Vec2 point) const;
private:
std::vector<Line *> findLines(cocos2d::Vec2 point, bool orientation) const;
std::vector<Segment *> findSegments(cocos2d::Vec2 point) const;
Kit * _kit;
};
}
}
#endif | 18.723404 | 77 | 0.727273 | 1pkg |
f826e199873397f748c33e7cde8521e04347f672 | 5,141 | cpp | C++ | applicationsBin/sbReconf/makeConfigY.cpp | claytronics/visiblesim | 2762a88a23e50516d0f166dd9629f1ac7290fded | [
"Apache-2.0"
] | 4 | 2016-08-18T03:19:49.000Z | 2020-09-20T03:29:26.000Z | applicationsBin/sbReconf/makeConfigY.cpp | claytronics/visiblesim | 2762a88a23e50516d0f166dd9629f1ac7290fded | [
"Apache-2.0"
] | 2 | 2016-08-18T03:25:07.000Z | 2016-08-29T17:51:50.000Z | applicationsBin/sbReconf/makeConfigY.cpp | claytronics/visiblesim | 2762a88a23e50516d0f166dd9629f1ac7290fded | [
"Apache-2.0"
] | 3 | 2015-05-14T07:29:55.000Z | 2021-07-18T23:45:36.000Z | #include <iostream>
#include <fstream>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include "skeleton.h"
using namespace std;
int main(int argc,char **argv) {
int initSquareLx=41,initSquareLy=41,
conveyorBlocks=500,armLength=15;
int maxTimeSimulation=3000,iAngle=45;
double angle;
if (argc>1) {
initSquareLx = atoi(argv[1]);
cout << "initSquareLx=" << initSquareLx << endl;
}
if (argc>2) {
initSquareLy = atoi(argv[2]);
cout << "initSquareLy=" << initSquareLy << endl;
}
if (argc>3) {
conveyorBlocks = atoi(argv[3]);
cout << "conveyorBlocks=" << conveyorBlocks << endl;
}
if (argc>4) {
armLength = atoi(argv[4]);
cout << "armLength=" << armLength << endl;
}
if (argc>5) {
iAngle = atoi(argv[5]);
cout << "iangle=" << iAngle << endl;
}
angle = iAngle*M_PI/180.0;
if (argc>6) {
maxTimeSimulation = atoi(argv[6]);
cout << "maxTimeSimulation=" << maxTimeSimulation << endl;
}
int areaLx = 4+(max(initSquareLx,4*armLength)),
areaLy = 15+initSquareLy+2*armLength;
int cameraDist = 25.0*sqrt(areaLx*areaLx+areaLy*areaLy)/tan(50.0*M_PI/180.0);
int srcDist = 25.0*sqrt(areaLx*areaLx+areaLy*areaLy)/tan(45.0*M_PI/180.0);
Vecteur Origine(areaLx/2.0,areaLy-initSquareLy-3,0);
Vecteur P(Origine[0],Origine[1]-armLength/2,0);
Vecteur Q(P[0]+armLength*1.5*cos(angle),P[1]-armLength*1.5*sin(angle),0);
Vecteur R(P[0]-armLength*1.5*cos(angle),P[1]-armLength*1.5*sin(angle),0);
cout << "O=" << Origine << endl;
cout << "P=" << P << endl;
cout << "Q=" << Q << endl;
/*Skeleton *S = new SkelPoint(Origine,6,-0.1);
Skeleton *S0 = new SkelLine(Origine,P,3,-0.2);
S->add(S0);
Skeleton *S1 = new SkelPoint(P,3,-0.1);
S0->add(S1);
Skeleton *S2 = new SkelLine(P,Q,3,-0.2);
S1->add(S2);
Skeleton *S3 = new SkelPoint(Q,6,-0.1);
S2->add(S3);*/
Skeleton *S = new SkelLine(Origine,P,3,-0.2);
Skeleton *S2 = new SkelLine(P,Q,3,-0.2);
S->add(S2);
Skeleton *S3 = new SkelLine(P,R,3,-0.2);
S->add(S3);
float *grid = new float[areaLx * areaLy], *ptr=grid;
int i=areaLx*areaLy;
while (i--) {
*ptr++=0.0f;
}
int ix,iy;
for (iy=0; iy<areaLy; iy++) {
for (ix=0; ix<areaLx; ix++) {
Origine.set(ix,iy,0);
grid[iy*areaLx+ix] = S->potentiel(Origine);
}
}
float maxi=0,s;
int xmaxi,ymaxi;
for (i=0; i<conveyorBlocks; i++) {
maxi=0;
for (iy=0; iy<areaLy; iy++) {
for (ix=0; ix<areaLx; ix++) {
s=grid[iy*areaLx+ix];
if (s>=maxi) {
xmaxi = ix;
ymaxi = iy;
maxi = s;
}
}
}
grid[ymaxi*areaLx+xmaxi]=-1;
}
cout << maxi << endl;
char titre[1024];
sprintf(titre,"configMakeY%dx%d_%d_%d.xml",initSquareLx,initSquareLy,conveyorBlocks,armLength);
ofstream fout;
fout.open(titre);
fout << "<?xml version=\"1.0\" standalone=\"no\" ?>"<< endl;
fout << "<world gridSize=\""<< areaLx << "," << areaLy << "\" windowSize=\"1800,900\" maxSimulationTime=\"" << maxTimeSimulation << "mn\">" << endl;
fout << "<camera target=\""<< areaLx*25.0/2.0 << "," << areaLy*25.0/2.0 << ",0\" directionSpherical=\"0,38," << cameraDist << "\" angle=\"50\"/>" << endl;
fout << "<spotlight target=\""<< areaLx*25.0/2.0 << "," << areaLy*25.0/2.0 << ",0\" directionSpherical=\"-30,50," << srcDist << "\" angle=\"45\"/>" << endl;
fout << "<blockList color=\"0,255,0\" blocksize=\"25.0,25.0,11.0\">" << endl;
for (iy=0; iy<initSquareLy; iy++) {
fout << "<blocksLine line=\"" << initSquareLy+1-iy << "\" values=\"00";
for (ix=0; ix<areaLx/2-initSquareLx; ix++) {
fout << "0";
}
for (ix=0; ix<initSquareLx; ix++) {
fout << "1";
}
for (ix=areaLx/2; ix<areaLx; ix++) {
fout << "0";
}
fout << "\"/>" << endl;
}
fout << "</blockList>\n<targetGrid>" << endl;
/* int ix0=2+initSquareLx-overlapLx,
iy0=2+initSquareLy-overlapLy;
for (iy=0; iy<finalSquareLy; iy++) {
fout << "<targetLine line=\"" << finalSquareLy-1+iy0-iy << "\" values=\"";
for (ix=0; ix<ix0; ix++) {
fout << "0";
}
for (ix=0; ix<finalSquareLx; ix++) {
fout << "1";
}
fout << "00\"/>" << endl;
}*/
for (iy=0; iy<areaLy; iy++) {
fout << "<targetLine line=\"" << areaLy-iy-1 << "\" values=\"";
for (ix=0; ix<areaLx; ix++) {
fout << (grid[ix+iy*areaLx]==-1)?1:0 ;
//fout << grid[ix+iy*areaLx];
}
fout << "\"/>" << endl;
}
fout << "</targetGrid>" << endl;
// lecture du fichier capabilities.xml
ifstream fin("capabilities.xml");
char line[1024];
while (!fin.eof()) {
fin.getline(line,1024);
fout << line << endl;
}
fout << "</world>\n";
delete S;
fout.close();
return 0;
}
| 30.420118 | 157 | 0.51313 | claytronics |
f827a230332c0358261ed44f6ecdbd15a798b337 | 1,251 | hxx | C++ | opencascade/ShapeExtend_Parametrisation.hxx | valgur/OCP | 2f7d9da73a08e4ffe80883614aedacb27351134f | [
"Apache-2.0"
] | 117 | 2020-03-07T12:07:05.000Z | 2022-03-27T07:35:22.000Z | opencascade/ShapeExtend_Parametrisation.hxx | CadQuery/cpp-py-bindgen | 66e7376d3a27444393fc99acbdbef40bbc7031ae | [
"Apache-2.0"
] | 66 | 2019-12-20T16:07:36.000Z | 2022-03-15T21:56:10.000Z | opencascade/ShapeExtend_Parametrisation.hxx | CadQuery/cpp-py-bindgen | 66e7376d3a27444393fc99acbdbef40bbc7031ae | [
"Apache-2.0"
] | 76 | 2020-03-16T01:47:46.000Z | 2022-03-21T16:37:07.000Z | // Created on: 1998-07-21
// Created by: data exchange team
// Copyright (c) 1998-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _ShapeExtend_Parametrisation_HeaderFile
#define _ShapeExtend_Parametrisation_HeaderFile
//! Defines kind of global parametrisation on the composite surface
//! each patch of the 1st row and column adds its range, Ui+1 = Ui + URange(i,1), etc.
//! each patch gives range 1.: Ui = i-1, Vj = j-1
//! uniform parametrisation with global range [0,1]
enum ShapeExtend_Parametrisation
{
ShapeExtend_Natural,
ShapeExtend_Uniform,
ShapeExtend_Unitary
};
#endif // _ShapeExtend_Parametrisation_HeaderFile
| 39.09375 | 86 | 0.780176 | valgur |
f82b1039c9d734ac60363adfdb91874ca6e969c2 | 39,825 | cpp | C++ | main/dsp/DCO_Synth.cpp | shroomist/Glo_v1 | 19e09790fa9f26926f7565f026ebb98fec4243ee | [
"Apache-2.0"
] | 16 | 2019-10-09T17:20:15.000Z | 2021-09-05T03:26:00.000Z | main/dsp/DCO_Synth.cpp | shroomist/Glo_v1 | 19e09790fa9f26926f7565f026ebb98fec4243ee | [
"Apache-2.0"
] | 1 | 2019-12-16T20:29:33.000Z | 2019-12-16T20:29:33.000Z | main/dsp/DCO_Synth.cpp | shroomist/Glo_v1 | 19e09790fa9f26926f7565f026ebb98fec4243ee | [
"Apache-2.0"
] | 3 | 2019-11-01T01:03:00.000Z | 2022-02-16T13:35:34.000Z | /*
* DCO_synth.cpp
*
* Created on: 11 May 2017
* Author: mario
*
* Based on "The Tiny-TS Touch Synthesizer" by Janost 2016, Sweden
* https://janostman.wordpress.com/the-tiny-ts-diy-touch-synthesizer/
* https://www.kickstarter.com/projects/732508269/the-tiny-ts-an-open-sourced-diy-touch-synthesizer/
*
*/
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
#include <DCO_Synth.h>
#include <Accelerometer.h>
//#include <stdbool.h>
//#include <string.h>
//#include <stddef.h>
//#include <stdlib.h>
//#include <math.h>
//#include <InitChannels.h>
#include <Interface.h>
//#include <MusicBox.h>
#include <hw/codec.h>
#include <hw/signals.h>
#include <hw/ui.h>
#include <notes.h>
#include <FreqDetect.h>
//#include <hw/init.h>
#include <hw/gpio.h>
#include <hw/sdcard.h>
#include <hw/midi.h>
#include <hw/leds.h>
//#include <hw/sha1.h>
//#include <stdio.h>
//#define DEBUG_DCO
#define MIX_INPUT
#define MIX_ECHO
//#define USE_AUTOCORRELATION
//#define LPF_ENABLED
#define ADC_LPF_ALPHA_DCO 0.2f //up to 1.0 for max feedback = no filtering
#define ADC_SAMPLE_GAIN 4 //integer value
#define DYNAMIC_LIMITER
//#define STATIC_LIMITER
extern float ADC_LPF_ALPHA;
const uint8_t DCO_Synth::sinetable256[256] = {
0,0,0,0,1,1,1,2,2,3,4,5,5,6,7,9,10,11,12,14,15,16,18,20,21,23,25,27,29,31,
33,35,37,39,42,44,46,49,51,54,56,59,62,64,67,70,73,76,78,81,84,87,90,93,96,99,102,105,108,111,115,118,121,124,
127,130,133,136,139,143,146,149,152,155,158,161,164,167,170,173,176,178,181,184,187,190,192,195,198,200,203,205,208,210,212,215,217,219,221,223,225,227,229,231,233,234,236,238,239,240,
242,243,244,245,247,248,249,249,250,251,252,252,253,253,253,254,254,254,254,254,254,254,253,253,253,252,252,251,250,249,249,248,247,245,244,243,242,240,239,238,236,234,233,231,229,227,225,223,
221,219,217,215,212,210,208,205,203,200,198,195,192,190,187,184,181,178,176,173,170,167,164,161,158,155,152,149,146,143,139,136,133,130,127,124,121,118,115,111,108,105,102,99,96,93,90,87,84,81,78,
76,73,70,67,64,62,59,56,54,51,49,46,44,42,39,37,35,33,31,29,27,25,23,21,20,18,16,15,14,12,11,10,9,7,6,5,5,4,3,2,2,1,1,1,0,0,0
};
//uint8_t DCO_Synth::*sawtable256;
//uint8_t DCO_Synth::*squaretable256;
DCO_Synth::DCO_Synth()
{
envtick = 549;
DOUBLE = 0;
RESO = 64; //resonant peak mod volume
//-------- Synth parameters --------------
//volatile uint8_t VCA=255; //VCA level 0-255
ATTACK = 1; // ENV Attack rate 0-255
RELEASE = 1; // ENV Release rate 0-255
//ENVELOPE=0; // ENV Shape
//TRIG=0; //MIDItrig 1=note ON
//-----------------------------------------
FREQ = 0; //DCO pitch
DCO_BLOCKS_ACTIVE = DCO_BLOCKS_MAX;// / 2;
DCO_mode = 0;
SET_mode = 0;
button_set_held = 0;
MIDI_note_set = 0;//, MIDI_note_on = 0;
use_table256 = (uint8_t*)sinetable256;
sawtable256 = (uint8_t*)malloc(256*sizeof(uint8_t));
squaretable256 = (uint8_t*)malloc(256*sizeof(uint8_t));
for(int i=0;i<256;i++)
{
sawtable256[i] = i;
squaretable256[i] = (i<128)?0:255;
}
}
DCO_Synth::~DCO_Synth(void)
{
printf("DCO_Synth::~DCO_Synth(void)\n");
free(sawtable256);
free(squaretable256);
#ifdef USE_AUTOCORRELATION
stop_autocorrelation();
#endif
}
//---------------------------------------------------------------------------------------------------------------------
// Old, simpler version (no controls during play, apart from IR sensors) but keeping here as it is fun to play
// Some leftovers from the original Tiny-TS code
//---------------------------------------------------------------------------------------------------------------------
//mixed sound output variable
//int16_t OutSample = 128;
//uint8_t GATEIO=0; //0=Gate is output, 1=Gate is input
//uint16_t COARSEPITCH;
//uint8_t ENVsmoothing;
//uint8_t envcnt=10;
//int16_t ENV;
//uint8_t k=0;
//uint8_t z;
//int8_t MUX=0;
void DCO_Synth::v1_init()//int mode)
{
//-----------------------------------------------------------------------------------
// Tiny-TS variables init
//-----------------------------------------------------------------------------------
sample_i16 = 128;
FREQ=DCO_FREQ_DEFAULT;//440;//MIDI2FREQ(key+12+(COARSEPITCH/21.3125));
//uint16_t CVout=COARSEPITCH+(key*21.33);
//OCR1AH = (CVout>>8);
//OCR1AL = CVout&255;
//---------------------------------------------------------------
//--------------- ADC block -------------------------------------
//if (MUX==0) COARSEPITCH=(ADCL+(ADCH<<8));
//COARSEPITCH=0;//(uint16_t)123;//45;
//if (MUX==1) DOUBLE=(ADCL+(ADCH<<8))>>2;
DOUBLE = 12;
//if (MUX==2) PHASEamt=(((ADCL+(ADCH<<8)))>>3);
PHASEamt = 9;
//if (MUX==3) ENVamt=((ADCL+(ADCH<<8))>>3);
ENVamt = 123;
//if (MUX==4) ATTACK=ATTrates[15-((ADCL+(ADCH<<8))>>6)];
ATTACK = 64;//ATTrates[12];
//if (MUX==5) RELEASE=RELrates[15-((ADCL+(ADCH<<8))>>6)];
RELEASE = 64;//RELrates[6];
ECHO_MIXING_GAIN_MUL = 3; //amount of signal to feed back to echo loop, expressed as a fragment
ECHO_MIXING_GAIN_DIV = 4; //e.g. if MUL=2 and DIV=3, it means 2/3 of signal is mixed in
ADC_LPF_ALPHA = ADC_LPF_ALPHA_DCO;
#ifdef USE_AUTOCORRELATION
start_autocorrelation(0); //start at core 0 as the DCO is running at core 1
#endif
}
void DCO_Synth::v1_play_loop()
{
int i;
int midi_override = 0;
while(!event_next_channel)
{
if(waveform)
{
//-------------------- DCO block ------------------------------------------
DCO_output[0] = 0;
DCO_output[1] = 0;
for (int b=0; b<DCO_BLOCKS_ACTIVE; b++)
{
phacc[b] += FREQ + (b * DOUBLE);
if (phacc[b] & 0x8000) {
phacc[b] &= 0x7FFF;
otone1[b] += 2;
pdacc[b] += PDmod;
}
if (!otone1[b]) pdacc[b] = 0;
otone2[b] = (pdacc[b] >> 3) & 255;
uint8_t env = (255-otone1[b]);
DCO_output[b%2] +=
//DCO_output[b/(DCO_BLOCKS_ACTIVE/2)] +=
(use_table256[otone2[b]] + use_table256[(otone2[b] + (127 - env)) & 255]);
}
//---------------------------------------------------------------------------
//------------------ VCA block ------------------------------------
/*
if ((ATTACK==255)&&(TRIG==1)) VCA=255;
if (!(envcnt--)) {
envcnt=20;
if (VCA<volume) VCA++;
if (VCA>volume) VCA--;
}
*/
/*
#define M(MX, MX1, MX2) \
asm volatile ( \
"clr r26 \n\t"\
"mulsu %B1, %A2 \n\t"\
"movw %A0, r0 \n\t"\
"mul %A1, %A2 \n\t"\
"add %A0, r1 \n\t"\
"adc %B0, r26 \n\t"\
"clr r1 \n\t"\
: \
"=&r" (MX) \
: \
"a" (MX1), \
"a" (MX2) \
:\
"r26"\
)
*/
//DCO>>=1;
//DCO>>=2;
//DCO_output>>=4;
////M(ENV, (int16_t)DCO, VCA);
//ENV = (int16_t)DCO * VCA;
//OCR2A = ENV>>1;
//OutSample = (int16_t)DCO * VCA;
//sample_i16 = (int16_t)DCO_output * VCA;
//sample_i16 = (int16_t)DCO_output;
//-----------------------------------------------------------------
if (!(envtick--)) {
envtick=582;
//--------------------- ENV block ---------------------------------
/*
if ((TRIG==1)&&(volume<255)) {
volume+=ATTACK;
if (volume>255) volume=255;
}
if ((TRIG==0)&&(volume>0)) {
volume-=RELEASE;
if (volume<0) volume=0;
}
*/
//-----------------------------------------------------------------
//--------- Resonant Peak ENV modulation ----------------------------------------
//if(!DCO_mode)
{
PDmod=((RESO*ENVamt)>>8)+PHASEamt;
if (PDmod>255) PDmod=255;
//if (PDmod>8192) PDmod=8192;
}
//-----------------------------------------------------------------
}
//-------------------------------------------------------------------------
// listen and analyse
//-------------------------------------------------------------------------
#ifdef USE_AUTOCORRELATION
if(dco_control_mode==2)
{
if(autocorrelation_rec_sample)
{
autocorrelation_buffer[--autocorrelation_rec_sample] = (int16_t)ADC_sample;
}
}
#endif
//-------------------------------------------------------------------------
// send sample to codec
//-------------------------------------------------------------------------
sample_i16 = (int16_t)DCO_output[0];
}
else
{
sample_i16 = 0;
}
#ifdef MIX_INPUT
#ifdef LPF_ENABLED
sample_lpf[0] = sample_lpf[0] + ADC_LPF_ALPHA * ((float)((int16_t)(ADC_sample>>16)) - sample_lpf[0]);
sample_i16 += (int16_t)(sample_lpf[0] * ADC_SAMPLE_GAIN); //low-pass
//sample_i16 += (int16_t)(ADC_sample>>16) - (int16_t)(sample_lpf[0] * ADC_SAMPLE_GAIN); //high-pass
#else
sample_i16 += ((int16_t)(ADC_sample>>16)) * ADC_SAMPLE_GAIN;
#endif
#endif
#ifdef MIX_ECHO
//add echo from the loop
sample_i16 += echo_buffer[echo_buffer_ptr];
#endif
#ifdef DYNAMIC_LIMITER
//apply dynamic limiter
echo_mix_f = (float)sample_i16 * limiter_coeff;
if(echo_mix_f < -DYNAMIC_LIMITER_THRESHOLD_ECHO_DCO && limiter_coeff > 0)
{
limiter_coeff *= DYNAMIC_LIMITER_COEFF_MUL_DCO;
}
sample_i16 = (int16_t)echo_mix_f;
#endif
#ifdef STATIC_LIMITER
while(sample_i16 > 16000 || sample_i16 < -16000)
{
sample_i16 /= 2;
}
#endif
sample32 = sample_i16 << 16;
if(waveform)
{
sample_i16 = (int16_t)DCO_output[1];
}
else
{
sample_i16 = 0;
}
#ifdef MIX_INPUT
#ifdef LPF_ENABLED
sample_lpf[1] = sample_lpf[1] + ADC_LPF_ALPHA * ((float)((int16_t)ADC_sample) - sample_lpf[1]);
sample_i16 += (int16_t)(sample_lpf[1] * ADC_SAMPLE_GAIN); //low-pass
//sample_i16 += (int16_t)ADC_sample - (int16_t)(sample_lpf[1] * ADC_SAMPLE_GAIN); //high-pass
#else
sample_i16 += ((int16_t)(ADC_sample)) * ADC_SAMPLE_GAIN;
#endif
#endif
#ifdef MIX_ECHO
//---------------------------------------------------------------------------------------
//wrap the echo loop
echo_buffer_ptr0++;
if(echo_buffer_ptr0 >= echo_dynamic_loop_length)
{
echo_buffer_ptr0 = 0;
}
echo_buffer_ptr = echo_buffer_ptr0 + 1;
if(echo_buffer_ptr >= echo_dynamic_loop_length)
{
echo_buffer_ptr = 0;
}
//add echo from the loop
sample_i16 += echo_buffer[echo_buffer_ptr];
#ifdef DYNAMIC_LIMITER
//apply dynamic limiter
echo_mix_f = (float)sample_i16 * limiter_coeff;
if(echo_mix_f < -DYNAMIC_LIMITER_THRESHOLD_ECHO_DCO && limiter_coeff > 0)
{
limiter_coeff *= DYNAMIC_LIMITER_COEFF_MUL_DCO;
}
sample_i16 = (int16_t)echo_mix_f;
#endif
#ifdef STATIC_LIMITER
while(sample_i16 > 16000 || sample_i16 < -16000)
{
sample_i16 /= 2;
}
#endif
#ifdef DYNAMIC_LIMITER
if(erase_echo==1 || (limiter_coeff < DYNAMIC_LIMITER_COEFF_DEFAULT))
{
ECHO_MIXING_GAIN_MUL = 1.0f;
}
else
{
ECHO_MIXING_GAIN_MUL = 3.0f;
}
#endif
if(erase_echo!=2)
{
//store result to echo, the amount defined by a fragment
echo_buffer[echo_buffer_ptr0] = (int16_t)((float)sample_i16 * ECHO_MIXING_GAIN_MUL / ECHO_MIXING_GAIN_DIV);
}
#endif
/*
if(erase_echo)
{
echo_buffer[echo_buffer_ptr0] /= 2;
}
*/
//---------------------------------------------------------------------------------------
sample32 += sample_i16;
#ifdef BOARD_WHALE
if(add_beep)
{
if(sampleCounter & (1<<add_beep))
{
sample32 += (100 + (100<<16));
}
}
#endif
for(i=0;i<dco_oversample;i++)
{
i2s_push_sample(I2S_NUM, (char *)&sample32, portMAX_DELAY);
sd_write_sample(&sample32);
}
#if defined(MIX_INPUT) || defined(USE_AUTOCORRELATION)
for(i=0;i<dco_oversample;i++)
{
/*ADC_result = */i2s_pop_sample(I2S_NUM, (char*)&ADC_sample, portMAX_DELAY);
}
#endif
//---------------------------------------------------------------------------------------
sampleCounter++;
if(TIMING_BY_SAMPLE_1_SEC)
{
sampleCounter = 0;
seconds++;
}
#ifdef BOARD_WHALE
if (TIMING_BY_SAMPLE_EVERY_100_MS==0)
{
RGB_LED_R_OFF;
RGB_LED_G_OFF;
RGB_LED_B_OFF;
}
if (TIMING_BY_SAMPLE_EVERY_100_MS==1000 && waveform)
{
RGB_LED_R_OFF;
RGB_LED_B_OFF;
if(param==0) { RGB_LED_R_ON; RGB_LED_G_ON; RGB_LED_B_ON; }
if(param==1) { RGB_LED_R_ON; RGB_LED_G_ON; }
if(param==2) { RGB_LED_R_ON; RGB_LED_B_ON; }
if(param==3) { RGB_LED_G_ON; }
if(param==4) { RGB_LED_R_ON; }
}
#endif
ui_command = 0;
if (TIMING_EVERY_20_MS==31) //50Hz
{
#define DCO_UI_CMD_NEXT_PARAM 1
#define DCO_UI_CMD_PREV_PARAM 2
#define DCO_UI_CMD_OVERSAMPLE_UP 3
#define DCO_UI_CMD_OVERSAMPLE_DOWN 4
#define DCO_UI_CMD_NEXT_WAVEFORM 5
#define DCO_UI_CMD_NEXT_DELAY 6
#define DCO_UI_CMD_RANDOMIZE_PARAMS 7
#define DCO_UI_CMD_DRIFT_PARAMS 8
//map UI commands
#ifdef BOARD_WHALE
if(short_press_volume_plus) { ui_command = DCO_UI_CMD_NEXT_PARAM; short_press_volume_plus = 0; }
if(short_press_volume_minus) { ui_command = DCO_UI_CMD_PREV_PARAM; short_press_volume_minus = 0; }
if(short_press_sequence==2) { ui_command = DCO_UI_CMD_OVERSAMPLE_UP; short_press_sequence = 0; }
if(short_press_sequence==-2) { ui_command = DCO_UI_CMD_OVERSAMPLE_DOWN; short_press_sequence = 0; }
if(short_press_sequence==3) { ui_command = DCO_UI_CMD_NEXT_WAVEFORM; short_press_sequence = 0; }
if(short_press_sequence==-3) { ui_command = DCO_UI_CMD_NEXT_DELAY; short_press_sequence = 0; }
if(short_press_sequence==SEQ_PLUS_MINUS) { ui_command = DCO_UI_CMD_RANDOMIZE_PARAMS; short_press_sequence = 0; }
if(short_press_sequence==SEQ_MINUS_PLUS) { ui_command = DCO_UI_CMD_DRIFT_PARAMS; short_press_sequence = 0; }
#endif
#ifdef BOARD_GECHO
if(btn_event_ext==BUTTON_EVENT_SHORT_PRESS+BUTTON_1) { ui_command = DCO_UI_CMD_DRIFT_PARAMS; btn_event_ext = 0; }
if(btn_event_ext==BUTTON_EVENT_SHORT_PRESS+BUTTON_2) { ui_command = DCO_UI_CMD_NEXT_WAVEFORM; btn_event_ext = 0; }
if(btn_event_ext==BUTTON_EVENT_RST_PLUS+BUTTON_2) { ui_command = DCO_UI_CMD_OVERSAMPLE_UP; btn_event_ext = 0; }
if(btn_event_ext==BUTTON_EVENT_RST_PLUS+BUTTON_1) { ui_command = DCO_UI_CMD_OVERSAMPLE_DOWN; btn_event_ext = 0; }
//if(event_channel_options) { ui_command = DCO_UI_CMD_RANDOMIZE_PARAMS; event_channel_options = 0; }
#endif
//FREQ = ADC_last_result[0] * 4;
//FREQ = (uint16_t)((acc_res[0] + 1.0f) * 440.0f * 16);
#ifdef BOARD_WHALE
if(event_channel_options)
{
event_channel_options = 0;
dco_control_mode++;
if(dco_control_mode==DCO_CONTROL_MODES)
{
dco_control_mode = 0;
}
printf("DCO Control mode = %d\n", dco_control_mode);
}
if(ui_command==DCO_UI_CMD_NEXT_PARAM)
{
if(dco_control_mode==1 || dco_control_mode==2)
{
param++;
if(param==DCO_MAX_PARAMS)
{
param = 0;
}
}
}
if(ui_command==DCO_UI_CMD_PREV_PARAM)
{
if(dco_control_mode==1 || dco_control_mode==2)
{
param--;
if(param==0)
{
param = DCO_MAX_PARAMS-1;
}
}
}
#endif
if(ui_command==DCO_UI_CMD_OVERSAMPLE_DOWN)
{
if(dco_oversample<8)
{
//dco_oversample*=2;
dco_oversample++;
}
printf("DCO Oversample = %d\n", dco_oversample);
}
if(ui_command==DCO_UI_CMD_OVERSAMPLE_UP)
{
if(dco_oversample>1)
{
//dco_oversample/=2;
dco_oversample--;
printf("DCO Oversample = %d\n", dco_oversample);
}
}
if(ui_command==DCO_UI_CMD_NEXT_WAVEFORM)
{
waveform++;
if(waveform==1)
{
use_table256 = (uint8_t*)sinetable256;
}
else if(waveform==2)
{
use_table256 = squaretable256;
}
else if(waveform==3)
{
use_table256 = sawtable256;
}
else
{
waveform = 0;
}
printf("waveform set to type #%d\n",waveform);
}
#ifdef BOARD_WHALE
if(ui_command==DCO_UI_CMD_NEXT_DELAY)
{
if(echo_dynamic_loop_current_step!=ECHO_DYNAMIC_LOOP_LENGTH_ECHO_OFF)
{
echo_dynamic_loop_current_step = ECHO_DYNAMIC_LOOP_LENGTH_ECHO_OFF;
}
else
{
echo_dynamic_loop_current_step = ECHO_DYNAMIC_LOOP_LENGTH_DEFAULT_STEP;
}
echo_dynamic_loop_length = echo_dynamic_loop_steps[echo_dynamic_loop_current_step];
printf("echo set to step #%d, length = %d\n",echo_dynamic_loop_current_step,echo_dynamic_loop_length);
}
#endif
if(ui_command==DCO_UI_CMD_RANDOMIZE_PARAMS)
{
//randomize all params
if(!midi_override)
{
new_random_value();
FREQ = random_value;
}
new_random_value();
DOUBLE = random_value;
PHASEamt = random_value<<8;
new_random_value();
ENVamt = random_value;
new_random_value();
RESO = random_value;
}
if(ui_command==DCO_UI_CMD_DRIFT_PARAMS)
{
drift_params++;
if(drift_params==DRIFT_PARAMS_MAX+1)
{
drift_params = 0;
}
drift_params_cnt = 0;
printf("drift_params = %d\n", drift_params);
}
if(!drift_params)
{
if(use_acc_or_ir_sensors==PARAMETER_CONTROL_SENSORS_ACCELEROMETER)
{
if(dco_control_mode==0)
{
if(!shift_param && (acc_res[0] > 0.3f))
{
printf("shift_param = 1, param++\n");
shift_param = 1;
param++;
if(param==DCO_MAX_PARAMS)
{
param = 0;
}
sampleCounter = 0;
}
else if(!shift_param && (acc_res[0] < -0.3f))
{
printf("shift_param = 1, param--\n");
shift_param = 1;
param--;
if(param<0)
{
param = DCO_MAX_PARAMS - 1;
}
sampleCounter = 0;
}
else if(shift_param && (fabs(acc_res[0]) < 0.2f))
{
shift_param = 0;
printf("shift_param = 0\n");
}
}
//printf("acc_res[0-2]==%f,\t%f,\t%f...\t", acc_res[0],acc_res[1],acc_res[2]);
if(param==0) //FREQ
{
FREQ = (uint16_t)(acc_res[1] * DCO_FREQ_DEFAULT * 2);
//printf("FREQ=%d\n",FREQ);
}
if(param==1) //DOUBLE
{
DOUBLE = (uint8_t)(acc_res[1] * 256);
//printf("DOUBLE=%d\n",DOUBLE);
}
if(param==2) //PHASEamt
{
PHASEamt = (uint8_t)(acc_res[1] * 256);
//printf("PHASEamt=%d\n",PHASEamt);
}
if(param==3) //ENVamt
{
ENVamt = (uint8_t)(acc_res[1] * 32);
//printf("ENVamt=%d\n",ENVamt);
}
if(param==4) //RESO
{
RESO = (uint16_t)(acc_res[1] * 4096);
//printf("RESO=%d\n",RESO);
}
/*
if(param==5) //DCO_BLOCKS_ACTIVE
{
DCO_BLOCKS_ACTIVE = (uint8_t)(((acc_res[1] + 1.0f) * (DCO_BLOCKS_MAX-1))/2);
printf("DCO_BLOCKS_ACTIVE=%d\n",DCO_BLOCKS_ACTIVE);
}
*/
/*
if(!erase_echo && acc_res[2] > 0.7f)
{
erase_echo = 2;
}
else
{
erase_echo = 0;
}
*/
if(acc_res[2] > 0.7f)
{
//ECHO_MIXING_GAIN_MUL = 1.0f;
//if(erase_echo!=1) printf("setting erase_echo => 1\n");
erase_echo = 1;
}
else if(acc_res[0] < -0.7f)
{
//ECHO_MIXING_GAIN_MUL = 1.0f;
//if(erase_echo!=2) printf("setting erase_echo => 2\n");
erase_echo = 2;
}
else
{
//ECHO_MIXING_GAIN_MUL = 3.0f;
//if(erase_echo!=0) printf("setting erase_echo => 0\n");
erase_echo = 0;
}
}
else //if sensors used
{
if(!midi_override)
{
FREQ = (uint16_t)(ir_res[0] * DCO_FREQ_DEFAULT * 2);
//printf("FREQ=%d\n",FREQ);
}
DOUBLE = (uint8_t)(ir_res[1] * 256);
//printf("DOUBLE=%d\n",DOUBLE);
PHASEamt = (uint8_t)(ir_res[2] * 256);
//printf("PHASEamt=%d\n",PHASEamt);
ENVamt = (uint8_t)(ir_res[3] * 32);
//printf("ENVamt=%d\n",ENVamt);
RESO = (uint16_t)(ir_res[3] * 4096);
}
}
#ifdef USE_AUTOCORRELATION
if(autocorrelation_result_rdy && dco_control_mode==2)
{
//printf("ac res = %d,%d,%d,%d\n", autocorrelation_result[0], autocorrelation_result[1], autocorrelation_result[2], autocorrelation_result[3]);
autocorrelation_result_rdy = 0;
//FREQ = (256-autocorrelation_result[0])<<8;//(uint16_t)((acc_res[0] + 1.0f) * 440.0f * 16);
//FREQ = (autocorrelation_result[0])<<8;//(uint16_t)((acc_res[0] + 1.0f) * 440.0f * 16);
//int x = ac_to_freq(autocorrelation_result[0]);
int x = (uint16_t)((acc_res[0] + 1.0f) * DCO_FREQ_DEFAULT/2 );
if(x>100)
{
FREQ = x;
printf("%d => %d\n", autocorrelation_result[0], FREQ);
}
}
//DOUBLE = ADC_last_result[1] / 8;
//DOUBLE = ADC_last_result[1] / 12;
//DOUBLE = 220;//(uint8_t)((acc_res[1] + 1.0f) * 120); //6; //default 12?
//PHASEamt = ADC_last_result[2] / 8;
//PHASEamt = ADC_last_result[2] / 16;
//PHASEamt = 110;//(uint8_t)((acc_res[2] + 1.0f) * 120); //4; //default 9?
//ENVamt = ADC_last_result[3] * 16; /// 4;
//ENVamt = 123;//(acc_res[2] + 1.0f) * 128;//64; //default 123
#endif
#ifdef DIRECT_PARAM_CONTROL
//direct controlls by buttons
if(event_channel_options)
{
event_channel_options = 0;
param++;
if(param==1)
{
printf("updating DOUBLE\n");
}
if(param==2)
{
printf("updating PHASEamt\n");
}
if(param==3)
{
printf("updating ENVamt\n");
}
if(param==DCO_MAX_PARAMS)
{
param = 0;
printf("updating FREQ\n");
}
printf("FREQ=%d,DOUBLE=%d,PHASEamt=%d,ENVamt=%d\n",FREQ,DOUBLE,PHASEamt,ENVamt);
}
if(short_press_sequence)
{
if(param==0) //FREQ (16-bit)
{
if(short_press_volume_minus) {FREQ--; short_press_volume_minus = 0; }
if(short_press_volume_plus) {FREQ++; short_press_volume_plus = 0; }
if(abs(short_press_sequence)==2) FREQ += short_press_sequence*10/2;
if(abs(short_press_sequence)==3) FREQ += short_press_sequence*100/3;
if(abs(short_press_sequence)==4) FREQ += short_press_sequence*1000/4;
printf("FREQ updated to %d\n", FREQ);
}
if(param==1) //DOUBLE (8-bit)
{
if(short_press_volume_minus) {DOUBLE--; short_press_volume_minus = 0; }
if(short_press_volume_plus) {DOUBLE++; short_press_volume_plus = 0; }
if(abs(short_press_sequence)==2) DOUBLE += short_press_sequence*10/2;
if(abs(short_press_sequence)==3) DOUBLE += short_press_sequence*100/3;
printf("DOUBLE updated to %d\n", DOUBLE);
}
if(param==2) //PHASE (8-bit)
{
if(short_press_volume_minus) {PHASEamt--; short_press_volume_minus = 0; }
if(short_press_volume_plus) {PHASEamt++; short_press_volume_plus = 0; }
if(abs(short_press_sequence)==2) PHASEamt += short_press_sequence*10/2;
if(abs(short_press_sequence)==3) PHASEamt += short_press_sequence*100/3;
printf("PHASEamt updated to %d\n", PHASEamt);
}
if(param==3) //ENVamt (8-bit)
{
if(short_press_volume_minus) {ENVamt--; short_press_volume_minus = 0; }
if(short_press_volume_plus) {ENVamt++; short_press_volume_plus = 0; }
if(abs(short_press_sequence)==2) ENVamt += short_press_sequence*10/2;
if(abs(short_press_sequence)==3) ENVamt += short_press_sequence*100/3;
printf("ENVamt updated to %d\n", ENVamt);
}
short_press_sequence = 0;
}
#endif
#ifdef DEBUG_DCO
printf("FREQ=%d,DOUBLE=%d,PHASEamt=%d,ENVamt=%d\n",FREQ,DOUBLE,PHASEamt,ENVamt);
#endif
}
if (TIMING_EVERY_20_MS == 47) //50Hz
{
if(!midi_override && MIDI_keys_pressed)
{
printf("MIDI active, will receive chords\n");
midi_override = 1;
}
if(midi_override && MIDI_notes_updated)
{
MIDI_notes_updated = 0;
LED_W8_all_OFF();
LED_B5_all_OFF();
MIDI_to_LED(MIDI_last_chord[0], 1);
FREQ = MIDI_note_to_freq(MIDI_last_chord[0]+36); //shift a couple octaves up as the FREQ parameter here works differently
}
}
//if (TIMING_EVERY_250_MS == 39) //4Hz
if (TIMING_EVERY_125_MS == 39) //8Hz
{
if(drift_params==4
|| (drift_params==3 && drift_params_cnt%2==0)
|| (drift_params==2 && drift_params_cnt%4==0)
|| (drift_params==1 && drift_params_cnt%8==0))
{
//adjust all params by small random value
new_random_value();
if(!midi_override)
{
FREQ += ((int8_t)random_value)/8;
}
DOUBLE += ((int8_t)(random_value>>8))/8;
PHASEamt += ((int8_t)(random_value>>16))/8;
ENVamt += ((int8_t)(random_value>>24))/8;
new_random_value();
RESO += ((int16_t)random_value/128);
}
else if(drift_params==8
|| (drift_params==7 && drift_params_cnt%2==0)
|| (drift_params==6 && drift_params_cnt%4==0)
|| (drift_params==5 && drift_params_cnt%8==0))
{
//randomize all params
if(!midi_override)
{
new_random_value();
FREQ = random_value;
}
new_random_value();
DOUBLE = random_value;
PHASEamt = random_value<<8;
new_random_value();
ENVamt = random_value;
new_random_value();
RESO = random_value;
}
#if 0
else if(drift_params==9 || (drift_params==8 && drift_params_cnt%2==0) || (drift_params==7 && drift_params_cnt%4==0))
{
//randomize all params
new_random_value();
FREQ = random_value;
new_random_value();
DOUBLE = random_value;
PHASEamt = random_value<<8;
new_random_value();
ENVamt = random_value;
new_random_value();
RESO = random_value;
}
else if(drift_params==12 || (drift_params==11 && drift_params_cnt%2==0) || (drift_params==10 && drift_params_cnt%4==0))
{
//randomize all params
new_random_value();
FREQ = random_value;
new_random_value();
DOUBLE = random_value;
PHASEamt = random_value<<8;
new_random_value();
ENVamt = random_value;
new_random_value();
RESO = random_value;
}
else if(drift_params==15 || (drift_params==14 && drift_params_cnt%2==0) || (drift_params==13 && drift_params_cnt%4==0))
{
//randomize all params
new_random_value();
FREQ = random_value;
new_random_value();
DOUBLE = random_value;
PHASEamt = random_value<<8;
new_random_value();
ENVamt = random_value;
new_random_value();
RESO = random_value;
}
else if(drift_params==18 || (drift_params==17 && drift_params_cnt%2==0) || (drift_params==16 && drift_params_cnt%4==0))
{
//randomize all params
new_random_value();
FREQ = random_value;
new_random_value();
DOUBLE = random_value;
PHASEamt = random_value<<8;
new_random_value();
ENVamt = random_value;
new_random_value();
RESO = random_value;
}
/*else if(drift_params==21 || (drift_params==20 && drift_params_cnt%2==0) || (drift_params==19 && drift_params_cnt%4==0))
{
//randomize all params
new_random_value();
FREQ = random_value;
new_random_value();
DOUBLE = random_value;
PHASEamt = random_value<<8;
new_random_value();
ENVamt = random_value;
new_random_value();
RESO = random_value;
}*/
#endif
drift_params_cnt++;
}
if (TIMING_EVERY_20_MS == 33) //50Hz
{
if(limiter_coeff < DYNAMIC_LIMITER_COEFF_DEFAULT)
{
//limiter_coeff += DYNAMIC_LIMITER_COEFF_DEFAULT / 20; //timing @20Hz, limiter will fully recover within 1 second
limiter_coeff += DYNAMIC_LIMITER_COEFF_DEFAULT / 20; //timing @ 50Hz, limiter will fully recover within 0.4 second
printf("limiter_coeff=%f\n",limiter_coeff);
}
}
}
}
#if 0
void DCO_Synth::v2_init()
{
init_codec();
//-----------------------------------------------------------------------------------
// Gecho variables and peripherals init
//-----------------------------------------------------------------------------------
GPIO_LEDs_Buttons_Reset();
//ADC_DeInit(); //reset ADC module
ADC_configure_SENSORS(ADCConvertedValues);
//ADC_configure_CV_GATE(CV_GATE_PC0_PB0); //PC0 stays the same as if configured for IRS1
//int calibration_success = Calibrate_CV(); //if successful, array with results is stored in *calibrated_cv_values
//-----------------------------------------------------------------------------------
// Tiny-TS variables init
//-----------------------------------------------------------------------------------
sample_i16 = 128;
FREQ=440;//MIDI2FREQ(key+12+(COARSEPITCH/21.3125));
DOUBLE=12;
PHASEamt=9;
ENVamt=123;
ATTACK=64;//ATTrates[12];
RELEASE=64;//RELrates[6];
DCO_BLOCKS_ACTIVE = 24;
RESO = 64;
//if(mode==1)
//{
//load the default sequence
//char *seq = "a3a2a3a2c3a2d3c3a2a2a3a2g3c3f#3e3";
//parse_notes(seq, sequence, NULL);
//SEQUENCER_THRESHOLD = 200;
//}
//echo loop
init_echo_buffer();
ECHO_MIXING_GAIN_MUL = 1; //amount of signal to feed back to echo loop, expressed as a fragment
ECHO_MIXING_GAIN_DIV = 4; //e.g. if MUL=2 and DIV=3, it means 2/3 of signal is mixed in
for(int i=0;i<128;i++)
{
MIDI_notes_to_freq[i] = NOTE_FREQ_A4 * pow(HALFTONE_STEP_COEF, i - 33);
}
}
void DCO_Synth::v2_play_loop()
{
while(1)
{
//-------------------- DCO block ------------------------------------------
DCO_output[0] = 0;
DCO_output[1] = 0;
for (int b=0; b<DCO_BLOCKS_ACTIVE; b++)
{
phacc[b] += FREQ + (b * DOUBLE);
if (phacc[b] & 0x8000) {
phacc[b] &= 0x7FFF;
otone1[b] += 2;
pdacc[b] += PDmod;
}
if (!otone1[b]) pdacc[b] = 0;
otone2[b] = (pdacc[b] >> 3) & 255;
uint8_t env = (255-otone1[b]);
DCO_output[b%2] += (use_table256[otone2[b]] + use_table256[(otone2[b] + (127 - env)) & 255]);
}
if (!(envtick--)) {
envtick=582;
//--------- Resonant Peak ENV modulation ----------------------------------------
//if(!DCO_mode)
{
PDmod=((RESO*ENVamt)>>8)+PHASEamt;
if (PDmod>255) PDmod=255;
}
}
//-------------------------------------------------------------------------
// send sample to codec
//-------------------------------------------------------------------------
sample_i16 = (int16_t)DCO_output[0];
sample_i16 += echo_buffer[echo_buffer_ptr];
while (!SPI_I2S_GetFlagStatus(CODEC_I2S, SPI_I2S_FLAG_TXE));
SPI_I2S_SendData(CODEC_I2S, sample_i16);
sample_i16 = (int16_t)DCO_output[1];
//wrap in the echo loop
echo_buffer_ptr0++;
if(echo_buffer_ptr0 >= echo_dynamic_loop_length)
{
echo_buffer_ptr0 = 0;
}
echo_buffer_ptr = echo_buffer_ptr0 + 1;
if(echo_buffer_ptr >= echo_dynamic_loop_length)
{
echo_buffer_ptr = 0;
}
//add echo from the loop
sample_i16 += echo_buffer[echo_buffer_ptr];
//store result to echo, the amount defined by a fragment
echo_buffer[echo_buffer_ptr0] = sample_i16 * ECHO_MIXING_GAIN_MUL / ECHO_MIXING_GAIN_DIV;
while (!SPI_I2S_GetFlagStatus(CODEC_I2S, SPI_I2S_FLAG_TXE));
SPI_I2S_SendData(CODEC_I2S, sample_i16);
sampleCounter++;
if (TIMING_BY_SAMPLE_ONE_SECOND_W_CORRECTION)
{
sampleCounter = 0;
seconds++;
}
if (TIMING_BY_SAMPLE_EVERY_10_MS==0) //100Hz
{
if(ADC_process_sensors()==1)
{
ADC_last_result[2] = -ADC_last_result[2];
ADC_last_result[3] = -ADC_last_result[3];
CLEAR_ADC_RESULT_RDY_FLAG;
sensors_loop++;
IR_sensors_LED_indicators(ADC_last_result);
if(SET_mode==0)
{
FREQ = ADC_last_result[0] * 4;
//DOUBLE = ADC_last_result[1] / 8;
DOUBLE = ADC_last_result[1] / 12;
//PHASEamt = ADC_last_result[2] / 8;
PHASEamt = ADC_last_result[2] / 16;
//if(!DCO_mode)
ENVamt = ADC_last_result[3] * 16; /// 4;
//}
//else
//{
// if(ADC_last_result[3] > 200)
// {
// //PDmod = ADC_last_result[3] / 2; /// 4;
// ENVamt = ADC_last_result[3] * 32; /// 4;
// }
// else
// {
// PDmod = 255;
// }
//}
}
else
{
if(BUTTON_U1_ON)
{
FREQ = ADC_last_result[0] * 8;
}
if(BUTTON_U2_ON)
{
DOUBLE = ADC_last_result[1] / 12;
}
if(BUTTON_U3_ON)
{
PHASEamt = ADC_last_result[2] / 16;
}
if(BUTTON_U4_ON)
{
ENVamt = ADC_last_result[3] * 16;
}
}
}
if(BUTTON_SET_ON)
{
if(!button_set_held)
{
if(!SET_mode)
{
LED_SIG_ON;
SET_mode = 1;
button_set_held = 1;
}
else
{
LED_SIG_OFF;
SET_mode = 0;
button_set_held = 1;
}
}
}
else
{
button_set_held = 0;
}
}
}
}
#endif
#if 0
//---------------------------------------------------------------------------------
// version with sequencer
//---------------------------------------------------------------------------------
void DCO_Synth::v3_play_loop()
{
#define SEQ_MAX_NOTES 32 //maximum length = 32 notes
#define SEQ_NOTE_DIVISION 8 //steps per note
float sequence_notes[SEQ_MAX_NOTES * SEQ_NOTE_DIVISION];
int seq_ptr = 0, seq_length;
const char *sequence = "a3a3a3a3 c4a3d4c4 a3a3a3a3 d4c4e4d4 a4g4e4a4 g4e4a4g4 f#4d4a3f#4 d4a3c4b3";
//MusicBox *chord = new MusicBox();
seq_length = MusicBox::get_song_total_melody_notes((char*)sequence);
parse_notes((char*)sequence, sequence_notes, NULL);
#define SEQ_SPREAD 1
spread_notes(sequence_notes, seq_length, SEQ_SPREAD); //spread the sequence 8 times
seq_length *= SEQ_SPREAD;
//FREQ = MIDI_notes_to_freq[data];
DOUBLE=8;
PHASEamt=217;
ENVamt=144;
SET_mode = 1;
DCO_BLOCKS_ACTIVE = 2;//16;
#define FREQ_MULTIPLIER 12
//use_table256 = (uint8_t*)sawtable256;
use_table256 = (uint8_t*)squaretable256;
while(1)
{
//-------------------- DCO block ------------------------------------------
DCO_output[0] = 0;
DCO_output[1] = 0;
for (int b=0; b<DCO_BLOCKS_ACTIVE; b++)
{
phacc[b] += FREQ + (b * DOUBLE);
if (phacc[b] & 0x8000) {
phacc[b] &= 0x7FFF;
otone1[b] += 2;
pdacc[b] += PDmod;
}
if (!otone1[b]) pdacc[b] = 0;
otone2[b] = (pdacc[b] >> 3) & 255;
uint8_t env = (255-otone1[b]);
DCO_output[b%2] += (use_table256[otone2[b]] + use_table256[(otone2[b] + (127 - env)) & 255]);
}
if (!(envtick--)) {
envtick=582;
//--------- Resonant Peak ENV modulation ----------------------------------------
//if(!DCO_mode)
{
PDmod=((RESO*ENVamt)>>8)+PHASEamt;
if (PDmod>255) PDmod=255;
}
}
//-------------------------------------------------------------------------
// send sample to codec
//-------------------------------------------------------------------------
sample_i16 = (int16_t)DCO_output[0];
sample_i16 += echo_buffer[echo_buffer_ptr];
while (!SPI_I2S_GetFlagStatus(CODEC_I2S, SPI_I2S_FLAG_TXE));
SPI_I2S_SendData(CODEC_I2S, sample_i16);
sample_i16 = (int16_t)DCO_output[1];
//wrap in the echo loop
echo_buffer_ptr0++;
if(echo_buffer_ptr0 >= echo_dynamic_loop_length)
{
echo_buffer_ptr0 = 0;
}
echo_buffer_ptr = echo_buffer_ptr0 + 1;
if(echo_buffer_ptr >= echo_dynamic_loop_length)
{
echo_buffer_ptr = 0;
}
//add echo from the loop
sample_i16 += echo_buffer[echo_buffer_ptr];
//store result to echo, the amount defined by a fragment
echo_buffer[echo_buffer_ptr0] = sample_i16 * ECHO_MIXING_GAIN_MUL / ECHO_MIXING_GAIN_DIV;
while (!SPI_I2S_GetFlagStatus(CODEC_I2S, SPI_I2S_FLAG_TXE));
SPI_I2S_SendData(CODEC_I2S, sample_i16);
sampleCounter++;
if (TIMING_BY_SAMPLE_ONE_SECOND_W_CORRECTION)
{
sampleCounter = 0;
seconds++;
}
if (TIMING_BY_SAMPLE_EVERY_10_MS==0) //100Hz
{
if(ADC_process_sensors()==1)
{
ADC_last_result[2] = -ADC_last_result[2];
ADC_last_result[3] = -ADC_last_result[3];
CLEAR_ADC_RESULT_RDY_FLAG;
sensors_loop++;
IR_sensors_LED_indicators(ADC_last_result);
if(SET_mode==0)
{
FREQ = ADC_last_result[0] * 4;
//DOUBLE = ADC_last_result[1] / 8;
DOUBLE = ADC_last_result[1] / 12;
//PHASEamt = ADC_last_result[2] / 8;
PHASEamt = ADC_last_result[2] / 16;
//if(!DCO_mode)
ENVamt = ADC_last_result[3] * 16; /// 4;
//}
//else
//{
// if(ADC_last_result[3] > 200)
// {
// //PDmod = ADC_last_result[3] / 2; /// 4;
// ENVamt = ADC_last_result[3] * 32; /// 4;
// }
// else
// {
// PDmod = 255;
// }
//}
}
else
{
if(BUTTON_U1_ON)
{
FREQ = ADC_last_result[0] * 8;
}
if(BUTTON_U2_ON)
{
DOUBLE = ADC_last_result[1] / 12;
}
if(BUTTON_U3_ON)
{
PHASEamt = ADC_last_result[2] / 16;
}
if(BUTTON_U4_ON)
{
ENVamt = ADC_last_result[3] * 16;
}
}
}
if(BUTTON_SET_ON)
{
if(!button_set_held)
{
if(!SET_mode)
{
LED_SIG_ON;
SET_mode = 1;
button_set_held = 1;
}
else
{
LED_SIG_OFF;
SET_mode = 0;
button_set_held = 1;
}
}
}
else
{
button_set_held = 0;
}
}
//if (TIMING_BY_SAMPLE_EVERY_250_MS==0) //4Hz
if (TIMING_BY_SAMPLE_EVERY_125_MS==0) //8Hz
{
//if(ADC_last_result[0] < SEQUENCER_THRESHOLD)
//{
if(sequence_notes[seq_ptr] > 0)
{
FREQ = sequence_notes[seq_ptr] * FREQ_MULTIPLIER;
}
if (++seq_ptr == seq_length)
{
seq_ptr = 0;
}
//}
}
}
}
void DCO_Synth::v4_play_loop()
//SIGNAL(PWM_INTERRUPT)
{
uint8_t value;
uint16_t output;
// incorporating DuaneB's volatile fix
uint16_t syncPhaseAcc;
volatile uint16_t syncPhaseInc;
uint16_t grainPhaseAcc;
volatile uint16_t grainPhaseInc;
uint16_t grainAmp;
volatile uint8_t grainDecay;
uint16_t grain2PhaseAcc;
volatile uint16_t grain2PhaseInc;
uint16_t grain2Amp;
volatile uint8_t grain2Decay;
int led_status = 0;
while(1)
{
syncPhaseAcc += syncPhaseInc;
if (syncPhaseAcc < syncPhaseInc) {
// Time to start the next grain
grainPhaseAcc = 0;
grainAmp = 0x7fff;
grain2PhaseAcc = 0;
grain2Amp = 0x7fff;
//LED_PORT ^= 1 << LED_BIT; // Faster than using digitalWrite
led_status?LED_SIG_ON:LED_SIG_OFF;
led_status=led_status?0:1;
}
// Increment the phase of the grain oscillators
grainPhaseAcc += grainPhaseInc;
grain2PhaseAcc += grain2PhaseInc;
// Convert phase into a triangle wave
value = (grainPhaseAcc >> 7) & 0xff;
if (grainPhaseAcc & 0x8000) value = ~value;
// Multiply by current grain amplitude to get sample
output = value * (grainAmp >> 8);
// Repeat for second grain
value = (grain2PhaseAcc >> 7) & 0xff;
if (grain2PhaseAcc & 0x8000) value = ~value;
output += value * (grain2Amp >> 8);
// Make the grain amplitudes decay by a factor every sample (exponential decay)
grainAmp -= (grainAmp >> 8) * grainDecay;
grain2Amp -= (grain2Amp >> 8) * grain2Decay;
// Scale output to the available range, clipping if necessary
output >>= 9;
if (output > 255) output = 255;
// Output to PWM (this is faster than using analogWrite)
//PWM_VALUE = output;
//-------------------------------------------------------------------------
// send sample to codec
//-------------------------------------------------------------------------
sample_i16 = (int16_t)output;//[0];
sample_i16 += echo_buffer[echo_buffer_ptr];
while (!SPI_I2S_GetFlagStatus(CODEC_I2S, SPI_I2S_FLAG_TXE));
SPI_I2S_SendData(CODEC_I2S, sample_i16);
sample_i16 = (int16_t)output;//[1];
//wrap in the echo loop
echo_buffer_ptr0++;
if(echo_buffer_ptr0 >= echo_dynamic_loop_length)
{
echo_buffer_ptr0 = 0;
}
echo_buffer_ptr = echo_buffer_ptr0 + 1;
if(echo_buffer_ptr >= echo_dynamic_loop_length)
{
echo_buffer_ptr = 0;
}
//add echo from the loop
sample_i16 += echo_buffer[echo_buffer_ptr];
//store result to echo, the amount defined by a fragment
echo_buffer[echo_buffer_ptr0] = sample_i16 * ECHO_MIXING_GAIN_MUL / ECHO_MIXING_GAIN_DIV;
while (!SPI_I2S_GetFlagStatus(CODEC_I2S, SPI_I2S_FLAG_TXE));
SPI_I2S_SendData(CODEC_I2S, sample_i16);
sampleCounter++;
if (TIMING_BY_SAMPLE_ONE_SECOND_W_CORRECTION)
{
sampleCounter = 0;
seconds++;
}
}
}
#endif
| 26.097641 | 197 | 0.590358 | shroomist |
f82d36f3a41917690f648621c7fbd59844900288 | 3,301 | cpp | C++ | tc 160+/InstantRunoff.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | 3 | 2015-05-25T06:24:37.000Z | 2016-09-10T07:58:00.000Z | tc 160+/InstantRunoff.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | null | null | null | tc 160+/InstantRunoff.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | 5 | 2015-05-25T06:24:40.000Z | 2021-08-19T19:22:29.000Z | #include <algorithm>
#include <cassert>
#include <cstdio>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <climits>
using namespace std;
class InstantRunoff {
public:
string outcome(string candidates, vector <string> ballots) {
while (candidates.size() > 0) {
vector<int> win(26, 0);
int best = -1;
char who = 0;
for (int i=0; i<(int)ballots.size(); ++i) {
++win[ballots[i][0] - 'A'];
if (best < win[ballots[i][0]-'A']) {
who = ballots[i][0];
best = win[ballots[i][0]-'A'];
}
}
if (best*2 > (int)ballots.size())
return string(1, who);
int worst = INT_MAX;
for (int i=0; i<26; ++i)
if (candidates.find(char('A'+i)) != string::npos)
worst = min(worst, win[i]);
for (int i=0; i<26; ++i)
if (candidates.find(char('A'+i)) != string::npos && win[i]==worst) {
for (int j=0; j<(int)ballots.size(); ++j)
ballots[j].erase(ballots[j].find(char('A'+i)), 1);
candidates.erase(candidates.find(char('A'+i)), 1);
}
}
return string();
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const string &Expected, const string &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { string Arg0 = "ABC"; string Arr1[] = {"ACB", "BCA", "ACB", "BCA", "CBA"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arg2 = "B"; verify_case(0, Arg2, outcome(Arg0, Arg1)); }
void test_case_1() { string Arg0 = "DCBA"; string Arr1[] = {"ACBD", "ACBD", "ACBD", "BCAD", "BCAD", "DBCA", "CBDA"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arg2 = "B"; verify_case(1, Arg2, outcome(Arg0, Arg1)); }
void test_case_2() { string Arg0 = "ACB"; string Arr1[] = {"ACB", "BCA", "ACB", "BCA", "ACB", "BCA", "CBA", "CAB"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arg2 = ""; verify_case(2, Arg2, outcome(Arg0, Arg1)); }
void test_case_3() { string Arg0 = "CAB"; string Arr1[] = {"ACB", "BCA", "ACB", "BCA", "ACB", "BCA", "CAB", "CAB"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arg2 = "A"; verify_case(3, Arg2, outcome(Arg0, Arg1)); }
void test_case_4() { string Arg0 = "Z"; string Arr1[] = {"Z"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arg2 = "Z"; verify_case(4, Arg2, outcome(Arg0, Arg1)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
InstantRunoff ___test;
___test.run_test(-1);
}
// END CUT HERE
| 45.219178 | 315 | 0.566192 | ibudiselic |
f82d52b36f61ff0da4e1bb804899e48f572ec1c3 | 1,199 | hpp | C++ | win32.cpp/include/win32/high_resolution_clock.hpp | fallfromgrace/win32.cpp | cab9fbc2e595fb2c9114d0251b04d895185c5fcb | [
"MIT"
] | null | null | null | win32.cpp/include/win32/high_resolution_clock.hpp | fallfromgrace/win32.cpp | cab9fbc2e595fb2c9114d0251b04d895185c5fcb | [
"MIT"
] | null | null | null | win32.cpp/include/win32/high_resolution_clock.hpp | fallfromgrace/win32.cpp | cab9fbc2e595fb2c9114d0251b04d895185c5fcb | [
"MIT"
] | null | null | null | #pragma once
#include <chrono>
#include <Windows.h>
#include "more\includes.hpp"
#include "win32\error.hpp"
namespace win32
{
//
class high_resolution_clock
{
public:
typedef uint64_t rep;
typedef std::nano period;
typedef std::chrono::duration<rep, period> duration;
typedef std::chrono::time_point<high_resolution_clock> time_point;
static const bool_t is_steady = true;
//
static inline time_point now()
{
LARGE_INTEGER count;
if (::QueryPerformanceCounter(&count) == FALSE)
throw win32::get_last_error();
return time_point(duration(
count.QuadPart * static_cast<rep>(period::den) / high_resolution_clock::frequency()));
}
// Gets the frequency of the high_resolution_clock
static inline uint64_t frequency()
{
static uint64_t cached_frequency = 0;
if (cached_frequency == 0)
cached_frequency = query_frequency();
return cached_frequency;
}
// Queries the frequency of the high_resolution_clock
static inline uint64_t query_frequency()
{
LARGE_INTEGER frequency;
if (::QueryPerformanceFrequency(&frequency) == FALSE)
throw win32::get_last_error();
return static_cast<uint64_t>(frequency.QuadPart);
}
};
} | 23.509804 | 90 | 0.723103 | fallfromgrace |
f830dc93f661a5eb56e9fa87881de4f1a8e34c97 | 16,015 | cpp | C++ | blast/src/objtools/alnmgr/alnvecprint.cpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | 31 | 2016-12-09T04:56:59.000Z | 2021-12-31T17:19:10.000Z | blast/src/objtools/alnmgr/alnvecprint.cpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | 6 | 2017-03-10T17:25:13.000Z | 2021-09-22T15:49:49.000Z | blast/src/objtools/alnmgr/alnvecprint.cpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | 20 | 2015-01-04T02:15:17.000Z | 2021-12-03T02:31:43.000Z | /* $Id: alnvecprint.cpp 339805 2011-10-03 17:28:28Z grichenk $
* ===========================================================================
*
* 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.
*
* ===========================================================================
*
* Author: Kamen Todorov, NCBI
*
* File Description:
* CAlnVec printer.
*
* ===========================================================================
*/
#include <ncbi_pch.hpp>
#include <objtools/alnmgr/alnvec.hpp>
USING_SCOPE(ncbi);
USING_SCOPE(objects);
CAlnVecPrinter::CAlnVecPrinter(const CAlnVec& aln_vec,
CNcbiOstream& out)
: CAlnMapPrinter(aln_vec, out),
m_AlnVec(aln_vec)
{
}
void
CAlnVecPrinter::x_SetChars()
{
CAlnVec& aln_vec = const_cast<CAlnVec&>(m_AlnVec);
m_OrigSetGapChar = aln_vec.IsSetGapChar();
if (m_OrigSetGapChar) {
m_OrigGapChar = aln_vec.GetGapChar(0);
}
aln_vec.SetGapChar('-');
m_OrigSetEndChar = aln_vec.IsSetEndChar();
if (m_OrigSetEndChar) {
m_OrigEndChar = aln_vec.GetEndChar();
}
aln_vec.SetEndChar('-');
}
void
CAlnVecPrinter::x_UnsetChars()
{
CAlnVec& aln_vec = const_cast<CAlnVec&>(m_AlnVec);
if (m_OrigSetGapChar) {
aln_vec.SetGapChar(m_OrigGapChar);
} else {
aln_vec.UnsetGapChar();
}
if (m_OrigSetEndChar) {
aln_vec.SetEndChar(m_OrigEndChar);
} else {
aln_vec.UnsetEndChar();
}
}
void CAlnVecPrinter::PopsetStyle(int scrn_width,
EAlgorithm algorithm)
{
x_SetChars();
switch(algorithm) {
case eUseSeqString:
{
TSeqPos aln_len = m_AlnVec.GetAlnStop() + 1;
const CAlnMap::TNumrow nrows = m_NumRows;
const CAlnMap::TNumseg nsegs = m_AlnVec.GetNumSegs();
const CDense_seg::TStarts& starts = m_AlnVec.GetDenseg().GetStarts();
const CDense_seg::TLens& lens = m_AlnVec.GetDenseg().GetLens();
vector<string> buffer(nrows);
for (CAlnMap::TNumrow row = 0; row < nrows; row++) {
// allocate space for the row
buffer[row].reserve(aln_len + 1);
string buff;
int seg, pos, left_seg = -1, right_seg = -1;
TSignedSeqPos start;
TSeqPos len;
// determine the ending right seg
for (seg = nsegs - 1, pos = seg * nrows + row;
seg >= 0; --seg, pos -= nrows) {
if (starts[pos] >= 0) {
right_seg = seg;
break;
}
}
for (seg = 0, pos = row; seg < nsegs; ++seg, pos += nrows) {
len = lens[seg];
if ((start = starts[pos]) >= 0) {
left_seg = seg; // ending left seg is at most here
m_AlnVec.GetSeqString(buff,
row,
start,
start + len * m_AlnVec.GetWidth(row) - 1);
buffer[row] += buff;
} else {
// add appropriate number of gap/end chars
char* ch_buff = new char[len+1];
char fill_ch;
if (left_seg < 0 || seg > right_seg && right_seg > 0) {
fill_ch = m_AlnVec.GetEndChar();
} else {
fill_ch = m_AlnVec.GetGapChar(row);
}
memset(ch_buff, fill_ch, len);
ch_buff[len] = 0;
buffer[row] += ch_buff;
delete[] ch_buff;
}
}
}
TSeqPos pos = 0;
do {
for (CAlnMap::TNumrow row = 0; row < nrows; row++) {
PrintNumRow(row);
PrintId(row);
PrintSeqPos(m_AlnVec.GetSeqPosFromAlnPos(row, pos, CAlnMap::eLeft));
*m_Out << buffer[row].substr(pos, scrn_width)
<< " "
<< m_AlnVec.GetSeqPosFromAlnPos(row, pos + scrn_width - 1,
CAlnMap::eLeft)
<< endl;
}
*m_Out << endl;
pos += scrn_width;
if (pos + scrn_width > aln_len) {
scrn_width = aln_len - pos;
}
} while (pos < aln_len);
break;
}
case eUseAlnSeqString:
{
TSeqPos aln_pos = 0;
CAlnMap::TSignedRange rng;
do {
// create range
rng.Set(aln_pos, aln_pos + scrn_width - 1);
string aln_seq_str;
aln_seq_str.reserve(scrn_width + 1);
// for each sequence
for (CAlnMap::TNumrow row = 0; row < m_NumRows; row++) {
PrintNumRow(row);
PrintId(row);
PrintSeqPos(m_AlnVec.GetSeqPosFromAlnPos(row, rng.GetFrom(),
CAlnMap::eLeft));
*m_Out << m_AlnVec.GetAlnSeqString(aln_seq_str, row, rng)
<< " "
<< m_AlnVec.GetSeqPosFromAlnPos(row, rng.GetTo(),
CAlnMap::eLeft)
<< endl;
}
*m_Out << endl;
aln_pos += scrn_width;
} while (aln_pos < m_AlnVec.GetAlnStop());
break;
}
case eUseWholeAlnSeqString:
{
CAlnMap::TNumrow row, nrows = m_NumRows;
vector<string> buffer(nrows);
vector<CAlnMap::TSeqPosList> insert_aln_starts(nrows);
vector<CAlnMap::TSeqPosList> insert_starts(nrows);
vector<CAlnMap::TSeqPosList> insert_lens(nrows);
vector<CAlnMap::TSeqPosList> scrn_lefts(nrows);
vector<CAlnMap::TSeqPosList> scrn_rights(nrows);
// Fill in the vectors for each row
for (row = 0; row < nrows; row++) {
m_AlnVec.GetWholeAlnSeqString
(row,
buffer[row],
&insert_aln_starts[row],
&insert_starts[row],
&insert_lens[row],
scrn_width,
&scrn_lefts[row],
&scrn_rights[row]);
}
// Visualization
TSeqPos pos = 0, aln_len = m_AlnVec.GetAlnStop() + 1;
do {
for (row = 0; row < nrows; row++) {
PrintNumRow(row);
PrintId(row);
PrintSeqPos(scrn_lefts[row].front());
*m_Out << buffer[row].substr(pos, scrn_width)
<< " "
<< scrn_rights[row].front()
<< endl;
scrn_lefts[row].pop_front();
scrn_rights[row].pop_front();
}
*m_Out << endl;
pos += scrn_width;
if (pos + scrn_width > aln_len) {
scrn_width = aln_len - pos;
}
} while (pos < aln_len);
break;
}
}
x_UnsetChars();
}
void CAlnVecPrinter::ClustalStyle(int scrn_width,
EAlgorithm algorithm)
{
x_SetChars();
*m_Out << "CLUSTAL W (1.83) multiple sequence alignment" << endl << endl;
switch(algorithm) {
case eUseSeqString:
{
TSeqPos aln_len = m_AlnVec.GetAlnStop() + 1;
const CAlnMap::TNumseg nsegs = m_AlnVec.GetNumSegs();
const CDense_seg::TStarts& starts = m_AlnVec.GetDenseg().GetStarts();
const CDense_seg::TLens& lens = m_AlnVec.GetDenseg().GetLens();
CAlnMap::TNumrow row;
vector<string> buffer(m_NumRows+1);
for (row = 0; row < m_NumRows; row++) {
// allocate space for the row
buffer[row].reserve(aln_len + 1);
string buff;
int seg, pos, left_seg = -1, right_seg = -1;
TSignedSeqPos start;
TSeqPos len;
// determine the ending right seg
for (seg = nsegs - 1, pos = seg * m_NumRows + row;
seg >= 0; --seg, pos -= m_NumRows) {
if (starts[pos] >= 0) {
right_seg = seg;
break;
}
}
for (seg = 0, pos = row; seg < nsegs; ++seg, pos += m_NumRows) {
len = lens[seg];
if ((start = starts[pos]) >= 0) {
left_seg = seg; // ending left seg is at most here
m_AlnVec.GetSeqString(buff,
row,
start,
start + len * m_AlnVec.GetWidth(row) - 1);
buffer[row] += buff;
} else {
// add appropriate number of gap/end chars
char* ch_buff = new char[len+1];
char fill_ch;
if (left_seg < 0 || seg > right_seg && right_seg > 0) {
fill_ch = m_AlnVec.GetEndChar();
} else {
fill_ch = m_AlnVec.GetGapChar(row);
}
memset(ch_buff, fill_ch, len);
ch_buff[len] = 0;
buffer[row] += ch_buff;
delete[] ch_buff;
}
}
}
// Find identities
buffer[m_NumRows].resize(aln_len);
for (TSeqPos pos = 0; pos < aln_len; pos++) {
bool identity = true;
char residue = buffer[0][pos];
for (row = 1; row < m_NumRows; row++) {
if (buffer[row][pos] != residue) {
identity = false;
break;
}
}
buffer[m_NumRows][pos] = (identity ? '*' : ' ');
}
TSeqPos aln_pos = 0;
do {
for (CAlnMap::TNumrow row = 0; row < m_NumRows; row++) {
PrintId(row);
*m_Out << buffer[row].substr(aln_pos, scrn_width)
<< endl;
}
m_Out->width(m_IdFieldLen);
*m_Out << "";
*m_Out << buffer[m_NumRows].substr(aln_pos, scrn_width)
<< endl << endl;
aln_pos += scrn_width;
if (aln_pos + scrn_width > aln_len) {
scrn_width = aln_len - aln_pos;
}
} while (aln_pos < aln_len);
break;
}
case eUseAlnSeqString:
{
TSeqPos aln_pos = 0;
TSeqPos aln_stop = m_AlnVec.GetAlnStop();
CAlnMap::TSignedRange rng;
string identities_str;
identities_str.reserve(scrn_width + 1);
do {
// create range
rng.Set(aln_pos, min(aln_pos + scrn_width - 1, aln_stop));
string aln_seq_str;
aln_seq_str.reserve(scrn_width + 1);
// for each sequence
for (CAlnMap::TNumrow row = 0; row < m_NumRows; row++) {
PrintId(row);
*m_Out << m_AlnVec.GetAlnSeqString(aln_seq_str, row, rng)
<< endl;
if (row == 0) {
identities_str = aln_seq_str;
} else {
for (size_t i = 0; i < aln_seq_str.length(); i++) {
if (aln_seq_str[i] != identities_str[i]) {
identities_str[i] = ' ';
}
}
}
}
for (size_t i = 0; i < identities_str.length(); i++) {
if (identities_str[i] != ' ') {
identities_str[i] = '*';
}
}
m_Out->width(m_IdFieldLen);
*m_Out << "";
*m_Out << identities_str
<< endl << endl;
aln_pos += scrn_width;
} while (aln_pos < m_AlnVec.GetAlnStop());
break;
}
case eUseWholeAlnSeqString:
{
CAlnMap::TNumrow row;
vector<string> buffer(m_NumRows+1);
// Fill in the vectors for each row
for (row = 0; row < m_NumRows; row++) {
m_AlnVec.GetWholeAlnSeqString(row, buffer[row]);
}
TSeqPos pos = 0;
const TSeqPos aln_len = m_AlnVec.GetAlnStop() + 1;
// Find identities
buffer[m_NumRows].resize(aln_len);
for (pos = 0; pos < aln_len; pos++) {
bool identity = true;
char residue = buffer[0][pos];
for (row = 1; row < m_NumRows; row++) {
if (buffer[row][pos] != residue) {
identity = false;
break;
}
}
buffer[m_NumRows][pos] = (identity ? '*' : ' ');
}
// Visualization
pos = 0;
do {
for (row = 0; row < m_NumRows; row++) {
PrintId(row);
*m_Out << buffer[row].substr(pos, scrn_width)
<< endl;
}
m_Out->width(m_IdFieldLen);
*m_Out << "";
*m_Out << buffer[m_NumRows].substr(pos, scrn_width)
<< endl << endl;
pos += scrn_width;
if (pos + scrn_width > aln_len) {
scrn_width = aln_len - pos;
}
} while (pos < aln_len);
break;
}
}
x_UnsetChars();
}
| 36.06982 | 88 | 0.424539 | mycolab |
f833abf19ec3c0320b53c6030e926fc05814edaa | 1,041 | cpp | C++ | problems19dec/snake/3.cpp | Gomango999/codebreaker | 407c4ac7a69c8db52cc7d2a57034cdda243c9134 | [
"MIT"
] | 1 | 2021-12-11T01:43:27.000Z | 2021-12-11T01:43:27.000Z | problems19dec/snake/3.cpp | Gomango999/codebreaker | 407c4ac7a69c8db52cc7d2a57034cdda243c9134 | [
"MIT"
] | null | null | null | problems19dec/snake/3.cpp | Gomango999/codebreaker | 407c4ac7a69c8db52cc7d2a57034cdda243c9134 | [
"MIT"
] | 1 | 2021-12-15T07:04:29.000Z | 2021-12-15T07:04:29.000Z | // No comment
#include <iostream>
#include <algorithm>
using namespace std;
char makeBeef(char x) {
string snake = "SNAKE";
string cow = "ANGUS";
for(int i = 0; i < 5; i++) {
if(snake[i] == x) {
return cow[i];
}
}
return 'X';
}
int N;
string S;
const int FAIL = -1234;
int _K;
int f(char thing, int start) {
if(start == FAIL || _K == 0) {
return FAIL;
}
int k = _K;
for(int i = start; i < N; i++) {
if(S[i] == thing) {
k--;
}
if(k == 0) {
return i;
}
}
return FAIL;
}
const int NO_SOLN = 0;
int main() {
cin >> N >> S;
transform(begin(S), end(S), begin(S), makeBeef);
int best = NO_SOLN;
int l = 0;
int r = N;
while(l <= r) {
_K = (l+r)/2;
if(f('S', f('U', f('G', f('N', f('A', 0))))) == FAIL) {
r = _K-1;
} else {
l = _K+1;
best = best < _K ? _K : best;
}
}
cout << best << "\n";
return 0;
}
| 17.065574 | 63 | 0.411143 | Gomango999 |
f83595e4245ba99a0f4e521570d5c4197e4d71f3 | 335 | cpp | C++ | C++/TheCherno/21-main.cpp | Youngermaster/learning-programming-languages | 55ce852799ced3d656df01230e4fd9e619ed3f6b | [
"MIT"
] | 1 | 2020-07-20T15:28:50.000Z | 2020-07-20T15:28:50.000Z | C++/TheCherno/21-main.cpp | Youngermaster/learning-programming-languages | 55ce852799ced3d656df01230e4fd9e619ed3f6b | [
"MIT"
] | 1 | 2022-03-02T13:16:03.000Z | 2022-03-02T13:16:03.000Z | C++/TheCherno/21-main.cpp | Youngermaster/Learning-Programming-Languages | b94d3d85abc6c107877b11b42a3862d4aae8e3ee | [
"MIT"
] | null | null | null | #include <iostream>
#define LOG(x) std::cout << x << std::endl
int s_variable = 5;
// * To avoid the linking error we add extern
// * to get this variable from another file.
extern int noStaticVariable;
void function()
{
LOG(s_variable);
LOG(noStaticVariable);
}
int main(int argc, char const *argv[])
{
function();
}
| 15.952381 | 45 | 0.665672 | Youngermaster |
f83beb1a440c9892cbc3ec8a1aebb5a50ff8a714 | 2,586 | hpp | C++ | NCGB/Compile/src/OBSOLETE2009/BaGBListIterator.hpp | mcdeoliveira/NC | 54b2a81ebda9e5260328f88f83f56fe8cf472ac3 | [
"BSD-3-Clause"
] | 103 | 2016-09-21T06:01:23.000Z | 2022-03-27T06:52:10.000Z | NCGB/Compile/src/OBSOLETE2009/BaGBListIterator.hpp | albinjames/NC | 157a55458931a18dd1f42478872c9df0de5cc450 | [
"BSD-3-Clause"
] | 11 | 2017-03-27T13:11:42.000Z | 2022-03-08T13:46:14.000Z | NCGB/Compile/src/OBSOLETE2009/BaGBListIterator.hpp | albinjames/NC | 157a55458931a18dd1f42478872c9df0de5cc450 | [
"BSD-3-Clause"
] | 21 | 2017-06-23T09:01:21.000Z | 2022-02-18T06:24:00.000Z | // BaGBListIterator.h
#ifndef INCLUDED_BAGBLISTITERATOR_H
#define INCLUDED_BAGBLISTITERATOR_H
#include "ListChoice.hpp"
#ifdef USE_OLD_GBLIST
#ifdef DEBUGGBListIterator
#ifndef INCLUDED_DEBUG1_H
#include "Debug1.hpp"
#endif
#endif
#ifndef INCLUDED_DLLIST_H
#include "DLList.hpp"
#endif
#ifndef INCLUDED_DEBUG1_H
#include "Debug1.hpp"
#endif
class MyOstream;
class BaGBListIterator {
static void errorh(int);
static void errorc(int);
void operator = (const BaGBListIterator & x);
// not implemented
public:
BaGBListIterator();
BaseDLList * _ptr;
Pix _p;
#ifdef DEBUGGBListIterator
int _n;
#endif
BaGBListIterator(const BaGBListIterator & ptr);
explicit BaGBListIterator(BaseDLList & ptr);
BaGBListIterator(Pix p,BaseDLList & ptr);
protected:
virtual ~BaGBListIterator();
void assign(const BaGBListIterator &);
public:
bool operator ==(const BaGBListIterator & x) const;
bool operator !=(const BaGBListIterator & x) const;
void operator ++();
void operator ++(int);
void operator --();
void operator --(int);
void advance(int n);
friend MyOstream & operator <<(MyOstream & os,const BaGBListIterator & iter);
};
inline void BaGBListIterator::assign(const BaGBListIterator & r) {
_ptr = r._ptr;
_p = r._p;
#ifdef DEBUGGBListIterator
_n = r._n;
#endif
}
inline bool BaGBListIterator::operator ==(const BaGBListIterator & iter)
const {
return (_p)== (iter._p);
}
inline bool BaGBListIterator::operator !=(const BaGBListIterator & iter)
const { return !((*this)==iter);};
inline BaGBListIterator::BaGBListIterator() : _ptr(0), _p(0) { }
inline BaGBListIterator::BaGBListIterator(BaseDLList & ptr) :
_ptr(&ptr), _p(0)
#ifdef DEBUGGBListIterator
,_n(1)
#endif
{
_p = _ptr->first();
}
inline
BaGBListIterator::BaGBListIterator(Pix p, BaseDLList & ptr) :
_ptr(&ptr), _p(p)
#ifdef DEBUGGBListIterator
,_n(1)
#endif
{ };
inline
BaGBListIterator::BaGBListIterator(const BaGBListIterator & ptr) :
_ptr(ptr._ptr), _p(ptr._p)
#ifdef DEBUGGBListIterator
,_n(ptr._n)
#endif
{ };
inline void BaGBListIterator::operator ++() {
if(_p==0) errorh(__LINE__);
_ptr->next(_p);
#ifdef DEBUGGBListIterator
++_n;
if(_n>_ptr->length()+1) errorh(__LINE__);
#endif
};
inline void BaGBListIterator::operator --() {
if(_p==0) {
_p = _ptr->last();
} else {
_ptr->prev(_p);
};
#ifdef DEBUGGBListIterator
--_n;
if(_n<=0) errorh(__LINE__);
#endif
};
#endif
#endif
| 21.731092 | 80 | 0.669374 | mcdeoliveira |
f83ceabbb354e8ab2cd9ff9f4dbf28f93f9eadb4 | 3,071 | cpp | C++ | src/io.cpp | tguyard/sentry-native | e33c68d1d61a65a089a431185584fa304c81c58f | [
"MIT"
] | 1 | 2019-11-25T22:33:56.000Z | 2019-11-25T22:33:56.000Z | src/io.cpp | detwiler/sentry-native | d2035afffcad282a44195cacc0d300de7fe0e36d | [
"MIT"
] | null | null | null | src/io.cpp | detwiler/sentry-native | d2035afffcad282a44195cacc0d300de7fe0e36d | [
"MIT"
] | null | null | null | #include <cstdlib>
#include "internal.hpp"
#include "io.hpp"
#include "path.hpp"
#ifndef _WIN32
#include <fcntl.h>
#include <unistd.h>
#endif
using namespace sentry;
IoWriter::IoWriter() {
}
IoWriter::~IoWriter() {
}
FileIoWriter::FileIoWriter() : m_buflen(0) {
// on non win32 platforms we only use open/write/close so that
// we can achieve something close to being async safe so we can
// use this class in crashing situations.
#ifdef _WIN32
m_file = nullptr;
#else
m_fd = -1;
#endif
}
FileIoWriter::~FileIoWriter() {
close();
}
bool FileIoWriter::open(const Path &path, const char *mode) {
#ifdef _WIN32
m_file = path.open(mode);
return m_file != nullptr;
#else
int flags = 0;
for (; *mode; mode++) {
switch (*mode) {
case 'r':
flags |= O_RDONLY;
break;
case 'w':
flags |= O_WRONLY | O_CREAT | O_TRUNC;
break;
case 'a':
flags |= O_WRONLY | O_CREAT | O_APPEND;
break;
case 'b':
break;
case '+':
flags |= O_RDWR;
break;
default:;
}
}
m_fd = ::open(path.as_osstr(), flags,
S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH);
return m_fd >= 0;
#endif
}
void FileIoWriter::write(const char *buf, size_t len) {
size_t to_write = len;
while (to_write) {
size_t can_write = std::min(BUF_SIZE - m_buflen, to_write);
memcpy(m_buf + m_buflen, buf, can_write);
m_buflen += can_write;
to_write -= can_write;
buf += can_write;
if (m_buflen == BUF_SIZE) {
flush();
}
}
}
void FileIoWriter::flush() {
#ifdef _WIN32
fwrite(m_buf, 1, m_buflen, m_file);
fflush(m_file);
#else
::write(m_fd, m_buf, m_buflen);
#endif
m_buflen = 0;
}
void FileIoWriter::close() {
flush();
#ifdef _WIN32
fclose(m_file);
#else
::close(m_fd);
#endif
m_buflen = 0;
}
MemoryIoWriter::MemoryIoWriter(size_t bufsize)
: m_terminated(false),
m_buflen(0),
m_bufcap(bufsize),
m_buf((char *)malloc(bufsize)) {
}
MemoryIoWriter::~MemoryIoWriter() {
free(m_buf);
}
void MemoryIoWriter::flush() {
if (!m_terminated) {
write_char(0);
m_buflen -= 1;
m_terminated = true;
}
}
void MemoryIoWriter::write(const char *buf, size_t len) {
size_t size_needed = m_buflen + len;
if (size_needed > m_bufcap) {
size_t new_bufcap = m_bufcap;
while (new_bufcap < size_needed) {
new_bufcap *= 1.3;
}
m_buf = (char *)realloc(m_buf, new_bufcap);
m_bufcap = new_bufcap;
}
memcpy(m_buf + m_buflen, buf, len);
m_buflen += len;
m_terminated = false;
}
char *MemoryIoWriter::take() {
flush();
char *rv = m_buf;
m_buf = nullptr;
return rv;
}
const char *MemoryIoWriter::buf() const {
return m_buf;
}
size_t MemoryIoWriter::len() const {
return m_buflen;
}
| 20.610738 | 67 | 0.565939 | tguyard |
f83eebc3951e3b7c9f6af443f0c97b8c68eafbb1 | 4,607 | cpp | C++ | 2022.04.04. Test 2.d.r/2022.04.04. Test 2.d.r/Fraction.cpp | whitehet-sex-lman/The-first-course-2021.Cplpl | 2bd2ad443d9c055fcd0694970d0a2f245b37f962 | [
"Apache-2.0"
] | null | null | null | 2022.04.04. Test 2.d.r/2022.04.04. Test 2.d.r/Fraction.cpp | whitehet-sex-lman/The-first-course-2021.Cplpl | 2bd2ad443d9c055fcd0694970d0a2f245b37f962 | [
"Apache-2.0"
] | null | null | null | 2022.04.04. Test 2.d.r/2022.04.04. Test 2.d.r/Fraction.cpp | whitehet-sex-lman/The-first-course-2021.Cplpl | 2bd2ad443d9c055fcd0694970d0a2f245b37f962 | [
"Apache-2.0"
] | null | null | null | #include "Fraction.h"
Fraction::Fraction(long long numerator, long long denominator)
{
if (numerator < 0 && denominator > 0 || numerator >= 0 && denominator > 0)
{
this->numerator = numerator;
this->denominator = denominator;
}
else if (numerator < 0 && denominator < 0 || numerator >= 0 && denominator < 0)
{
this->numerator = -numerator;
this->denominator = -denominator;
}
}
Fraction::Fraction(const Fraction& fraction) : numerator(fraction.numerator), denominator(fraction.denominator) {}
Fraction::~Fraction()
{
this->numerator = 0;
this->denominator = 0;
}
Fraction Fraction::absf()
{
if (this->numerator >= 0)
{
return Fraction(this->numerator, this->denominator);
}
else
{
return Fraction(-this->numerator, this->denominator);
}
}
Fraction Fraction::powf(int n)
{
return Fraction(pow(this->numerator, n), pow(this->denominator, n));
}
Fraction Fraction::reverse()
{
return Fraction(this->denominator, this->numerator);
}
Fraction Fraction::operator=(Fraction& fraction)
{
this->numerator = fraction.numerator;
this->denominator = fraction.denominator;
return *this;
}
long long Fraction::nod()
{
long long result = 1;
for (long long i = 1; i < min(abs(this->numerator), abs(this->denominator)); ++i)
{
if (this->numerator / i == 0 and this->denominator / i == 0)
{
result = i;
}
}
return result;
}
bool operator==(Fraction fraction1, Fraction fraction2)
{
if (fraction1.denominator == fraction2.numerator && fraction1.denominator == fraction2.denominator)
{
return true;
}
else
{
return false;
}
}
bool operator<(Fraction fraction1, Fraction fraction2)
{
if (fraction1.numerator * fraction2.denominator < fraction2.numerator * fraction1.denominator)
{
return true;
}
else
{
return false;
}
}
bool operator<=(Fraction fraction1, Fraction fraction2)
{
if (fraction1.numerator * fraction2.denominator <= fraction2.numerator * fraction1.denominator)
{
return true;
}
else
{
return false;
}
}
bool operator>(Fraction fraction1, Fraction fraction2)
{
if (fraction1.numerator * fraction2.denominator > fraction2.numerator * fraction1.denominator)
{
return true;
}
else
{
return false;
}
}
bool operator>=(Fraction fraction1, Fraction fraction2)
{
if (fraction1.numerator * fraction2.denominator >= fraction2.numerator * fraction1.denominator)
{
return true;
}
else
{
return false;
}
}
Fraction operator+(Fraction fraction1, Fraction fraction2)
{
long long nod = Fraction(fraction1.numerator * fraction2.denominator + fraction2.numerator * fraction1.denominator, fraction1.denominator * fraction2.denominator).nod();
return Fraction((fraction1.numerator * fraction2.denominator + fraction2.numerator * fraction1.denominator) / nod, fraction1.denominator * fraction2.denominator / nod);
}
Fraction operator*(Fraction fraction, double n)
{
long long nod = Fraction(fraction.numerator * n, fraction.denominator).nod();
return Fraction(fraction.numerator * n / nod, fraction.denominator / nod);
}
Fraction operator*(double n, Fraction fraction)
{
long long nod = Fraction(fraction.numerator * n, fraction.denominator).nod();
return Fraction(fraction.numerator * n / nod, fraction.denominator / nod);
}
Fraction operator*(Fraction fraction1, Fraction fraction2)
{
long long nod = Fraction(fraction1.numerator * fraction2.numerator, fraction1.denominator * fraction2.denominator).nod();
return Fraction(fraction1.numerator * fraction2.numerator / nod, fraction1.denominator * fraction2.denominator / nod);
}
Fraction operator/(Fraction fraction, double n)
{
long long nod = Fraction(fraction.numerator, fraction.denominator * n).nod();
return Fraction(fraction.numerator / nod, fraction.denominator * n / nod);
}
Fraction operator/(double n, Fraction& fraction)
{
return n * fraction.reverse();
}
Fraction operator/(Fraction fraction1, Fraction fraction2)
{
return fraction1 * fraction2.reverse();
}
Fraction operator-(Fraction fraction1, Fraction fraction2)
{
long long nod = Fraction(fraction1.numerator * fraction2.denominator - fraction2.numerator * fraction1.denominator, fraction1.denominator * fraction2.denominator).nod();
return Fraction((fraction1.numerator * fraction2.denominator - fraction2.numerator * fraction1.denominator) / nod, fraction1.denominator * fraction2.denominator / nod);
}
ostream& operator<<(ostream& stream, Fraction fraction)
{
if (fraction.numerator == 0)
{
stream << 0;
}
else if (fraction.denominator == 1)
{
stream << fraction.numerator;
}
else
{
stream << fraction.numerator << " / " << fraction.denominator;
}
return stream;
}
| 24.247368 | 170 | 0.725418 | whitehet-sex-lman |
f8407239587e83ddf553d64c386171ffe45ab521 | 1,650 | hpp | C++ | src/cpa/cpa.hpp | DfX-NYUAD/CPA | 4b1364e7b0eb7d0580b4e90e5a05a109551ed49d | [
"MIT"
] | null | null | null | src/cpa/cpa.hpp | DfX-NYUAD/CPA | 4b1364e7b0eb7d0580b4e90e5a05a109551ed49d | [
"MIT"
] | null | null | null | src/cpa/cpa.hpp | DfX-NYUAD/CPA | 4b1364e7b0eb7d0580b4e90e5a05a109551ed49d | [
"MIT"
] | null | null | null | /* Copyright (c) 2013 Tescase
*
* 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.
*/
//
// This file contains the serial and parallel
// CPA algorithms
//
#ifndef SCA_CPA_CPA_H
#define SCA_CPA_CPA_H
#include <string>
namespace cpa
{
// The serial CPU based CPA function
void cpa(std::string data_path, std::string ct_path, std::string key_path, std::string perm_path, bool candidates, int permutations, int steps, int steps_start, int steps_stop, float rate_stop, bool verbose, bool key_expansion);
// The parallel GPU based CPA function
void pcpa(std::string data_path, std::string ct_path);
} //end namespace
#endif
| 37.5 | 228 | 0.762424 | DfX-NYUAD |
f84549bb0abe8eca74e63b64cbcad69b6498552b | 2,553 | cpp | C++ | assec-renderer/platform/directx12/directx12_command_list.cpp | TeamVistic/assec-renderer | 5c6fc9a46fc3f6302471a22bfd2bdf2942b794db | [
"Apache-2.0"
] | null | null | null | assec-renderer/platform/directx12/directx12_command_list.cpp | TeamVistic/assec-renderer | 5c6fc9a46fc3f6302471a22bfd2bdf2942b794db | [
"Apache-2.0"
] | null | null | null | assec-renderer/platform/directx12/directx12_command_list.cpp | TeamVistic/assec-renderer | 5c6fc9a46fc3f6302471a22bfd2bdf2942b794db | [
"Apache-2.0"
] | null | null | null | #include "pch.h"
#include "directx12_command_list.h"
namespace assec::renderer
{
ComPtr<ID3D12GraphicsCommandList2> create_command_list(ComPtr<ID3D12Device2> device,
ComPtr<ID3D12CommandAllocator> command_allocator, D3D12_COMMAND_LIST_TYPE type)
{
ComPtr<ID3D12GraphicsCommandList2> result;
throw_if_failed(device->CreateCommandList(0, type, command_allocator.Get(), nullptr, IID_PPV_ARGS(&result)));
return result;
}
directx12_command_list::directx12_command_list(ComPtr<ID3D12Device2> device, ComPtr<ID3D12CommandAllocator> command_allocator, D3D12_COMMAND_LIST_TYPE type)
: m_native(create_command_list(device, command_allocator, type)) {}
ComPtr<ID3D12GraphicsCommandList2> directx12_command_list::native() const { return this->m_native; }
ComPtr<ID3D12CommandAllocator> directx12_command_list::command_allocator() const
{
ID3D12CommandAllocator* command_allocator;
UINT size = sizeof(command_allocator);
throw_if_failed(this->native()->GetPrivateData(__uuidof(ID3D12CommandAllocator), &size, &command_allocator));
return command_allocator;
}
void directx12_command_list::update_subresources(directx12_resource& destination, directx12_resource& intermediate,
uint32_t offset, uint32_t first, std::vector<D3D12_SUBRESOURCE_DATA> subresources) const
{
UpdateSubresources(this->m_native.Get(),
destination.native().Get(), intermediate.native().Get(),
offset, first, subresources.size(), subresources.data());
}
void directx12_command_list::clear_render_target_view(const directx12_resource& texture, CD3DX12_CPU_DESCRIPTOR_HANDLE handle, resource_state_tracker& resource_tracker, const glm::vec4 color) const
{
if (resource_tracker.retreive_state(texture) != D3D12_RESOURCE_STATE_RENDER_TARGET)
{
auto barrier = resource_tracker.transition_barrier(texture, D3D12_RESOURCE_STATE_RENDER_TARGET);
this->native()->ResourceBarrier(1, &barrier);
}
this->native()->ClearRenderTargetView(handle, glm::value_ptr(color), 0, nullptr);
}
void directx12_command_list::clear_depth_target_view(const directx12_resource& texture, CD3DX12_CPU_DESCRIPTOR_HANDLE handle, resource_state_tracker& resource_tracker, D3D12_CLEAR_FLAGS flags, float depth, uint8_t stencil) const
{
if (resource_tracker.retreive_state(texture) != D3D12_RESOURCE_STATE_DEPTH_WRITE)
{
auto barrier = resource_tracker.transition_barrier(texture, D3D12_RESOURCE_STATE_DEPTH_WRITE);
this->native()->ResourceBarrier(1, &barrier);
}
this->native()->ClearDepthStencilView(handle, flags, depth, stencil, 0, nullptr);
}
}
| 48.169811 | 229 | 0.806894 | TeamVistic |