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
109
| 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
48.5k
⌀ | 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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8594d7298aa88da4685fb15da26a7e2b0b33d489
| 1,034
|
hpp
|
C++
|
uActor/include/controllers/telemetry_actor.hpp
|
uActor/uActor
|
1180db98f48ad447639a3d625573307d87b28902
|
[
"MIT"
] | 1
|
2021-09-15T12:41:37.000Z
|
2021-09-15T12:41:37.000Z
|
uActor/include/controllers/telemetry_actor.hpp
|
uActor/uActor
|
1180db98f48ad447639a3d625573307d87b28902
|
[
"MIT"
] | null | null | null |
uActor/include/controllers/telemetry_actor.hpp
|
uActor/uActor
|
1180db98f48ad447639a3d625573307d87b28902
|
[
"MIT"
] | null | null | null |
#ifndef UACTOR_INCLUDE_CONTROLLERS_TELEMETRY_ACTOR_HPP_
#define UACTOR_INCLUDE_CONTROLLERS_TELEMETRY_ACTOR_HPP_
#include <string>
#include <string_view>
#include "actor_runtime/native_actor.hpp"
#include "telemetry_data.hpp"
namespace uActor::Controllers {
class TelemetryActor : public ActorRuntime::NativeActor {
public:
// TODO(raphaelhetzel) not a fan of using a static here,
// evaluate ways of passing data to native actors.
static std::function<void()> telemetry_fetch_hook;
TelemetryActor(ActorRuntime::ManagedNativeActor* actor_wrapper,
std::string_view node_id, std::string_view actor_type,
std::string_view instance_id)
: ActorRuntime::NativeActor(actor_wrapper, node_id, actor_type,
instance_id) {}
void receive(const PubSub::Publication& publication);
private:
void try_publish_telemetry_datapoint(const TelemetryData& data);
};
} // namespace uActor::Controllers
#endif // UACTOR_INCLUDE_CONTROLLERS_TELEMETRY_ACTOR_HPP_
| 31.333333
| 71
| 0.749516
|
uActor
|
8596f764caaf8323a6d6056876be72ec98b56cd6
| 2,972
|
cpp
|
C++
|
src/StartDownloadConnectionInformation.cpp
|
JoystreamClassic/joystream-node
|
2450382bb937abdd959b460791c25f2d8f127168
|
[
"MIT"
] | null | null | null |
src/StartDownloadConnectionInformation.cpp
|
JoystreamClassic/joystream-node
|
2450382bb937abdd959b460791c25f2d8f127168
|
[
"MIT"
] | 9
|
2017-11-14T06:05:50.000Z
|
2018-07-08T18:21:17.000Z
|
src/StartDownloadConnectionInformation.cpp
|
JoystreamClassic/joystream-node
|
2450382bb937abdd959b460791c25f2d8f127168
|
[
"MIT"
] | 4
|
2017-11-14T06:04:17.000Z
|
2018-08-24T07:39:00.000Z
|
/**
* Copyright (C) JoyStream - All Rights Reserved
* Unauthorized copying of this file, via any medium is strictly prohibited
* Proprietary and confidential
* Written by Bedeho Mender <bedeho.mender@gmail.com>, January 19 2017
*/
#include "StartDownloadConnectionInformation.hpp"
#include "SellerTerms.hpp"
#include "PrivateKey.hpp"
#include "PubKeyHash.hpp"
#include <extension/Common.hpp> //std::hash<endpoint> specialization
#include "libtorrent-node/endpoint.hpp"
#include "libtorrent-node/peer_id.hpp"
#include "libtorrent-node/utils.hpp"
#define SELLER_TERMS_KEY "sellerTerms"
#define INDEX_KEY "index"
#define VALUE_KEY "value"
#define BUYER_CONTRACT_SK_KEY "buyerContractSk"
#define BUYER_FINAL_PK_HASH_KEY "buyerFinalPkHash"
namespace joystream {
namespace node {
namespace StartDownloadConnectionInformation {
NAN_MODULE_INIT(Init) {
// export PeerNotReadyToStartDownloadCause
}
v8::Local<v8::Object> encode(const protocol_session::StartDownloadConnectionInformation & inf) {
v8::Local<v8::Object> o = Nan::New<v8::Object>();
SET_VAL(o, SELLER_TERMS_KEY, seller_terms::encode(inf.sellerTerms));
SET_UINT32(o, INDEX_KEY, inf.index);
SET_NUMBER(o, VALUE_KEY, inf.value);
SET_VAL(o, BUYER_CONTRACT_SK_KEY, private_key::encode(inf.buyerContractKeyPair.sk()));
SET_VAL(o, BUYER_FINAL_PK_HASH_KEY, pubkey_hash::encode(inf.buyerFinalPkHash));
return o;
}
protocol_session::StartDownloadConnectionInformation decode(const v8::Local<v8::Value> & v) {
v8::Local<v8::Object> o = ToV8<v8::Object>(v);
protocol_wire::SellerTerms terms(seller_terms::decode(GET_VAL(o, SELLER_TERMS_KEY)));
Coin::PrivateKey sk(private_key::decode(GET_VAL(o, BUYER_CONTRACT_SK_KEY)));
Coin::PubKeyHash pubKeyHash(pubkey_hash::decode(GET_VAL(o, BUYER_FINAL_PK_HASH_KEY)));
return protocol_session::StartDownloadConnectionInformation(terms,
GET_UINT32(o, INDEX_KEY),
GET_INT64(o, VALUE_KEY),
Coin::KeyPair(sk),
pubKeyHash);
}
}// StartDownloadConnectionInformation namespace
namespace PeerToStartDownloadInformationMap {
//v8::Local<v8::Object> encode(const protocol_session::PeerToStartDownloadInformationMap<libtorrent::peer_id> & information) {
//}
protocol_session::PeerToStartDownloadInformationMap<libtorrent::peer_id> decode(const v8::Local<v8::Value> & v) {
return std_lib_utils::decode<libtorrent::peer_id, protocol_session::StartDownloadConnectionInformation>(v,
&libtorrent::node::peer_id::decode,
&joystream::node::StartDownloadConnectionInformation::decode);
}
}
}
}
| 37.15
| 171
| 0.66319
|
JoystreamClassic
|
859c4ef2f5a88852afc3c71ae9ece7b5a79fe08b
| 1,412
|
cpp
|
C++
|
Juego Progra 2/Bomberman/Nivel4.cpp
|
upcgames/Bomberman-1
|
d077af34e0b896281a3b04169d698c03f7f86e91
|
[
"MIT"
] | 2
|
2017-06-22T16:44:59.000Z
|
2020-11-24T16:46:59.000Z
|
Juego Progra 2/Bomberman/Nivel4.cpp
|
upcgames/Bomberman-1
|
d077af34e0b896281a3b04169d698c03f7f86e91
|
[
"MIT"
] | 1
|
2017-07-07T15:18:09.000Z
|
2017-07-07T15:18:09.000Z
|
Juego Progra 2/Bomberman/Nivel4.cpp
|
upcgames/Bomberman-1
|
d077af34e0b896281a3b04169d698c03f7f86e91
|
[
"MIT"
] | 1
|
2020-11-24T16:47:08.000Z
|
2020-11-24T16:47:08.000Z
|
#include "Winform.h"
namespace Bomberman
{
Nivel4::Nivel4()
{
Objetos matriz[9][13] = {
{ oPiso, oPiso, oPiso, oPiso, oCaja, oPiso, oPiso, oPiso, oCaja, oPiso, oCaja, oPiso, oPiso },
{ oPiso, oBloque, oPiso, oBloque, oPiso, oBloque, oPiso, oBloque, oPiso, oBloque, oPiso, oBloque, oPiso },
{ oCaja, oCaja, oCaja, oPiso, oCaja, oPiso, oPiso, oPiso, oPiso, oPiso, oPiso, oPiso, oPiso },
{ oCaja, oBloque, oPiso, oBloque, oPiso, oBloque, oPiso, oBloque, oPiso, oBloque, oPiso, oBloque, oPiso },
{ oPiso, oPiso, oCaja, oPiso, oPiso, oPiso, oCaja, oPiso, oCaja, oPiso, oCaja, oPiso, oPiso },
{ oPiso, oBloque, oPiso, oBloque, oPiso, oBloque, oPiso, oBloque, oPiso, oBloque, oPiso, oBloque, oPiso },
{ oCaja, oCaja, oPiso, oPiso, oCaja, oPiso, oPiso, oPiso, oCaja, oPiso, oCaja, oPiso, oPiso },
{ oPiso, oBloque, oPiso, oBloque, oPiso, oBloque, oPiso, oBloque, oPiso, oBloque, oPiso, oBloque, oPiso },
{ oPortal, oPiso, oPiso, oPiso, oCaja, oPiso, oCaja, oPiso, oCaja, oPiso, oPiso, oPiso, oPiso } };
generarMatrizObjetos(matriz);
arregloMalignos = gcnew ArrMalignos(4);
arregloMalignos->arreglo[0] = gcnew Maligno3(gcnew Posicion(384, 384), 0);
arregloMalignos->arreglo[1] = gcnew Maligno3(gcnew Posicion(768, 0), 0);
arregloMalignos->arreglo[2] = gcnew Maligno3(gcnew Posicion(512, 64), 0);
arregloMalignos->arreglo[3] = gcnew Maligno3(gcnew Posicion(768, 512), 0);
}
}
| 54.307692
| 109
| 0.69051
|
upcgames
|
85a2332a69317f89c9ce9efe23a16c204ba51695
| 22,654
|
cpp
|
C++
|
Plugins/org.mitk.lancet.nodeeditor/src/internal/volumeRegistrator.cpp
|
zhaomengxiao/MITK
|
a09fd849a4328276806008bfa92487f83a9e2437
|
[
"BSD-3-Clause"
] | null | null | null |
Plugins/org.mitk.lancet.nodeeditor/src/internal/volumeRegistrator.cpp
|
zhaomengxiao/MITK
|
a09fd849a4328276806008bfa92487f83a9e2437
|
[
"BSD-3-Clause"
] | 1
|
2021-12-22T10:19:02.000Z
|
2021-12-22T10:19:02.000Z
|
Plugins/org.mitk.lancet.nodeeditor/src/internal/volumeRegistrator.cpp
|
zhaomengxiao/MITK_lancet
|
a09fd849a4328276806008bfa92487f83a9e2437
|
[
"BSD-3-Clause"
] | null | null | null |
#include "itkCastImageFilter.h"
#include "itkCommand.h"
#include "itkNormalizedCorrelationTwoImageToOneImageMetric.h"
#include "itkPowellOptimizer.h"
#include "itkTwoProjectionImageRegistrationMethod.h"
#include "itkEuler3DTransform.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkRayCastInterpolateImageFunction.h"
// --------
#include "itkFlipImageFilter.h"
#include "itkImage.h"
#include "itkImageDuplicator.h"
#include "itkImageRegionIteratorWithIndex.h"
#include "itkSiddonJacobsRayCastInterpolateImageFunction.h"
#include "drrInterpolator.h"
#include "itkTimeProbesCollectorBase.h"
#include "twoprojectionregistration.h"
#include "volumeRegistrator.h"
//------------
#include "itkResampleImageFilter.h"
#include "itkRescaleIntensityImageFilter.h"
#include "mitkITKImageImport.h"
#include "mitkImageAccessByItk.h"
#include "mitkImageCast.h"
#include <itkShiftScaleImageFilter.h>
#include <mitkImageToItk.h>
#include <ITKOptimizer.h>
#include "vtkTransform.h"
#include "vtkSmartPointer.h"
class CommandIterationUpdate : public itk::Command
{
public:
typedef CommandIterationUpdate Self;
typedef itk::Command Superclass;
typedef itk::SmartPointer<Self> Pointer;
itkNewMacro(Self);
protected:
CommandIterationUpdate() {};
public:
typedef itk::PowellOptimizer OptimizerType;
typedef const OptimizerType* OptimizerPointer;
void Execute(itk::Object* caller, const itk::EventObject& event) { Execute((const itk::Object*)caller, event); }
void Execute(const itk::Object* object, const itk::EventObject& event)
{
OptimizerPointer optimizer = dynamic_cast<OptimizerPointer>(object);
if (typeid(event) != typeid(itk::IterationEvent))
{
return;
}
// std::cout << "Iteration: " << optimizer->GetCurrentIteration() << std::endl;
std::cout << "Similarity: " << optimizer->GetValue() << std::endl;
std::cout << "Position: " << optimizer->GetCurrentPosition() << std::endl;
}
};
void VolumeRegistrator::link_drr1_cast(mitk::Image::ConstPointer inputImage)
{
if (inputImage->GetDimension() != 3)
{
MITK_ERROR << "works only with 3D images, sorry.";
// itkExceptionMacro("works only with 3D images, sorry.");
return;
}
// AccessFixedDimensionByItk(inputImage.GetPointer(), drr1_cast, 3);
mitk::CastToItkImage(inputImage, m_image_tmp1);
}
void VolumeRegistrator::link_drr2_cast(mitk::Image::ConstPointer inputImage)
{
if (inputImage->GetDimension() != 3)
{
MITK_ERROR << "works only with 3D images, sorry.";
// itkExceptionMacro("works only with 3D images, sorry.");
return;
}
//AccessFixedDimensionByItk(inputImage.GetPointer(), drr2_cast, 3);
mitk::CastToItkImage(inputImage, m_image_tmp2);
}
void VolumeRegistrator::link_3d_cast(mitk::Image::ConstPointer inputImage)
{
if (inputImage->GetDimension() != 3)
{
MITK_ERROR << "works only with 3D images, sorry.";
// itkExceptionMacro("works only with 3D images, sorry.");
return;
}
//AccessFixedDimensionByItk(inputImage.GetPointer(), ct3d_cast, 3);
mitk::CastToItkImage(inputImage, m_image3Df);
}
template <typename TPixel>
void VolumeRegistrator::drr1_cast(const itk::Image<TPixel, 3>* itkImage)
{
typedef float InternalPixelType;
typedef itk::Image<TPixel, 3> RawImageType;
typedef itk::Image<InternalPixelType, 3> InternalImageType;
typedef itk::CastImageFilter<RawImageType, InternalImageType> CastFilterType3D;
CastFilterType3D::Pointer caster3D = CastFilterType3D::New();
caster3D->SetInput(itkImage);
caster3D->Update();
m_image_tmp1 = caster3D->GetOutput();
}
template <typename TPixel>
void VolumeRegistrator::drr2_cast(const itk::Image<TPixel, 3>* itkImage)
{
typedef float InternalPixelType;
typedef itk::Image<TPixel, 3> RawImageType;
typedef itk::Image<InternalPixelType, 3> InternalImageType;
typedef itk::CastImageFilter<RawImageType, InternalImageType> CastFilterType3D;
CastFilterType3D::Pointer caster3D = CastFilterType3D::New();
caster3D->SetInput(itkImage);
caster3D->Update();
m_image_tmp2 = caster3D->GetOutput();
}
template <typename TPixel>
void VolumeRegistrator::ct3d_cast(const itk::Image<TPixel, 3>* itkImage)
{
typedef float InternalPixelType;
typedef itk::Image<TPixel, 3> RawImageType;
typedef itk::Image<InternalPixelType, 3> InternalImageType;
typedef itk::CastImageFilter<RawImageType, InternalImageType> CastFilterType3D;
CastFilterType3D::Pointer caster3D = CastFilterType3D::New();
caster3D->SetInput(itkImage);
caster3D->Update();
m_image3Df = caster3D->GetOutput();
}
void VolumeRegistrator::Clear() {}
VolumeRegistrator::VolumeRegistrator() = default;
VolumeRegistrator::~VolumeRegistrator() = default;
void VolumeRegistrator::registration()
{
if (m_image3Df == nullptr || m_image_tmp1 == nullptr || m_image_tmp2 == nullptr)
{
MITK_ERROR << "SurfaceRegistration Error: Input not ready";
return;
}
// Retrieve the initial euler transform from the matrix
typedef float InternalPixelType;
typedef itk::Image<InternalPixelType, 3> InternalImageType;
typedef itk::Euler3DTransform<double> TransformType;
typedef itk::PowellOptimizer OptimizerType;
typedef itk::NormalizedCorrelationTwoImageToOneImageMetric<InternalImageType, InternalImageType> MetricType;
// typedef itk::SiddonJacobsRayCastInterpolateImageFunction<InternalImageType, double> InterpolatorType;
typedef itk::DrrInterpolator<InternalImageType, double> InterpolatorType;
typedef itk::TwoProjectionImageRegistrationMethod<InternalImageType, InternalImageType> RegistrationType;
MetricType::Pointer metric = MetricType::New();
TransformType::Pointer transform = TransformType::New();
OptimizerType::Pointer optimizer = OptimizerType::New();
InterpolatorType::Pointer interpolator1 = InterpolatorType::New();
InterpolatorType::Pointer interpolator2 = InterpolatorType::New();
RegistrationType::Pointer registrator = RegistrationType::New();
metric->ComputeGradientOff();
metric->SetSubtractMean(true);
registrator->SetMetric(metric);
registrator->SetOptimizer(optimizer);
registrator->SetTransform(transform);
registrator->SetInterpolator1(interpolator1);
registrator->SetInterpolator2(interpolator2);
if (m_debug)
{
metric->DebugOn();
// transform->DebugOn();
// optimizer->DebugOn();
interpolator1->DebugOn();
interpolator2->DebugOn();
// registration->DebugOn();
}
// To simply Siddon-Jacob's fast ray-tracing algorithm, we force the origin of the CT image
// to be (0,0,0). Because we align the CT isocenter with the central axis, the projection
// geometry is fully defined. The origin of the CT image becomes irrelavent.
InternalImageType::PointType image3DOrigin;
image3DOrigin[0] = 0.0;
image3DOrigin[1] = 0.0;
image3DOrigin[2] = 0.0;
m_image3Df->SetOrigin(image3DOrigin);
// set spacing for DRR 1 and DRR 2
InternalImageType::SpacingType spacing;
spacing[0] = m_sx_1;
spacing[1] = m_sy_1;
spacing[2] = 1.0;
m_image_tmp1->SetSpacing(spacing);
spacing[0] = m_sx_2;
spacing[1] = m_sy_2;
m_image_tmp2->SetSpacing(spacing);
// Flip in y-direction for DRR 1 and DRR 2 (might be redundant ??)
typedef itk::FlipImageFilter<InternalImageType> FlipFilterType;
FlipFilterType::Pointer flipFilter1 = FlipFilterType::New();
FlipFilterType::Pointer flipFilter2 = FlipFilterType::New();
typedef FlipFilterType::FlipAxesArrayType FlipAxesArrayType;
FlipAxesArrayType flipArray;
flipArray[0] = 0;
flipArray[1] = 0; // do not flip, because in the new drrGenerator, the resulted image is not flipped along y axis
flipArray[2] = 0;
flipFilter1->SetFlipAxes(flipArray);
flipFilter2->SetFlipAxes(flipArray);
flipFilter1->SetInput(m_image_tmp1);
flipFilter2->SetInput(m_image_tmp2);
// The input 2D images may have 16 bits. We rescale the pixel value to between 0-255.
typedef itk::RescaleIntensityImageFilter<InternalImageType, InternalImageType> Input2DRescaleFilterType;
Input2DRescaleFilterType::Pointer rescaler2D1 = Input2DRescaleFilterType::New();
rescaler2D1->SetOutputMinimum(0);
rescaler2D1->SetOutputMaximum(255);
rescaler2D1->SetInput(flipFilter1->GetOutput());
Input2DRescaleFilterType::Pointer rescaler2D2 = Input2DRescaleFilterType::New();
rescaler2D2->SetOutputMinimum(0);
rescaler2D2->SetOutputMaximum(255);
rescaler2D2->SetInput(flipFilter2->GetOutput());
rescaler2D1->Update();
rescaler2D2->Update();
registrator->SetFixedImage1(rescaler2D1->GetOutput());
registrator->SetFixedImage2(rescaler2D2->GetOutput());
registrator->SetMovingImage(m_image3Df);
// Initialise the transform
// ~~~~~~~~~~~~~~~~~~~~~~~~
// Set the order of the computation. Default ZXY
transform->SetComputeZYX(true);
// The transform is initialised with the translation [tx,ty,tz] and
// rotation [rx,ry,rz] specified on the command line
TransformType::OutputVectorType translation;
// translation[0] = m_tx;
// translation[1] = m_ty;
// translation[2] = m_tz;
translation[0] = m_ArrayMatrixWorldToCt[3];
translation[1] = m_ArrayMatrixWorldToCt[7];
translation[2] = m_ArrayMatrixWorldToCt[11];
transform->SetTranslation(translation);
// constant for converting degrees to radians
const double dtr = (atan(1.0) * 4.0) / 180.0;
Eigen::Matrix4d eigenMatrixWorldToCt{m_ArrayMatrixWorldToCt};
eigenMatrixWorldToCt.transposeInPlace();
double rx, ry, rz;
// double piParameter = 180 / 3.1415926;
if (eigenMatrixWorldToCt(0, 2) < 1)
{
if (eigenMatrixWorldToCt(0, 2) > -1)
{
ry = asin(eigenMatrixWorldToCt(0, 2));
rx = atan2(-eigenMatrixWorldToCt(1, 2), eigenMatrixWorldToCt(2, 2));
rz = atan2(-eigenMatrixWorldToCt(0, 1), eigenMatrixWorldToCt(0, 0));
}
else
{
ry = -3.1415926 / 2;
rx = -atan2(eigenMatrixWorldToCt(1, 0), eigenMatrixWorldToCt(1, 1));
rz = 0;
}
}
else
{
ry = 3.1415926 / 2;
rx = atan2(eigenMatrixWorldToCt(1, 0), eigenMatrixWorldToCt(1, 1));
rz = 0;
}
m_rx = rx;
m_ry = ry;
m_rz = rz;
transform->SetRotation(m_rx, m_ry, m_rz);
TransformType::InputPointType worldOrigin;
worldOrigin[0] = 0;
worldOrigin[1] = 0;
worldOrigin[2] = 0;
transform->SetCenter(worldOrigin);
// The centre of rotation is set by default to the centre of the 3D
// volume but can be offset from this position using a command
// line specified translation [cx,cy,cz]
InternalImageType::PointType origin3D = m_image3Df->GetOrigin(); // might have some problem, since the image has be cast, the original code used uncast image
const itk::Vector<double, 3> resolution3D = m_image3Df->GetSpacing();
typedef InternalImageType::RegionType ImageRegionType3D;
typedef ImageRegionType3D::SizeType SizeType3D;
ImageRegionType3D region3D = m_image3Df->GetBufferedRegion();
SizeType3D size3D = region3D.GetSize();
TransformType::InputPointType isocenter;
// isocenter[0] = m_cx + origin3D[0] + resolution3D[0] * static_cast<double>(size3D[0]) / 2.0;
// isocenter[1] = m_cy + origin3D[1] + resolution3D[1] * static_cast<double>(size3D[1]) / 2.0;
// isocenter[2] = m_cz + origin3D[2] + resolution3D[2] * static_cast<double>(size3D[2]) / 2.0;
int MovingImagePixelNums[3]
{
static_cast<int>(size3D[0]),
static_cast<int>(size3D[1]),
static_cast<int>(size3D[2])
};
double MovingImageResolution[3]{resolution3D[0], resolution3D[1], resolution3D[2]};
// transform->SetCenter(isocenter);
if (m_verbose)
{
std::cout << "3D image size: " << size3D[0] << ", " << size3D[1] << ", " << size3D[2] << std::endl
<< " resolution: " << resolution3D[0] << ", " << resolution3D[1] << ", " << resolution3D[2] << std::endl
<< "Transform: " << transform << std::endl;
}
// Set the origin of the 2D image
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// For correct (perspective) projection of the 3D volume, the 2D
// image needs to be placed at a certain distance (the source-to-
// isocenter distance {scd} ) from the focal point, and the normal
// from the imaging plane to the focal point needs to be specified.
//
// By default, the imaging plane normal is set by default to the
// center of the 2D image but may be modified from this using the
// command line parameters [image1centerX, image1centerY,
// image2centerX, image2centerY].
double origin2D1[3];
double origin2D2[3];
// Note: Two 2D images may have different image sizes and pixel dimensions, although
// scd are the same.
const itk::Vector<double, 3> resolution2D1 = m_image_tmp1->GetSpacing();
const itk::Vector<double, 3> resolution2D2 = m_image_tmp2->GetSpacing();
typedef InternalImageType::RegionType ImageRegionType2D;
typedef ImageRegionType2D::SizeType SizeType2D;
ImageRegionType2D region2D1 = rescaler2D1->GetOutput()->GetBufferedRegion();
ImageRegionType2D region2D2 = rescaler2D2->GetOutput()->GetBufferedRegion();
SizeType2D size2D1 = region2D1.GetSize();
SizeType2D size2D2 = region2D2.GetSize();
origin2D1[0] = - m_RaySource1[0]; // m_o2Dx_1 - resolution2D1[0] * (size2D1[0] - 1.) / 2.;
origin2D1[1] = - m_RaySource1[1]; // m_o2Dy_1 - resolution2D1[1] * (size2D1[1] - 1.) / 2.;
origin2D1[2] = - m_RaySource1[2];
rescaler2D1->GetOutput()->SetOrigin(origin2D1);
origin2D2[0] = - m_RaySource2[0]; // m_o2Dx_1 - resolution2D2[0] * (size2D2[0] - 1.) / 2.;
origin2D2[1] = - m_RaySource2[1]; // m_o2Dy_1 - resolution2D2[1] * (size2D2[1] - 1.) / 2.;
origin2D2[2] = - m_RaySource2[2];
rescaler2D2->GetOutput()->SetOrigin(origin2D2);
// TODO: ROI is set here
registrator->SetFixedImageRegion1(rescaler2D1->GetOutput()->GetBufferedRegion());
registrator->SetFixedImageRegion2(rescaler2D2->GetOutput()->GetBufferedRegion());
if (m_verbose)
{
std::cout << "2D image 1 size: " << size2D1[0] << ", " << size2D1[1] << ", " << size2D1[2] << std::endl
<< " resolution: " << resolution2D1[0] << ", " << resolution2D1[1] << ", " << resolution2D1[2]
<< std::endl
<< " and position: " << origin2D1[0] << ", " << origin2D1[1] << ", " << origin2D1[2] << std::endl
<< "2D image 2 size: " << size2D2[0] << ", " << size2D2[1] << ", " << size2D2[2] << std::endl
<< " resolution: " << resolution2D2[0] << ", " << resolution2D2[1] << ", " << resolution2D2[2]
<< std::endl
<< " and position: " << origin2D2[0] << ", " << origin2D2[1] << ", " << origin2D2[2] << std::endl;
}
// Initialize the ray cast interpolator
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// The ray cast interpolator is used to project the 3D volume. It
// does this by casting rays from the (transformed) focal point to
// each (transformed) pixel coordinate in the 2D image.
//
// In addition a threshold may be specified to ensure that only
// intensities greater than a given value contribute to the
// projected volume. This can be used, for instance, to remove soft
// tissue from projections of CT data and force the registration
// to find a match which aligns bony structures in the images.
// Transform from Imager1 to Internal Ct
auto vtkTransformImager1ToInternalCt = vtkSmartPointer<vtkTransform>::New();
vtkTransformImager1ToInternalCt->PostMultiply();
vtkTransformImager1ToInternalCt->Identity();
vtkTransformImager1ToInternalCt->RotateX(-90);
double translationImager1ToInternalCt[3]{m_RaySource1[0] - resolution3D[0] * static_cast<double>(size3D[0]) / 2.0,
m_RaySource1[1] - resolution3D[2] * static_cast<double>(size3D[2]) / 2.0,
resolution3D[1] * static_cast<double>(size3D[1]) / 2.0};
vtkTransformImager1ToInternalCt->Translate(translationImager1ToInternalCt);
vtkTransformImager1ToInternalCt->Update();
// Calculate transform offset 1
Eigen::Matrix4d eigenMatrixWorldToImager1{m_ArrayMatrixWorldToImager1};
Eigen::Matrix4d eigenMatrixImager1ToInernalCt{vtkTransformImager1ToInternalCt->GetMatrix()->GetData()};
eigenMatrixWorldToImager1.transposeInPlace();
eigenMatrixImager1ToInernalCt.transposeInPlace();
Eigen::Matrix4d eigenMatrixTransformOffset1 = (eigenMatrixWorldToImager1 * eigenMatrixImager1ToInernalCt).inverse();
eigenMatrixTransformOffset1.transposeInPlace();
double arrayTransformOffset1[16];
for (int i = 0; i < 16; i = i + 1)
{
arrayTransformOffset1[i] = double(eigenMatrixTransformOffset1(i));
}
// Transform from Imager2 to Internal Ct
auto vtkTransformImager2ToInternalCt = vtkSmartPointer<vtkTransform>::New();
vtkTransformImager2ToInternalCt->PostMultiply();
vtkTransformImager2ToInternalCt->Identity();
vtkTransformImager2ToInternalCt->RotateX(-90);
double translationImager2ToInternalCt[3]{m_RaySource2[0] - resolution3D[0] * static_cast<double>(size3D[0]) / 2.0,
m_RaySource2[1] - resolution3D[2] * static_cast<double>(size3D[2]) / 2.0,
resolution3D[1] * static_cast<double>(size3D[1]) / 2.0};
vtkTransformImager2ToInternalCt->Translate(translationImager2ToInternalCt);
vtkTransformImager2ToInternalCt->Update();
// Calculate transform offset 2
Eigen::Matrix4d eigenMatrixWorldToImager2{m_ArrayMatrixWorldToImager2};
Eigen::Matrix4d eigenMatrixImager2ToInernalCt{vtkTransformImager2ToInternalCt->GetMatrix()->GetData()};
eigenMatrixWorldToImager2.transposeInPlace();
eigenMatrixImager2ToInernalCt.transposeInPlace();
Eigen::Matrix4d eigenMatrixTransformOffset2 = (eigenMatrixWorldToImager2 * eigenMatrixImager2ToInernalCt).inverse();
eigenMatrixTransformOffset2.transposeInPlace();
double arrayTransformOffset2[16];
for (int i = 0; i < 16; i = i + 1)
{
arrayTransformOffset2[i] = double(eigenMatrixTransformOffset2(i));
}
// 2D Image 1
// interpolator1->SetProjectionAngle(dtr * m_angleDRR1);
interpolator1->SetFocalPointToIsocenterDistance(m_RaySource1[2]);
interpolator1->SetThreshold(m_threshold);
interpolator1->SetTransform(transform);
interpolator1->SetMovingImageSpacing(MovingImageResolution);
interpolator1->SetMovingImagePixelNumbers(MovingImagePixelNums);
interpolator1->SetArrayTransformOffset(arrayTransformOffset1);
interpolator1->Initialize();
// 2D Image 2
// interpolator2->SetProjectionAngle(dtr * m_angleDRR2);
interpolator2->SetFocalPointToIsocenterDistance(m_RaySource2[2]);
interpolator2->SetThreshold(m_threshold);
interpolator2->SetTransform(transform);
interpolator2->SetMovingImageSpacing(MovingImageResolution);
interpolator2->SetMovingImagePixelNumbers(MovingImagePixelNums);
interpolator2->SetArrayTransformOffset(arrayTransformOffset2);
interpolator2->Initialize();
// Set up the transform and start position
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// The registration start position is intialised using the
// transformation parameters.
registrator->SetInitialTransformParameters(transform->GetParameters());
// We wish to minimize the negative normalized correlation similarity measure.
// optimizer->SetMaximize( true ); // for GradientDifferenceTwoImageToOneImageMetric
optimizer->SetMaximize(false); // for NCC Normalized Cross Correlation
if (m_switchOffOptimizer)
{
optimizer->SetMaximumIteration(0);
optimizer->SetMaximumLineIteration(0);
optimizer->SetStepLength(0);
optimizer->SetStepTolerance(10);
optimizer->SetValueTolerance(1);
}
else
{
optimizer->SetMaximumIteration(10);
optimizer->SetMaximumLineIteration(4); // for Powell's method
optimizer->SetStepLength(4);
optimizer->SetStepTolerance(0.02);
optimizer->SetValueTolerance(0.001);
}
// The optimizer weightings are set such that one degree equates to
// one millimeter.
itk::Optimizer::ScalesType weightings(transform->GetNumberOfParameters());
weightings[0] = 1. / dtr;
weightings[1] = 1. / dtr;
weightings[2] = 1. / dtr;
weightings[3] = 1.;
weightings[4] = 1.;
weightings[5] = 1.;
optimizer->SetScales(weightings);
if (m_verbose)
{
optimizer->Print(std::cout);
}
// Create the observers
// ~~~~~~~~~~~~~~~~~~~~
CommandIterationUpdate::Pointer observer = CommandIterationUpdate::New();
optimizer->AddObserver(itk::IterationEvent(), observer);
// Create a timer to record calculation time.
itk::TimeProbesCollectorBase timer;
if (m_verbose)
{
std::cout << "Starting the registration now..." << std::endl;
}
try
{
timer.Start("Registration");
// Start the registration.
registrator->StartRegistration();
timer.Stop("Registration");
}
catch (itk::ExceptionObject & err)
{
std::cout << "ExceptionObject caught !" << std::endl;
std::cout << err << std::endl;
return;
}
typedef RegistrationType::ParametersType ParametersType;
// Error here !!
ParametersType finalParameters = registrator->GetLastTransformParameters();
const double RotationAlongX = finalParameters[0] / dtr; // Convert radian to degree
const double RotationAlongY = finalParameters[1] / dtr;
const double RotationAlongZ = finalParameters[2] / dtr;
const double TranslationAlongX = finalParameters[3];
const double TranslationAlongY = finalParameters[4];
const double TranslationAlongZ = finalParameters[5];
m_RX = RotationAlongX;
m_RY = RotationAlongY;
m_RZ = RotationAlongZ;
m_TX = TranslationAlongX;
m_TY = TranslationAlongY;
m_TZ = TranslationAlongZ;
const int numberOfIterations = optimizer->GetCurrentIteration();
const double bestValue = optimizer->GetValue();
m_metric = bestValue;
std::cout << "Result = " << std::endl;
std::cout << " Rotation Along X = " << RotationAlongX << " deg" << std::endl;
std::cout << " Rotation Along Y = " << RotationAlongY << " deg" << std::endl;
std::cout << " Rotation Along Z = " << RotationAlongZ << " deg" << std::endl;
std::cout << " Translation X = " << TranslationAlongX << " mm" << std::endl;
std::cout << " Translation Y = " << TranslationAlongY << " mm" << std::endl;
std::cout << " Translation Z = " << TranslationAlongZ << " mm" << std::endl;
std::cout << " Number Of Iterations = " << numberOfIterations << std::endl;
std::cout << " Metric value = " << bestValue << std::endl;
timer.Report();
}
void VolumeRegistrator::SetRaySource1(double array[3])
{
for (int i = 0; i < 3; i = i + 1)
{
m_RaySource1[i] = array[i];
}
}
void VolumeRegistrator::SetRaySource2(double array[3])
{
for (int i = 0; i < 3; i = i + 1)
{
m_RaySource2[i] = array[i];
}
}
void VolumeRegistrator::SetArrayMatrixWorldToImager1(double array[16])
{
for (int i = 0; i < 16; i = i + 1)
{
m_ArrayMatrixWorldToImager1[i] = array[i];
}
}
void VolumeRegistrator::SetArrayMatrixWorldToImager2(double array[16])
{
for (int i = 0; i < 16; i = i + 1)
{
m_ArrayMatrixWorldToImager2[i] = array[i];
}
}
void VolumeRegistrator::SetArrayMatrixWorldToCt(double array[16])
{
for (int i = 0; i < 16; i = i + 1)
{
m_ArrayMatrixWorldToCt[i] = array[i];
}
}
| 35.068111
| 158
| 0.724155
|
zhaomengxiao
|
85a251844041754e9c15519365166a9df8cb8587
| 1,708
|
hpp
|
C++
|
nginx/third/ngxpp/NgxThread.hpp
|
lanru/annotated_nginx_wlh
|
8eac03dcf5cbf899996d68c01a7e586212e9059a
|
[
"BSD-2-Clause"
] | 144
|
2015-10-23T06:24:51.000Z
|
2022-01-07T07:24:13.000Z
|
nginx/third/ngxpp/NgxThread.hpp
|
lanru/annotated_nginx_wlh
|
8eac03dcf5cbf899996d68c01a7e586212e9059a
|
[
"BSD-2-Clause"
] | 7
|
2016-08-25T13:48:25.000Z
|
2020-06-08T06:53:05.000Z
|
nginx/third/ngxpp/NgxThread.hpp
|
lanru/annotated_nginx_wlh
|
8eac03dcf5cbf899996d68c01a7e586212e9059a
|
[
"BSD-2-Clause"
] | 85
|
2015-11-01T15:11:08.000Z
|
2021-11-30T02:39:57.000Z
|
// Copyright (c) 2017
// Author: Chrono Law
#ifndef _NGX_THREAD_HPP
#define _NGX_THREAD_HPP
#include "NgxPool.hpp"
#include "NgxEvent.hpp"
template<typename T>
class NgxThreadTask final : public NgxWrapper<ngx_thread_task_t>
{
public:
typedef NgxWrapper<ngx_thread_task_t> super_type;
typedef NgxThreadTask this_type;
typedef T task_ctx_type;
public:
NgxThreadTask(ngx_thread_task_t* t) : super_type(t)
{}
~NgxThreadTask() = default;
public:
T* ctx() const
{
return reinterpret_cast<T*>(get()->ctx);
}
template<typename F>
void handler(F f) const
{
if(!get()->handler)
{
get()->handler = f;
}
}
public:
NgxEvent event() const
{
return &get()->event;
}
public:
static ngx_thread_task_t* create(const NgxPool& pool)
{
auto p = pool.thread_task<T>();
return p;
}
};
class NgxThreadPool final : public NgxWrapper<ngx_thread_pool_t>
{
public:
typedef NgxWrapper<ngx_thread_pool_t> super_type;
typedef NgxThreadPool this_type;
public:
NgxThreadPool(ngx_thread_pool_t* p) : super_type(p)
{}
NgxThreadPool(ngx_str_t name) : super_type(acquire(name))
{}
~NgxThreadPool() = default;
public:
void post(ngx_thread_task_t* task) const
{
auto rc = ngx_thread_task_post(get(), task);
NgxException::require(rc);
}
public:
static ngx_thread_pool_t* acquire(ngx_str_t& name)
{
auto p = ngx_thread_pool_get((ngx_cycle_t *) ngx_cycle, &name);
NgxException::require(p);
return p;
}
};
#endif //_NGX_THREAD_HPP
| 21.08642
| 71
| 0.617096
|
lanru
|
85ad7eb7a24e786bf63ece3ada719c5086f94818
| 4,179
|
cpp
|
C++
|
interfaces/matlab/src/hash.cpp
|
hcl3210/opencv
|
b34b1c3540716a3dadfd2b9e3bbc4253774c636d
|
[
"BSD-3-Clause"
] | 1
|
2016-05-09T11:42:00.000Z
|
2016-05-09T11:42:00.000Z
|
interfaces/matlab/src/hash.cpp
|
hcl3210/opencv
|
b34b1c3540716a3dadfd2b9e3bbc4253774c636d
|
[
"BSD-3-Clause"
] | null | null | null |
interfaces/matlab/src/hash.cpp
|
hcl3210/opencv
|
b34b1c3540716a3dadfd2b9e3bbc4253774c636d
|
[
"BSD-3-Clause"
] | null | null | null |
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of Intel Corporation may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#include <string.h>
#include "hash.h"
#define HASHTABLE_SIZE 2*MAP_SIZE
typedef struct _HashEntry
{
unsigned hash;
int len;
struct _HashEntry* next;
MapEntry* mapentry;
} HashEntry;
HashEntry keyword_storage[MAP_SIZE];
HashEntry* keyword_table[HASHTABLE_SIZE];
static int hash_init = 0;
//-----------------------------------------------------------------------------
unsigned calc_hash( const char* text, int len )
{
int j, shift = 0;
unsigned hash = len;
for( j = 0; j < len; j++ )
{
shift += 11;
if( shift >= 32 ) shift -= 32;
hash ^= ((unsigned char*)text)[j] << shift;
}
return hash;
}
void InitHashTable( MapEntry* pMap )
{
if( !hash_init )
{
int i;
int count[HASHTABLE_SIZE];
memset( count, 0, sizeof(count));
memset( keyword_table, 0, sizeof( keyword_table));
for( i = 0; pMap[i].element != 0; i++ )
{
int idx, len;
keyword_storage[i].len = len = strlen( pMap[i].element );
keyword_storage[i].hash = calc_hash( pMap[i].element, len );
//keyword_storage[i].mapentry->element = pMap[i].element;
//keyword_storage[i].mapentry->image = pMap[i].image;
keyword_storage[i].mapentry = pMap + i;
idx = keyword_storage[i].hash % HASHTABLE_SIZE;
keyword_storage[i].next = keyword_table[idx];
keyword_table[idx] = keyword_storage + i;
count[idx]++;
}
hash_init = 1;
}
}
MapEntry* FindMapEntry(const char* pccStr)
{
int len;
unsigned int hash;
int idx;
HashEntry* entry;
len = strlen(pccStr);
hash = calc_hash( pccStr, len );
idx = hash % HASHTABLE_SIZE;
entry = keyword_table[idx];
while( entry )
{
if( entry->hash == hash &&
entry->len == len &&
!strncmp( entry->mapentry->element, pccStr, len )) break;
entry = entry->next;
}
return (entry ? entry->mapentry : 0);
}
//-----------------------------------------------------------------------------
| 33.432
| 90
| 0.618808
|
hcl3210
|
85aec8009d9f084abcc1309d1b9aa06b27cc4bba
| 11,756
|
cpp
|
C++
|
midori/src/midori/codegen.cpp
|
Raekye/hmmm
|
74dbbe46357918b1f3c9b2548c340b0050ce7bfe
|
[
"MIT"
] | 1
|
2016-06-26T06:16:51.000Z
|
2016-06-26T06:16:51.000Z
|
midori/src/midori/codegen.cpp
|
Raekye/hmmm
|
74dbbe46357918b1f3c9b2548c340b0050ce7bfe
|
[
"MIT"
] | 1
|
2019-08-15T07:29:19.000Z
|
2019-08-16T12:17:10.000Z
|
midori/src/midori/codegen.cpp
|
Raekye/hmmm
|
74dbbe46357918b1f3c9b2548c340b0050ce7bfe
|
[
"MIT"
] | null | null | null |
#include "codegen.h"
#include "types.h"
#include "type_checker.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Verifier.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Bitcode/BitcodeWriter.h"
#include "llvm/ExecutionEngine/ExecutionEngine.h"
#include "llvm/ExecutionEngine/GenericValue.h"
#include "llvm/ExecutionEngine/OrcMCJITReplacement.h"
#include "llvm/ExecutionEngine/MCJIT.h"
//#include "llvm/ExecutionEngine/Interpreter.h"
#include <tuple>
#include <utility>
#include <cassert>
CodeGen::CodeGen() : builder(this->context), module(new llvm::Module("midori", this->context)), type_manager(&(this->context)) {
llvm::BasicBlock::Create(this->context, "main");
}
void CodeGen::process(LangAST* program) {
TypeChecker tc(&(this->type_manager));
program->accept(&tc);
program->accept(this);
llvm::verifyModule(*(this->module), &(llvm::errs()));
}
std::error_code CodeGen::dump(std::string path) {
std::error_code ec;
llvm::raw_fd_ostream o(path, ec, llvm::sys::fs::OpenFlags::F_None);
llvm::WriteBitcodeToFile(this->module.get(), o);
return ec;
}
void CodeGen::run() {
llvm::Function* f = this->get_function("main");
llvm::ExecutionEngine* ee = llvm::EngineBuilder(std::move(this->module)).create();
ee->runFunction(f, {});
}
void CodeGen::visit(LangASTBasicType* v) {
(void) v;
}
void CodeGen::visit(LangASTPointerType* v) {
(void) v;
}
void CodeGen::visit(LangASTArrayType* v) {
(void) v;
}
void CodeGen::visit(LangASTBlock* v) {
this->push_scope();
for (std::unique_ptr<LangAST> const& l : v->lines) {
l->accept(this);
}
this->pop_scope();
this->ret = nullptr;
}
void CodeGen::visit(LangASTLIdent* v) {
LangASTLIdent::NameOrIndex& ni = v->parts.at(0);
assert(ni.index == nullptr);
assert(ni.name.length() > 0);
std::string name = ni.name;
Variable var = this->named_value(ni.name);
for (size_t i = 1; i < v->parts.size(); i++) {
LangASTLIdent::NameOrIndex& ni2 = v->parts.at(i);
if (ni2.index == nullptr) {
assert(ni2.name.length() > 0);
name += "." + ni2.name;
StructType* st = dynamic_cast<StructType*>(var.type);
assert(st != nullptr);
StructType::Field f = st->field(ni2.name);
assert(f.type != nullptr);
assert(f.index >= 0);
var.type = f.type;
var.value = this->builder.CreateStructGEP(st->llvm_type, var.value, f.index, name);
} else {
assert(ni2.name.length() == 0);
name += "[]";
ArrayType* at = dynamic_cast<ArrayType*>(var.type);
assert(at != nullptr);
ni2.index->accept(this);
llvm::Value* index = this->ret;
var.type = at->base;
var.value = this->builder.CreateGEP(at->llvm_type, var.value, index, name);
}
}
this->ret = var.value;
}
void CodeGen::visit(LangASTRIdent* v) {
v->ident->accept(this);
this->ret = this->builder.CreateLoad(this->ret, "load");
}
void CodeGen::visit(LangASTDecl* v) {
llvm::Type* t = this->type_manager.get(v->decl_type->name)->llvm_type;
llvm::Value* x = this->builder.CreateAlloca(t, nullptr, v->name);
this->set_named_value(v->name, Variable(v->type, x));
this->ret = x;
}
void CodeGen::visit(LangASTAssignment* v) {
v->left->accept(this);
llvm::Value* lhs = this->ret;
v->right->accept(this);
llvm::Value* rhs = this->ret;
this->builder.CreateStore(rhs, lhs);
// this->ret = rhs;
}
void CodeGen::visit(LangASTUnOp* v) {
v->expr->accept(this);
llvm::Value* expr = this->ret;
switch (v->op) {
case LangASTUnOp::Op::MINUS:
this->ret = this->builder.CreateNeg(expr, "negtmp");
break;
case LangASTUnOp::Op::NOT:
this->ret = this->builder.CreateNot(expr, "nottmp");
break;
default:
this->ret = nullptr;
}
}
void CodeGen::visit(LangASTBinOp* v) {
v->left->accept(this);
llvm::Value* lhs = this->ret;
v->right->accept(this);
llvm::Value* rhs = this->ret;
llvm::Type* type = lhs->getType();
this->ret = nullptr;
switch (v->op) {
case LangASTBinOp::Op::PLUS:
if (type->isIntegerTy()) {
this->ret = this->builder.CreateAdd(lhs, rhs, "addtmp");
} else if (type->isFloatingPointTy()) {
this->ret = this->builder.CreateFAdd(lhs, rhs, "addftmp");
}
break;
case LangASTBinOp::Op::MINUS:
if (type->isIntegerTy()) {
this->ret = this->builder.CreateSub(lhs, rhs, "subtmp");
} else if (type->isFloatingPointTy()) {
this->ret = this->builder.CreateFSub(lhs, rhs, "subftmp");
}
break;
case LangASTBinOp::Op::STAR:
if (type->isIntegerTy()) {
this->ret = this->builder.CreateMul(lhs, rhs, "multmp");
} else if (type->isFloatingPointTy()) {
this->ret = this->builder.CreateFMul(lhs, rhs, "mulftmp");
}
break;
case LangASTBinOp::Op::SLASH:
if (type->isIntegerTy()) {
this->ret = this->builder.CreateSDiv(lhs, rhs, "divtmp");
} else if (type->isFloatingPointTy()) {
this->ret = this->builder.CreateFDiv(lhs, rhs, "divftmp");
}
break;
case LangASTBinOp::Op::EQ:
if (type->isIntegerTy()) {
this->ret = this->builder.CreateICmpEQ(lhs, rhs, "eqtmp");
} else if (type->isFloatingPointTy()) {
this->ret = this->builder.CreateFCmpOEQ(lhs, rhs, "eqftmp");
}
break;
case LangASTBinOp::Op::NE:
if (type->isIntegerTy()) {
this->ret = this->builder.CreateICmpNE(lhs, rhs, "netmp");
} else if (type->isFloatingPointTy()) {
this->ret = this->builder.CreateFCmpONE(lhs, rhs, "neftmp");
}
break;
case LangASTBinOp::Op::LT:
if (type->isIntegerTy()) {
this->ret = this->builder.CreateICmpSLT(lhs, rhs, "lttmp");
} else if (type->isFloatingPointTy()) {
this->ret = this->builder.CreateFCmpOLT(lhs, rhs, "ltftmp");
}
break;
case LangASTBinOp::Op::GT:
if (type->isIntegerTy()) {
this->ret = this->builder.CreateICmpSGT(lhs, rhs, "gttmp");
} else if (type->isFloatingPointTy()) {
this->ret = this->builder.CreateFCmpOGT(lhs, rhs, "gtftmp");
}
break;
case LangASTBinOp::Op::LE:
if (type->isIntegerTy()) {
this->ret = this->builder.CreateICmpSGE(lhs, rhs, "getmp");
} else if (type->isFloatingPointTy()) {
this->ret = this->builder.CreateFCmpOGE(lhs, rhs, "geftmp");
}
break;
case LangASTBinOp::Op::GE:
if (type->isIntegerTy()) {
this->ret = this->builder.CreateICmpSLE(lhs, rhs, "letmp");
} else if (type->isFloatingPointTy()) {
this->ret = this->builder.CreateFCmpOLE(lhs, rhs, "leftmp");
}
break;
default:
this->ret = nullptr;
}
}
void CodeGen::visit(LangASTInt* v) {
Type* t = v->type;
if ((t == this->type_manager.get("Float")) || (t == this->type_manager.get("Double"))) {
this->ret = llvm::ConstantFP::get(t->llvm_type, (double) v->value);
return;
}
this->ret = llvm::ConstantInt::get(t->llvm_type, v->value, true);
}
void CodeGen::visit(LangASTDouble* v) {
this->ret = llvm::ConstantFP::get(v->type->llvm_type, v->value);
}
void CodeGen::visit(LangASTIf* v) {
this->push_scope();
v->predicate->accept(this);
llvm::Value* cond = this->ret;
llvm::Function* f = this->builder.GetInsertBlock()->getParent();
llvm::BasicBlock* then_bb = llvm::BasicBlock::Create(this->context, "then", f);
llvm::BasicBlock* else_bb = llvm::BasicBlock::Create(this->context, "else");
llvm::BasicBlock* merge_bb = llvm::BasicBlock::Create(this->context, "ifcont");
int x = 0;
this->builder.CreateCondBr(cond, then_bb, else_bb);
this->builder.SetInsertPoint(then_bb);
v->block_if->accept(this);
if (this->builder.GetInsertBlock()->getTerminator() == nullptr) {
this->builder.CreateBr(merge_bb);
x++;
}
f->getBasicBlockList().push_back(else_bb);
this->builder.SetInsertPoint(else_bb);
if (v->block_else != nullptr) {
v->block_else->accept(this);
}
if (this->builder.GetInsertBlock()->getTerminator() == nullptr) {
this->builder.CreateBr(merge_bb);
x++;
}
if (x > 0) {
f->getBasicBlockList().push_back(merge_bb);
this->builder.SetInsertPoint(merge_bb);
}
this->pop_scope();
this->ret = nullptr;
}
void CodeGen::visit(LangASTWhile* v) {
this->push_scope();
llvm::Function* f = this->builder.GetInsertBlock()->getParent();
llvm::BasicBlock* cond_bb = llvm::BasicBlock::Create(this->context, "cond", f);
llvm::BasicBlock* loop_bb = llvm::BasicBlock::Create(this->context, "loop");
llvm::BasicBlock* after_bb = llvm::BasicBlock::Create(this->context, "after");
this->builder.CreateBr(cond_bb);
this->builder.SetInsertPoint(cond_bb);
v->predicate->accept(this);
llvm::Value* cond = this->ret;
this->builder.CreateCondBr(cond, loop_bb, after_bb);
f->getBasicBlockList().push_back(loop_bb);
this->builder.SetInsertPoint(loop_bb);
v->block->accept(this);
if (this->builder.GetInsertBlock()->getTerminator() == nullptr) {
this->builder.CreateBr(cond_bb);
}
f->getBasicBlockList().push_back(after_bb);
this->builder.SetInsertPoint(after_bb);
this->pop_scope();
this->ret = nullptr;
}
void CodeGen::visit(LangASTPrototype* v) {
std::vector<llvm::Type*> arg_types;
for (std::unique_ptr<LangASTDecl> const& a : v->args) {
arg_types.push_back(a->type->llvm_type);
}
llvm::FunctionType* ft = llvm::FunctionType::get(this->type_manager.get(v->return_type->name)->llvm_type, arg_types, false);
llvm::Function* f = llvm::Function::Create(ft, llvm::Function::ExternalLinkage, v->name, this->module.get());
Int i = 0;
for (llvm::Argument& a : f->args()) {
a.setName(v->args.at(i)->name);
i++;
}
this->ret = f;
}
void CodeGen::visit(LangASTFunction* v) {
this->push_scope();
llvm::BasicBlock* old = this->builder.GetInsertBlock();
v->proto->accept(this);
llvm::Function* f = llvm::dyn_cast<llvm::Function>(this->ret);
llvm::BasicBlock* bb = llvm::BasicBlock::Create(this->context, "entry", f);
this->builder.SetInsertPoint(bb);
Int i = 0;
for (llvm::Argument& a : f->args()) {
v->proto->args.at(i)->accept(this);
llvm::Value* alloc = this->ret;
this->builder.CreateStore(&a, alloc);
i++;
}
v->body->accept(this);
if (this->builder.GetInsertBlock()->getTerminator() == nullptr) {
if (v->proto->return_type->name == this->type_manager.void_type()->name) {
this->builder.CreateRetVoid();
}
}
f->print(llvm::errs());
llvm::verifyFunction(*f, &(llvm::errs()));
this->pop_scope();
this->builder.SetInsertPoint(old);
this->ret = f;
}
void CodeGen::visit(LangASTReturn* v) {
if (v->val == nullptr) {
this->ret = this->builder.CreateRetVoid();
return;
}
v->val->accept(this);
this->ret = this->builder.CreateRet(this->ret);
}
void CodeGen::visit(LangASTCall* v) {
llvm::Function* f = this->get_function(v->function);
if (f->arg_size() != v->args.size()) {
this->ret = nullptr;
return;
}
std::vector<llvm::Value*> args;
for (std::unique_ptr<LangASTExpression> const& a : v->args) {
a->accept(this);
args.push_back(this->ret);
}
if (f->getReturnType() == this->type_manager.void_type()->llvm_type) {
this->ret = this->builder.CreateCall(f, args);
return;
}
this->ret = this->builder.CreateCall(f, args, "calltmp");
}
void CodeGen::visit(LangASTClassDef* v) {
(void) v;
}
void CodeGen::push_scope() {
this->frames.emplace_front();
}
void CodeGen::pop_scope() {
this->frames.pop_front();
}
CodeGen::Variable CodeGen::named_value(std::string s) {
for (std::map<std::string, Variable> const& f : this->frames) {
std::map<std::string, Variable>::const_iterator it = f.find(s);
if (it != f.end()) {
return it->second;
}
}
return Variable(nullptr, nullptr);
}
void CodeGen::set_named_value(std::string s, Variable v) {
std::map<std::string, Variable>& m = this->frames.front();
std::map<std::string, Variable>::iterator it;
bool inserted;
std::tie(it, inserted) = m.emplace(std::piecewise_construct, std::forward_as_tuple(s), std::forward_as_tuple(v));
assert(inserted);
}
llvm::Function* CodeGen::get_function(std::string name) {
if (llvm::Function* f = this->module->getFunction(name)) {
return f;
}
return nullptr;
}
| 29.39
| 128
| 0.668255
|
Raekye
|
85c6e98ea12ac77490c0d5aa8060aa546f1204f7
| 87
|
cc
|
C++
|
code/utils/fastio.cc
|
Zeldacrafter/CompProg
|
5367583f45b6fe30c4c84f3ae81accf14f8f7fd3
|
[
"Unlicense"
] | 4
|
2020-02-06T15:44:57.000Z
|
2020-12-21T03:51:21.000Z
|
code/utils/fastio.cc
|
Zeldacrafter/CompProg
|
5367583f45b6fe30c4c84f3ae81accf14f8f7fd3
|
[
"Unlicense"
] | null | null | null |
code/utils/fastio.cc
|
Zeldacrafter/CompProg
|
5367583f45b6fe30c4c84f3ae81accf14f8f7fd3
|
[
"Unlicense"
] | null | null | null |
#include "../template.hh"
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
}
| 14.5
| 31
| 0.632184
|
Zeldacrafter
|
85d418de98e3578d322f9675da6e78d94b9aa496
| 12,272
|
cpp
|
C++
|
Tests/GeometryShop/stencilTestbed/exec/dirichletTest.cpp
|
malvarado27/Amrex
|
8d5c7a37695e7dc899386bfd1f6ac28221984976
|
[
"BSD-3-Clause-LBNL"
] | 1
|
2021-05-20T13:04:05.000Z
|
2021-05-20T13:04:05.000Z
|
Tests/GeometryShop/stencilTestbed/exec/dirichletTest.cpp
|
malvarado27/Amrex
|
8d5c7a37695e7dc899386bfd1f6ac28221984976
|
[
"BSD-3-Clause-LBNL"
] | null | null | null |
Tests/GeometryShop/stencilTestbed/exec/dirichletTest.cpp
|
malvarado27/Amrex
|
8d5c7a37695e7dc899386bfd1f6ac28221984976
|
[
"BSD-3-Clause-LBNL"
] | null | null | null |
#include <cmath>
#include "AMReX_GeometryShop.H"
#include "AMReX_BoxIterator.H"
#include "AMReX_ParmParse.H"
#include "AMReX_RealVect.H"
#include "AMReX_SphereIF.H"
#include "AMReX_EBCellFAB.H"
#include "AMReX_VolIndex.H"
#include "AMReX_FaceIndex.H"
#include "AMReX_TestbedUtil.H"
#include <AMReX_ParallelDescriptor.H>
#include <AMReX_Utility.H>
#include "lapl_nd_F.H"
#include <AMReX_MultiFab.H>
#include <AMReX_Print.H>
#include <AMReX_ArrayLim.H>
#include <map>
#include <fstream>
#include "dirichletTest_F.H"
using namespace amrex;
using std::cout;
using std::endl;
////////////
//gets regular grid stencil for kappa*div(grad phi) with neumann eb and domamin bcs.
void getRegularStencil(VoFStencil & a_stencil,
const IntVect & a_iv,
const Box & a_domain,
const Real & a_dx)
{
// Assumes data outside domain lives at cell center as is correct
a_stencil.clear();
Real dxinvsq = 1.0/a_dx/a_dx;
for(int idir = 0; idir < SpaceDim; idir++)
{
IntVect ivlo = a_iv - BASISV(idir);
IntVect ivhi = a_iv + BASISV(idir);
a_stencil.add(VolIndex(ivlo, 0), dxinvsq);
a_stencil.add(VolIndex(ivhi, 0), dxinvsq);
}
a_stencil.add(VolIndex(a_iv, 0), -2*SpaceDim*dxinvsq);
}
void getFluxStencil(VoFStencil & a_stencil,
const FaceIndex & a_face,
const IrregNode & a_node,
const int & a_index,
const BaseFab<int> & a_regIrregCovered,
const Box & a_domain,
const Real & a_dx)
{
FaceStencil interpSten = TestbedUtil::getInterpStencil(a_face,
a_node, a_index, a_regIrregCovered,
a_domain, a_dx);
a_stencil.clear();
for (int isten = 0; isten < interpSten.size(); isten++)
{
const FaceIndex& face = interpSten.face(isten);
const Real& weight = interpSten.weight(isten);
VoFStencil faceCentSten;
if(!face.isBoundary())
{
faceCentSten.add(face.getVoF(Side::Hi), 1.0/a_dx, 0);
faceCentSten.add(face.getVoF(Side::Lo), -1.0/a_dx, 0);
}
else
{
//no flux at boundaries for this test
}
faceCentSten *= weight;
a_stencil += faceCentSten;
}
}
////////////
void getIrregularStencil(VoFStencil & a_stencil,
const IrregNode & a_node,
const BaseFab<int> & a_regIrregCovered,
const Box & a_domain,
const Real & a_dx)
{
//gets stencil for kappa*div(grad phi) with neumann eb and domamin bcs.
a_stencil.clear();
const IntVect& iv = a_node.m_cell;
for (int idir = 0; idir < SpaceDim; idir++)
{
for (SideIterator sit; sit.ok(); ++sit)
{
int index = IrregNode::index(idir, sit());
const std::vector<int>& arcs = a_node.m_arc[index];
//this checks for both boundary faces and covered cells
if((arcs.size() > 0) && (arcs[0] >= 0))
{
int isign = sign(sit());
//assuming no multi-valued stuff here
IntVect ivneigh = iv + isign*BASISV(idir);
FaceIndex face(VolIndex(iv, 0), VolIndex(ivneigh, 0));
VoFStencil fluxStencil;
getFluxStencil(fluxStencil, face, a_node, index, a_regIrregCovered, a_domain, a_dx);
Real areaFrac = a_node.m_areaFrac[index][0];
fluxStencil *= Real(isign)*areaFrac/a_dx;
a_stencil += fluxStencil;
}
}
}
}
////////////
void
defineGeometry(BaseFab<int> & a_regIrregCovered,
Vector<IrregNode> & a_nodes,
const Real & a_radius,
const RealVect & a_center,
const Box & a_domain,
const Real & a_dx)
{
//inside regular tells whether domain is inside or outside the sphere
//bool insideRegular = true;
bool insideRegular = false;
SphereIF sphere(a_radius, a_center, insideRegular);
int verbosity = 0;
ParmParse pp;
pp.get("verbosity", verbosity);
GeometryShop gshop(sphere, verbosity);
BaseFab<int> regIrregCovered;
std::vector<IrregNode> nodes;
Box validRegion = a_domain;
Box ghostRegion = a_domain; //whole domain so ghosting does not matter
RealVect origin = RealVect::Zero;
gshop.fillGraph(a_regIrregCovered, a_nodes, validRegion, ghostRegion, a_domain, origin, a_dx);
}
void getStencils(BaseFab<VoFStencil> & a_stencil,
const BaseFab<int> & a_regIrregCovered,
const std::vector<IrregNode> & a_nodes,
const Box & a_domain,
const Real & a_dx)
{
a_stencil.resize(a_domain, 1);
for(BoxIterator boxit(a_domain); boxit.ok(); ++boxit)
{
const IntVect& iv = boxit();
VoFStencil pointSten;
if(a_regIrregCovered(iv, 0) == 1)
{
//regular cells are set to 1
getRegularStencil(pointSten, iv, a_domain, a_dx);
}
else if (a_regIrregCovered(iv, 0) == -1)
{
//coveredCells do not get a stencil
}
else if(a_regIrregCovered(iv, 0) == 0)
{
//remaining cells are irregular--doing those separately.
}
else
{
Abort("bogus value in regirregcovered");
}
a_stencil(iv, 0) = pointSten;
}
for(int ivec = 0; ivec < a_nodes.size(); ivec++)
{
const IntVect& iv = a_nodes[ivec].m_cell;
if(a_regIrregCovered(iv, 0) != 0)
{
Abort("regirregcovered and nodes inconsistent");
}
VoFStencil pointSten;
getIrregularStencil(pointSten, a_nodes[ivec], a_regIrregCovered, a_domain, a_dx);
a_stencil(iv, 0) = pointSten;
}
}
struct FaceData
{
FaceData(const RealVect& a_centroid,
Real a_aperature) : m_centroid(a_centroid), m_aperature(a_aperature) {}
FaceData() {}
RealVect m_centroid;
Real m_aperature;
};
struct EBBndryData
{
EBBndryData(const RealVect& a_normal,
const RealVect& a_bndry_centroid,
Real a_value)
: m_normal(a_normal), m_bndry_centroid(a_bndry_centroid), m_value(a_value) {}
EBBndryData() {}
RealVect m_normal, m_bndry_centroid;
Real m_value;
};
void
applyStencilAllFortran(EBCellFAB & a_dst,
const EBCellFAB & a_src,
const BaseFab<VoFStencil> & a_stencil,
const BaseFab<int> & a_regIrregCovered,
const std::vector<IrregNode> & a_nodes,
const Box & a_domain,
Real a_dx)
{
BoxArray ba(a_domain);
DistributionMapping dm(ba);
MultiFab srcMF(ba,dm,1,1);
IntVect tilesize(AMREX_D_DECL(10240,8,32));
int num_tiles = srcMF.getTileArray(tilesize)->tileArray.size();
std::vector<std::vector<int> > tileNodes(num_tiles);
#ifdef _OPENMP
#pragma omp parallel
#endif
for (MFIter mfi(srcMF,tilesize); mfi.isValid(); ++mfi)
{
const Box& tbx = mfi.tilebox();
for (int n=0; n<a_nodes.size(); ++n)
{
const IrregNode& node = a_nodes[n];
const IntVect& iv = node.m_cell;
if (tbx.contains(iv))
{
tileNodes[mfi.tileIndex()].push_back(n);
}
}
}
std::vector<std::vector<Stencil> > stencilData(num_tiles);
std::vector<std::vector<Real> > stencilBData(num_tiles);
std::vector<std::vector<IntVect> > stencilBase(num_tiles);
std::cout << "IntVect is standard layout? " << std::is_standard_layout<IntVect>::value << " size = " << sizeof(IntVect) << '\n';
std::cout << "Stencil is standard layout? " << std::is_standard_layout<Stencil>::value << " size = " << sizeof(Stencil) << '\n';
std::cout << "RealVect is standard layout? " << std::is_standard_layout<RealVect>::value << " size = " << sizeof(RealVect) << '\n';
std::vector<RealVect> bndry_normals;
std::vector<RealVect> bndry_centroids;
std::vector<IntVect> ivs;
std::vector<Real> bndry_values;
std::vector<Real> gtmp;
// Build stencils
#ifdef _OPENMP
#pragma omp parallel
#endif
for (MFIter mfi(srcMF,tilesize); mfi.isValid(); ++mfi)
{
int tid = mfi.tileIndex();
int num_tileNodes = tileNodes[tid].size();
if (num_tileNodes > 0)
{
stencilData[tid].resize(num_tileNodes);
stencilBData[tid].resize(num_tileNodes);
stencilBase[tid].resize(num_tileNodes);
bndry_normals.resize(num_tileNodes);
bndry_centroids.resize(num_tileNodes);
ivs.resize(num_tileNodes);
bndry_values.resize(num_tileNodes);
for (int n=0; n<num_tileNodes; ++n)
{
const IrregNode& node = a_nodes[tileNodes[tid][n]];
RealVect& normal = bndry_normals[n];
normal = RealVect(AMREX_D_DECL(0,0,0));
for (int idir=0; idir<SpaceDim; ++idir)
{
for (SideIterator sit; sit.ok(); ++sit)
{
int index = IrregNode::index(idir, sit());
const std::vector<int>& arcs = node.m_arc[index];
if((arcs.size() > 0) && (arcs[0] >= 0))
{
normal[idir] += sign(sit()) * node.m_areaFrac[index][0];
}
}
}
bndry_centroids[n] = node.m_bndryCentroid;
ivs[n] = node.m_cell;
bndry_values[n] = 1;
}
get_bndry_grad_stencil(&(stencilData[tid][0]), &(stencilBData[tid][0]), &(stencilBase[tid][0]),
&(bndry_normals[0]), &(bndry_centroids[0]), &(ivs[0]), &num_tileNodes, &a_dx);
gtmp.resize(num_tileNodes);
const BaseFab<Real> & rega_src = a_src.getSingleValuedFAB();
apply_bndry_grad_stencil(&(gtmp[0]), &(bndry_values[0]),
BL_TO_FORTRAN_N(rega_src,0),
&(stencilData[tid][0]), &(stencilBData[tid][0]), &(stencilBase[tid][0]),
&num_tileNodes);
}
}
}
int testStuff()
{
int eekflag = 0;
Real radius = 0.5;
Real domlen = 1;
std::vector<Real> centervec(SpaceDim);
std::vector<int> ncellsvec(SpaceDim);
ParmParse pp;
pp.getarr( "n_cell" , ncellsvec, 0, SpaceDim);
pp.get( "sphere_radius", radius);
pp.getarr("sphere_center", centervec, 0, SpaceDim);
pp.get("domain_length", domlen); //
IntVect ivlo = IntVect::TheZeroVector();
IntVect ivhi;
for(int idir = 0; idir < SpaceDim; idir++)
{
ivhi[idir] = ncellsvec[idir] - 1;
}
Box domain(ivlo, ivhi);
std::vector<Real> dx(SpaceDim);
for (int idir=0; idir<SpaceDim; ++idir)
{
dx[idir] = domlen/ncellsvec[idir];
}
Vector<Real> probLo(SpaceDim,0);
BaseFab<int> regIrregCovered;
Vector<IrregNode> nodes;
RealVect center;
for(int idir = 0; idir < SpaceDim; idir++)
{
center[idir] = centervec[idir];
}
amrex::Print() << "Define geometry\n";
BL_PROFILE_VAR("define_geometry",dg);
defineGeometry(regIrregCovered, nodes, radius, center, domain, dx[0]);
BL_PROFILE_VAR_STOP(dg);
#if 0
EBCellFAB src(grow(domain, 1), 1); //for a ghost cell
BL_PROFILE_VAR("init_data",init);
BaseFab<Real> & regsrc = src.getSingleValuedFAB();
init_phi(BL_TO_FORTRAN_N(regsrc,0),
src.box().loVect(), src.box().hiVect(),
&(probLo[0]), &(dx[0]));
BL_PROFILE_VAR_STOP(init);
EBCellFAB dst(domain, 1);
BaseFab<VoFStencil> stencils;
amrex::Print() << "Getting stencils\n";
BL_PROFILE_VAR("getting_stencils",gs);
getStencils(stencils, regIrregCovered, nodes, domain, dx[0]);
BL_PROFILE_VAR_STOP(gs);
amrex::Print() << "Fortran everywhere\n";
BL_PROFILE_VAR("fortran_everywhere",fe);
applyStencilAllFortran(dst, src, stencils, regIrregCovered, nodes, domain, dx[0]);
BL_PROFILE_VAR_STOP(fe);
#endif
return eekflag;
}
int
main(int argc,char **argv)
{
amrex::Initialize(argc,argv);
{
BL_PROFILE_VAR("main()", pmain);
int eekflag = testStuff();
if (eekflag != 0)
{
cout << "non zero eek detected = " << eekflag << endl;
cout << "sphere test failed" << endl;
}
else
{
cout << "stencil test passed" << endl;
}
BL_PROFILE_VAR_STOP(pmain);
}
amrex::Finalize();
return 0;
}
| 30.376238
| 134
| 0.597376
|
malvarado27
|
85d835266d81d732ebc3afe51727c027f702ff1c
| 445
|
cpp
|
C++
|
10799.cpp
|
jaemin2682/BAEKJOON_ONLINE_JUDGE
|
0d5c6907baee61e1fabdbcd96ea473079a9475ed
|
[
"MIT"
] | null | null | null |
10799.cpp
|
jaemin2682/BAEKJOON_ONLINE_JUDGE
|
0d5c6907baee61e1fabdbcd96ea473079a9475ed
|
[
"MIT"
] | null | null | null |
10799.cpp
|
jaemin2682/BAEKJOON_ONLINE_JUDGE
|
0d5c6907baee61e1fabdbcd96ea473079a9475ed
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <memory.h>
#include <stack>
using namespace std;
int main() {
string str;
cin >> str;
int stack = 0;
int cnt = 0;
for (int i = 0; i < str.size(); i++) {
if (str[i] == '(' && str[i + 1] == ')') {
cnt += stack;
i++; continue;
}
else if (str[i] == '(') stack++;
else if (str[i] == ')') {
stack--; cnt++;
}
}
cout << cnt;
return 0;
}
| 15.892857
| 43
| 0.516854
|
jaemin2682
|
85d90d31873f73245e390cc069adc3154c136e58
| 9,968
|
cpp
|
C++
|
src/qsiproject.cpp
|
Eggbertx/QtSphere-IDE
|
7ae7ed840fcef7a79fb47a6903afb95ca23838ca
|
[
"BSD-2-Clause"
] | 12
|
2017-05-04T16:58:07.000Z
|
2021-06-09T03:08:29.000Z
|
src/qsiproject.cpp
|
Eggbertx/QtSphere-IDE
|
7ae7ed840fcef7a79fb47a6903afb95ca23838ca
|
[
"BSD-2-Clause"
] | 1
|
2017-06-19T03:30:22.000Z
|
2018-04-09T21:35:00.000Z
|
src/qsiproject.cpp
|
Eggbertx/QtSphere-IDE
|
7ae7ed840fcef7a79fb47a6903afb95ca23838ca
|
[
"BSD-2-Clause"
] | 1
|
2018-09-04T00:27:54.000Z
|
2018-09-04T00:27:54.000Z
|
#include <QDebug>
#include <QFile>
#include <QDir>
#include <QFileInfo>
#include <QFileInfoList>
#include <QRegularExpression>
#include <QRegularExpressionMatchIterator>
#include <QRegularExpressionMatch>
#include <QStringList>
#include <QTextStream>
#include "qsiproject.h"
#include "util.h"
#define QUOTE_REGEX "\"|'|`"
QSIProject::QSIProject(QObject *parent) : QObject(parent) {
m_projectDir = "";
m_projectFilePath = "";
m_projectFileFormat = QSIProject::UnknownProjectType;
m_buildDir = "";
}
QSIProject::~QSIProject() {
}
bool QSIProject::open(QString path) {
m_projectDir = path;
QFileInfo fileInfo(m_projectDir);
if(!fileInfo.exists()) {
errorBox("Project file " + m_projectDir + " doesn't exist!");
return false;
}
if(fileInfo.isDir()) {
QStringList filters({"*.ssproj", "Cellscript.js", "Cellscript.mjs", "Cellscript.cjs", "game.sgm"});
QFileInfoList infoList = QDir(m_projectDir).entryInfoList(filters,QDir::Files|QDir::NoDotAndDotDot);
// look for *.ssproj, Cellscript.js, Cellscript.mjs, Cellscript.cjs, and game.sgm, in that order
for(int f = 0; f < infoList.length(); f++) {
QFileInfo fi = infoList.at(f);
m_projectFilePath = fi.filePath();
QString fileName = fi.fileName();
QString suffix = fi.suffix();
if(suffix == "ssproj") {
m_projectFileFormat = QSIProject::SSProject;
break;
} else if(fileName == "Cellscript.js") {
m_compiler = "Cell";
m_projectFileFormat = QSIProject::Cellscript_js;
break;
} else if(fileName == "Cellscript.mjs") {
m_compiler = "Cell";
m_projectFileFormat = QSIProject::Cellscript_mjs;
break;
} else if(fileName == "Cellscript.cjs") {
m_compiler = "Cell";
m_projectFileFormat = QSIProject::Cellscript_cjs;
break;
} else if(fileName == "game.sgm") {
m_projectFileFormat = QSIProject::SGM;
break;
}
}
} else {
m_projectFilePath = fileInfo.filePath();
}
if(m_projectFilePath == "") {
return false;
}
QFile* projectFile = new QFile(m_projectFilePath);
bool success = prepareProjectFile(projectFile);
projectFile->close();
delete projectFile;
return success;
}
bool QSIProject::save() {
m_projectFilePath = QDir(m_projectDir).absoluteFilePath(QDir(m_projectDir).dirName() + ".ssproj");
QFile* projectFile = new QFile(m_projectFilePath);
if(!projectFile->open(QFile::WriteOnly)) {
errorBox("Unable to open '" + m_projectFilePath + "': " + projectFile->errorString());
delete projectFile;
return false;
}
QString ssText;
QTextStream(&ssText) <<
"[.ssproj]\r\n" <<
"author=" << m_author << "\r\n" <<
"compiler=" << getCompiler() << "\r\n" <<
"description=" << m_summary << "\r\n" <<
"mainScript=" << m_script << "\r\n" <<
"name=" << getName() << "\r\n" <<
"screenHeight=" << m_height << "\r\n" <<
"screenWidth=" << m_width << "\r\n";
bool success = false;
if(projectFile->write(ssText.toLatin1()) > -1) {
m_projectFileFormat = QSIProject::SSProject;
success = true;
}
projectFile->close();
return success;
}
QString QSIProject::getName() {
if(m_name == "") return QFileInfo(m_projectDir).baseName();
return m_name;
}
void QSIProject::setName(QString name) {
m_name = name;
}
QString QSIProject::getResolutionString() {
QString resolution = "";
return resolution.sprintf("%dx%d", m_width, m_height);
}
QString QSIProject::getAuthor() {
return m_author;
}
void QSIProject::setAuthor(QString author) {
m_author = author;
}
int QSIProject::getWidth() {
return m_width;
}
void QSIProject::setWidth(int width) {
m_width = width;
}
int QSIProject::getHeight() {
return m_height;
}
void QSIProject::setHeight(int height) {
m_height = height;
}
void QSIProject::setSize(int width, int height) {
m_width = width;
m_height = height;
}
int QSIProject::getAPILevel() {
return m_apiLevel;
}
void QSIProject::setAPILevel(int level) {
m_apiLevel = level;
}
int QSIProject::getVersion() {
return m_version;
}
void QSIProject::setVersion(int version) {
m_version = version;
}
QString QSIProject::getSaveID() {
return m_saveID;
}
void QSIProject::setSaveID(QString id) {
m_saveID = id;
}
QString QSIProject::getSummary() {
return m_summary;
}
void QSIProject::setSummary(QString summary) {
m_summary = summary;
}
QString QSIProject::getBuildDir() {
if(m_compiler == "Vanilla") return getPath(false);
return m_buildDir;
}
void QSIProject::setBuildDir(QString dir) {
m_buildDir = dir;
}
QString QSIProject::getMainScript() {
return m_script;
}
void QSIProject::setMainScript(QString path) {
m_script = path;
}
QString QSIProject::getPath(bool projectFile) {
if(projectFile) return m_projectFilePath;
return m_projectDir;
}
void QSIProject::setPath(QString path, bool projectFile) {
if(projectFile) m_projectFilePath = path;
else m_projectDir = path;
}
QIcon QSIProject::getIcon() {
QFileInfo icon_fi = QFileInfo(QDir(m_projectDir), "icon.png");
if(icon_fi.exists()) {
return QIcon(icon_fi.canonicalFilePath());
}
return QIcon(":/icons/sphere-icon.png");
}
QSIProject::ProjectFileFormat QSIProject::getProjectFormat() {
return m_projectFileFormat;
}
QString QSIProject::getCompiler() {
return m_compiler;
}
void QSIProject::setCompiler(QString compiler) {
m_compiler = compiler;
}
bool QSIProject::prepareProjectFile(QFile* projectFile) {
if(projectFile == nullptr) return false;
if(!projectFile->isOpen()) {
if(!projectFile->open(QFile::ReadOnly)) {
errorBox("Unable to open project file in '" + m_projectFilePath + "'");
return false;
}
}
switch(m_projectFileFormat) {
case QSIProject::SSProject:
return readSSProj(projectFile);
case QSIProject::Cellscript_js:
case QSIProject::Cellscript_mjs:
case QSIProject::Cellscript_cjs:
return readCellscript(projectFile);
case QSIProject::SGM:
return readSGM(projectFile);
default:
// no project file in directory
return false;
}
}
bool QSIProject::readSSProj(QFile* projectFile) {
QTextStream stream(projectFile);
while(!stream.atEnd()) {
QStringList arr = stream.readLine().split("=");
if(arr.length() != 2) continue;
QString key = arr.at(0);
QString value = arr.at(1);
if(key == "author") m_author = value;
else if(key == "buildDir") m_buildDir = QDir(m_projectDir).absoluteFilePath(value);
else if(key == "compiler") {
m_compiler = value;
}
else if(key == "description") m_summary = value;
else if(key == "mainScript") m_script = value;
else if(key == "name") m_name = value;
else if(key == "screenHeight") m_height = value.toInt();
else if(key == "screenWidth") m_width = value.toInt();
}
return true;
}
QString QSIProject::getCellscriptStringValue(QString cellscriptStr, QString key, QString defaultValue) {
QString value = defaultValue;
QString reStr = "(" + key + "):\\s*(" + QUOTE_REGEX + ")(.*)(" + QUOTE_REGEX + "),";
QRegularExpression re(reStr, QRegularExpression::OptimizeOnFirstUsageOption);
QStringList captureList = re.match(cellscriptStr).capturedTexts();
if(captureList.length() > 4)
value = captureList.at(3);
return value
.replace("\\'", "'")
.replace("\\\"", "\"")
.replace("\\`","`");
}
int QSIProject::getCellscriptIntValue(QString cellscriptStr, QString key, int defaultValue) {
int value = defaultValue;
QString reStr = "(" + key + "):\\s*(\\d+).*,";
QRegularExpression re(reStr, QRegularExpression::OptimizeOnFirstUsageOption);
QStringList captureList = re.match(cellscriptStr).capturedTexts();
if(captureList.length() >= 3) {
bool ok = false;
value = captureList.at(2).toInt(&ok);
if(!ok) value = defaultValue;
}
return value;
}
bool QSIProject::readCellscript(QFile* projectFile) {
QTextStream stream(projectFile);
QString text = stream.readAll();
m_name = getCellscriptStringValue(text, "name");
m_author = getCellscriptStringValue(text, "author");
m_version = getCellscriptIntValue(text, "version", 1);
m_apiLevel = getCellscriptIntValue(text, "apiLevel", 1);
m_saveID = getCellscriptStringValue(text, "saveID");
m_summary = getCellscriptStringValue(text, "summary");
m_script = getCellscriptStringValue(text, "main");
QStringList resolution = getCellscriptStringValue(text, "resolution").split("x");
bool ok = false;
if(resolution.length() != 2) {
m_width = -1;
m_height = -1;
return true;
}
m_width = resolution.at(0).toInt(&ok);
if(!ok) m_width = -1;
m_height = resolution.at(1).toInt(&ok);
if(!ok) m_height = -1;
if(m_width < 0 || m_height < 0) {
qDebug() << m_name << "has an invalid resolution:" << resolution.at(0) << "x" << resolution.at(1);
}
m_compiler = "Cell";
/*qDebug().nospace().noquote() <<
"Project: " << m_name << "\n" <<
"Author: " << m_author << "\n" <<
"Version: " << m_version << "\n" <<
"API Level: " << m_apiLevel << "\n" <<
"Save ID: " << m_saveID << "\n" <<
"Summary: " << m_summary << "\n" <<
"Resolution: " << m_width << "x" << m_height << "\n" <<
"Main script: " << m_script << "\n";*/
m_buildDir = QFileInfo(*projectFile).dir().absoluteFilePath("dist/");
return true;
}
bool QSIProject::readSGM(QFile *projectFile) {
QTextStream stream(projectFile);
while(!stream.atEnd()) {
QString line = stream.readLine();
if(line == "") continue;
QString key = line.section("=", 0, 0);
QString value = line.section("=", 1);
if(key == "name") m_name = value;
else if(key == "author") m_author = value;
else if(key == "description") m_summary = value;
else if(key == "screen_width") m_width = value.toInt();
else if(key == "screen_height") m_height = value.toInt();
else if(key == "script") m_script = value;
}
m_compiler = "Vanilla";
m_buildDir = QFileInfo(*projectFile).dir().path();
return true;
}
| 27.688889
| 105
| 0.661116
|
Eggbertx
|
85dbe2608391566cff2e04033a9ea0c5b5be9cec
| 712
|
cpp
|
C++
|
Source/041.SapXepTang.cpp
|
tannd/learning-cplus
|
1969b7ce5dd331348330df8121fdafec16325589
|
[
"Apache-2.0"
] | 2
|
2016-12-15T07:17:33.000Z
|
2018-10-18T15:15:30.000Z
|
Source/041.SapXepTang.cpp
|
tannd/learning-cplus
|
1969b7ce5dd331348330df8121fdafec16325589
|
[
"Apache-2.0"
] | null | null | null |
Source/041.SapXepTang.cpp
|
tannd/learning-cplus
|
1969b7ce5dd331348330df8121fdafec16325589
|
[
"Apache-2.0"
] | null | null | null |
//============================================================================//
// Unit 041 : Sap xep mang tang dan
// Author : Nguyen.Duy.Tan
// Date : 18/11/2011 (dd/mm/yyyy)
//============================================================================//
#include <stdio.h>
#include <conio.h>
void nhap(int A[100], int n)
{
int i;
for (i=0;i<n;i++)
{
printf("\nnhap phan tu thu A[%d]=",i);
scanf("%d",&A[i]);
}
}
main()
{
int n,A[100],i,j;
printf("\nnhap so phan tu cua day n= ");
scanf("%d",&n);
nhap(A,n);
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
if(A[i]>A[j])
{
int tg;
tg=A[i];
A[i]=A[j];
A[j]=tg;
}
for(i=0;i<n;i++)
printf(" %d ",A[i]);
getch();
}
| 18.736842
| 80
| 0.373596
|
tannd
|
85e04fc53cafac91ba1c99ee8fd15640972e8382
| 82
|
hpp
|
C++
|
include/Engine/IUpdatable.hpp
|
FoxelCode/Barkanoid
|
3e582cbfb4bf13aa522d344489c8b0bac77fa8c5
|
[
"Unlicense"
] | null | null | null |
include/Engine/IUpdatable.hpp
|
FoxelCode/Barkanoid
|
3e582cbfb4bf13aa522d344489c8b0bac77fa8c5
|
[
"Unlicense"
] | null | null | null |
include/Engine/IUpdatable.hpp
|
FoxelCode/Barkanoid
|
3e582cbfb4bf13aa522d344489c8b0bac77fa8c5
|
[
"Unlicense"
] | null | null | null |
#pragma once
class IUpdatable
{
public:
virtual void Update(float delta) = 0;
};
| 11.714286
| 38
| 0.719512
|
FoxelCode
|
85e44c2aa042f5cbd8cf6510cf9fc9e69e8f0ddd
| 1,044
|
cpp
|
C++
|
math/crt-extgcd.cpp
|
Yoko303/algorithm
|
9caa62f8e9a8a01c20256029d21dbe088cc19790
|
[
"Unlicense"
] | null | null | null |
math/crt-extgcd.cpp
|
Yoko303/algorithm
|
9caa62f8e9a8a01c20256029d21dbe088cc19790
|
[
"Unlicense"
] | null | null | null |
math/crt-extgcd.cpp
|
Yoko303/algorithm
|
9caa62f8e9a8a01c20256029d21dbe088cc19790
|
[
"Unlicense"
] | null | null | null |
#include <iostream>
#include <vector>
using namespace std;
using ll = long long;
ll mod(ll a, ll m) { return (a%m + m) % m; }
ll ext_gcd(ll a, ll b, ll& x, ll& y) {
if(b == 0) { x = 1; y = 0; return a; }
ll g = ext_gcd(b, a % b, y, x);
y -= a/b * x;
return g;
}
pair<ll, ll> crt_extgcd(const vector<ll>& r, const vector<ll>& m) {
pair<ll, ll> ret;
ll& rem = ret.first;
ll& mod = ret.second;
rem = 0, mod = 1;
for(int i = 0; i < (int)r.size(); ++i) {
ll inv_mod, _;
ll div = ext_gcd(mod, m[i], inv_mod, _); // mod*inv_mod = 1 (mod m[i]/div)
if((r[i] - rem) % div != 0) return make_pair(0, -1);
ll tmp = (r[i] - rem) / div * inv_mod % (m[i] / div);
rem += mod * tmp;
mod *= m[i] / div; // lcm(m, m[i])
}
rem = (rem % mod + mod) % mod;
return ret;
}
int main() {
vector<ll> mod = {3, 5};
vector<ll> rem = {2, 3};
pair<ll, ll> p = crt_extgcd(rem, mod);
cout << "rem = " << p.first << " (mod = " << p.second << ")" << endl;
}
| 26.769231
| 85
| 0.471264
|
Yoko303
|
85e9a516c869525d7025cdb4093b54b5ff78abbb
| 1,153
|
cpp
|
C++
|
platform/windows/error_util.cpp
|
mexicowilly/Chucho
|
f4235420437eb2078ab592540c0d729b7b9a3c10
|
[
"Apache-2.0"
] | 4
|
2016-12-06T05:33:29.000Z
|
2017-12-17T17:04:25.000Z
|
platform/windows/error_util.cpp
|
mexicowilly/Chucho
|
f4235420437eb2078ab592540c0d729b7b9a3c10
|
[
"Apache-2.0"
] | 147
|
2016-09-05T14:00:46.000Z
|
2021-08-24T14:43:07.000Z
|
platform/windows/error_util.cpp
|
mexicowilly/Chucho
|
f4235420437eb2078ab592540c0d729b7b9a3c10
|
[
"Apache-2.0"
] | 4
|
2017-11-08T04:12:39.000Z
|
2022-01-04T06:40:16.000Z
|
/*
* Copyright 2013-2021 Will Mason
*
* 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 "error_util.hpp"
namespace chucho
{
namespace error_util
{
std::string message(DWORD err)
{
char* msg;
if (FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
nullptr,
err,
0,
reinterpret_cast<char*>(&msg),
1,
nullptr) == 0)
{
return std::string();
}
std::string result(msg);
LocalFree(msg);
return result;
}
}
}
| 25.065217
| 83
| 0.606245
|
mexicowilly
|
85f55f8ff08cc111c81a0fb2a084ff982dc53107
| 1,711
|
cpp
|
C++
|
11_recursion/06/06.cpp
|
bilyanhadzhi/intro_to_programming_labs
|
083bfaad1fdb423c0d8320b3e882316fa56c0bf8
|
[
"MIT"
] | 3
|
2020-11-05T10:11:31.000Z
|
2020-11-14T16:10:27.000Z
|
11_recursion/06/06.cpp
|
bilyanhadzhi/intro_to_programming_labs
|
083bfaad1fdb423c0d8320b3e882316fa56c0bf8
|
[
"MIT"
] | null | null | null |
11_recursion/06/06.cpp
|
bilyanhadzhi/intro_to_programming_labs
|
083bfaad1fdb423c0d8320b3e882316fa56c0bf8
|
[
"MIT"
] | 1
|
2021-06-17T13:21:58.000Z
|
2021-06-17T13:21:58.000Z
|
#include <iostream>
#include <iomanip>
bool can_move(int n, int** board, int x, int y, int dx, int dy)
{
int new_x = x + dx;
int new_y = y + dy;
if (new_x < 0 || new_x >= n || new_y < 0 || new_y >= n)
{
return false;
}
return board[new_x][new_y] == -1;
}
bool knights_tour_rec(int n, int** board, int x, int y, int curr_move)
{
if (curr_move >= n * n)
{
return true;
}
int next_move_x[8] = { -2, -1, 1, 2, 2, 1, -1, -2 };
int next_move_y[8] = { 1, 2, 2, 1, -1, -2, -2, -1 };
for (int i = 0; i < 8; i++)
{
if (can_move(n, board, x, y, next_move_x[i], next_move_y[i]))
{
int next_x = x + next_move_x[i];
int next_y = y + next_move_y[i];
board[next_x][next_y] = curr_move;
if (knights_tour_rec(n, board, next_x, next_y, curr_move + 1))
{
return true;
}
board[next_x][next_y] = -1;
}
}
return false;
}
void knights_tour(int n)
{
int** board = new int* [n];
for (int i = 0; i < n; i++)
{
board[i] = new int[n];
for (int j = 0; j < n; j++)
{
board[i][j] = -1;
}
}
board[0][0] = 0;
if (knights_tour_rec(n, board, 0, 0, 1))
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
std::cout << std::setw(2) << board[i][j] << " ";
}
std::cout << "\n";
}
}
// free memory
for (int i = 0; i < n; i++)
{
delete[] board[i];
}
delete[] board;
}
int main()
{
int n;
std::cin >> n;
knights_tour(n);
}
| 19.011111
| 74
| 0.421391
|
bilyanhadzhi
|
65a35e3e212d7da5f1958af0b3c4298aaceb91e4
| 607
|
cpp
|
C++
|
example/neighbour_example.cpp
|
arapelle/dirn
|
79e7daea5e7ee38d985c8fdd985a34544d220930
|
[
"MIT"
] | null | null | null |
example/neighbour_example.cpp
|
arapelle/dirn
|
79e7daea5e7ee38d985c8fdd985a34544d220930
|
[
"MIT"
] | 2
|
2020-09-10T09:51:38.000Z
|
2020-09-10T21:18:28.000Z
|
example/neighbour_example.cpp
|
arapelle/dirn
|
79e7daea5e7ee38d985c8fdd985a34544d220930
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <dirn/directions4.hpp>
#include <dirn/neighbourhood.hpp>
class vec2
{
int x_;
int y_;
public:
vec2(int x = 0, int y = 0)
: x_(x), y_(y)
{}
const int& x() const { return x_; }
int& x() { return x_; }
const int& y() const { return y_; }
int& y() { return y_; }
auto operator<=>(const vec2& v) const = default;
};
int main()
{
vec2 position(0,0);
vec2 new_position = *dirn::neighbour(position, dirn::directions4::right);
std::cout << new_position.x() << " " << new_position.y() << std::endl;
return EXIT_SUCCESS;
}
| 19.580645
| 77
| 0.576606
|
arapelle
|
65a41bcd0316cb7710b58f064120fe705f18ef34
| 395
|
cpp
|
C++
|
src/World.cpp
|
jacksonwilliampluskota/GamePlaatformOF
|
53701190f21aa956864311ca6d971f80c206a0cd
|
[
"MIT"
] | 1
|
2020-02-18T13:35:44.000Z
|
2020-02-18T13:35:44.000Z
|
src/World.cpp
|
jacksonwilliampluskota/GamePlaatformOF
|
53701190f21aa956864311ca6d971f80c206a0cd
|
[
"MIT"
] | null | null | null |
src/World.cpp
|
jacksonwilliampluskota/GamePlaatformOF
|
53701190f21aa956864311ca6d971f80c206a0cd
|
[
"MIT"
] | 1
|
2020-02-18T13:32:02.000Z
|
2020-02-18T13:32:02.000Z
|
#include "World.h"
#include <stdio.h>
World::World()
{
}
void World::moeda_setup(string state, int x, int y)
{
animationCoin = new Animation();
positionCoin.set(x, y);
animationCoin->setup(state, 4, 8);
}
void World::moeda_update(float deltaTime)
{
}
void World::moeda_draw()
{
ofPushMatrix();
animationCoin->draw(positionCoin.x, positionCoin.y);
ofPopMatrix();
}
World::~World()
{
}
| 13.62069
| 53
| 0.688608
|
jacksonwilliampluskota
|
65ad8f3820547925d46eb02c0129db4515650788
| 1,217
|
cpp
|
C++
|
averageOfNums.cpp
|
nikeshsraj10/parallel-programming-multithreading
|
046af811add225fa6f40fbb63d5656e6c72de7dd
|
[
"MIT"
] | null | null | null |
averageOfNums.cpp
|
nikeshsraj10/parallel-programming-multithreading
|
046af811add225fa6f40fbb63d5656e6c72de7dd
|
[
"MIT"
] | null | null | null |
averageOfNums.cpp
|
nikeshsraj10/parallel-programming-multithreading
|
046af811add225fa6f40fbb63d5656e6c72de7dd
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <thread>
#include <vector>
using namespace std;
void average(vector<vector<int>>& A, vector<vector<int>>& B, int n, int r1, int r2, int c1, int c2) {
for (int i = r1; i <= r2; i++) {
for (int j = c1; j <= c2; j++) {
int N, E, S, W;
N = (i - 1 >= 0)? A[i - 1][j] : 0;
E = (j + 1 <= n - 1) ? A[i][j + 1] : 0;
S = (i + 1 <= n - 1) ? A[i + 1][j] : 0;
W = (j - 1 >= 0) ? A[i][j - 1] : 0;
B[i][j] = (N + E + S + W) / 4;
}
}
}
int main() {
int n;
cout << "Enter matrix size" << endl;
cin >> n;
vector<vector<int>> A(n, vector<int>(n));
for (auto &i : A) {
for (auto &j : i) { j = rand() % 5; }
}
vector<vector<int>> B(n, vector<int>(n));
thread t1{ average, ref(A), ref(B), n, 0, n / 2, 0, n / 2 }; //Using {} is more recent
thread t2{ average, ref(A), ref(B), n, 0, n / 2, n / 2+1, n-1 };
thread t3{ average, ref(A), ref(B), n, n/2+1, n-1, 0, n / 2 };
thread t4{ average, ref(A), ref(B), n, n/2+1, n-1, n/2+1, n-1 };
t1.join();
t2.join();
t3.join();
t4.join();
for (auto i : A) {
for (auto j : i) {
cout << j << " ";
}
cout << endl;
}
cout << endl;
for (auto i : B) {
for (auto j : i) {
cout << j << " ";
}
cout << endl;
}
}
| 23.403846
| 101
| 0.459326
|
nikeshsraj10
|
65afe8678836fb9569db6a751536eec964f2ff01
| 1,112
|
cpp
|
C++
|
ClientEngine/game/engine/Stage/UnitPart/UnitExecute/ExecuteParameter.cpp
|
twesd/editor
|
10ea9f535115dadab5694fecdb0c499d0013ac1b
|
[
"MIT"
] | null | null | null |
ClientEngine/game/engine/Stage/UnitPart/UnitExecute/ExecuteParameter.cpp
|
twesd/editor
|
10ea9f535115dadab5694fecdb0c499d0013ac1b
|
[
"MIT"
] | null | null | null |
ClientEngine/game/engine/Stage/UnitPart/UnitExecute/ExecuteParameter.cpp
|
twesd/editor
|
10ea9f535115dadab5694fecdb0c499d0013ac1b
|
[
"MIT"
] | null | null | null |
#include "ExecuteParameter.h"
#include "../../UnitInstance/UnitInstanceStandard.h"
ExecuteParameter::ExecuteParameter(SharedParams_t params) :
ExecuteBase(params)
{
_behavior = NULL;
}
ExecuteParameter::~ExecuteParameter()
{
}
// Добавить параметр
void ExecuteParameter::AddParameter( stringc name, stringc val )
{
Parameter parameter;
parameter.Name = name;
parameter.Value = val;
_parameters.push_back(parameter);
}
// Выполнить действие
void ExecuteParameter::Run(scene::ISceneNode* node, core::array<Event_t*>& events)
{
ExecuteBase::Run(node, events);
if(IsGlobal)
{
Parameter param;
for (u32 i = 0; i < _parameters.size() ; i++)
{
param.Value = GetGlobalParameter(_parameters[i].Name);
param.Change(_parameters[i].Value);
SetGlobalParameter(_parameters[i].Name, param.Value);
}
}
else
{
UnitParameters* behaviorParams = _behavior->GetParameters();
for (u32 i = 0; i < _parameters.size() ; i++)
{
behaviorParams->Set(_parameters[i].Name, _parameters[i].Value);
}
}
}
void ExecuteParameter::SetBehavior( UnitBehavior* behavior )
{
_behavior = behavior;
}
| 21.384615
| 82
| 0.714928
|
twesd
|
65b0b82cbc83c964bdcb65afee46f16f943582bf
| 5,022
|
cpp
|
C++
|
src/model/mesh_part.cpp
|
Shtille/scythe
|
795b482921bed9ab36fd9ced38863371c75367ab
|
[
"MIT"
] | null | null | null |
src/model/mesh_part.cpp
|
Shtille/scythe
|
795b482921bed9ab36fd9ced38863371c75367ab
|
[
"MIT"
] | 8
|
2018-07-12T14:10:53.000Z
|
2020-09-17T11:15:52.000Z
|
src/model/mesh_part.cpp
|
Shtille/scythe
|
795b482921bed9ab36fd9ced38863371c75367ab
|
[
"MIT"
] | null | null | null |
#include "mesh_part.h"
#include "material.h"
namespace scythe {
MeshPart::MeshPart(Renderer * renderer)
: primitive_mode_(PrimitiveType::kTriangleStrip)
, renderer_(renderer)
, material_(nullptr)
, vertex_buffer_(nullptr)
, index_buffer_(nullptr)
, vertex_array_object_(0)
, num_vertices_(0)
, vertices_array_(nullptr)
, num_indices_(0)
, index_size_(0)
, indices_array_(nullptr)
{
}
MeshPart::~MeshPart()
{
if (vertex_buffer_)
renderer_->DeleteVertexBuffer(vertex_buffer_);
if (index_buffer_)
renderer_->DeleteIndexBuffer(index_buffer_);
if (vertex_array_object_)
renderer_->context()->DeleteVertexArrayObject(vertex_array_object_);
FreeArrays();
}
void MeshPart::FreeArrays()
{
if (vertices_array_)
{
delete [] vertices_array_;
vertices_array_ = nullptr;
}
if (indices_array_)
{
delete [] indices_array_;
indices_array_ = nullptr;
}
}
void MeshPart::TransformVertices(const VertexFormat * vertex_format, BoundingBox * bounding_box, bool keep_data)
{
num_vertices_ = (U32)vertices_.size();
vertices_array_ = new U8[num_vertices_ * vertex_format->vertex_size()];
U8 *ptr = vertices_array_;
for (auto &v : vertices_)
{
for (U32 i = 0; i < vertex_format->num_attributes(); ++i)
{
const VertexAttribute& attribute = vertex_format->attributes()[i];
switch (attribute.type)
{
case VertexAttribute::kVertex:
memcpy(ptr, v.position, sizeof(v.position));
if (bounding_box)
{
bounding_box->min.MakeMinimum(v.position);
bounding_box->max.MakeMaximum(v.position);
}
break;
case VertexAttribute::kNormal:
memcpy(ptr, v.normal, sizeof(v.normal));
break;
case VertexAttribute::kTexcoord:
memcpy(ptr, v.texcoord, sizeof(v.texcoord));
break;
case VertexAttribute::kTangent:
memcpy(ptr, v.tangent, sizeof(v.tangent));
break;
case VertexAttribute::kBinormal:
memcpy(ptr, v.binormal, sizeof(v.binormal));
break;
default:
assert(!"Unknown vertex attribute");
}
ptr += attribute.GetSize();
}
}
if (!keep_data)
{
vertices_.clear();
vertices_.shrink_to_fit();
}
if (!indices_.empty())
{
num_indices_ = (U32)indices_.size();
if (num_indices_ > 0xffff)
{
index_size_ = sizeof(U32);
index_data_type_ = DataType::kUnsignedInt;
indices_array_ = new U8[num_indices_ * index_size_];
U32 *indices = reinterpret_cast<U32*>(indices_array_);
for (size_t i = 0; i < indices_.size(); ++i)
{
indices[i] = static_cast<U32>(indices_[i]);
}
}
else
{
index_size_ = sizeof(U16);
index_data_type_ = DataType::kUnsignedShort;
indices_array_ = new U8[num_indices_ * index_size_];
U16 *indices = reinterpret_cast<U16*>(indices_array_);
for (size_t i = 0; i < indices_.size(); ++i)
{
indices[i] = static_cast<U16>(indices_[i]);
}
}
if (!keep_data)
{
indices_.clear();
indices_.shrink_to_fit();
}
}
}
bool MeshPart::MakeRenderable(const VertexFormat * vertex_format, BoundingBox * bounding_box, bool keep_data)
{
const bool have_indices = !indices_.empty();
TransformVertices(vertex_format, bounding_box, keep_data);
renderer_->context()->GenVertexArrayObject(vertex_array_object_);
renderer_->context()->BindVertexArrayObject(vertex_array_object_);
renderer_->AddVertexBuffer(vertex_buffer_, num_vertices_ * vertex_format->vertex_size(), vertices_array_, BufferUsage::kStaticDraw);
if (vertex_buffer_ == nullptr) return false;
if (have_indices)
{
renderer_->AddIndexBuffer(index_buffer_, num_indices_, index_size_, indices_array_, BufferUsage::kStaticDraw);
if (index_buffer_ == nullptr) return false;
}
const char* base = (char*)0;
for (U32 i = 0; i < vertex_format->num_attributes(); ++i)
{
const VertexFormat::Attrib& generic = vertex_format->generic(i);
renderer_->context()->VertexAttribPointer(i, generic.size, DataType::kFloat, vertex_format->vertex_size(), base + generic.offset);
renderer_->context()->EnableVertexAttribArray(i);
}
renderer_->context()->BindVertexArrayObject(0);
FreeArrays();
return true;
}
void MeshPart::CleanUp()
{
vertices_.clear();
vertices_.shrink_to_fit();
indices_.clear();
indices_.shrink_to_fit();
}
void MeshPart::Render()
{
renderer_->context()->BindVertexArrayObject(vertex_array_object_);
if (index_buffer_ == nullptr)
renderer_->context()->DrawArrays(primitive_mode_, 0, num_vertices_);
else
renderer_->context()->DrawElements(primitive_mode_, num_indices_, index_data_type_);
renderer_->context()->BindVertexArrayObject(0);
}
void MeshPart::ScaleVertices(const Vector3& scale)
{
for (auto& v : vertices_)
v.position *= scale;
}
void MeshPart::ScaleTexcoord(const Vector2& scale)
{
for (auto& v : vertices_)
v.texcoord *= scale;
}
void MeshPart::TranslateVertices(const Vector3& offset)
{
for (auto& v : vertices_)
v.position += offset;
}
} // namespace scythe
| 27.145946
| 134
| 0.691358
|
Shtille
|
65b211d32e64dc9f199acfd583066d2c8d19a85d
| 176
|
hpp
|
C++
|
include/queue.hpp
|
Dacilndak/ds
|
edae4a057912946329066338bada4deea8d723ab
|
[
"MIT"
] | null | null | null |
include/queue.hpp
|
Dacilndak/ds
|
edae4a057912946329066338bada4deea8d723ab
|
[
"MIT"
] | null | null | null |
include/queue.hpp
|
Dacilndak/ds
|
edae4a057912946329066338bada4deea8d723ab
|
[
"MIT"
] | null | null | null |
#ifndef _MPH_WRAPPER_QUEUE_H_
#define _MPH_WRAPPER_QUEUE_H_
#include <queue/queue.hpp>
#include <queue/deque.hpp>
template <typename T> using DoubleQueue = Deque<T>;
#endif
| 17.6
| 51
| 0.784091
|
Dacilndak
|
65b8fe5092ddff65bc1f0e696534a9b309762332
| 10,455
|
cpp
|
C++
|
pass/semantic/tests/lnast_semantic_test.cpp
|
maximiliantiao/livehd
|
88215f0d6fc395db96e6ed058f00b9205454bd0c
|
[
"BSD-3-Clause"
] | null | null | null |
pass/semantic/tests/lnast_semantic_test.cpp
|
maximiliantiao/livehd
|
88215f0d6fc395db96e6ed058f00b9205454bd0c
|
[
"BSD-3-Clause"
] | null | null | null |
pass/semantic/tests/lnast_semantic_test.cpp
|
maximiliantiao/livehd
|
88215f0d6fc395db96e6ed058f00b9205454bd0c
|
[
"BSD-3-Clause"
] | null | null | null |
#include "semantic_check.hpp"
#include "lnast.hpp"
int main(void) {
int line_num, pos1, pos2 = 0;
Lnast* lnast = new Lnast();
Semantic_pass s;
// ======================== Testing Assign Operations ========================
// auto idx_root = Lnast_node::create_top ("top", line_num, pos1, pos2);
// auto node_stmts = Lnast_node::create_stmts ("stmts", line_num, pos1, pos2);
// auto node_assign = Lnast_node::create_assign ("assign", line_num, pos1, pos2);
// auto node_target = Lnast_node::create_ref ("val", line_num, pos1, pos2);
// auto node_const = Lnast_node::create_const ("0d1023u10", line_num, pos1, pos2);
// lnast->set_root(idx_root);
// auto idx_stmts = lnast->add_child(lnast->get_root(), node_stmts);
// auto idx_assign = lnast->add_child(idx_stmts, node_assign);
// auto idx_target = lnast->add_child(idx_assign, node_target);
// auto idx_const = lnast->add_child(idx_assign, node_const);
// ===========================================================================
// ==================== Testing N-ary + U-nary Operations ====================
// auto idx_root = Lnast_node::create_top ("top", line_num, pos1, pos2);
// auto node_stmts = Lnast_node::create_stmts ("stmts", line_num, pos1, pos2);
// auto node_minus = Lnast_node::create_minus ("minus", line_num, pos1, pos2);
// auto node_lhs1 = Lnast_node::create_ref ("___a", line_num, pos1, pos2);
// auto node_op1 = Lnast_node::create_ref ("x", line_num, pos1, pos2);
// auto node_op2 = Lnast_node::create_const ("0d1", line_num, pos1, pos2);
// auto node_plus = Lnast_node::create_plus ("plus", line_num, pos1, pos2);
// auto node_lhs2 = Lnast_node::create_ref ("___b", line_num, pos1, pos2);
// auto node_op3 = Lnast_node::create_ref ("___a", line_num, pos1, pos2);
// auto node_op4 = Lnast_node::create_const ("0d3", line_num, pos1, pos2);
// auto node_op5 = Lnast_node::create_const ("0d2", line_num, pos1, pos2);
// auto node_dpa = Lnast_node::create_dp_assign ("dp_assign", line_num, pos1, pos2);
// auto node_lhs3 = Lnast_node::create_ref ("total", line_num, pos1, pos2);
// auto node_op6 = Lnast_node::create_ref ("___b", line_num, pos1, pos2);
// lnast->set_root(idx_root);
// auto idx_stmts = lnast->add_child(lnast->get_root(), node_stmts);
// auto idx_minus = lnast->add_child(idx_stmts, node_minus);
// auto idx_lhs1 = lnast->add_child(idx_minus, node_lhs1);
// auto idx_op1 = lnast->add_child(idx_minus, node_op1);
// auto idx_op2 = lnast->add_child(idx_minus, node_op2);
// auto idx_plus = lnast->add_child(idx_stmts, node_plus);
// auto idx_lhs2 = lnast->add_child(idx_plus, node_lhs2);
// auto idx_op3 = lnast->add_child(idx_plus, node_op3);
// auto idx_op4 = lnast->add_child(idx_plus, node_op4);
// auto idx_op5 = lnast->add_child(idx_plus, node_op5);
// auto idx_assign = lnast->add_child(idx_stmts, node_dpa);
// auto idx_lhs3 = lnast->add_child(idx_assign, node_lhs3);
// auto idx_op6 = lnast->add_child(idx_assign, node_op6);
// ===========================================================================
// ========================== Testing If Operation ===========================
// auto idx_root = Lnast_node::create_top("top", line_num, pos1, pos2);
// lnast->set_root(idx_root);
// auto idx_stmts0 = lnast->add_child(lnast->get_root(), Lnast_node::create_stmts ("stmts0", line_num, pos1, pos2));
// auto idx_if = lnast->add_child(idx_stmts0, Lnast_node::create_if ("if", line_num, pos1, pos2));
// auto idx_cstmts = lnast->add_child(idx_if, Lnast_node::create_cstmts("cstmts", line_num, pos1, pos2));
// auto idx_gt = lnast->add_child(idx_cstmts, Lnast_node::create_gt ("gt", line_num, pos1, pos2));
// auto idx_lhs1 = lnast->add_child(idx_gt, Lnast_node::create_ref ("lhs", line_num, pos1, pos2));
// auto idx_op1 = lnast->add_child(idx_gt, Lnast_node::create_ref ("op1", line_num, pos1, pos2));
// auto idx_op2 = lnast->add_child(idx_gt, Lnast_node::create_const ("op2", line_num, pos1, pos2));
// auto idx_cond1 = lnast->add_child(idx_if, Lnast_node::create_cond ("cond", line_num, pos1, pos2));
// auto idx_stmts1 = lnast->add_child(idx_if, Lnast_node::create_stmts ("stmts1", line_num, pos1, pos2));
// auto idx_plus = lnast->add_child(idx_stmts1, Lnast_node::create_plus ("plus", line_num, pos1, pos2));
// auto idx_lhs2 = lnast->add_child(idx_plus, Lnast_node::create_ref ("lhs", line_num, pos1, pos2));
// auto idx_op3 = lnast->add_child(idx_plus, Lnast_node::create_ref ("op3", line_num, pos1, pos2));
// auto idx_op4 = lnast->add_child(idx_plus, Lnast_node::create_const ("op4", line_num, pos1, pos2));
// auto idx_assign = lnast->add_child(idx_stmts1, Lnast_node::create_assign("assign", line_num, pos1, pos2));
// auto idx_lhs3 = lnast->add_child(idx_assign, Lnast_node::create_ref ("lhs", line_num, pos1, pos2));
// auto idx_op5 = lnast->add_child(idx_assign, Lnast_node::create_ref ("op5", line_num, pos1, pos2));
// ============================ For Loop Operation ===========================
// auto idx_root = Lnast_node::create_top("top", line_num, pos1, pos2);
// lnast->set_root(idx_root);
// auto idx_stmts0 = lnast->add_child(lnast->get_root(), Lnast_node::create_stmts ("stmts0", line_num, pos1, pos2));
// auto idx_for = lnast->add_child(idx_stmts0, Lnast_node::create_for ("for", line_num, pos1, pos2));
// auto idx_stmts1 = lnast->add_child(idx_for, Lnast_node::create_stmts ("stmts", line_num, pos1, pos2));
// auto idx_itr = lnast->add_child(idx_for, Lnast_node::create_ref ("it_name", line_num, pos1, pos2));
// auto idx_itr_range = lnast->add_child(idx_for, Lnast_node::create_ref ("tup", line_num, pos1, pos2));
// auto idx_select = lnast->add_child(idx_stmts1, Lnast_node::create_select ("select", line_num, pos1, pos2));
// auto idx_lhs = lnast->add_child(idx_select, Lnast_node::create_ref ("lhs", line_num, pos1, pos2));
// auto idx_op4 = lnast->add_child(idx_select, Lnast_node::create_ref ("op1", line_num, pos1, pos2));
// auto idx_op5 = lnast->add_child(idx_select, Lnast_node::create_ref ("op2", line_num, pos1, pos2));
// ===========================================================================
// =========================== While Loop Operation ==========================
// auto idx_root = Lnast_node::create_top("top", line_num, pos1, pos2);
// lnast->set_root(idx_root);
// auto idx_stmts0 = lnast->add_child(lnast->get_root(), Lnast_node::create_stmts ("stmts0", line_num, pos1, pos2));
// auto idx_while = lnast->add_child(idx_stmts0, Lnast_node::create_while ("while", line_num, pos1, pos2));
// auto idx_cond = lnast->add_child(idx_while, Lnast_node::create_cond ("cond", line_num, pos1, pos2));
// auto idx_stmts1 = lnast->add_child(idx_while, Lnast_node::create_stmts ("stmts", line_num, pos1, pos2));
// auto idx_ref = lnast->add_child(idx_cond, Lnast_node::create_ref ("condition", line_num, pos1, pos2));
// ===========================================================================
// =========================== Func Def Operation ============================
// auto idx_root = Lnast_node::create_top("top", line_num, pos1, pos2);
// lnast->set_root(idx_root);
// auto idx_stmts0 = lnast->add_child(lnast->get_root(), Lnast_node::create_stmts ("stmts0", line_num, pos1, pos2));
// auto idx_func = lnast->add_child(idx_stmts0, Lnast_node::create_func_def("func_def", line_num, pos1, pos2));
// auto idx_fname = lnast->add_child(idx_func, Lnast_node::create_ref ("func_name", line_num, pos1, pos2));
// auto idx_cond = lnast->add_child(idx_func, Lnast_node::create_cond ("condition", line_num, pos1, pos2));
// auto idx_stmts1 = lnast->add_child(idx_func, Lnast_node::create_stmts ("stmts", line_num, pos1, pos2));
// auto idx_io1 = lnast->add_child(idx_func, Lnast_node::create_ref ("in1", line_num, pos1, pos2));
// auto idx_io2 = lnast->add_child(idx_func, Lnast_node::create_ref ("in2", line_num, pos1, pos2));
// auto idx_io3 = lnast->add_child(idx_func, Lnast_node::create_ref ("out1", line_num, pos1, pos2));
// auto idx_ref = lnast->add_child(idx_cond, Lnast_node::create_ref ("true", line_num, pos1, pos2));
// auto idx_xor = lnast->add_child(idx_stmts1, Lnast_node::create_xor ("xor", line_num, pos1, pos2));
// auto idx_lhs_1 = lnast->add_child(idx_xor, Lnast_node::create_ref ("lhs", line_num, pos1, pos2));
// auto idx_op1_1 = lnast->add_child(idx_xor, Lnast_node::create_ref ("op1", line_num, pos1, pos2));
// auto idx_op2 = lnast->add_child(idx_xor, Lnast_node::create_ref ("op2", line_num, pos1, pos2));
// auto idx_assign = lnast->add_child(idx_stmts1, Lnast_node::create_assign("assign", line_num, pos1, pos2));
// auto idx_lhs_2 = lnast->add_child(idx_assign, Lnast_node::create_ref ("lhs", line_num, pos1, pos2));
// auto idx_op1_2 = lnast->add_child(idx_assign, Lnast_node::create_ref ("rhs", line_num, pos1, pos2));
// ===========================================================================
// =========================== Func Call Operation ===========================
// auto idx_root = Lnast_node::create_top("top", line_num, pos1, pos2);
// lnast->set_root(idx_root);
// auto idx_stmts0 = lnast->add_child(lnast->get_root(), Lnast_node::create_stmts ("stmts0", line_num, pos1, pos2));
// auto idx_fcall = lnast->add_child(idx_stmts0, Lnast_node::create_func_call("func_call", line_num, pos1, pos2));
// auto idx_lhs = lnast->add_child(idx_fcall, Lnast_node::create_ref ("lhs", line_num, pos1, pos2));
// auto idx_target = lnast->add_child(idx_fcall, Lnast_node::create_ref ("func_name", line_num, pos1, pos2));
// auto idx_arg = lnast->add_child(idx_fcall, Lnast_node::create_ref ("arguments", line_num, pos1, pos2));
// ===========================================================================
s.semantic_check(lnast);
return 0;
}
| 61.140351
| 121
| 0.610904
|
maximiliantiao
|
65bdf857146a86817765e8af2852b726c29c1865
| 2,717
|
cpp
|
C++
|
tests/src/test_comparisons.cpp
|
cmas1/HolorLib
|
bb62dc738298b7e229a1965a5bfc206395f68b88
|
[
"MIT"
] | 1
|
2022-01-20T12:48:36.000Z
|
2022-01-20T12:48:36.000Z
|
tests/src/test_comparisons.cpp
|
cmas1/HolorLib
|
bb62dc738298b7e229a1965a5bfc206395f68b88
|
[
"MIT"
] | null | null | null |
tests/src/test_comparisons.cpp
|
cmas1/HolorLib
|
bb62dc738298b7e229a1965a5bfc206395f68b88
|
[
"MIT"
] | null | null | null |
// This file is part of Holor, a C++ header-only template library for multi-dimensional containers
// Copyright 2020-2022 Carlo Masone
// 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 <algorithm>
#include <array>
#include <vector>
#include <holor/holor_full.h>
#include <gtest/gtest.h>
using namespace holor;
TEST(TestHolorComparisons, CheckComparisons){
{
Holor<int, 2> h1 {{1,2}, {3,4}};
Holor<int, 2> h2 {{1,2}, {3,4}};
EXPECT_TRUE( (h1==h2) );
EXPECT_TRUE( (h2==h1) );
EXPECT_TRUE( (h1==Holor<int, 2>{{1,2}, {3,4}}) );
EXPECT_TRUE( (Holor<int, 2>{{1,2}, {3,4}} == h1) );
}
{
std::vector<int> vec{1,2,3,4};
std::array<int,4> arr{1,2,3,4};
HolorRef<int, 2> h1 (vec.data(), Layout<2>(2,2));
HolorRef<int, 2> h2 (arr.data(), Layout<2>(2,2));
EXPECT_TRUE( (h1 == h2) );
EXPECT_TRUE( (h2 == h1) );
EXPECT_TRUE( (h1 == HolorRef<int, 2>(arr.data(), Layout<2>(2,2))) );
EXPECT_TRUE( (HolorRef<int, 2>(arr.data(), Layout<2>(2,2)) == h1) );
}
{
std::vector<int> vec{1,2,3,4};
HolorRef<int, 2> h1 (vec.data(), Layout<2>(2,2));
Holor<int, 2> h2{{1, 2}, {3, 4}};
EXPECT_TRUE( (h1 == h2) );
EXPECT_TRUE( (h2 == h1) );
EXPECT_TRUE( (h2 == HolorRef<int, 2>(vec.data(), Layout<2>(2,2))) );
EXPECT_TRUE( (HolorRef<int, 2>(vec.data(), Layout<2>(2,2)) == h2) );
EXPECT_TRUE( (h1 == Holor<int, 2>{{1,2}, {3,4}}) );
EXPECT_TRUE( (Holor<int, 2>{{1,2}, {3,4}} == h1) );
}
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 35.285714
| 98
| 0.622746
|
cmas1
|
65c2a37f7fe81f129b08baa6011382616fa71d87
| 336
|
cpp
|
C++
|
NKZX_NOI_OJ/P1298.cpp
|
Rose2073/RoseCppSource
|
bdaf5de04049b07bbe0e1ef976d1fbe72520fa03
|
[
"Apache-2.0"
] | 1
|
2021-04-05T16:26:00.000Z
|
2021-04-05T16:26:00.000Z
|
NKZX_NOI_OJ/P1298.cpp
|
Rose2073/RoseCppSource
|
bdaf5de04049b07bbe0e1ef976d1fbe72520fa03
|
[
"Apache-2.0"
] | null | null | null |
NKZX_NOI_OJ/P1298.cpp
|
Rose2073/RoseCppSource
|
bdaf5de04049b07bbe0e1ef976d1fbe72520fa03
|
[
"Apache-2.0"
] | null | null | null |
#include<cstdio>
bool yy[1001];
int main(){
int jj,zz,kk=0;
scanf("%d",&jj);
for(int i=0;i<jj;i++){
scanf("%d",&zz);
if(!yy[zz]){
yy[zz]=1;
kk++;
}
}
printf("%d\n",kk);
for(int i=1;i<=1000;i++){
if(yy[i])
printf("%d ",i);
}
return 0;
}
| 16.8
| 29
| 0.372024
|
Rose2073
|
65c2a8014a18d147935d01e4c3bc02c4c99bfe6b
| 1,158
|
cpp
|
C++
|
tests/wavelet_matrix_test.cpp
|
keijak/hikidashi-cpp
|
63d01dfa1587fa56fd7f4e50712f7c10d8168520
|
[
"Apache-2.0"
] | null | null | null |
tests/wavelet_matrix_test.cpp
|
keijak/hikidashi-cpp
|
63d01dfa1587fa56fd7f4e50712f7c10d8168520
|
[
"Apache-2.0"
] | null | null | null |
tests/wavelet_matrix_test.cpp
|
keijak/hikidashi-cpp
|
63d01dfa1587fa56fd7f4e50712f7c10d8168520
|
[
"Apache-2.0"
] | null | null | null |
#include <bits/stdc++.h>
#include "../src/wavelet_matrix.hpp"
#include "gtest/gtest.h"
using namespace std;
struct WaveletMatrixTest : public ::testing::Test {
vector<unsigned> vec;
WaveletMatrix<unsigned> wm;
WaveletMatrixTest() {
vec = {1, 3, 5, 7, 3, 2, 4, 1, 2, 3, 4};
wm = WaveletMatrix<unsigned>(vec);
}
};
TEST_F(WaveletMatrixTest, Basic) {
EXPECT_EQ(wm.size(), vec.size());
for (int i = 0; i < int(vec.size()); ++i) {
EXPECT_EQ(wm[i], vec[i]);
}
}
TEST_F(WaveletMatrixTest, Rank) {
EXPECT_EQ(wm.rank(3, 1), 0);
EXPECT_EQ(wm.rank(3, 2), 1);
EXPECT_EQ(wm.rank(3, 3), 1);
EXPECT_EQ(wm.rank(3, 5), 2);
EXPECT_EQ(wm.rank(3, 10), 3);
EXPECT_EQ(wm.rank(3, wm.size()), 3);
}
TEST_F(WaveletMatrixTest, KthSmallest) {
EXPECT_EQ(wm.kth_smallest(0, wm.size(), 0), 1);
EXPECT_EQ(wm.kth_smallest(1, 7, 0), 2);
EXPECT_EQ(wm.kth_smallest(1, 7, 1), 3);
EXPECT_EQ(wm.kth_smallest(1, 7, 2), 3);
EXPECT_EQ(wm.kth_smallest(1, 7, 3), 4);
EXPECT_EQ(wm.kth_smallest(1, 7, 4), 5);
EXPECT_EQ(wm.kth_smallest(10, 11, 0), 4);
}
TEST_F(WaveletMatrixTest, KthLargest) {
EXPECT_EQ(wm.kth_largest(0, wm.size(), 0), 7);
}
| 25.173913
| 51
| 0.635579
|
keijak
|
65c892a3f041a6b504ef1025ee4bd0f9400b46b4
| 2,777
|
cc
|
C++
|
src/client/StatusCommand.cc
|
ryan-rao/LTFS-Data-Management
|
041960282d20aeefb8da20eabf04367a164a5903
|
[
"Apache-2.0"
] | 19
|
2018-06-28T03:53:41.000Z
|
2022-03-15T16:17:33.000Z
|
src/client/StatusCommand.cc
|
ryan-rao/LTFS-Data-Management
|
041960282d20aeefb8da20eabf04367a164a5903
|
[
"Apache-2.0"
] | 13
|
2018-04-25T15:40:14.000Z
|
2021-01-18T11:03:27.000Z
|
src/client/StatusCommand.cc
|
ryan-rao/LTFS-Data-Management
|
041960282d20aeefb8da20eabf04367a164a5903
|
[
"Apache-2.0"
] | 8
|
2018-08-08T05:40:31.000Z
|
2022-03-22T16:21:06.000Z
|
/*******************************************************************************
* Copyright 2018 IBM Corp. 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
*
* https://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 <sys/resource.h>
#include <string>
#include <list>
#include <sstream>
#include <exception>
#include "src/common/errors.h"
#include "src/common/LTFSDMException.h"
#include "src/common/Message.h"
#include "src/common/Trace.h"
#include "src/communication/ltfsdm.pb.h"
#include "src/communication/LTFSDmComm.h"
#include "LTFSDMCommand.h"
#include "StatusCommand.h"
/** @page ltfsdm_status ltfsdm status
The ltfsdm status command provides the status of the LTFS Data Management service.
<tt>@LTFSDMC0030I</tt>
parameters | description
---|---
- | -
Example:
@verbatim
[root@visp ~]# ltfsdm status
LTFSDMC0032I(0068): The LTFS Data Management server process is operating with pid 13378.
@endverbatim
The corresponding class is @ref StatusCommand.
*/
void StatusCommand::printUsage()
{
INFO(LTFSDMC0030I);
}
void StatusCommand::doCommand(int argc, char **argv)
{
int pid;
processOptions(argc, argv);
if (argc > 1) {
printUsage();
THROW(Error::GENERAL_ERROR);
}
try {
connect();
} catch (const std::exception& e) {
MSG(LTFSDMC0026E);
return;
}
TRACE(Trace::normal, requestNumber);
commCommand.Clear();
LTFSDmProtocol::LTFSDmStatusRequest *statusreq =
commCommand.mutable_statusrequest();
statusreq->set_key(key);
statusreq->set_reqnumber(requestNumber);
try {
commCommand.send();
} catch (const std::exception& e) {
MSG(LTFSDMC0027E);
THROW(Error::GENERAL_ERROR);
}
try {
commCommand.recv();
} catch (const std::exception& e) {
MSG(LTFSDMC0028E);
THROW(Error::GENERAL_ERROR);
}
const LTFSDmProtocol::LTFSDmStatusResp statusresp =
commCommand.statusresp();
if (statusresp.success() == true) {
pid = statusresp.pid();
MSG(LTFSDMC0032I, pid);
} else {
MSG(LTFSDMC0029E);
THROW(Error::GENERAL_ERROR);
}
}
| 25.018018
| 93
| 0.623335
|
ryan-rao
|
65cd4d0b865ea0a1db86efa80b5310220d5aaab9
| 451
|
cpp
|
C++
|
tests/RenderCommandStream.cpp
|
KieranHsieh/GLB
|
9d959cca69984c876ef6e4267ed12ee80d444620
|
[
"MIT"
] | null | null | null |
tests/RenderCommandStream.cpp
|
KieranHsieh/GLB
|
9d959cca69984c876ef6e4267ed12ee80d444620
|
[
"MIT"
] | 20
|
2021-05-08T08:43:13.000Z
|
2021-05-14T00:02:59.000Z
|
tests/RenderCommandStream.cpp
|
KieranHsieh/GLB
|
9d959cca69984c876ef6e4267ed12ee80d444620
|
[
"MIT"
] | null | null | null |
#include "includes.hpp"
TEST_CASE("RenderCommandStream Add") {
using namespace GLB;
RenderCommandStream strm;
RenderCommandCustom cmd;
strm << cmd;
for(auto& cmd : strm) {
REQUIRE(cmd->localType == RenderCommandType::CUSTOM);
}
}
TEST_CASE("RenderCommandStream Size") {
using namespace GLB;
RenderCommandStream strm;
RenderCommandCustom cmd;
strm << cmd << cmd << cmd;
REQUIRE(strm.Size() == 3);
}
| 23.736842
| 61
| 0.658537
|
KieranHsieh
|
65ced6c6308cb6e81e4c1b3a69f280edddd80180
| 2,945
|
cpp
|
C++
|
2018-nov-23/K/K.cpp
|
acmiut/contests
|
757e198914697e81b9f3640ae315c3b539a49d17
|
[
"Apache-2.0"
] | null | null | null |
2018-nov-23/K/K.cpp
|
acmiut/contests
|
757e198914697e81b9f3640ae315c3b539a49d17
|
[
"Apache-2.0"
] | null | null | null |
2018-nov-23/K/K.cpp
|
acmiut/contests
|
757e198914697e81b9f3640ae315c3b539a49d17
|
[
"Apache-2.0"
] | 3
|
2019-03-31T13:29:09.000Z
|
2021-12-20T02:03:06.000Z
|
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
using namespace std;
typedef vector<int> VI;
typedef vector<VI> VVI;
const int INF = 1000000000;
struct MinCostMaxFlow {
int N;
VVI cap, flow, cost;
VI found, dad, dist, pi;
bool search(int source, int sink) {
fill(found.begin(), found.end(), false);
fill(dist.begin(), dist.end(), INF);
dist[source] = 0;
while (source != N) {
int best = N;
found[source] = true;
for (int k = 0; k < N; k++) {
if (found[k]) continue;
if (flow[k][source]) {
int val = dist[source] + pi[source] - pi[k] - cost[k][source];
if (dist[k] > val) {
dist[k] = val;
dad[k] = source;
}
}
if (flow[source][k] < cap[source][k]) {
int val = dist[source] + pi[source] - pi[k] + cost[source][k];
if (dist[k] > val) {
dist[k] = val;
dad[k] = source;
}
}
if (dist[k] < dist[best]) best = k;
}
source = best;
}
for (int k = 0; k < N; k++)
pi[k] = min(pi[k] + dist[k], INF);
return found[sink];
}
pair<int,int> getMaxFlow(const VVI &cap, const VVI &cost, int source, int sink) {
this->cap = cap;
this->cost = cost;
N = cap.size();
found = VI(N);
flow = VVI(N,VI(N));
dist = VI(N+1);
dad = VI(N);
pi = VI(N);
int totflow = 0, totcost = 0;
while (search(source, sink)) {
int amt = INF;
for (int x = sink; x != source; x = dad[x])
amt = min(amt, flow[x][dad[x]] ? flow[x][dad[x]] :
cap[dad[x]][x] - flow[dad[x]][x]);
for (int x = sink; x != source; x = dad[x]) {
if (flow[x][dad[x]]) {
flow[x][dad[x]] -= amt;
totcost -= amt * cost[x][dad[x]];
} else {
flow[dad[x]][x] += amt;
totcost += amt * cost[dad[x]][x];
}
}
totflow += amt;
}
return make_pair(totflow, totcost);
}
};
int main() {
int T;
cin >> T;
for (int tc = 0; tc < T; tc++) {
int M, N, A, B;
cin >> M >> N >> A >> B;
VI Acomp(N), Bcomp(N);
for (int i = 0; i < N; i++) cin >> Acomp[i];
for (int i = 0; i < N; i++) cin >> Bcomp[i];
VVI mat(M, VI(N));
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
cin >> mat[i][j];
}
}
int nv = 2 * N + M + 2;
VVI cap(nv, VI(nv)), cost(nv, VI(nv));
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
cap[i][N+j] = cap[N+j][M+N+i] = 100;
cost[i][N+j] = A * mat[j][i];
cost[N+j][M+N+i] = B * mat[j][i];
}
cap[nv-2][i] = Acomp[i];
cap[M+N+i][nv-1] = Bcomp[i];
}
MinCostMaxFlow flow;
pair<int, int> ans = flow.getMaxFlow(cap, cost, nv-2, nv-1);
cout << ans.second << endl;
}
}
| 24.541667
| 84
| 0.43837
|
acmiut
|
65d256ca83b4847e47c91e2b473ba8e56b843ced
| 442
|
cpp
|
C++
|
Math/TrailingZerosInFactorial.cpp
|
007mathur/InterviewBit
|
6b5560871d54b97546de10d83f6c4e74c420ce02
|
[
"MIT"
] | 1
|
2022-02-01T14:10:27.000Z
|
2022-02-01T14:10:27.000Z
|
Math/TrailingZerosInFactorial.cpp
|
007mathur/InterviewBit
|
6b5560871d54b97546de10d83f6c4e74c420ce02
|
[
"MIT"
] | null | null | null |
Math/TrailingZerosInFactorial.cpp
|
007mathur/InterviewBit
|
6b5560871d54b97546de10d83f6c4e74c420ce02
|
[
"MIT"
] | null | null | null |
//In a factorial a zero arises from the multiplication of 2*5.
//Every second number is even, so there are abundant 2s in the sea of prime factors of numbers.
//5s can be counted by adding all the factors of power of 5.
//As the numbers of 5s are less, the number of 0s is equal to this sum.
int Solution::trailingZeroes(int A) {
int ans=0;
for(int i=5;i<=A;i=i*5){
int temp = A/i;
ans += temp;
}
return ans;
}
| 36.833333
| 95
| 0.662896
|
007mathur
|
65d34015e89382a3aaa7f8761285f313294415a0
| 797
|
cpp
|
C++
|
notebook/demo/src/compdict.cpp
|
BrinedYoung/home
|
c8832758b3693c4f0af2839dd352b387e7854826
|
[
"MIT"
] | 1
|
2020-03-05T02:46:48.000Z
|
2020-03-05T02:46:48.000Z
|
notebook/demo/src/compdict.cpp
|
BrinedYoung/home
|
c8832758b3693c4f0af2839dd352b387e7854826
|
[
"MIT"
] | null | null | null |
notebook/demo/src/compdict.cpp
|
BrinedYoung/home
|
c8832758b3693c4f0af2839dd352b387e7854826
|
[
"MIT"
] | null | null | null |
/*
g++ -std=c++11 -o demo compdict.cpp
*/
#include <unordered_map>
#include <string>
#include <iostream>
using namespace std;
typedef string (*myFunc)(void);
typedef unordered_map<string, myFunc> compdict;
/* The functions */
string Boiler(void)
{
return "- BOILER -";
}
string Condenser(void)
{
return "-CONDENSER-";
}
string TurbineEx1(void)
{
return " -TURBINE-EX1- ";
}
int main()
{
compdict comps = {{"BOILER", &Boiler}, { "CONDENSER", &Condenser},{"TURBINE-EX1", &TurbineEx1}};
cout <<comps["BOILER"]()<< endl;
unordered_map<string, myFunc>::iterator iter;
for (iter = comps.begin(); iter != comps.end(); iter++)
{
cout << "key = " << iter->first << " result of the function "<< iter->second() << endl;
}
return 0;
}
| 18.113636
| 101
| 0.59724
|
BrinedYoung
|
65ddd600c50f69ef358fd25dba0ed22f2ca84226
| 10,149
|
cpp
|
C++
|
Source/Source.cpp
|
iiKurt/Egg
|
68371a017b80261c31258ef13c2ac2364ac44c02
|
[
"MIT"
] | null | null | null |
Source/Source.cpp
|
iiKurt/Egg
|
68371a017b80261c31258ef13c2ac2364ac44c02
|
[
"MIT"
] | 5
|
2022-01-03T05:18:28.000Z
|
2022-01-03T05:25:19.000Z
|
Source/Source.cpp
|
iiKurt/Egg
|
68371a017b80261c31258ef13c2ac2364ac44c02
|
[
"MIT"
] | null | null | null |
// TODOs:
// Consistent {} spacing and general formatting
// Huge project: seperate things into functions/classes? that have draw methods and properties such as color etc...
// Gamestates and all...
// File organisation and naming
// Using SDL and standard IO
#include <string>
#include <cstdlib> // srand, rand
#include <ctime> // time
#include <map>
#include <SDL.h>
#include "Font/LoadPSF.hpp"
#include "LoadTexture.hpp"
#include "DrawPSF.hpp"
#include "Resource.hpp"
#include "Resources.h"
// Game constants
const int ArrayHeight = 2;
const int ArrayLength = 8;
const int ArrayBreak = ArrayLength / 2;
const int StartIndex = ArrayLength - 1;
// Screen dimension constants (640 * 480)
int SCREEN_WIDTH = 410;
int SCREEN_HEIGHT = 240;
// Some global stuffs
int rendering = 0; // Look into "semaphores lazy foo SDL"
// The window we'll be rendering to
SDL_Window* window = NULL;
// The surface contained by the window
SDL_Renderer* renderer = NULL;
// Font
PSF1_FONT* font = NULL;
// Textures
SDL_Texture* happyMac = NULL;
SDL_Texture* sadMac = NULL;
// Rectangles for drawing which will specify source (inside the texture) and target (on the screen) for rendering our textures.
// Dimensions of Mac image are 26 * 29
SDL_Rect SrcR = { 0, 0, 26, 29 };
SDL_Rect DestR = { 0, 0, 26, 29 };
// Function declarations
inline long map(long x, long in_min, long in_max, long out_min, long out_max);
inline unsigned int aSensibleTime();
Uint32 tickerCallback(Uint32 interval, void* param);
Uint32 wonCallback(Uint32 interval, void* param);
void update();
void render();
// Game things
int acknowledgedWin = 0;
unsigned int acknowledgedWinCount = 0;
int knowsHowToPlay = 0;
int won = 0;
SDL_TimerID ticker;
short currentIndex = StartIndex;
short word[ArrayHeight][ArrayLength] = {{ 0 }}; // Clang go brrrr
std::map<int, std::string> eggEggTexts = {
{ 3, "You won!" },
{ 4, "Yep..."},
{ 5, "You sure did."},
{ 6, "Would you like a trophy?"},
{ 7, "Sorry, we're all out of stock."},
{ 9, "Could you please stop pressing [Space]?"},
{ 10, "ZZZzzzzZZZzzZZZzzZzz"},
{ 11, "zzzZZZZzzzZZzzzZZzZZ"},
{ 13, "Agh! I'm trying to sleep here..." },
{ 15, "Go away please!" },
{ 20, "I don't have anything of value here..." },
{ 30, "I am impressed by your persistence." },
{ 50, "Ok this is it, or is it?" },
{ 100, "Do you really have nothing better to do?" },
{ 500, "This must be getting old..." },
{ 1000, "R.I.P. keyboard." },
{ 2002, "Ayy" },
{ 5000, "I don't have anything for you."},
{ 10000, "Fine: 🏆"}, // 🏆
{ 10001, "Yeah this isn't a unicode font... ain't no trophies here."},
{ 10002, "Only corruption."},
{ 10004, "~\\_(^_^)_/~"}
};
// Executes on a different thread
// https://stackoverflow.com/a/40693139
static int resizeEventWatcher(void* data, SDL_Event* event) {
// Unused
(void)data;
if (event->type == SDL_WINDOWEVENT &&
event->window.event == SDL_WINDOWEVENT_RESIZED) {
SCREEN_WIDTH = event->window.data1;
SCREEN_HEIGHT = event->window.data2;
render();
}
return 0;
}
int main(int argc, char* argv[]) // int argc, char* args[]
{
// Unused
(void)argc;
(void)argv;
// Initialize SDL
if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER) < 0)
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL could not initialize! SDL_Error: %s\n", SDL_GetError());
}
else
{
// Create window
window = SDL_CreateWindow("Egg", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT,
SDL_WINDOW_SHOWN|
SDL_WINDOW_RESIZABLE);
if (window == NULL)
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Window could not be created! SDL_Error: %s\n", SDL_GetError());
}
else // Window creation successful
{
// Define window behaviour
SDL_SetWindowMinimumSize(window, 410, 240); // 100, 70
// Add some event watchers
SDL_AddEventWatch(resizeEventWatcher, window);
// Create a hardware accelerated renderer
renderer = SDL_CreateRenderer(window, 0, SDL_RENDERER_ACCELERATED);
// Could have all the file resource loading stuff under one try block
try {
// Load font
#ifdef _WIN32
Resource fontR = Resource(RESOURCE_FONT_PATH, RESOURCE_FONT, FILE_PSF);
#else
Resource fontR = Resource(RESOURCE_FONT_PATH);
#endif
font = LoadPSF1Font(&fontR);
// Load textures
#ifdef _WIN32
Resource happyMacR = Resource(RESOURCE_HAPPYMAC_PATH, RESOURCE_HAPPYMAC, FILE_BITMAP);
Resource sadMacR = Resource(RESOURCE_SADMAC_PATH, RESOURCE_HAPPYMAC, FILE_BITMAP);
#else
Resource happyMacR = Resource(RESOURCE_HAPPYMAC_PATH);
Resource sadMacR = Resource(RESOURCE_SADMAC_PATH);
#endif
happyMac = LoadTexture(renderer, &happyMacR);
sadMac = LoadTexture(renderer, &sadMacR);
}
catch (const FileError& ex) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "File load error: %s Filename: %s", ex.what(), ex.path);
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR,
"File load error",
(std::string() + ex.what() + "\r\nFilename: " + ex.path).c_str(),
window);
return 1;
}
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Successfully loaded"); // Shorthand: SDL_Log("whatever");
// Set color
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
// Fill screen with color
SDL_RenderClear(renderer);
// So we don't have to wait for the timer to finish to see the render
render();
///////////////////////////////////////////////////////////////////////////////////////////////////
srand((unsigned)time(0));
// Populate top row of numbers
for (short i = 0; i < ArrayLength; i++) {
word[0][i] = rand() % 16;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
SDL_Event event;
ticker = SDL_AddTimer(aSensibleTime(), tickerCallback, NULL);
int running = 1;
while (running)
{
if (SDL_WaitEvent(&event) != 0) {
switch (event.type) {
case SDL_KEYDOWN:
switch (event.key.keysym.sym) {
case SDLK_SPACE:
if (won) {
acknowledgedWinCount++;
}
else { // Don't process key stuff
knowsHowToPlay = 1;
if (word[1][currentIndex] == word[0][currentIndex]) {
if (--currentIndex < 0) { // End of the row, game complete
won = 1; // heh
SDL_RemoveTimer(ticker);
ticker = SDL_AddTimer(500, wonCallback, NULL);
render(); // show that happy mac!
break;
}
}
else if (currentIndex < StartIndex) { // Pressed at wrong time
currentIndex++; // Go back
}
update();
}
render();
break;
}
break;
// Handle OS level events
case SDL_QUIT:
running = 0;
break;
}
}
}
}
}
// Remove timer
SDL_RemoveTimer(ticker);
// Destory renderer
SDL_DestroyRenderer(renderer);
// Destroy window
SDL_DestroyWindow(window);
// Quit SDL subsystems
SDL_Quit();
return 0;
}
// Utility functions
inline long map(long x, long in_min, long in_max, long out_min, long out_max) {
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
inline unsigned int aSensibleTime() {
//return map(currentIndex, 0, StartIndex, 500, 1500); // Hard mode
return map(currentIndex, 0, StartIndex, 1500, 500); // EZ mode
}
Uint32 tickerCallback(Uint32 interval, void* param) {
// Unused
(void)interval;
(void)param;
SDL_RemoveTimer(ticker);
ticker = SDL_AddTimer(aSensibleTime(), tickerCallback, NULL);
update();
render();
return 0;
}
Uint32 wonCallback(Uint32 interval, void* param) {
// Unused
(void)interval;
(void)param;
SDL_RemoveTimer(ticker);
acknowledgedWin = 1;
render();
return 0;
}
// Update and render methods
void update() {
word[1][currentIndex] = rand() % 16; // Generate random number
}
void render() {
if (rendering) {
return;
}
rendering = 1;
if (!knowsHowToPlay) {
SDL_SetRenderDrawColor(renderer, 0, 192, 224, 255);
// 45 characters in help text, each one is 8 px long:
PrintString(renderer, font, "Press [Space] to confirm current character...", (SCREEN_WIDTH / 2) - ((45 * 8) / 2), 20);
}
// Draw Mac (26 * 29 image)
DestR.x = (SCREEN_WIDTH / 2) - (26 / 2);
DestR.y = (SCREEN_HEIGHT / 2) - ((29 / 2) * 3);
if (won) {
SDL_RenderCopy(renderer, happyMac, &SrcR, &DestR);
if (eggEggTexts.count(acknowledgedWinCount) == 1) { // Item exists
// Do the eggEgg stuffs
SDL_SetRenderDrawColor(renderer, 0, 192, 224, 255);
std::string text = eggEggTexts[acknowledgedWinCount];
// Calculate how many px the string would be if each char is 8 px long
PrintString(renderer, font, text.c_str(), (SCREEN_WIDTH / 2) - ((text.length() * 8) / 2), 20);
//std::cout << eggEggTexts[acknowledgedWinCount] << std::endl;
}
}
else {
SDL_RenderCopy(renderer, sadMac, &SrcR, &DestR);
}
if (won && !acknowledgedWin) {
// Only applies to text
SDL_SetRenderDrawColor(renderer, 0, 255, 0, 255);
}
else {
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
}
for (short i = 0; i < ArrayLength; i++) { // For each column
int x; // https://stackoverflow.com/a/8735780
int y;
for (int j = 0; j < ArrayHeight; j++) // For each row
{
// First number = offset
// Second number - 6 = padding between each char
// 10, 10
x = ((SCREEN_WIDTH / 2) - ((ArrayLength / 2) * 10)) + (10 * i);
// 14, 16
y = ((SCREEN_HEIGHT / 2) - ((ArrayHeight / 2) * -6)) + (16 * j);
if (i < ArrayBreak) // Left side
{
x -= 2;
}
else {
x += 2;
}
PrintCharacter(renderer, font, (word[j][i] > 9) ? (word[j][i] - 10) + 'A' : word[j][i] + '0', x, y);
}
if (currentIndex == i) {
SDL_RenderDrawLine(renderer, x, y + 14, x + 7, y + 14);
}
}
// Draw any pending data to the screen
SDL_RenderPresent(renderer);
// Clear the screen for next time
// The backbuffer should be considered invalidated after each present;
// do not assume that previous contents will exist between frames.
// Set color
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
// Fill screen with color
SDL_RenderClear(renderer);
rendering = 0;
}
| 27.504065
| 127
| 0.638092
|
iiKurt
|
65de7a666a5bd8d8ff8d756440b2c5f883b6d66b
| 1,478
|
cpp
|
C++
|
client/include/util/Path.cpp
|
MayconFelipeA/sampvoiceatt
|
3fae8a2cf37dfad2e3925d56aebfbbcd4162b0ff
|
[
"MIT"
] | 97
|
2019-01-13T20:19:19.000Z
|
2022-02-27T18:47:11.000Z
|
client/include/util/Path.cpp
|
MayconFelipeA/sampvoiceatt
|
3fae8a2cf37dfad2e3925d56aebfbbcd4162b0ff
|
[
"MIT"
] | 92
|
2019-01-23T23:02:31.000Z
|
2022-03-23T19:59:40.000Z
|
client/include/util/Path.cpp
|
MayconFelipeA/sampvoiceatt
|
3fae8a2cf37dfad2e3925d56aebfbbcd4162b0ff
|
[
"MIT"
] | 69
|
2019-01-13T22:01:40.000Z
|
2022-03-09T00:55:49.000Z
|
/*
This is a SampVoice project file
Developer: CyberMor <cyber.mor.2020@gmail.ru>
See more here https://github.com/CyberMor/sampvoice
Copyright (c) Daniel (CyberMor) 2020 All rights reserved
*/
#include "Path.h"
#include <array>
#include <ShlObj.h>
#include "Logger.h"
Path::Path()
{
constexpr char kSVDirRelativePath[] = "\\" "GTA San Andreas User Files"
"\\" "sampvoice";
std::array<char, MAX_PATH> myDocumentsPath {};
if (const auto hResult = SHGetFolderPath(NULL, CSIDL_MYDOCUMENTS | CSIDL_FLAG_CREATE,
NULL, SHGFP_TYPE_CURRENT, myDocumentsPath.data()); FAILED(hResult))
{
Logger::LogToFile("[err:path] : failed to get 'MyDocuments' directory (code:%ld)", hResult);
throw std::exception();
}
this->pathString.reserve(MAX_PATH);
this->pathString.append(myDocumentsPath.data());
this->pathString.append(kSVDirRelativePath, sizeof(kSVDirRelativePath) - 1);
if (const auto rCode = SHCreateDirectoryEx(NULL, this->pathString.c_str(), NULL);
rCode != ERROR_ALREADY_EXISTS && rCode != ERROR_FILE_EXISTS && rCode != ERROR_SUCCESS)
{
Logger::LogToFile("[err:path] : failed to create plugin directory (code:%d)", rCode);
throw std::exception();
}
}
Path::operator const char* () const noexcept
{
return this->pathString.c_str();
}
Path::operator const std::string& () const noexcept
{
return this->pathString;
}
| 27.37037
| 100
| 0.655616
|
MayconFelipeA
|
65e4df8c42cdd84dcb7e0060dee85073cdf56b1e
| 21,895
|
cc
|
C++
|
util/Scattering.cc
|
erikleitch/climax
|
66ce64b0ab9f3a3722d3177cc5215ccf59369e88
|
[
"MIT"
] | 1
|
2018-11-01T05:15:31.000Z
|
2018-11-01T05:15:31.000Z
|
util/Scattering.cc
|
erikleitch/climax
|
66ce64b0ab9f3a3722d3177cc5215ccf59369e88
|
[
"MIT"
] | null | null | null |
util/Scattering.cc
|
erikleitch/climax
|
66ce64b0ab9f3a3722d3177cc5215ccf59369e88
|
[
"MIT"
] | 2
|
2017-05-02T19:35:55.000Z
|
2018-03-07T00:54:51.000Z
|
#include "gcp/util/Constants.h"
#include "gcp/util/Energy.h"
#include "gcp/util/FileHandler.h"
#include "gcp/util/Scattering.h"
#include "gcp/util/SzCalculator.h"
#include "gsl/gsl_sf_gamma.h"
#include <fcntl.h>
#include <arpa/inet.h>
#include <unistd.h>
using namespace std;
using namespace gcp::util;
static double betacf(double a, double b, double x);
/**.......................................................................
* Constructor.
*/
Scattering::Scattering()
{
norm_ = 1.0;
debug_ = false;
double k = Constants::kBoltzCgs_;
double c = Constants::lightSpeed_.centimetersPerSec();
double h = Constants::hPlanckCgs_;
double T = Constants::Tcmb_.K();
double kT = k*T;
double hc = h*c;
planckNormalization_.setJyPerSr(2*(kT*kT*kT)/(hc*hc) * 1e23);
}
/**.......................................................................
* Destructor.
*/
Scattering::~Scattering() {}
/**.......................................................................
* Initialize a thermal tail distribution
*/
void Scattering::initializeThermalTailDistribution(Temperature& Te, double alpha, double p1, double p2)
{
electronTemperature_ = Te;
Energy thermalE;
thermalE = Te;
Energy restMassE;
restMassE = Constants::electronMass_;
//------------------------------------------------------------
// Calculate eta -- the ratio of the thermal to rest-mass energy
//------------------------------------------------------------
eta_ = restMassE / thermalE;
alpha_ = alpha;
p1_ = p1;
p2_ = p2;
lowLim_ = 0.0;
highLim_ = p2_;
//------------------------------------------------------------
// And normalize momentum distribution for this temperature
//------------------------------------------------------------
momentumDistribution_ = &intThermalTailDistribution;
photonRedistributionFunction_ = &photonRedistributionFunctionInfinite;
equivalentThermalEnergyFunction_ = &equivalentThermalEnergyFunctionInfinite;
norm_ = integratorDist_.integrateFromLowlimToHighlim(momentumDistribution_, (void*)this, 0, highLim_);
equivalentThermalEnergyPerRestmass_ = equivalentThermalEnergyFunction_((void*)this);
}
/**.......................................................................
* Initialize a thermal distribution
*/
void Scattering::initializeThermalDistribution(Temperature& Te)
{
electronTemperature_ = Te;
Energy thermalE;
thermalE = Te;
Energy restMassE;
restMassE = Constants::electronMass_;
//------------------------------------------------------------
// Calculate eta -- the ratio of the thermal to rest-mass energy
//------------------------------------------------------------
eta_ = restMassE / thermalE;
//------------------------------------------------------------
// And normalize momentum distribution for this temperature
//------------------------------------------------------------
momentumDistribution_ = &intThermalMomentumDistribution;
photonRedistributionFunction_ = &photonRedistributionFunctionInfinite;
equivalentThermalEnergyFunction_ = &equivalentThermalEnergyFunctionInfinite;
norm_ = integratorDist_.integrateFromLowlimToInfty(momentumDistribution_, (void*)this, 0);
equivalentThermalEnergyPerRestmass_ = equivalentThermalEnergyFunction_((void*)this);
}
/**.......................................................................
* Initialize a power-law distribution
*/
void Scattering::initializePowerlawDistribution(double alpha, double p1, double p2)
{
Energy restMassE;
restMassE = Constants::electronMass_;
alpha_ = alpha;
p1_ = p1;
p2_ = p2;
lowLim_ = p1_;
highLim_ = p2_;
//------------------------------------------------------------
// And normalize momentum distribution for this temperature
//------------------------------------------------------------
momentumDistribution_ = &intPowerlawMomentumDistribution;
equivalentThermalEnergyFunction_ = &equivalentThermalEnergyFunctionFinite;
photonRedistributionFunction_ = &photonRedistributionFunctionFinite;
norm_ = integratorDist_.integrateFromLowlimToHighlim(momentumDistribution_, (void*)this, lowLim_, highLim_);
equivalentThermalEnergyPerRestmass_ = equivalentThermalEnergyFunction_((void*)this);
}
/**.......................................................................
* Initialize a mono-energetic spectrum
*/
void Scattering::initializeMonoEnergeticDistribution(double p)
{
initializePowerlawDistribution(0.0, 0.9*p, 1.1*p);
}
/**.......................................................................
* Initialize a power-law distribution
*/
void Scattering::initializePowerlawDistribution2(double alpha, double p1, double p2)
{
alpha_ = alpha;
p1_ = p1;
p2_ = p2;
lowLim_ = p1_;
highLim_ = p2_;
//------------------------------------------------------------
// And normalize momentum distribution for this temperature
//------------------------------------------------------------
momentumDistribution_ = &intPowerlawMomentumDistribution;
equivalentThermalEnergyFunction_ = &equivalentThermalEnergyFunctionFinite;
photonRedistributionFunction_ = &photonRedistributionFunctionPowerlaw;
equivalentThermalEnergyPerRestmass_ = equivalentThermalEnergyFunction_((void*)this);
}
/**.......................................................................
* Calculate a power-law momentum distribution
*/
double Scattering::powerlawMomentumDistribution(double p, double alpha, double p1, double p2)
{
if(p < p1 || p > p2)
return 0;
double pa = pow(p, -alpha);
double p1a = pow(p1, 1.0-alpha);
double p2a = pow(p2, 1.0-alpha);
return (alpha-1.0) * pa / (p1a - p2a);
}
INT_FN(Scattering::intPowerlawMomentumDistribution)
{
Scattering* s = (Scattering*) params;
return s->powerlawMomentumDistribution(x, s->alpha_, s->p1_, s->p2_);
}
double Scattering::thermalMomentumDistribution(double p, double eta, double norm)
{
double p2 = p*p;
return p2 * exp(-eta * sqrt(1.0+p2)) / norm;
}
INT_FN(Scattering::intThermalMomentumDistribution)
{
Scattering* s = (Scattering*) params;
return s->thermalMomentumDistribution(x, s->eta_, s->norm_);
}
double Scattering::thermalTailDistribution(double p, double eta, double norm, double alpha, double p1, double p2)
{
if(p <= p1)
return thermalMomentumDistribution(p, eta, norm);
else if(p > p2)
return 0.0;
else
return thermalMomentumDistribution(p, eta, norm) * pow(p/p1, -alpha);
}
INT_FN(Scattering::intThermalTailDistribution)
{
Scattering* s = (Scattering*) params;
return s->thermalTailDistribution(x, s->eta_, s->norm_, s->alpha_, s->p1_, s->p2_);
}
/**.......................................................................
* Evaluate the photon redistribution function for a mono-energetic
* electron distribution, from Ensslin and Kaiser, A&A 360, 417 (2000),
*
* where t is the ratio of the shifted frequency to the unshifted frequency:
*
* t = nu' / nu
*
* and p is the normalized electron momentum:
*
* p = beta_e * gamma_e
*
* (for v_e = beta_e * c, and gamma = (k T_e)/(m_e c^2))
*
*/
double Scattering::photonRedistributionFunctionMono(double t, double p)
{
double p2, p4, p5, p6;
p2 = p*p;
p4 = p2*p2;
p5 = p4*p;
p6 = p4*p2;
double flnt = fabs(log(t));
double ashp = asinh(p);
if(flnt > 2*ashp)
return 0.0;
double prefac1 = -3*fabs(1.0-t)/(32*p6*t);
double fac1 = (1.0 + (10.0 + 8*p2 + 4*p4)*t + t*t);
double prefac2 = 3*(1.0 + t)/(8*p5);
double subfac21 = (3.0 + 3*p2 + p4) / sqrt(1.0 + p2);
double subfac22 = -(3.0 + 2*p2) / (2*p) * (2*ashp - flnt);
double fac2 = subfac21 + subfac22;
return prefac1 * fac1 + prefac2 * fac2;
}
INT_FN(Scattering::intScatteringKernel)
{
Scattering* s = (Scattering*) params;
// COUT("Inside kernel with x = " << x << " eta = " << s->eta_ << " norm = " << s->norm_ << " t = " << s->t_);
// COUT("fac1 = " << s->thermalMomentumDistribution(x, s->eta_, s->norm_));
// COUT("fac2 = " << s->photonRedistributionFunctionMono(s->t_, x));
return s->momentumDistribution_(x, params) * s->photonRedistributionFunctionMono(s->t_, x);
}
INT_FN(Scattering::equivalentThermalEnergyKernel)
{
Scattering* s = (Scattering*) params;
// Convert from scaled momentum to beta
double beta = x/sqrt(1.0 + x*x);
return s->momentumDistribution_(x, params) * x * beta / 3;
}
/**.......................................................................
* Calculate the photon redistribution function for the current
* momentum distribution
*/
REDIST_FN(Scattering::photonRedistributionFunctionFinite)
{
Scattering* s = (Scattering*) params;
s->t_ = t;
return s->integratorDist_.integrateFromLowlimToHighlim(&s->intScatteringKernel, params, s->lowLim_, s->highLim_);
}
REDIST_FN(Scattering::photonRedistributionFunctionInfinite)
{
Scattering* s = (Scattering*) params;
s->t_ = t;
return s->integratorDist_.integrateFromLowlimToInfty(&s->intScatteringKernel, params, 0);
}
/**.......................................................................
* Calculate the photon redistribution function for a powerlaw
* momentum distribution
*/
REDIST_FN(Scattering::photonRedistributionFunctionPowerlaw)
{
Scattering* s = (Scattering*) params;
return s->powerlawPhotonRedistributionFunction(t, s->alpha_, s->p1_, s->p2_);
}
/**.......................................................................
* Calculate the equivalent thermal energy for the current momentum
* distribution
*/
ETE_FN(Scattering::equivalentThermalEnergyFunctionFinite)
{
Scattering* s = (Scattering*) params;
return s->integratorDist_.integrateFromLowlimToHighlim(&s->equivalentThermalEnergyKernel, params, s->lowLim_, s->highLim_);
}
ETE_FN(Scattering::equivalentThermalEnergyFunctionInfinite)
{
Scattering* s = (Scattering*) params;
return s->integratorDist_.integrateFromLowlimToInfty(&s->equivalentThermalEnergyKernel, params, 0);
}
double Scattering::g(double x)
{
return (scatteredSpectralShape(x) - planckSpectralShape(x)) / equivalentThermalEnergyPerRestmass_;
}
double Scattering::jmi(double x)
{
return (scatteredSpectralShape(x) - planckSpectralShape(x));
}
/**.......................................................................
* Main method of this class. Calculate the conversion from Compton Y
* to intensity given an arbitrary electron distribution
*/
void Scattering::comptonYToDeltaI(Frequency& freq, Intensity& YtoI)
{
double x = SzCalculator::planckX(freq, Constants::Tcmb_);
YtoI.setJyPerSr(g(x) * planckNormalization_.JyPerSr());
}
/**.......................................................................
* Main method of this class. Calculate the conversion from Compton Y
* to intensity given an arbitrary electron distribution
*/
void Scattering::comptonYToDeltaT(Frequency& freq, Temperature& YtoT)
{
double x = SzCalculator::planckX(freq, Constants::Tcmb_);
double ex = exp(x);
YtoT.setK((ex-1)*(ex-1)/(x*x*x*x*ex) * g(x) * Constants::Tcmb_.K());
}
/**.......................................................................
* Return the Planck intensity spectrum
*/
Intensity Scattering::planck(Frequency& freq, Temperature& temp)
{
Intensity intensity;
double x = SzCalculator::planckX(freq, temp);
double fac = planckSpectralShape(x);
intensity.setJyPerSr(fac * planckNormalization_.JyPerSr());
return intensity;
}
/**.......................................................................
* Return the scattered Planck intensity spectrum
*/
Intensity Scattering::scatteredPlanckSpectrum(Frequency& freq, Temperature& temp)
{
Intensity intensity;
double x = SzCalculator::planckX(freq, temp);
double fac = scatteredSpectralShape(x);
intensity.setJyPerSr(fac * planckNormalization_.JyPerSr());
return intensity;
}
/**.......................................................................
* Return the Planck intensity spectrum
*/
double Scattering::planckSpectralShape(double x)
{
return x*x*x / (exp(x) - 1.0);
}
/**.......................................................................
* Return h(x)
*/
double Scattering::h(double x)
{
double ex = exp(x);
return x*x*x*x*ex / ((ex - 1.0) * (ex - 1.0));
}
/**.......................................................................
* Return h(x)
*/
double Scattering::kompaneetsSpectralShape(double x)
{
double ex = exp(x);
return h(x) * (x * (ex + 1)/(ex - 1) - 4);
}
/**.......................................................................
* Calculate the scattered Planck spectrum given an arbitrary
* electron distribution
*/
double Scattering::scatteredSpectralShape(double x)
{
x_ = x;
return integratorSpec_.integrateFromLowlimToInfty(&intScatteredSpectrumKernel, (void*)this, 0);
}
INT_FN(Scattering::intScatteredSpectrumKernel)
{
Scattering* s = (Scattering*) params;
return s->photonRedistributionFunction_(x, params) * s->planckSpectralShape(s->x_/x);
}
double Scattering::powerlawPhotonRedistributionFunction(double t, double alpha, double p1, double p2)
{
double lnt = fabs(log(t));
double ashp = asinh(p2);
if(lnt > 2*ashp)
return 0.0;
double prefac = (alpha-1.0) / (pow(p1, 1.0-alpha) - pow(p2, 1.0-alpha)) * 3*(1.0+t)/16;
double tsqrt2 = sqrt(t)/2;
double p1arg = p1 > tsqrt2 ? p1 : tsqrt2;
double p2arg = p2 > tsqrt2 ? p2 : tsqrt2;
double fac1 = powerlawEvalFn(t, p2arg, alpha);
double fac2 = powerlawEvalFn(t, p1arg, alpha);
if(debug_) {
COUT("t = " << t << " lnt = " << lnt << " ashp = " << ashp << " tsqrt2 = " << tsqrt2 << " p1 = " << p1 << " p2 = " << p2 << " alpha = " << alpha);
}
if(fac1 > fac2) {
COUT("returning 0.0 for t = " << t);
} else {
COUT("Not returning 0.0 for t = " << t);
}
return fac1 > fac2 ? prefac * (fac1 - fac2) : 0.0;
// return prefac * (fac1 - fac2);
}
double Scattering::powerlawEvalFn(double t, double p, double alpha)
{
double lnt = fabs(log(t));
double ashp = asinh(p);
double x = 1.0/(1.0 + p*p);
double fac1 = -incompleteBetaBx((1.0+alpha)/2, -alpha/2, x);
double fac2 = -incompleteBetaBx((3.0+alpha)/2, -(2.0+alpha)/2, x) * (7.0+3*alpha)/(3.0+alpha);
double fac3 = -incompleteBetaBx((5.0+alpha)/2, -(4.0+alpha)/2, x) * (12.0+3*alpha)/(5.0+alpha);
double p2 = p*p;
double prefac4 = pow(p, -5.0-alpha);
double fac41 = (3.0/(5+alpha) + 2*p*p/(3+alpha)) * (2*ashp-lnt);
double fac42 = fabs((1.0-t)/(1.0+t)) * ((1+t*t)/(2*(5+alpha)*t) + 5.0/(5+alpha) + 4*p2/(3+alpha) + 2*p2*p2/(1+alpha));
double fac4 = prefac4 * (fac41 + fac42);
return fac1 + fac2 + fac3 + fac4;
}
/**.......................................................................
* Returns the incomplete beta function:
*
* B_x(a,b) = I_x(a,b) * B(a,b)
*
*/
double Scattering::incompleteBetaBx(double a, double b, double x)
{
return gsl_sf_beta_inc(a, b, x) * gsl_sf_beta(a,b);
}
/**.......................................................................
* Returns the incomplete beta function:
*
* B_x(a,b)
* I_x(a,b) = --------
* B(a,b)
*
*/
double Scattering::incompleteBetaIx(double a, double b, double x)
{
return gsl_sf_beta_inc(a, b, x);
}
double betacf(double a, double b, double x)
{
int m,m2;
double aa,c,d,del,h,qab,qam,qap;
unsigned maxIt = 100;
double eps = 3.0e-7;
double fpMin = 1.0e-30;
qab=a+b;
qap=a+1.0;
qam=a-1.0;
c=1.0;
d=1.0-qab*x/qap;
if (fabs(d) < fpMin) d=fpMin;
d=1.0/d;
h=d;
for (m=1;m<=maxIt;m++) {
m2=2*m;
aa=m*(b-m)*x/((qam+m2)*(a+m2));
d=1.0+aa*d;
if (fabs(d) < fpMin) d=fpMin;
c=1.0+aa/c;
if (fabs(c) < fpMin) c=fpMin;
d=1.0/d;
h *= d*c;
aa = -(a+m)*(qab+m)*x/((a+m2)*(qap+m2));
d=1.0+aa*d;
if (fabs(d) < fpMin) d=fpMin;
c=1.0+aa/c;
if (fabs(c) < fpMin) c=fpMin;
d=1.0/d;
del=d*c;
h *= del;
if (fabs(del-1.0) < eps) break;
}
if (m > maxIt)
ThrowError("a or b too big, or maxIt too small in betacf()");
return h;
}
void Scattering::setDebug(bool debug)
{
debug_ = debug;
}
void Scattering::computePowerlawGrid(double alphaMin, double alphaMax, unsigned nAlpha,
double p1Min, double p1Max, unsigned nP1,
double p2Min, double p2Max, unsigned nP2,
double xMin, double xMax, unsigned nx,
std::string fileName)
{
if(FileHandler::fileExists(fileName)) {
ThrowSimpleError("File: " << fileName << " already exists");
}
int fd = open(fileName.c_str(), O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR);
COUT("Opened " << fileName << " fd = " << fd);
//------------------------------------------------------------
// Write the grid size
//------------------------------------------------------------
unsigned nl = htonl(nAlpha);
write(fd, (void*)&nl, sizeof(nl));
write(fd, (void*)&alphaMin, sizeof(double));
write(fd, (void*)&alphaMax, sizeof(double));
nl = htonl(nP1);
write(fd, (void*)&nl, sizeof(nl));
write(fd, (void*)&p1Min, sizeof(double));
write(fd, (void*)&p1Max, sizeof(double));
nl = htonl(nP2);
write(fd, (void*)&nl, sizeof(nl));
write(fd, (void*)&p2Min, sizeof(double));
write(fd, (void*)&p2Max, sizeof(double));
nl = htonl(nx);
write(fd, (void*)&nl, sizeof(nl));
write(fd, (void*)&xMin, sizeof(double));
write(fd, (void*)&xMax, sizeof(double));
//------------------------------------------------------------
// Now calculate the grid
//------------------------------------------------------------
double dAlpha = (alphaMax - alphaMin) / (nAlpha-1);
double dP1 = (p1Max - p1Min) / (nP1-1);
double dP2 = (p2Max - p2Min) / (nP2-1);
double dx = (xMax - xMin) / (nx-1);
for(unsigned iAlpha=0; iAlpha < nAlpha; iAlpha++) {
double alpha = alphaMin + iAlpha * dAlpha;
for(unsigned iP1=0; iP1 < nP1; iP1++) {
double p1 = p1Min + iP1 * dP1;
for(unsigned iP2=0; iP2 < nP2; iP2++) {
double p2 = p2Min + iP2 * dP2;
initializePowerlawDistribution(alpha, p1, p2);
for(unsigned ix=0; ix < nx; ix++) {
double x = xMin + dx * ix;
double val = g(x);
write(fd, (void*)&val, sizeof(val));
}
}
}
}
//------------------------------------------------------------
// Finally close the file
//------------------------------------------------------------
close(fd);
}
void Scattering::loadPowerlawGrid(std::string fileName)
{
powerlawGridder_.initialize(fileName);
}
double Scattering::GridParameter::distance(double val, unsigned ind)
{
return (val - (min_ + delta_ * ind)) / delta_;
}
void Scattering::GridParameter::findBracketing(double val, int& i1, int& i2)
{
int iNear = (int)(val - min_) / delta_;
double nearVal = min_ + delta_ * iNear;
if(iNear >= npt_-1) {
i1 = npt_ - 2;
i2 = npt_ - 1;
} else if(iNear <= 0) {
i1 = 0;
i2 = 1;
} else {
i1 = nearVal < val ? iNear : iNear-1;
i2 = nearVal < val ? iNear+1 : iNear;
}
}
void Scattering::GridParameter::load(int fd)
{
unsigned nl;
double val;
::read(fd, &nl, sizeof(nl));
npt_ = htonl(nl);
::read(fd, &val, sizeof(double));
min_ = val;
::read(fd, &val, sizeof(double));
max_ = val;
delta_ = (max_ - min_) / (npt_-1);
}
void Scattering::PowerlawGridder::initialize(std::string fileName)
{
int fd = open(fileName.c_str(), O_RDONLY);
parameters_.resize(4);
parameters_[0].load(fd);
parameters_[1].load(fd);
parameters_[2].load(fd);
parameters_[3].load(fd);
//------------------------------------------------------------
// Now load the data
//------------------------------------------------------------
unsigned nArr = parameters_[0].npt_ * parameters_[1].npt_ * parameters_[2].npt_;
vals_.resize(nArr);
unsigned xLen = parameters_[3].npt_;
for(unsigned i=0; i < nArr; i++) {
vals_[i].resize(xLen);
for(unsigned ix=0; ix < xLen; ix++) {
::read(fd, &vals_[i][ix], sizeof(double));
}
}
close(fd);
}
/**.......................................................................
* Get the requested grid value
*/
double Scattering::PowerlawGridder::getVal(int iAlpha, int iP1, int iP2, int iX)
{
int nAlpha = parameters_[0].npt_;
int nP1 = parameters_[1].npt_;
int nP2 = parameters_[2].npt_;
int nX = parameters_[3].npt_;
int ind = iP2 + nP2*(iP1 + nP1*iAlpha);
return vals_[ind][iX];
}
/**.......................................................................
* Interpolate the requested point off the 4-dimensional grid!
*/
double Scattering::PowerlawGridder::interpolate(double alpha, double p1, double p2, double x)
{
int iAlphaMin, iAlphaMax;
int iP1Min, iP1Max;
int iP2Min, iP2Max;
int iXMin, iXMax;
parameters_[0].findBracketing(alpha, iAlphaMin, iAlphaMax);
parameters_[1].findBracketing(p1, iP1Min, iP1Max);
parameters_[2].findBracketing(p2, iP2Min, iP2Max);
parameters_[3].findBracketing(x, iXMin, iXMax);
double mean = 0.0;
double wtSum = 0.0;
double dist2, wt;
double sigInPixels = 0.594525;
for(int iAlpha=iAlphaMin; iAlpha <= iAlphaMax; iAlpha++) {
double dAlpha = parameters_[0].distance(alpha, iAlpha);
for(int iP1=iP1Min; iP1 <= iP1Max; iP1++) {
double dP1 = parameters_[1].distance(p1, iP1);
for(int iP2=iP2Min; iP2 <= iP2Max; iP2++) {
double dP2 = parameters_[2].distance(p2, iP2);
for(int iX=iXMin; iX <= iXMax; iX++) {
double dX = parameters_[3].distance(x, iX);
dist2 = dAlpha*dAlpha + dP1*dP1 + dP2*dP2 + dX*dX;
wt = exp(-dist2 / (2*sigInPixels*sigInPixels));
double val = getVal(iAlpha, iP1, iP2, iX);
mean += ((val - mean)*wt) / (wtSum + wt);
wtSum += wt;
}
}
}
}
return mean;
}
ostream&
gcp::util::operator<<(std::ostream& os, const Scattering::GridParameter& param)
{
os << "nPt = " << param.npt_;
os << " min = " << param.min_;
os << " max = " << param.max_;
return os;
}
| 28.885224
| 150
| 0.573601
|
erikleitch
|
65eb1e71085a34b134bed47ba37871e40babe266
| 676
|
cpp
|
C++
|
Codeforces/A. Anton and Letters.cpp
|
Mhmd-Hisham/Problem-Solving
|
7ce0955b697e735c5ccb37347d9bec83e57339b5
|
[
"MIT"
] | null | null | null |
Codeforces/A. Anton and Letters.cpp
|
Mhmd-Hisham/Problem-Solving
|
7ce0955b697e735c5ccb37347d9bec83e57339b5
|
[
"MIT"
] | null | null | null |
Codeforces/A. Anton and Letters.cpp
|
Mhmd-Hisham/Problem-Solving
|
7ce0955b697e735c5ccb37347d9bec83e57339b5
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
/*
Problem: A. Anton and Letters
Link : https://codeforces.com/contest/443/problem/A
Solution by: Mohamed Hisham El-Banna
Gmail : Mohamed00Hisham@Gmail.com
Github : www.github.com/Mhmd-Hisham
LinkedIn: www.linkedin.com/in/Mhmd-Hisham
*/
using namespace std;
char letter;
unordered_set< char > letters_set;
int main () {
while ( scanf("%c", &letter) && letter != '}' ){
if (isalpha(letter)) letters_set.insert(letter);
}
printf("%d\n", int(letters_set.size()));
return 0;
}
/*
input:-
-----------
{b, a, b, a}
output:-
-----------
2
Resources:-
-------------
STL SET data structure: https://www.geeksforgeeks.org/set-in-cpp-stl/
*/
| 16.9
| 69
| 0.642012
|
Mhmd-Hisham
|
65efd20bbec69912adf7502a21907de70da281e3
| 2,909
|
cpp
|
C++
|
src/hit_ids_and.cpp
|
kasperwelbers/textquery
|
893ef26b3864a56bae10a3b235a4b900bb12bce7
|
[
"MIT"
] | 1
|
2022-02-18T23:21:13.000Z
|
2022-02-18T23:21:13.000Z
|
src/hit_ids_and.cpp
|
kasperwelbers/textquery
|
893ef26b3864a56bae10a3b235a4b900bb12bce7
|
[
"MIT"
] | null | null | null |
src/hit_ids_and.cpp
|
kasperwelbers/textquery
|
893ef26b3864a56bae10a3b235a4b900bb12bce7
|
[
"MIT"
] | null | null | null |
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::plugins(cpp11)]]
bool match_shortest(std::string &x, std::set<std::string> &group_set){
for (const auto &y : group_set) {
unsigned int length = x.size();
if (y.size() < length) length = y.size();
if (x.substr(0,length) == y.substr(0,length)) return true;
}
return false;
}
// [[Rcpp::export]]
NumericVector AND_hit_ids_cpp(NumericVector con, NumericVector subcon, NumericVector term_i, double n_unique, std::vector<std::string> group_i, LogicalVector replace, bool feature_mode) {
double n = con.size();
bool use_subcon = subcon.size() > 0; // use the fact that as.Numeric(NULL) in R returns a vector of length 0 (NULL handling in Rcpp is cumbersome)
bool new_assign;
NumericVector out(n);
std::map<int,std::set<int> > tracker; // keeps track of new unique term_is and their position. When n_unique is reached: returns hit_id and resets
std::map<int,std::set<std::string> > group_tracker; // in AND, if one term of a group is found, every term must be true (because we search nested)
int iw = 0;
int hit_id = 1;
for (int i = 0; i < n; i++) {
for (iw = i; iw < n; iw++) {
if (con[iw] != con[i]) break; // break if different (next) context
if (use_subcon) {
if (subcon[iw] != subcon[i]) break;
}
if (!replace[iw] and !feature_mode) {
if (out[iw] > 0) continue; // skip already assigned
if (tracker.count(term_i[iw])) { // skip if unique term_i already observed...
if (group_i[iw] == "") continue; // but only if there's no group_id...
//if (group_tracker[term_i[iw]].count(group_i[iw])) continue; // or if group_i is already observed
if (match_shortest(group_i[iw], group_tracker[term_i[iw]])) continue; // alternative: match on higher level (prevent double counting)
}
}
tracker[term_i[iw]].insert(iw);
if (group_i[iw] != "") group_tracker[term_i[iw]].insert(group_i[iw]);
if (!replace[iw] and !feature_mode) {
if ((group_tracker.size() == 0) && (tracker.size() == n_unique)) break;
}
}
if (tracker.size() == n_unique) { // if a full set was observed
new_assign = false;
for (const auto &positions : tracker){
for (const auto &position : positions.second) {
if (out[position] == 0) new_assign = true;
out[position] = hit_id; // assign hit_id for positions stored in tracker
}
}
if (!feature_mode) {
hit_id ++; // up counter and reset the tracker
if (replace[i] and new_assign) i--; // if term is a replaceable term, repeat the loop until no new hits are found
}
}
tracker.clear();
group_tracker.clear();
}
return out;
}
| 42.779412
| 187
| 0.591268
|
kasperwelbers
|
65f0d22d0744c1c91859d2cccb24c065f9d6521c
| 1,615
|
hpp
|
C++
|
phylanx/execution_tree/primitives/variable.hpp
|
NK-Nikunj/phylanx
|
6898992513a122c49d26947d877f329365486665
|
[
"BSL-1.0"
] | null | null | null |
phylanx/execution_tree/primitives/variable.hpp
|
NK-Nikunj/phylanx
|
6898992513a122c49d26947d877f329365486665
|
[
"BSL-1.0"
] | null | null | null |
phylanx/execution_tree/primitives/variable.hpp
|
NK-Nikunj/phylanx
|
6898992513a122c49d26947d877f329365486665
|
[
"BSL-1.0"
] | null | null | null |
// Copyright (c) 2017-2018 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)
#if !defined(PHYLANX_PRIMITIVES_VARIABLE_SEP_05_2017_1105AM)
#define PHYLANX_PRIMITIVES_VARIABLE_SEP_05_2017_1105AM
#include <phylanx/config.hpp>
#include <phylanx/execution_tree/primitives/base_primitive.hpp>
#include <phylanx/execution_tree/primitives/primitive_component_base.hpp>
#include <hpx/lcos/future.hpp>
#include <hpx/lcos/local/spinlock.hpp>
#include <set>
#include <string>
#include <vector>
namespace phylanx { namespace execution_tree { namespace primitives
{
class variable : public primitive_component_base
{
using mutex_type = hpx::lcos::local::spinlock;
public:
static match_pattern_type const match_data;
variable() = default;
variable(std::vector<primitive_argument_type>&& operands,
std::string const& name, std::string const& codename);
hpx::future<primitive_argument_type> eval(
std::vector<primitive_argument_type> const& params) const override;
void store(primitive_argument_type && data) override;
topology expression_topology(
std::set<std::string>&& functions) const override;
private:
mutable bool evaluated_;
mutable mutex_type mtx_;
};
PHYLANX_EXPORT primitive create_variable(hpx::id_type const& locality,
primitive_argument_type&& operand,
std::string const& name = "", std::string const& codename = "");
}}}
#endif
| 29.363636
| 80
| 0.716409
|
NK-Nikunj
|
65f0f7fa29980491436ea5a606f79359d0733068
| 1,382
|
cpp
|
C++
|
framework/source/geometry_node.cpp
|
ChristopherScholl/CGLab-Scholl119705-Schwegler121501
|
a93b6a92d0293892ae0762d825e5acbd3218a646
|
[
"MIT"
] | null | null | null |
framework/source/geometry_node.cpp
|
ChristopherScholl/CGLab-Scholl119705-Schwegler121501
|
a93b6a92d0293892ae0762d825e5acbd3218a646
|
[
"MIT"
] | null | null | null |
framework/source/geometry_node.cpp
|
ChristopherScholl/CGLab-Scholl119705-Schwegler121501
|
a93b6a92d0293892ae0762d825e5acbd3218a646
|
[
"MIT"
] | null | null | null |
#include "geometry_node.hpp"
// constructors
GeometryNode::GeometryNode(){}
GeometryNode::GeometryNode(model const& geometry) : geometry_(geometry) {}
GeometryNode::GeometryNode(
std::string const& name,
std::shared_ptr<Node> const& parent,
glm::fmat4 const& localTansform,
float size,
float speed,
float distance,
glm::fvec3 color,
std::string texture,
int index
) :
Node(name, parent, localTansform),
size_(size),
speed_(speed),
distance_(distance),
color_(glm::normalize(color)),
texture_(texture),
index_(index)
{}
// get attribute methods
model GeometryNode::getGeometry() const {
return geometry_;
}
float GeometryNode::getSize() const {
return size_;
}
float GeometryNode::getSpeed() const {
return speed_;
}
float GeometryNode::getDistance() const {
return distance_;
}
glm::fvec3 GeometryNode::getColor() const {
return color_;
}
std::string GeometryNode::getTexture() const {
return texture_;
}
texture_object GeometryNode::getTextureObject() const {
return texture_object_;
}
int GeometryNode::getIndex() const {
return index_;
}
// set attribute methods
void GeometryNode::setGeometry(model const& geometry) {
geometry_ = geometry;
}
void GeometryNode::setColor(glm::fvec3 const& color) {
color_ = color;
}
void GeometryNode::setTextureObject(texture_object texture_object){
texture_object_ = texture_object;
}
| 22.290323
| 74
| 0.737337
|
ChristopherScholl
|
65fd17b433a315e61e4595b23d4476495b43670d
| 291
|
hpp
|
C++
|
lib/exe/Process.hpp
|
MikaylaFischler/dorm-leds
|
d5edd7b1d8ba1bc76e13c2ee37cb4f9b1d272d9b
|
[
"MIT"
] | 2
|
2018-10-03T05:40:00.000Z
|
2018-12-07T00:39:03.000Z
|
lib/exe/Process.hpp
|
MikaylaFischler/dorm-leds
|
d5edd7b1d8ba1bc76e13c2ee37cb4f9b1d272d9b
|
[
"MIT"
] | 5
|
2017-09-02T03:57:24.000Z
|
2018-01-14T17:52:15.000Z
|
lib/exe/Process.hpp
|
MikaylaFischler/dorm-leds
|
d5edd7b1d8ba1bc76e13c2ee37cb4f9b1d272d9b
|
[
"MIT"
] | null | null | null |
#ifndef PROCESS_HPP_
#define PROCESS_HPP_
#include <Arduino.h>
#include <ArduinoSTL.h>
#include <vector>
#include "Executable.hpp"
class Process : public Executable {
protected:
Process() {}
public:
virtual ~Process() {}
virtual void init() {};
virtual void step() {};
};
#endif
| 13.857143
| 35
| 0.690722
|
MikaylaFischler
|
5a024191ee9116364aaf45552ea9da220efe1eef
| 1,112
|
cpp
|
C++
|
src/main.cpp
|
korenandr/poco_restful_webservice
|
864b02fb0cd500c9c74fb2f6931c44ecd6f4d019
|
[
"Apache-2.0"
] | 1
|
2021-07-01T18:45:35.000Z
|
2021-07-01T18:45:35.000Z
|
src/main.cpp
|
korenandr/poco_restful_webservice
|
864b02fb0cd500c9c74fb2f6931c44ecd6f4d019
|
[
"Apache-2.0"
] | null | null | null |
src/main.cpp
|
korenandr/poco_restful_webservice
|
864b02fb0cd500c9c74fb2f6931c44ecd6f4d019
|
[
"Apache-2.0"
] | null | null | null |
/*
* (C) Copyright 2017 Edson (http://edsonaraujosoares.com) and others.
*
* 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.
*
* Contributors:
* Edson Araújo Soares
* Korenevich Andrei Alexandrovich
*/
#include <iostream>
#include "Interface/Container.h"
int main(int argc, char * argv[])
{
try
{
// Check command line arguments and run application
return Interface::Container{}.run(argc, argv);
}
catch (const std::exception& exc)
{
std::cerr << "Failed to run application: " << exc.what() << std::endl;
return EXIT_FAILURE;
}
}
| 27.121951
| 78
| 0.678957
|
korenandr
|
5a08819a7f34b2df7d9bb45919ecfad6625cdd96
| 2,674
|
cpp
|
C++
|
Source/ThirdPersonCamera/Camera/HoatCameraModifierFocusWalkDirection.cpp
|
ArnaudSpicht/third-person-camera
|
7bedf626d15820d0ff3563b503729d8e2ce5aaa9
|
[
"MIT"
] | 156
|
2018-04-27T20:27:12.000Z
|
2022-02-25T02:46:02.000Z
|
Source/ThirdPersonCamera/Camera/HoatCameraModifierFocusWalkDirection.cpp
|
ArnaudSpicht/third-person-camera
|
7bedf626d15820d0ff3563b503729d8e2ce5aaa9
|
[
"MIT"
] | 1
|
2020-11-30T01:46:13.000Z
|
2021-10-07T03:49:18.000Z
|
Source/ThirdPersonCamera/Camera/HoatCameraModifierFocusWalkDirection.cpp
|
ArnaudSpicht/third-person-camera
|
7bedf626d15820d0ff3563b503729d8e2ce5aaa9
|
[
"MIT"
] | 41
|
2018-05-01T04:16:47.000Z
|
2022-01-07T11:22:13.000Z
|
#include "HoatCameraModifierFocusWalkDirection.h"
#include "GameFramework/Actor.h"
#include "Camera/PlayerCharacterInterface.h"
UHoatCameraModifierFocusWalkDirection::UHoatCameraModifierFocusWalkDirection(const FObjectInitializer& ObjectInitializer /*= FObjectInitializer::Get()*/)
: Super(ObjectInitializer)
{
RotationSpeed = 10.0f;
}
bool UHoatCameraModifierFocusWalkDirection::ModifyCamera(float DeltaTime, struct FMinimalViewInfo& InOutPOV)
{
//UE_LOG(hoat, Log, TEXT("Location: %s, Rotation: %s, FOV: %f"), *InOutPOV.Location.ToString(), *InOutPOV.Rotation.Euler().ToString(), InOutPOV.FOV);
return Super::ModifyCamera(DeltaTime, InOutPOV);
}
bool UHoatCameraModifierFocusWalkDirection::ProcessViewRotation(class AActor* ViewTarget, float DeltaTime, FRotator& OutViewRotation, FRotator& OutDeltaRot)
{
Super::ProcessViewRotation(ViewTarget, DeltaTime, OutViewRotation, OutDeltaRot);
// Tick cooldown.
if (DirectionChangeCooldownRemaining > 0)
{
DirectionChangeCooldownRemaining -= DeltaTime;
}
IPlayerCharacterInterface* playerCharacter = Cast<IPlayerCharacterInterface>(ViewTarget);
if (!playerCharacter)
{
return false;
}
// Check if we should apply automatic rotation.
if (RotateOnlyWhileCharacterIsMoving && !playerCharacter->GotMovementInput())
{
return false;
}
if (PlayerHasRecentlyChangedCamera())
{
return false;
}
// Get current actor and view rotations.
const float actorYaw = ViewTarget->GetActorRotation().Yaw;
const float viewYaw = OutViewRotation.Yaw;
// Always take the "short route" while rotating.
float yawDelta = actorYaw - viewYaw;
while (yawDelta < -180.0f)
{
yawDelta += 360.0f;
}
while (yawDelta > 180.0f)
{
yawDelta -= 360.0f;
}
// Check direction of rotation.
float yawDeltaSign = FMath::Sign(yawDelta);
if (PreviousYawDeltaSign != yawDeltaSign)
{
if (DirectionChangeCooldownRemaining > 0)
{
return false;
}
else
{
PreviousYawDeltaSign = yawDeltaSign;
DirectionChangeCooldownRemaining = DirectionChangeCooldown;
}
}
// Apply rotation speed.
float appliedYawDelta = yawDeltaSign * RotationSpeed * DeltaTime;
// Prevent flipping back and forth for very small deltas.
if (FMath::Abs(yawDelta) < FMath::Abs(appliedYawDelta))
{
PreviousYawDeltaSign = 0.0f;
DirectionChangeCooldownRemaining = DirectionChangeCooldown;
appliedYawDelta = yawDelta;
}
OutDeltaRot.Yaw += appliedYawDelta;
return false;
}
| 28.147368
| 156
| 0.690352
|
ArnaudSpicht
|
5a0907b201a56b997378bace9740a2b40330dcbe
| 991
|
cpp
|
C++
|
libraries/models/src/ModelTreeHeadlessViewer.cpp
|
Adrianl3d/hifi
|
7bd01f606b768f6aa3e21d48959718ad249a3551
|
[
"Apache-2.0"
] | null | null | null |
libraries/models/src/ModelTreeHeadlessViewer.cpp
|
Adrianl3d/hifi
|
7bd01f606b768f6aa3e21d48959718ad249a3551
|
[
"Apache-2.0"
] | null | null | null |
libraries/models/src/ModelTreeHeadlessViewer.cpp
|
Adrianl3d/hifi
|
7bd01f606b768f6aa3e21d48959718ad249a3551
|
[
"Apache-2.0"
] | null | null | null |
//
// ModelTreeHeadlessViewer.cpp
// libraries/models/src
//
// Created by Brad Hefta-Gaub on 2/26/14.
// Copyright 2014 High Fidelity, Inc.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
#include "ModelTreeHeadlessViewer.h"
ModelTreeHeadlessViewer::ModelTreeHeadlessViewer() :
OctreeHeadlessViewer() {
}
ModelTreeHeadlessViewer::~ModelTreeHeadlessViewer() {
}
void ModelTreeHeadlessViewer::init() {
OctreeHeadlessViewer::init();
}
void ModelTreeHeadlessViewer::update() {
if (_tree) {
ModelTree* tree = static_cast<ModelTree*>(_tree);
if (tree->tryLockForWrite()) {
tree->update();
tree->unlock();
}
}
}
void ModelTreeHeadlessViewer::processEraseMessage(const QByteArray& dataByteArray, const SharedNodePointer& sourceNode) {
static_cast<ModelTree*>(_tree)->processEraseMessage(dataByteArray, sourceNode);
}
| 25.410256
| 121
| 0.706357
|
Adrianl3d
|
5a0f69ba96e0fe3713c71cc449550e800411079e
| 539
|
cpp
|
C++
|
Testbot/src/main/cpp/TestRobot.cpp
|
CJBuchel/KillSwitch-EventCode
|
d0cf3e5a0ae8d042137bfab129f0f69631609ec3
|
[
"MIT"
] | 1
|
2021-10-10T06:52:19.000Z
|
2021-10-10T06:52:19.000Z
|
Testbot/src/main/cpp/TestRobot.cpp
|
CJBuchel/KillSwitch-EventCode
|
d0cf3e5a0ae8d042137bfab129f0f69631609ec3
|
[
"MIT"
] | null | null | null |
Testbot/src/main/cpp/TestRobot.cpp
|
CJBuchel/KillSwitch-EventCode
|
d0cf3e5a0ae8d042137bfab129f0f69631609ec3
|
[
"MIT"
] | null | null | null |
#include "TestRobot.h"
#include <actuators/VoltageController.h>
#include <math.h>
#include <iostream>
using namespace frc;
using namespace curtinfrc;
void Robot::RobotInit() {
xbox = new curtinfrc::controllers::XboxController(0);
}
void Robot::AutonomousInit() {}
void Robot::AutonomousPeriodic() {}
void Robot::TeleopInit() {}
void Robot::TeleopPeriodic() {
double leftSpeed = -xbox->GetAxis(1); // L Y axis
double rightSpeed = -xbox->GetAxis(5); // R Y axis
}
void Robot::TestInit() {}
void Robot::TestPeriodic() {}
| 17.966667
| 55
| 0.695733
|
CJBuchel
|
5a0fad0973d0f544531cf3ca92f6d346571cd7f7
| 1,193
|
cpp
|
C++
|
benchmarks/cpp/dry.cpp
|
satoshigeyuki/Centaurus
|
032ffec87fc8ddb129347974d3478fd1ee5f305a
|
[
"MIT"
] | 3
|
2021-02-23T01:34:28.000Z
|
2021-07-19T08:07:10.000Z
|
benchmarks/cpp/dry.cpp
|
satoshigeyuki/Centaurus
|
032ffec87fc8ddb129347974d3478fd1ee5f305a
|
[
"MIT"
] | null | null | null |
benchmarks/cpp/dry.cpp
|
satoshigeyuki/Centaurus
|
032ffec87fc8ddb129347974d3478fd1ee5f305a
|
[
"MIT"
] | null | null | null |
#include <chrono>
#include "CodeGenEM64T.hpp"
#include "Stage1Runner.hpp"
int main(int argc, const char *argv[])
{
if (argc < 3) return 0;
const char *grammar_path = argv[1];
const char *input_path = argv[2];
const bool result_captured = argc > 3 && argv[3] == std::string("debug");
Centaurus::Grammar<char> grammar;
Centaurus::ParserEM64T<char> parser;
grammar.parse(grammar_path);
parser.init(grammar);
const int worker_num = 1;
using namespace std::chrono;
auto start = high_resolution_clock::now();;
Centaurus::Stage1Runner runner{input_path, &parser, 8 * 1024 * 1024, worker_num * 2, true, result_captured};
runner.start();
runner.wait();
auto end = high_resolution_clock::now();;
if (result_captured) {
for (auto& chunk : runner.result_chunks()) {
for (auto& m : chunk) {
if (m.get_machine_id() == 0 && m.get_offset() == 0) break;
std::cout << (m.is_start_marker() ? "S " : "E ") << m.get_machine_id() << "\t" << m.get_offset() << std::endl;
}
}
} else {
std::cout << duration_cast<milliseconds>(end - start).count() << std::endl;
}
return 0;
}
| 27.113636
| 120
| 0.604359
|
satoshigeyuki
|
5a161508863f11d0148cd63cb3f7851e4922212e
| 2,429
|
cpp
|
C++
|
2D/PointAndSegment.cpp
|
xwen99/Computational-Geometry-Algorithm-Library
|
f3aa36217f17860f4cd87f93b63b253ad7b93b6f
|
[
"MIT"
] | 5
|
2019-07-08T14:00:26.000Z
|
2021-07-21T08:08:01.000Z
|
2D/PointAndSegment.cpp
|
xwen99/Computational-Geometry-Algorithm-Library
|
f3aa36217f17860f4cd87f93b63b253ad7b93b6f
|
[
"MIT"
] | null | null | null |
2D/PointAndSegment.cpp
|
xwen99/Computational-Geometry-Algorithm-Library
|
f3aa36217f17860f4cd87f93b63b253ad7b93b6f
|
[
"MIT"
] | 2
|
2019-10-12T08:43:55.000Z
|
2020-06-19T13:14:30.000Z
|
//向量点乘
double Dot(Vector A, Vector B) { return A.x * B.x + A.y * B.y; }
//向量模长
double Length(Vector A) { return sqrt(Dot(A, A)); }
//向量模长平方
double Length2(Vector A) { return Dot(A, A); }
//向量夹角
double Angle(Vector A, Vector B) { return acos(Dot(A, B) / Length(A) / Length(B)); }
//向量叉乘
double Cross(Vector A, Vector B) { return A.x * B.y - A.y * B.x; }
//三角形面积的2倍
double Area2(Point A, Point B, Point C) { return Cross(B - A, C - A); }
//向量旋转
Vector Rotate(Vector A, double rad)
{
return Vector(A.x * cos(rad) - A.y * sin(rad), A.x * sin(rad) + A.y * cos(rad));
}
//向量单位法向量(逆时针90°)
Vector Normal(Vector A)
{
double L = Length(A);
return Vector(-A.y / L, A.x / L);
}
//直线交点
Point GetLineIntersection(Point P, Vector v, Point Q, Vector w)
{
Vector u = P - Q;
double t = Cross(w, u) / Cross(v, w);
return P + v * t;
}
//两点距离
double Distance(Point A, Point B) { return sqrt(Dot(B - A, B - A)); }
//两点距离平方
double Distance2(Point A, Point B) { return Dot(B - A, B - A); }
//点到直线的距离
double DistanceToLine(Point P, Point A, Point B)
{
Vector v1 = B - A, v2 = P - A;
return fabs(Cross(v1, v2)) / Length(v1);
}
//点到线段的距离
double DistanceToSegment(Point P, Point A, Point B)
{
if (A == B)
return Length(P - A);
Vector v1 = B - A, v2 = P - A, v3 = P - B;
if (dcmp(Dot(v1, v2)) < 0)
return Length(v2);
else if (dcmp(Dot(v1, v3)) > 0)
return Length(v3);
else
return fabs(Cross(v1, v2)) / Length(v1);
}
//点在直线上的垂足
Point GetLineProjection(Point P, Point A, Point B)
{
Vector v = B - A;
return A + v * (Dot(v, P - A) / Dot(v, v));
}
//判断线段是否规范相交(不考虑端点)
bool SegmentProperIntersection(Point a1, Point a2, Point b1, Point b2)
{
double c1 = Cross(a2 - a1, b1 - a1), c2 = Cross(a2 - a1, b2 - a1),
c3 = Cross(b2 - b1, a1 - b1), c4 = Cross(b2 - b1, a2 - b1);
return dcmp(c1) * dcmp(c2) < 0 && dcmp(c3) * dcmp(c4) < 0;
}
//判断点是否在线段上
bool OnSegment(Point p, Point a1, Point a2)
{
return dcmp(Cross(a1 - p, a2 - p)) == 0 && dcmp(Dot(a1 - p, a2 - p)) <= 0;
}
//判断线段是否相交
bool SegmentIntersection(Point a1, Point a2, Point b1, Point b2)
{
if (dcmp(Cross(a2 - a1, b2 - b1)) == 0)
return OnSegment(a1, b1, b2) || OnSegment(a2, b1, b2) || OnSegment(b1, a1, a2) || OnSegment(b2, a1, a2);
else
{
Point p = GetLineIntersection(a1, a2 - a1, b1, b2 - b1);
return OnSegment(p, a1, a2) && OnSegment(p, b1, b2);
}
}
| 29.621951
| 112
| 0.575957
|
xwen99
|
5a16841b7b8f7ca761239074eee23e5d8e95c140
| 2,830
|
cpp
|
C++
|
sauce/core/fundamentals/things/strange__locked_data_t.cpp
|
oneish/strange
|
e6c47eca5738dd98f4e09ee5c0bb820146e8b48f
|
[
"Apache-2.0"
] | null | null | null |
sauce/core/fundamentals/things/strange__locked_data_t.cpp
|
oneish/strange
|
e6c47eca5738dd98f4e09ee5c0bb820146e8b48f
|
[
"Apache-2.0"
] | null | null | null |
sauce/core/fundamentals/things/strange__locked_data_t.cpp
|
oneish/strange
|
e6c47eca5738dd98f4e09ee5c0bb820146e8b48f
|
[
"Apache-2.0"
] | null | null | null |
#include "../../strange__core.h"
namespace strange
{
// locked_data_t
// data_o
template <typename type_d, typename lock_d>
data_o<std::remove_reference_t<type_d>> const* locked_data_t<type_d, lock_d>::_operations()
{
static data_o<std::remove_reference_t<type_d>> operations =
{
{
// any_a
data_a<std::remove_reference_t<type_d>>::cat,
locked_data_t<type_d, lock_d>::is,
locked_data_t<type_d, lock_d>::as,
locked_data_t<type_d, lock_d>::type,
locked_data_t<type_d, lock_d>::set_error,
locked_data_t<type_d, lock_d>::error,
locked_data_t<type_d, lock_d>::hash,
locked_data_t<type_d, lock_d>::equal,
locked_data_t<type_d, lock_d>::less,
locked_data_t<type_d, lock_d>::less_or_equal,
locked_data_t<type_d, lock_d>::pack,
locked_data_t<type_d, lock_d>::_free,
locked_data_t<type_d, lock_d>::_copy,
locked_data_t<type_d, lock_d>::_set_pointer,
locked_data_t<type_d, lock_d>::_pointer,
},
// data_a
locked_data_t<type_d, lock_d>::read_lock,
locked_data_t<type_d, lock_d>::write_lock,
locked_data_t<type_d, lock_d>::extract,
locked_data_t<type_d, lock_d>::mutate,
};
return &operations;
}
template <typename type_d, typename lock_d>
data_o<std::remove_reference_t<type_d>> const* locked_data_t<type_d, lock_d>::_pointer_operations()
{
static data_o<std::remove_reference_t<type_d>> operations = []()
{
data_o<std::remove_reference_t<type_d>> ops = *locked_data_t<type_d, lock_d>::_operations();
ops._copy = thing_t::_no_copy;
return ops;
}();
return &operations;
}
// any_a
template <typename type_d, typename lock_d>
var<symbol_a> locked_data_t<type_d, lock_d>::type(con<> const& me)
{
static auto r = sym("strange::locked_data");
return r;
}
template <typename type_d, typename lock_d>
void locked_data_t<type_d, lock_d>::_copy(con<> const& me,
var<> const& copy)
{
new locked_data_t<type_d, lock_d>{ copy, me };
locked_data_t<type_d, lock_d>::_clone(me, copy);
}
template <typename type_d, typename lock_d>
void locked_data_t<type_d, lock_d>::_set_pointer(con<> const& me,
bool is_pointer)
{
me.o = is_pointer ? locked_data_t<type_d, lock_d>::_pointer_operations() : locked_data_t<type_d, lock_d>::_operations();
}
// data_a
template <typename type_d, typename lock_d>
ptr<> locked_data_t<type_d, lock_d>::read_lock(con<data_a<std::remove_reference_t<type_d>>> const& me)
{
auto t = static_cast<locked_data_t<type_d, lock_d>*>(me.t);
return t->lock_.o->read_lock(t->lock_);
}
template <typename type_d, typename lock_d>
ptr<> locked_data_t<type_d, lock_d>::write_lock(var<data_a<std::remove_reference_t<type_d>>> const& me)
{
me.mut();
auto t = static_cast<locked_data_t<type_d, lock_d>*>(me.t);
return t->lock_.o->write_lock(t->lock_);
}
// instantiation
}
| 30.76087
| 122
| 0.713074
|
oneish
|
5a1de50e6303f0be94a78bc3366ea6e74e112c29
| 659
|
cpp
|
C++
|
dataset/test/modification/1541_control_replacement/59/transformation_1.cpp
|
Karina5005/Plagiarism
|
ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb
|
[
"MIT"
] | 3
|
2022-02-15T00:29:39.000Z
|
2022-03-15T08:36:44.000Z
|
dataset/test/modification/1541_control_replacement/59/transformation_1.cpp
|
Kira5005-code/Plagiarism
|
ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb
|
[
"MIT"
] | null | null | null |
dataset/test/modification/1541_control_replacement/59/transformation_1.cpp
|
Kira5005-code/Plagiarism
|
ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb
|
[
"MIT"
] | null | null | null |
#include <iomanip>
#include <iostream>
#include <iostream>
#define long long int
void solve() {
int n;
std::cin >> n;
if(!(n%2)){
{
int i=1;
for ( ; i<n; )
{
std::cout << i+1 << " " << i << " ";
i+=2;
}}
}
else {
std::cout << "3 1 2 ";
{
int i=4;
for ( ; i<n; )
{
std::cout << i+1 << " " << i << " ";
i+=2;
}}
}
std::cout << "\n";
}
signed main() {
std::cin.tie(0);
int t = 0;
std::cin >> t;
for ( ; t--; )
{
solve();
}
}
| 15.690476
| 49
| 0.291351
|
Karina5005
|
5a1ef76f296da1bbea41eddda924a8566e9f98db
| 1,129
|
cpp
|
C++
|
source/app/xml_logs/src/Backend.cpp
|
matus-chochlik/eagine-core
|
5bc2d6b9b053deb3ce6f44f0956dfccd75db4649
|
[
"BSL-1.0"
] | 1
|
2022-01-25T10:31:51.000Z
|
2022-01-25T10:31:51.000Z
|
source/app/xml_logs/src/Backend.cpp
|
matus-chochlik/eagine-core
|
5bc2d6b9b053deb3ce6f44f0956dfccd75db4649
|
[
"BSL-1.0"
] | null | null | null |
source/app/xml_logs/src/Backend.cpp
|
matus-chochlik/eagine-core
|
5bc2d6b9b053deb3ce6f44f0956dfccd75db4649
|
[
"BSL-1.0"
] | null | null | null |
///
/// Copyright Matus Chochlik.
/// Distributed under the GNU GENERAL PUBLIC LICENSE version 3.
/// See http://www.gnu.org/licenses/gpl-3.0.txt
///
#include "Backend.hpp"
//------------------------------------------------------------------------------
Backend::Backend(eagine::main_ctx_parent parent)
: QObject{nullptr}
, eagine::main_ctx_object{EAGINE_ID(Backend), parent}
, _server{*this}
, _entryLog{*this}
, _theme{*this} {}
//------------------------------------------------------------------------------
auto Backend::entryLog() noexcept -> EntryLog& {
return _entryLog;
}
//------------------------------------------------------------------------------
auto Backend::theme() noexcept -> Theme& {
return _theme;
}
//------------------------------------------------------------------------------
auto Backend::getEntryLog() noexcept -> EntryLog* {
return &_entryLog;
}
//------------------------------------------------------------------------------
auto Backend::getTheme() noexcept -> Theme* {
return &_theme;
}
//------------------------------------------------------------------------------
| 35.28125
| 80
| 0.390611
|
matus-chochlik
|
5a1f992efaf533a5f444ee930182a544f8f4229f
| 1,662
|
cpp
|
C++
|
src/tools/random.cpp
|
WatchJolley/rivercrossing
|
694c4245a8a5ae000e8d6338695a24dcedbb13a8
|
[
"MIT"
] | null | null | null |
src/tools/random.cpp
|
WatchJolley/rivercrossing
|
694c4245a8a5ae000e8d6338695a24dcedbb13a8
|
[
"MIT"
] | null | null | null |
src/tools/random.cpp
|
WatchJolley/rivercrossing
|
694c4245a8a5ae000e8d6338695a24dcedbb13a8
|
[
"MIT"
] | null | null | null |
#include <random>
#include <chrono>
#include <fstream>
std::mt19937_64 generator; // C++11 Mersene Twister 19937 generator (64 bit)
unsigned randomise(unsigned s=0) {
if (!s) {std::random_device seeder; s=seeder();}
if (!s) s = std::chrono::high_resolution_clock::now().time_since_epoch().count();
generator.seed(s);
return s;
}
int32_t random(int32_t n) { return std::uniform_int_distribution<int32_t> (0,n-1) (generator); } // 0..(n-1)
double randomdouble() { return std::generate_canonical<double,std::numeric_limits<double>::digits>(generator); }
float randomfloat() { return std::generate_canonical<float, std::numeric_limits<float>::digits>(generator); }
double randomdouble(double d) { return std::uniform_real_distribution<double> (0.0, d) (generator); }
float randomfloat(float f) { return std::uniform_real_distribution<float> (0.0f,f) (generator); }
double randomdoubleRng(double d, double dd) { return std::uniform_real_distribution<double> (d, dd) (generator); }
float randomfloatRng(float f, float ff) { return std::uniform_real_distribution<float> (f,ff) (generator); }
double randomGaussianDouble(double mean=0, double stddev=1.0) { return std::normal_distribution<double> (mean, stddev) (generator); }
float randomGaussianFloat(float mean=0.0f, float stddev=1.0f) { return std::normal_distribution<float> (mean, stddev) (generator); }
void random_writestate(std::ostream& sout) {sout << generator <<std::endl;}
void random_readstate(std::istream& sin) {sin >> generator;}
unsigned return_time() {return static_cast<long unsigned int>(std::chrono::high_resolution_clock::now().time_since_epoch().count()); };
| 51.9375
| 137
| 0.733454
|
WatchJolley
|
5a232a1b7f41a2e2cbbe98597506052f48c94cc6
| 2,211
|
cc
|
C++
|
01-elementary/07-iterators/src/main.cc
|
aohontsev/movax01h-cpp-practice
|
ee81a2502e662f55fc1587fb3cb9caf783b8694c
|
[
"MIT"
] | null | null | null |
01-elementary/07-iterators/src/main.cc
|
aohontsev/movax01h-cpp-practice
|
ee81a2502e662f55fc1587fb3cb9caf783b8694c
|
[
"MIT"
] | null | null | null |
01-elementary/07-iterators/src/main.cc
|
aohontsev/movax01h-cpp-practice
|
ee81a2502e662f55fc1587fb3cb9caf783b8694c
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2018.
// Author: Anton Okhontsev <anton.ohontsev@gmail.com>
#include "string"
#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <vector>
typedef std::string Date;
enum class MainFuncExitCodes {
SUCCESS = 0,
INPUT_STREAM_IS_EMPTY = 1,
INPUT_STREAM_IS_NOT_SORTED = 2,
BOUNDARY_VALUE_NOT_FOUND = 3
};
MainFuncExitCodes main_func(std::istringstream *str) {
// Fill vector from stream.
std::vector<Date> dates;
std::copy(std::istream_iterator<Date>(*str), std::istream_iterator<Date>(),
std::back_inserter(dates));
if (dates.empty()) {
std::cout << "Error. Input stream is empty.\n";
return MainFuncExitCodes::INPUT_STREAM_IS_EMPTY;
}
// Find first and last element.
std::vector<Date>::iterator first =
std::find(dates.begin(), dates.end(), Date("01/01/18"));
std::vector<Date>::iterator last =
std::find(dates.begin(), dates.end(), Date("31/12/18"));
if (first == dates.end() || last == dates.end()) {
std::cout << "Error. Cannot find first or last value.\n";
return MainFuncExitCodes::BOUNDARY_VALUE_NOT_FOUND;
} else if (last < first) {
std::cout << "Error. Input stream order is reversed or mixed.\n";
return MainFuncExitCodes::INPUT_STREAM_IS_NOT_SORTED;
}
// Print into console elements between firsl and lst element.
std::copy(first, last, std::ostream_iterator<Date>(std::cout, "\n"));
std::cout << "\n";
// Insert new element.
dates.insert(dates.end() - 1, Date("30/12/18"));
// Find first and last element.
first = std::find(dates.begin(), dates.end(), Date("01/01/18"));
last = std::find(dates.begin(), dates.end(), Date("31/12/18"));
if (first == dates.end() || last == dates.end()) {
std::cout << "Error. Cannot find first or last value.\n";
return MainFuncExitCodes::BOUNDARY_VALUE_NOT_FOUND;
} else if (last < first) {
std::cout << "Error. Input stream order is reversed or mixed.\n";
return MainFuncExitCodes::INPUT_STREAM_IS_NOT_SORTED;
}
// Print into console elements between firsl and lst element.
std::copy(first, last, std::ostream_iterator<Date>(std::cout, "\n"));
return MainFuncExitCodes::SUCCESS;
};
| 33.5
| 77
| 0.67119
|
aohontsev
|
5a27db71a33db825f048c416e1aa0acf7e167c91
| 979
|
cpp
|
C++
|
Review/main.cpp
|
ariyonaty/ECE3310
|
845d7204c16e84712fab2e25f79c0f16cb1e7c99
|
[
"MIT"
] | null | null | null |
Review/main.cpp
|
ariyonaty/ECE3310
|
845d7204c16e84712fab2e25f79c0f16cb1e7c99
|
[
"MIT"
] | null | null | null |
Review/main.cpp
|
ariyonaty/ECE3310
|
845d7204c16e84712fab2e25f79c0f16cb1e7c99
|
[
"MIT"
] | 1
|
2021-09-22T04:01:52.000Z
|
2021-09-22T04:01:52.000Z
|
#include <iostream>
#include <cmath>
class Shape
{
public:
virtual double Area() = 0;
};
class Circle : public Shape
{
protected:
double width;
public:
Circle(double w)
{
width = w;
}
double Area() override
{
return 3.1414 * pow((width / 2), 2);
}
};
struct Shape2
{
double length, width;
Shape2(double l = 1, double w = 1)
{
length = l;
width = w;
}
double Area()
{
return length * width;
}
private:
int id;
};
struct Circle2 : Shape2
{
Circle2(double width)
{
this->width = width;
}
double Area()
{
return 3.1414 * pow((width / 2), 2);
}
};
void ShowArea(Shape &shape);
int main()
{
Circle circle(10);
ShowArea(circle);
Circle2 circle2(10);
std::cout << "Circle Area: " << circle2.Area() << std::endl;
return 0;
}
void ShowArea(Shape &shape)
{
std::cout << "Area : " << shape.Area() << std::endl;
}
| 13.788732
| 64
| 0.527068
|
ariyonaty
|
5a27eabf43beaf6c70e6f94aec7102cb517d55f6
| 1,660
|
cpp
|
C++
|
src/camera/DepthCamera.cpp
|
aurthconan/fanLens
|
d05ce02cd748f21b6a5385892972accce54fd58d
|
[
"MIT"
] | null | null | null |
src/camera/DepthCamera.cpp
|
aurthconan/fanLens
|
d05ce02cd748f21b6a5385892972accce54fd58d
|
[
"MIT"
] | null | null | null |
src/camera/DepthCamera.cpp
|
aurthconan/fanLens
|
d05ce02cd748f21b6a5385892972accce54fd58d
|
[
"MIT"
] | null | null | null |
#include "DepthCamera.h"
#include <algo/rasterize/fanScanLineGenerator.h>
#include <texture/MemoryTexture.h>
#include <camera/RasterisationScanner.h>
#include <filler/DepthFiller.h>
using namespace fan;
class DepthPixelConvertor
: public fanTexture<int, float, 2>
{
public:
DepthPixelConvertor( fanTexture<int, float, 2>& zBuffer,
fanTexture<int, fanPixel, 2>& pixelTexture )
: fanTexture<int, float, 2>( zBuffer.getDimens() )
, mZBuffer( zBuffer )
, mPixelTexture( pixelTexture )
{
}
float getValue( fanVector<int, 2> index ) const
{
return mZBuffer.getValue( index );
}
void setValue( const fanVector<int, 2>& index,
const float& value )
{
if ( value < 0 || value > 1 ) {
return;
}
mZBuffer.setValue( index, value );
fanPixel pixel( 255, 255*value,
255*value,
255*value );
mPixelTexture.setValue( index, pixel );
}
fanTexture<int, float, 2>& mZBuffer;
fanTexture<int, fanPixel, 2>& mPixelTexture;
};
void DepthCamera::takePicture( fan::fanScene& scene,
fan::fanTexture<int, fanPixel, 2>& film,
fan::fanLens& lens )
{
fan::fanVector<int, 2> dimens = film.getDimens();
MemoryTexture<int, float, 2> zBuffer( dimens );
zBuffer.reset( 2.0f );
DepthPixelConvertor convertor( zBuffer, film );
DepthFiller filler;
RasterisationScanner<DepthFiller, float> depthFiller( filler );
depthFiller.takePicture( scene, convertor, lens );
}
| 27.666667
| 71
| 0.592771
|
aurthconan
|
5a282b8f07028d8d867d9c3bd39b5dbeb61df5e1
| 1,219
|
cpp
|
C++
|
cppp/src/9-sequential-container/45-46-50.cpp
|
ahxxm/cpp-exercise
|
abbe530770d49843ceaf706fb55b91ef100b1162
|
[
"WTFPL"
] | 2
|
2016-12-06T00:49:35.000Z
|
2017-01-15T07:00:24.000Z
|
cppp/src/9-sequential-container/45-46-50.cpp
|
ahxxm/cpp-exercise
|
abbe530770d49843ceaf706fb55b91ef100b1162
|
[
"WTFPL"
] | 5
|
2016-05-02T13:52:52.000Z
|
2016-09-28T07:57:09.000Z
|
cppp/src/9-sequential-container/45-46-50.cpp
|
ahxxm/cpp-exercise
|
abbe530770d49843ceaf706fb55b91ef100b1162
|
[
"WTFPL"
] | null | null | null |
#include <string>
#include <vector>
#include "gtest/gtest.h"
// 45: iterator, insert and append
// add prefix and suffix to a string
void add_prefix_suffix(std::string &s, const std::string &prefix, const std::string &suffix) {
s.insert(s.begin(), prefix.begin(), prefix.end());
s.append(suffix);
}
// 46: rewrite 45 with only insert
void insert_prefix_suffix(std::string &s, const std::string &prefix, const std::string &suffix) {
s.insert(s.begin(), prefix.begin(), prefix.end());
s.insert(s.end(), suffix.begin(), suffix.end());
}
// 50:
int sum_vector_int_string(std::vector<std::string> &va) {
int result = 0;
for (auto i : va) {
result += std::stoi(i);
}
return result;
}
TEST(MoreClassExerciseTest, SomeTest) {
std::string st = "string";
std::string pre = "p";
std::string suf = "d";
add_prefix_suffix(st, pre, suf);
EXPECT_EQ(st, "pstringd");
std::string st2 = "st";
insert_prefix_suffix(st2, pre, suf);
EXPECT_EQ(st2, "pstd");
std::vector<std::string> vi = {"1234", "123a"};
int sum = sum_vector_int_string(vi);
EXPECT_EQ(sum, 1357);
}
int main(int argc, char *argv[]) {
::testing::InitGoogleTest(&argc, argv);
int ret = RUN_ALL_TESTS();
return ret;
}
| 23.901961
| 97
| 0.655455
|
ahxxm
|
5a28405339af9d2936339626d1a63aa5da261607
| 4,655
|
cpp
|
C++
|
src/RkFehl.cpp
|
tmkwan/Cpp-Runge-Kutta-Fehlberg
|
4e1aeb1d0231acbb12c94617fb79a33b3f542726
|
[
"MIT"
] | null | null | null |
src/RkFehl.cpp
|
tmkwan/Cpp-Runge-Kutta-Fehlberg
|
4e1aeb1d0231acbb12c94617fb79a33b3f542726
|
[
"MIT"
] | null | null | null |
src/RkFehl.cpp
|
tmkwan/Cpp-Runge-Kutta-Fehlberg
|
4e1aeb1d0231acbb12c94617fb79a33b3f542726
|
[
"MIT"
] | null | null | null |
/*
* RkFehl.cpp
*
* This function runs the Runge-Kutta Fehlberg method on an
* ODE selected by the string given as an input. It uses
* adaptive time-stepping to create the output matrix.
*
* Created on: Aug 6, 2016
* Author: Ted Kwan
*/
#include "RkFehl.h"
using namespace std;
using namespace arma;
RkFehl::RkFehl() {
h = 0.5;
dim = 1;
vector<double> pars(2);
pars[0] = 1.0;
pars[1] = 1.0;
}
/**
* Constructor to run the RK45 method. Takes the inputs then calculates the solution
* to the ODE.
*
* @param params - Vector containing parameters for the ODE functions.
* @param fun - String containing which function to run.
* @param tf - Double representing the final time.
* @param h - Normal step-size value. Used for error.
* @param x - Initial conditions.
*/
RkFehl::RkFehl(vector<double> params, string fun, double tf, double h, vec x) {
// Choose the correct ODE to solve.
if ((fun.find("Duff") != string::npos)
|| (fun.find("duff") != string::npos)) {
ode = new Duffing(params);
dim = ode->dim;
} else if ((fun.find("Van") != string::npos)
|| (fun.find("van") != string::npos)) {
ode = new VanDerPol(params);
dim = ode->dim;
} else if ((fun.find("Lor") != string::npos)
|| (fun.find("lor") != string::npos)) {
ode = new Lorenz(params);
dim = ode->dim;
} else if ((fun.find("Ross") != string::npos)
|| (fun.find("ross") != string::npos)) {
ode = new Rossler(params);
dim = ode->dim;
} else if ((fun.find("Grad") != string::npos)
|| (fun.find("grad") != string::npos)) {
ode = new GradSystem(params);
dim = ode->dim;
} else if ((fun.find("clinic") != string::npos)
|| (fun.find("Clinic") != string::npos)) {
ode = new Heteroclinic(params);
dim = ode->dim;
} else if ((fun.find("olterra") != string::npos)
|| (fun.find("Lotka") != string::npos)) {
ode = new Volterra(params);
dim = ode->dim;
} else {
ode = new GradSystem(params);
dim = ode->dim;
}
// Store parameters from input.
this->h = h;
vec y1 = x;
t.push_back(0);
y.push_back(y1);
double tcurr = t[0];
double hc = h;
int i = 1;
// Setup error checking and truncation error for adaptive
// time stepping.
double epsloc = pow(h, 4);
double kappa = 0.84;
while (tcurr < tf) {
// Calculate the test step.
vector<vec> yv = testStep(tcurr, y[i - 1], hc);
// Evaluate the error at the current step.
double epsi = (norm(yv[0] - yv[1]));
int j = 0;
// Set optimal h.
if (epsi < epsloc) {
hc = hc * kappa * pow(epsloc / epsi, 0.25);
}
// Re-run if the error is too large on the optimal time step
// value.
while (epsi > epsloc && j < 30) {
j++;
hc = hc * kappa * pow(epsloc / epsi, 0.25);
yv = testStep(tcurr, y[i - 1], hc);
epsi = (norm(yv[0] - yv[1]));
}
// Save solution at current step.
tcurr = t[i - 1] + hc;
t.push_back(tcurr);
y.push_back(yv[1]);
i++;
}
// Erase memory no longer needed.
delete ode;
}
/**
* Calculate the next step for the RK45 method. Unused for now.
*
* @param t - current time.
* @param x - current values.
* @return - solution at next time.
*/
vec RkFehl::nextStep(double t, vec x) {
double hc = h;
vector<vec> yv = testStep(t, x, hc);
return x;
}
/**
* Calculates the RK45 method on the current step. This
* test is used to multiple times to ensure that the error is
* kept low.
*
* @param t - current time.
* @param x - current values.
* @param hc - current time-step.
* @return both of the function values to test for error.
*/
vector<vec> RkFehl::testStep(double t, vec x, double hc) {
// RK4 vector.
vec y4 = zeros<vec>(dim);
// RK5 vector.
vec y5 = zeros<vec>(dim);
// Calculate values according to the RK45 algorithm.
vec k1 = ode->evalF(t, x) * hc;
vec k2 = ode->evalF(t + hc / 4.0, x + k1 / 4.0) * hc;
vec k3 = ode->evalF(t + (3.0 * hc / 8.0),
x + (3.0 * k1 / 32.0) + (9.0 * k2 / 32.0)) * hc;
vec k4 = ode->evalF(t + (12.0 * hc / 13.0),
x + (1932.0 * k1 / 2197.0) - (7200.0 * k2 / 2197.0)
+ (7296.0 * k3 / 2197.0)) * hc;
vec k5 = ode->evalF(t + hc,
x + (439.0 * k1 / 216.0) - (8.0) * k2 + (3680.0 * k3 / 513.0)
- (845.0 * k4 / 4104.0)) * hc;
vec k6 = ode->evalF(t + hc / 2,
x - (8.0 / 27.0) * k1 + (2 * k2) - (3544.0 * k3 / 2565.0)
+ (1859.0 * k4 / 4104.0) - (11.0 / 40.0) * k5) * hc;
// Calculate the next step values.
y4 = x + (25 * k1 / 216.0) + (1408.0 * k3 / 2565.0) + (2197.0 * k4 / 4101.0)
- (k5 / 5);
y5 = x + (16 * k1 / 135.0) + (6656.0 * k3 / 12825.0)
+ (28561.0 * k4 / 56430.0) - (9.0 * k5 / 50.0) + (2.0 * k6 / 55.0);
// Setup output.
vector<vec> ret(2);
ret[0] = y4;
ret[1] = y5;
return ret;
}
RkFehl::~RkFehl() {
}
| 27.544379
| 84
| 0.58131
|
tmkwan
|
5a2ac588f4ba8bddf84dd6d0bc6922ab12e361c5
| 1,934
|
cc
|
C++
|
demo/echo_client.cc
|
gatieme/yohub
|
5cf68da73259c6fb75d35925ef44b1824efecc3f
|
[
"MIT"
] | 102
|
2015-01-12T01:30:00.000Z
|
2021-08-06T05:49:58.000Z
|
demo/echo_client.cc
|
guker/yohub
|
5cf68da73259c6fb75d35925ef44b1824efecc3f
|
[
"MIT"
] | 3
|
2015-01-21T08:57:12.000Z
|
2016-08-29T10:31:19.000Z
|
demo/echo_client.cc
|
guker/yohub
|
5cf68da73259c6fb75d35925ef44b1824efecc3f
|
[
"MIT"
] | 63
|
2015-01-04T02:17:17.000Z
|
2020-10-14T04:57:10.000Z
|
#include "share/log.h"
#include "network/event_pool.h"
#include "network/async_client.h"
#include "network/async_connection.h"
#include "network/buffer.h"
#include <string>
#include <boost/bind.hpp>
#include <signal.h>
using namespace yohub;
static bool stop = false;
class EchoClient {
public:
EchoClient(EventPool* event_pool, const InetAddress& remote)
: event_pool_(event_pool),
async_client_(event_pool_, remote)
{
async_client_.SetConnectionCallback(
boost::bind(&EchoClient::OnConnection, this, _1));
async_client_.SetReadCompletionCallback(
boost::bind(&EchoClient::OnReadCompletion, this, _1, _2));
}
~EchoClient() {
async_client_.Disconnect();
}
void Connect() {
async_client_.Connect();
}
private:
void OnConnection(const AsyncConnectionPtr& conn) {
LOG_TRACE("local=%s:%d, peer=%s:%d, %s",
conn->local_addr().ip().c_str(), conn->local_addr().port(),
conn->peer_addr().ip().c_str(), conn->peer_addr().port(),
conn->connected() ? "connected" : "disconnected");
conn->Write(std::string(" world "));
}
void OnReadCompletion(const AsyncConnectionPtr& conn, Buffer* buffer) {
std::string s(buffer->TakeAsString());
LOG_TRACE("received: %s", s.c_str());
conn->Write(s.data(), s.size());
}
EventPool* const event_pool_;
AsyncClient async_client_;
};
void SignalStop(int) {
LOG_TRACE("Stop running...");
stop = true;
}
int main() {
::signal(SIGINT, SignalStop);
log::SetLogLevel(log::TRACE);
EventPool event_pool(1, 1);
event_pool.Run();
InetAddress remote("127.0.0.1", 19910);
EchoClient client(&event_pool, remote);
client.Connect();
while (true) {
if (stop) {
event_pool.Stop();
break;
}
::usleep(1000);
}
}
| 24.481013
| 75
| 0.607549
|
gatieme
|
5a2e6375dfe8bb10a07261a93b5e267e734c4322
| 5,925
|
cpp
|
C++
|
src/asiUI/salome/moc_QtxColorButton.cpp
|
yeeeeeeti/3D_feature_extract
|
6297daa8afaac09aef9b44858e74fb2a95e1e7c5
|
[
"BSD-3-Clause"
] | null | null | null |
src/asiUI/salome/moc_QtxColorButton.cpp
|
yeeeeeeti/3D_feature_extract
|
6297daa8afaac09aef9b44858e74fb2a95e1e7c5
|
[
"BSD-3-Clause"
] | null | null | null |
src/asiUI/salome/moc_QtxColorButton.cpp
|
yeeeeeeti/3D_feature_extract
|
6297daa8afaac09aef9b44858e74fb2a95e1e7c5
|
[
"BSD-3-Clause"
] | null | null | null |
/****************************************************************************
** Meta object code from reading C++ file 'QtxColorButton.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.9.1)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "QtxColorButton.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'QtxColorButton.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.9.1. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_QtxColorButton_t {
QByteArrayData data[9];
char stringdata0[96];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_QtxColorButton_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_QtxColorButton_t qt_meta_stringdata_QtxColorButton = {
{
QT_MOC_LITERAL(0, 0, 14), // "QtxColorButton"
QT_MOC_LITERAL(1, 15, 7), // "clicked"
QT_MOC_LITERAL(2, 23, 0), // ""
QT_MOC_LITERAL(3, 24, 7), // "changed"
QT_MOC_LITERAL(4, 32, 9), // "onClicked"
QT_MOC_LITERAL(5, 42, 9), // "onToggled"
QT_MOC_LITERAL(6, 52, 13), // "onAboutToShow"
QT_MOC_LITERAL(7, 66, 13), // "onAutoClicked"
QT_MOC_LITERAL(8, 80, 15) // "onDialogClicked"
},
"QtxColorButton\0clicked\0\0changed\0"
"onClicked\0onToggled\0onAboutToShow\0"
"onAutoClicked\0onDialogClicked"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_QtxColorButton[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
7, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
2, // signalCount
// signals: name, argc, parameters, tag, flags
1, 1, 49, 2, 0x06 /* Public */,
3, 1, 52, 2, 0x06 /* Public */,
// slots: name, argc, parameters, tag, flags
4, 1, 55, 2, 0x08 /* Private */,
5, 1, 58, 2, 0x08 /* Private */,
6, 0, 61, 2, 0x08 /* Private */,
7, 1, 62, 2, 0x08 /* Private */,
8, 1, 65, 2, 0x08 /* Private */,
// signals: parameters
QMetaType::Void, QMetaType::QColor, 2,
QMetaType::Void, QMetaType::QColor, 2,
// slots: parameters
QMetaType::Void, QMetaType::Bool, 2,
QMetaType::Void, QMetaType::Bool, 2,
QMetaType::Void,
QMetaType::Void, QMetaType::Bool, 2,
QMetaType::Void, QMetaType::Bool, 2,
0 // eod
};
void QtxColorButton::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
QtxColorButton *_t = static_cast<QtxColorButton *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->clicked((*reinterpret_cast< QColor(*)>(_a[1]))); break;
case 1: _t->changed((*reinterpret_cast< QColor(*)>(_a[1]))); break;
case 2: _t->onClicked((*reinterpret_cast< bool(*)>(_a[1]))); break;
case 3: _t->onToggled((*reinterpret_cast< bool(*)>(_a[1]))); break;
case 4: _t->onAboutToShow(); break;
case 5: _t->onAutoClicked((*reinterpret_cast< bool(*)>(_a[1]))); break;
case 6: _t->onDialogClicked((*reinterpret_cast< bool(*)>(_a[1]))); break;
default: ;
}
} else if (_c == QMetaObject::IndexOfMethod) {
int *result = reinterpret_cast<int *>(_a[0]);
void **func = reinterpret_cast<void **>(_a[1]);
{
typedef void (QtxColorButton::*_t)(QColor );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&QtxColorButton::clicked)) {
*result = 0;
return;
}
}
{
typedef void (QtxColorButton::*_t)(QColor );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&QtxColorButton::changed)) {
*result = 1;
return;
}
}
}
}
const QMetaObject QtxColorButton::staticMetaObject = {
{ &QToolButton::staticMetaObject, qt_meta_stringdata_QtxColorButton.data,
qt_meta_data_QtxColorButton, qt_static_metacall, nullptr, nullptr}
};
const QMetaObject *QtxColorButton::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *QtxColorButton::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_QtxColorButton.stringdata0))
return static_cast<void*>(const_cast< QtxColorButton*>(this));
return QToolButton::qt_metacast(_clname);
}
int QtxColorButton::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QToolButton::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 7)
qt_static_metacall(this, _c, _id, _a);
_id -= 7;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 7)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 7;
}
return _id;
}
// SIGNAL 0
void QtxColorButton::clicked(QColor _t1)
{
void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 0, _a);
}
// SIGNAL 1
void QtxColorButton::changed(QColor _t1)
{
void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 1, _a);
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
| 33.857143
| 96
| 0.605401
|
yeeeeeeti
|
5a3a3f56303afc57a213d74f85375c003754fedd
| 6,848
|
cpp
|
C++
|
BasicGameFramework/Component/Player/PlayerMovement.cpp
|
dlwlxns4/WitchHouse
|
7b2fd8acead69baa9b0850e0ddcb7520b32ef47e
|
[
"BSD-3-Clause"
] | null | null | null |
BasicGameFramework/Component/Player/PlayerMovement.cpp
|
dlwlxns4/WitchHouse
|
7b2fd8acead69baa9b0850e0ddcb7520b32ef47e
|
[
"BSD-3-Clause"
] | null | null | null |
BasicGameFramework/Component/Player/PlayerMovement.cpp
|
dlwlxns4/WitchHouse
|
7b2fd8acead69baa9b0850e0ddcb7520b32ef47e
|
[
"BSD-3-Clause"
] | null | null | null |
#include "PlayerMovement.h"
#include "../CircleComponent.h"
#include "../../Object/GameObject.h"
#include "../../Util/Input.h"
#include "../../Util/Timer.h"
#include "PlayerSpriteRenderer.h"
#include "../../Manager/GameManager.h"
#include "../../Manager/PhysicsManager.h"
#include "../../Manager/GameManager.h"
#include "../../Manager/CameraManager.h"
#include "../../Manager/SceneManager.h"
#include "../../Scene/MainScene.h"
#include "../../Util/AboutTile.h"
#include <iostream>
PlayerMovement::~PlayerMovement()
{
Release();
}
void PlayerMovement::Init()
{
NullAction* nullAction = new NullAction(this->_owner);
actions[0] = nullAction;
InputAction* inputAction = new InputAction(this->_owner);
actions[1] = inputAction;
InitialAction* initialAction = new InitialAction(this->_owner);
actions[2] = initialAction;
IntoHouseAction* intoHouseAction = new IntoHouseAction(this->_owner);
actions[3] = intoHouseAction;
_actionSterategy = actions[0];
}
void PlayerMovement::Update()
{
_actionSterategy->DoAction();
}
void PlayerMovement::SetSpeed(float speed) noexcept
{
_speed = speed;
}
float PlayerMovement::GetSpeed() const noexcept
{
return _speed;
}
void PlayerMovement::SetActionStartegy(PlayerActionState action)
{
_actionSterategy = actions[static_cast<int>(action)];
}
IActionable* PlayerMovement::GetActionStartegy()
{
return _actionSterategy;
}
void PlayerMovement::Release()
{
if (actions.empty() == false)
{
for (size_t i = 0; i < actions.size(); ++i)
{
delete actions[i];
actions[i] = nullptr;
}
}
}
void PlayerMovement::TiggerHelper(int posX, int posY)
{
GameObject* trigger = PhysicsManager::GetInstance()->GetTriggerObj(posX, posY);
if (trigger != nullptr)
{
trigger->OnTrigger();
}
}
void InputAction::DoAction()
{
POINT pos = _obj->GetPosition();
if (GameManager::GetInstance()->GetState() == State::None)
{
if (Input::GetButton(VK_UP))
{
if (PhysicsManager::GetInstance()->IsCollide(_obj->GetPosition().x / TILE_SIZE, _obj->GetPosition().y / TILE_SIZE - 1) == false)
{
GameManager::GetInstance()->SetState(State::Move);
prevPosX = _obj->GetPosition().x / TILE_SIZE;
prevPosY = _obj->GetPosition().y / TILE_SIZE;
}
_obj->GetComponent<PlayerSpriteRenderer>()->SetDirection(UP_DIR);
}
else if (Input::GetButton(VK_DOWN))
{
if (PhysicsManager::GetInstance()->IsCollide(_obj->GetPosition().x / TILE_SIZE, _obj->GetPosition().y / TILE_SIZE + 1) == false)
{
GameManager::GetInstance()->SetState(State::Move);
prevPosX = _obj->GetPosition().x / TILE_SIZE;
prevPosY = _obj->GetPosition().y / TILE_SIZE;
}
_obj->GetComponent<PlayerSpriteRenderer>()->SetDirection(DOWN_DIR);
}
else if (Input::GetButton(VK_LEFT))
{
if (PhysicsManager::GetInstance()->IsCollide(_obj->GetPosition().x / TILE_SIZE - 1, _obj->GetPosition().y / TILE_SIZE) == false)
{
GameManager::GetInstance()->SetState(State::Move);
prevPosX = _obj->GetPosition().x / TILE_SIZE;
prevPosY = _obj->GetPosition().y / TILE_SIZE;
}
_obj->GetComponent<PlayerSpriteRenderer>()->SetDirection(LEFT_DIR);
}
else if (Input::GetButton(VK_RIGHT))
{
if (PhysicsManager::GetInstance()->IsCollide(_obj->GetPosition().x / TILE_SIZE + 1, _obj->GetPosition().y / TILE_SIZE) == false)
{
GameManager::GetInstance()->SetState(State::Move);
prevPosX = _obj->GetPosition().x / TILE_SIZE;
prevPosY = _obj->GetPosition().y / TILE_SIZE;
}
_obj->GetComponent<PlayerSpriteRenderer>()->SetDirection(RIGHT_DIR);
}
}
if (GameManager::GetInstance()->GetState() == State::Move)
{
Direction dir = _obj->GetComponent<PlayerSpriteRenderer>()->GetDirection();
POINT* camera = (CameraManager::GetInstance()->GetCameraPos());
int dx[] = { 0,-1,1,0 };
int dy[] = { 1,-0,0,-1 };
int tmpCameraPosX = camera->x + dx[(int)dir] * 32;
int tmpCameraPosY = camera->y + dy[(int)dir] * 32;
if (CameraManager::GetInstance()->CheckOutOfTileX(tmpCameraPosX) == false)
{
camera->x += dx[(int)dir] * 4;
}
if (CameraManager::GetInstance()->CheckOutOfTileY(tmpCameraPosY) == false)
{
camera->y += dy[(int)dir] * 4;
}
pos.x += dx[(int)dir] * 4;
pos.y += dy[(int)dir] * 4;
_obj->SetPosition(pos);
moveDistance += 4;
if (moveDistance >= 16)
{
_obj->GetComponent<PlayerSpriteRenderer>()->SetAlternateWalk();
}
if (moveDistance >= 32)
{
cout << "Player : " << pos.x / 32 << " " << pos.y / 32 << endl;
cout << "Camera : " << camera->x / 32 << " " << camera->y / 32 << endl;
moveDistance = 0;
GameManager::GetInstance()->SetState(State::None);
_obj->GetComponent<PlayerSpriteRenderer>()->SetFeet(1);
_obj->GetComponent<PlayerMovement>()->TiggerHelper(pos.x / 32, pos.y / 32);
}
PhysicsManager::GetInstance()->RePosCollider(prevPosX, prevPosY, (int)dir);
}
}
void InitialAction::DoAction()
{
#define LEFT 2
#define RIGHT 0
#define FRONT 1
motionDelay++;
if (motionDelay > 22)
{
int frameX = _obj->GetComponent<PlayerSpriteRenderer>()->GetFrameX();
if (isMotionFinish)
{
_obj->GetComponent<PlayerSpriteRenderer>()->SetState(PlayerSpriteState::Move);
_obj->GetComponent<PlayerMovement>()->SetActionStartegy(PlayerActionState::Input);
}
if (frameX == FRONT && isFront)
{
_obj->GetComponent<PlayerSpriteRenderer>()->SetFrameX(LEFT);
isFront = false;
}
else if (frameX == LEFT && isFront == false)
{
_obj->GetComponent<PlayerSpriteRenderer>()->SetFrameX(FRONT);
}
else if (frameX == 1 && isFront == false)
{
_obj->GetComponent<PlayerSpriteRenderer>()->SetFrameX(RIGHT);
isFront = false;
}
else
{
_obj->GetComponent<PlayerSpriteRenderer>()->SetFrameX(FRONT);
isFront = true;
isMotionFinish = true;
}
motionDelay = 0;
}
}
void IntoHouseAction::DoAction()
{
actionDelay++;
if (actionDelay >= animLimitTime)
{
motionDelay++;
if (motionDelay >= moitionLimitTime)
{
motionDelay = 0;
POINT pos = _obj->GetPosition();
POINT* camera = (CameraManager::GetInstance()->GetCameraPos());
Direction dir = _obj->GetComponent<PlayerSpriteRenderer>()->GetDirection();
int dx[] = { 0,-1,1,0 };
int dy[] = { 1,-0,0,-1 };
camera->x += dx[(int)dir] * 4;
camera->y += dy[(int)dir] * 4;
pos.x += dx[(int)dir] * 4;
pos.y += dy[(int)dir] * 4;
_obj->SetPosition(pos);
moveDistance += 4;
opacity -= 0.2f;
_obj->GetComponent<PlayerSpriteRenderer>()->SetOpacity(opacity);
_obj->GetComponent<PlayerSpriteRenderer>()->SetAlternateWalk();
if (moveDistance >= limitMoveDistance)
{
moveDistance = 0;
GameManager::GetInstance()->SetState(State::None);
_obj->GetComponent<PlayerSpriteRenderer>()->SetFeet(1);
motionCount++;
}
}
if (motionCount >= 2)
{
((MainScene*)(SceneManager::GetInstance()->GetCurrentScene()))->TransMap(nextScene);
}
}
}
| 24.992701
| 131
| 0.664282
|
dlwlxns4
|
5a3cb2fe0f92798500e8b3e298a895275fc5f2e5
| 567
|
cpp
|
C++
|
jp.atcoder/abc092/arc093_a/11933117.cpp
|
kagemeka/atcoder-submissions
|
91d8ad37411ea2ec582b10ba41b1e3cae01d4d6e
|
[
"MIT"
] | 1
|
2022-02-09T03:06:25.000Z
|
2022-02-09T03:06:25.000Z
|
jp.atcoder/abc092/arc093_a/11933117.cpp
|
kagemeka/atcoder-submissions
|
91d8ad37411ea2ec582b10ba41b1e3cae01d4d6e
|
[
"MIT"
] | 1
|
2022-02-05T22:53:18.000Z
|
2022-02-09T01:29:30.000Z
|
jp.atcoder/abc092/arc093_a/11933117.cpp
|
kagemeka/atcoder-submissions
|
91d8ad37411ea2ec582b10ba41b1e3cae01d4d6e
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n; cin >> n;
vector<int> a(n + 2);
for (int i = 1; i < n + 1; i++) cin >> a[i];
int s = 0;
for (int i = 0; i < n + 1; i++) {
s += abs(a[i+1] - a[i]);
}
for (int i = 1; i < n + 1; i++) {
int res;
if (a[i-1] <= a[i] && a[i] <= a[i+1]) res = s;
else if (a[i-1] >= a[i] && a[i] >= a[i+1]) res = s;
else res = s - 2 * min(abs(a[i] - a[i-1]), abs(a[i+1] - a[i]));
cout << res << '\n';
}
return 0;
}
| 23.625
| 68
| 0.405644
|
kagemeka
|
5a41b612b64a67861ac2b5f7fba964b361203b51
| 2,090
|
hpp
|
C++
|
include/json/AbstractJsonStateMapParser.hpp
|
SecureCloud-biz/Forecast.io-CPP
|
dc42abaa9d2887ae5e9a61336dd4cf4be1994993
|
[
"Apache-2.0"
] | 12
|
2015-04-08T16:18:08.000Z
|
2020-09-08T01:52:27.000Z
|
include/json/AbstractJsonStateMapParser.hpp
|
SecureCloud-biz/Forecast.io-CPP
|
dc42abaa9d2887ae5e9a61336dd4cf4be1994993
|
[
"Apache-2.0"
] | null | null | null |
include/json/AbstractJsonStateMapParser.hpp
|
SecureCloud-biz/Forecast.io-CPP
|
dc42abaa9d2887ae5e9a61336dd4cf4be1994993
|
[
"Apache-2.0"
] | 6
|
2015-07-24T01:19:58.000Z
|
2019-07-08T11:52:48.000Z
|
#ifndef ABSTRACTJSONSTATEMAPPARSER_HPP
#define ABSTRACTJSONSTATEMAPPARSER_HPP
#include "AbstractJsonParser.hpp" // Base class: json::AbstractJsonParser
#include <sstream>
#include <string>
#include <unordered_map>
#include "ParseError.hpp"
#include "../common/to_string.hpp"
namespace json
{
template<typename A>
class AbstractJsonStateMapParser: public AbstractJsonParser
{
public:
AbstractJsonStateMapParser(
const std::unordered_map<std::string, A>& attributeNames) :
attributeNames(attributeNames)
{
}
void parse(json_object* const & pJsonObj)
{
// Parse JSON data values
json_object_object_foreach(pJsonObj, key, value)
{
parseAttribute(key, value);
}
finishParse();
}
protected:
static std::string createUndefinedAttributeErrorMessage(
const std::string& attributeType, const A& attribute)
{
std::stringstream errorMessage(std::stringstream::out);
errorMessage << "No parsing logic for " << attributeType << " value "
<< common::to_quoted_string(attribute) << " is defined.";
return errorMessage.str();
}
static std::string createUnknownAttributeErrorMessage(
const std::string& key)
{
std::stringstream errorMessage(std::stringstream::out);
errorMessage << "Unknown JSON attribute name encountered: " << key;
return errorMessage.str();
}
virtual void finishParse()
{
// By default do nothing
}
virtual void handleUnmappedAttribute(const std::string& key, json_object* const & pValue)
{
(void)pValue; // Prevent "unused parameter" warning
throw json::ParseError(createUnknownAttributeErrorMessage(key));
}
virtual void parseAttribute(const A& attribute, json_object* const & pValue) = 0;
private:
const std::unordered_map<std::string, A>& attributeNames;
void parseAttribute(const std::string& key, json_object* const & pValue)
{
auto iter = attributeNames.find(key);
if (iter == attributeNames.end())
{
handleUnmappedAttribute(key, pValue);
}
else
{
const A& attribute = iter->second;
parseAttribute(attribute, pValue);
}
}
};
}
#endif // ABSTRACTJSONSTATEMAPPARSER_HPP
| 22.473118
| 90
| 0.733971
|
SecureCloud-biz
|
5a431cdbb6b1967255c17ce88df360c0af7587a7
| 1,756
|
cpp
|
C++
|
problems/codeforces/1244/c-the-football-season/code.cpp
|
brunodccarvalho/competitive
|
4177c439174fbe749293b9da3445ce7303bd23c2
|
[
"MIT"
] | 7
|
2020-10-15T22:37:10.000Z
|
2022-02-26T17:23:49.000Z
|
problems/codeforces/1244/c-the-football-season/code.cpp
|
brunodccarvalho/competitive
|
4177c439174fbe749293b9da3445ce7303bd23c2
|
[
"MIT"
] | null | null | null |
problems/codeforces/1244/c-the-football-season/code.cpp
|
brunodccarvalho/competitive
|
4177c439174fbe749293b9da3445ce7303bd23c2
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
#define long int64_t
#define bigint __int128_t
// *****
long gcd(long a, long b, long& x, long& y) {
long xn = 1, yn = 0;
x = 0, y = 1;
while (a != 0) {
long q = b / a;
b = b % a;
x = x - q * xn, y = y - q * yn;
swap(a, b), swap(x, xn), swap(y, yn);
}
if (b < 0) {
b = -b, x = -x, y = -y;
}
return b;
}
auto solve() {
long n, p, w, d;
cin >> n >> p >> w >> d;
long a, b;
long g = gcd(w, d, a, b);
// aw + bd = g
if (p % g != 0) {
cout << -1 << endl;
return;
}
bigint k = p / g, u = d / g, v = w / g; // u < v
// can set x=ka+mu, y=kb-mv
// need x>=0,y>=0 ==> -ka/u <= m <= kb/v
// need x+y<=n ==> (u-v)m <= n-k(a+b) <==> (v-u)m >= k(a+b)-n
bigint lo = a >= 0 ? -k * a / u : (-k * a + (u - 1)) / u;
bigint hi = b >= 0 ? k * b / v : (k * b - (v - 1)) / v;
assert(u < v);
long m = LLONG_MIN;
if (lo <= hi) {
// (v-u)m >= k(a+b)-n
bigint num = k * (a + b) - n;
if (num < 0) {
bigint minm = num / (v - u);
if (minm <= hi) {
m = max(lo, minm);
}
} else {
bigint minm = (num + (v - u - 1)) / (v - u);
if (minm <= hi) {
m = max(lo, minm);
}
}
}
if (m == LLONG_MIN) {
cout << -1 << endl;
} else {
long x = k * a + m * u, y = k * b - m * v, z = n - x - y;
assert(x >= 0 && y >= 0);
assert(x + y <= n);
assert(x * w + y * d == p);
cout << x << ' ' << y << ' ' << z << endl;
}
}
// *****
int main() {
setbuf(stdout, nullptr);
solve();
return 0;
}
| 23.105263
| 65
| 0.340547
|
brunodccarvalho
|
5a436ebdb47418288b67438e9bcbf4f6d8e194f5
| 457
|
cpp
|
C++
|
nocBunnyHop/src/Dandelion.cpp
|
TravelByRocket/immersive-science-visualizations
|
8cb47997cc97365df14dbd7ad915f162b5b35ff6
|
[
"MIT"
] | null | null | null |
nocBunnyHop/src/Dandelion.cpp
|
TravelByRocket/immersive-science-visualizations
|
8cb47997cc97365df14dbd7ad915f162b5b35ff6
|
[
"MIT"
] | null | null | null |
nocBunnyHop/src/Dandelion.cpp
|
TravelByRocket/immersive-science-visualizations
|
8cb47997cc97365df14dbd7ad915f162b5b35ff6
|
[
"MIT"
] | null | null | null |
//
// Dandelion.cpp
// nocBunnyHop
//
// Created by Bryan Costanza on 2/2/20.
//
#include "Dandelion.h"
void Dandelion::draw(){
int height = 10;
ofPushStyle();
ofFill();
ofSetColor(ofColor::lawnGreen);
ofDrawLine(loc.x, loc.y, loc.x, loc.y - height);
ofSetColor(ofColor::greenYellow);
ofDrawCircle(loc.x, loc.y - height, 3);
ofPopStyle();
ofLog() << "Dandelion::draw() at " << loc << " frame " << ofGetFrameNum();
}
| 21.761905
| 78
| 0.606127
|
TravelByRocket
|
5a475e65eda1f9350be5f50b4ef6ab0e55475875
| 452
|
hpp
|
C++
|
NWNXLib/API/API/CTlkTableToken.hpp
|
summonFox/unified
|
47ab7d051fe52c26e2928b569e9fe7aec5aa8705
|
[
"MIT"
] | 111
|
2018-01-16T18:49:19.000Z
|
2022-03-13T12:33:54.000Z
|
NWNXLib/API/API/CTlkTableToken.hpp
|
summonFox/unified
|
47ab7d051fe52c26e2928b569e9fe7aec5aa8705
|
[
"MIT"
] | 636
|
2018-01-17T10:05:31.000Z
|
2022-03-28T20:06:03.000Z
|
NWNXLib/API/API/CTlkTableToken.hpp
|
summonFox/unified
|
47ab7d051fe52c26e2928b569e9fe7aec5aa8705
|
[
"MIT"
] | 110
|
2018-01-16T19:05:54.000Z
|
2022-03-28T03:44:16.000Z
|
#pragma once
#include "nwn_api.hpp"
#include "CExoString.hpp"
#ifdef NWN_API_PROLOGUE
NWN_API_PROLOGUE(CTlkTableToken)
#endif
struct CTlkTableToken
{
uint32_t m_nHash;
CExoString m_sToken;
uint32_t m_nActionCode;
uint32_t m_nStrRef[4];
uint32_t m_nStrRefDefault;
#ifdef NWN_CLASS_EXTENSION_CTlkTableToken
NWN_CLASS_EXTENSION_CTlkTableToken
#endif
};
#ifdef NWN_API_EPILOGUE
NWN_API_EPILOGUE(CTlkTableToken)
#endif
| 12.914286
| 41
| 0.780973
|
summonFox
|
5a49e305ec89e26a1d3b9b62e09bded50ef263f0
| 1,444
|
cpp
|
C++
|
Strings/RollingHash.cpp
|
4eyes4u/Algorithms
|
afd8363ee39e5b7c499741f56922f16f4f50dc09
|
[
"MIT"
] | 2
|
2019-02-16T13:13:40.000Z
|
2019-03-19T20:05:42.000Z
|
Strings/RollingHash.cpp
|
4eyes4u/Algorithms
|
afd8363ee39e5b7c499741f56922f16f4f50dc09
|
[
"MIT"
] | null | null | null |
Strings/RollingHash.cpp
|
4eyes4u/Algorithms
|
afd8363ee39e5b7c499741f56922f16f4f50dc09
|
[
"MIT"
] | 1
|
2020-07-03T06:15:41.000Z
|
2020-07-03T06:15:41.000Z
|
/*
Name: Rolling hash
Time complexity:
-O(N + logMOD) for initialization
-O(1) for substrings' hash
* * *
Prime should be several magnitudes lower than moduo.
Several hash functions can be applied in order to reduce number of collisions.
*/
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
const int P = 131;
const int MOD = 1e9 + 7;
char s[N];
int h[N], p[N], inv[N];
int mod_pow(int x, int pw, int MOD) {
int ret = 1;
while (pw) {
if (pw & 1)
ret = (1ll * ret * x) % MOD;
pw >>= 1;
x = (1ll * x * x) % MOD;
}
return ret;
}
void precalc_powers(int n) {
p[0] = 1;
p[1] = P;
inv[0] = 1;
inv[1] = mod_pow(P, MOD - 2, MOD);
for (int i = 1; i < n; i++) {
p[i] = (1ll * p[i - 1] * P) % MOD;
inv[i] = (1ll * inv[i - 1] * inv[1]) % MOD;
}
}
void init(int n) {
precalc_powers(n);
h[0] = s[0];
for (int i = 1; i < n; i++) {
h[i] = (1ll * s[i] * p[i]) % MOD;
h[i] += h[i - 1];
if (h[i] >= MOD)
h[i] -= MOD;
}
}
int get_substring(int l, int r) {
int val = h[r] - h[l - 1] + MOD;
if (val >= MOD)
val -= MOD;
if (l)
val = (1ll * val * inv[l - 1]) % MOD;
return val;
}
int main() {
scanf("%s", s);
int n = strlen(s);
init(n);
printf("%d\n", get_substring(0, n - 1));
return 0;
}
| 18.278481
| 82
| 0.455679
|
4eyes4u
|
5a4c6363132c8ec500b2c4f3b1ce18202d89fafd
| 5,770
|
cpp
|
C++
|
source/XDynamicLibrary.cpp
|
MultiSight/multisight-xsdk
|
02268e1aeb1313cfb2f9515d08d131a4389e49f2
|
[
"BSL-1.0"
] | null | null | null |
source/XDynamicLibrary.cpp
|
MultiSight/multisight-xsdk
|
02268e1aeb1313cfb2f9515d08d131a4389e49f2
|
[
"BSL-1.0"
] | null | null | null |
source/XDynamicLibrary.cpp
|
MultiSight/multisight-xsdk
|
02268e1aeb1313cfb2f9515d08d131a4389e49f2
|
[
"BSL-1.0"
] | null | null | null |
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//
// XSDK
// Copyright (c) 2015 Schneider Electric
//
// Use, modification, and distribution is subject to the Boost Software License,
// Version 1.0 (See accompanying file LICENSE).
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#include "XSDK/XDynamicLibrary.h"
#include <vector>
#include <stdlib.h>
using namespace XSDK;
using namespace std;
#ifdef IS_LINUX
#include <cxxabi.h>
#include <execinfo.h>
#elif defined(IS_WINDOWS)
#include "DbgHelp.h"
#include "XSDK/OS.h"
#include "XSDK/XPath.h"
#else
#error ">> Unknown OS!"
#endif
//=============================================================================
// XDynamicLibrary() - ctor #1
//=============================================================================
XDynamicLibrary::XDynamicLibrary() :
_libraryInstance(NULL),
_libraryName("")
{
}
//=============================================================================
// XDynamicLibrary() - ctor #2
//=============================================================================
XDynamicLibrary::XDynamicLibrary(const XString& libraryName) :
_libraryInstance(NULL),
_libraryName(libraryName)
{
}
//=============================================================================
// ~XDynamicLibrary() - Destroys the object, unloads the library
// if necessary.
//=============================================================================
// virtual
XDynamicLibrary::~XDynamicLibrary() throw()
{
if (_libraryInstance != 0)
Unload();
}
//=============================================================================
// Load() - Used in conjunction with ctor #2 that takes a file name arg
// to load the library.
//=============================================================================
void XDynamicLibrary::Load(void)
{
// Defer to our load that takes an argument.
return Load(_libraryName);
}
//=============================================================================
// Load() - Loads the given library name.
//=============================================================================
void XDynamicLibrary::Load(const XString& libraryName)
{
if (false == libraryName.empty())
{
if( _libraryName != libraryName && _libraryInstance)
Unload();
#ifdef IS_WINDOWS
_libraryInstance = ::LoadLibraryW(libraryName.get_wide_string().data());
#elif defined(IS_LINUX)
_libraryInstance = dlopen(libraryName.c_str(), RTLD_NOW | RTLD_GLOBAL);
#else
#error >> "Unknown OS!"
#endif
if(_libraryInstance == 0)
{
#ifdef IS_WINDOWS
LPVOID pStr = 0;
DWORD_PTR args[1] = { (DWORD_PTR)_libraryName.c_str() };
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
NULL,
GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR)&pStr,
0,
(va_list*)args);
// The string already comes with a carriage return.
XString errorString = (LPTSTR)pStr;
LocalFree(pStr);
X_THROW(("Unable to load library(%s); error(%s)", libraryName.c_str(), errorString.c_str() ));
#elif defined(IS_LINUX)
XString dlError = dlerror();
if( dlError.Contains( "undefined symbol: " ) )
{
vector<XString> parts;
dlError.Split( "undefined symbol: ", parts );
if( parts.size() == 2 )
{
XString rhs = parts[1];
const size_t closeParen = rhs.find( ')' );
XString mangledName = rhs.substr( 0, (rhs.size()-closeParen) );
int status = 0;
char* demangled = abi::__cxa_demangle( mangledName.c_str(), NULL, NULL, &status );
XString demangledName = demangled;
free( demangled );
X_THROW(("Unable to load library(%s); error(%s); demangled undefined symbol(%s);", libraryName.c_str(), dlError.c_str(), demangledName.c_str() ));
}
}
else X_THROW(("Unable to load library(%s); error(%s)", libraryName.c_str(), dlerror() ));
#else
#error >> "Unknown OS!"
#endif
}
_libraryName = libraryName;
}
else
X_THROW(("Library name is empty"));
}
//=============================================================================
// ResolveSymbol - Looks up the given symbol in this library, returns a pointer
//=============================================================================
FARPROC XDynamicLibrary::ResolveSymbol(const XString& symbolName)
{
FARPROC symPtr = 0;
if (false == symbolName.empty())
{
#ifdef IS_WINDOWS
symPtr = ::GetProcAddress(_libraryInstance, symbolName.c_str());
#elif defined(IS_LINUX)
symPtr = dlsym(_libraryInstance, symbolName.c_str());
#else
#error >> "Unknown OS!"
#endif
}
return symPtr;
}
//=============================================================================
// Unload() - Unloads this library, .DLL or .so
//=============================================================================
void XDynamicLibrary::Unload(void)
{
if (_libraryInstance != 0)
{
#ifdef IS_WINDOWS
::FreeLibrary(_libraryInstance);
#elif defined(IS_LINUX)
dlclose(_libraryInstance);
#else
#error >> "Unknown OS!"
#endif
}
// Always set this to NULL, we're done.
_libraryInstance = 0;
}
| 31.703297
| 166
| 0.462912
|
MultiSight
|
53ff8057e0bca24f227762fd1d0d8f7f34184af9
| 4,196
|
cpp
|
C++
|
Examples/PDU/PDU_Factory2/KDIS.cpp
|
TangramFlex/KDIS_Fork
|
698d81a2de8b6df3fc99bb31b9d31eaa5368fda4
|
[
"BSD-2-Clause"
] | null | null | null |
Examples/PDU/PDU_Factory2/KDIS.cpp
|
TangramFlex/KDIS_Fork
|
698d81a2de8b6df3fc99bb31b9d31eaa5368fda4
|
[
"BSD-2-Clause"
] | null | null | null |
Examples/PDU/PDU_Factory2/KDIS.cpp
|
TangramFlex/KDIS_Fork
|
698d81a2de8b6df3fc99bb31b9d31eaa5368fda4
|
[
"BSD-2-Clause"
] | null | null | null |
/**********************************************************************
The following UNLICENSE statement applies to this example.
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
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 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.
For more information, please refer to <http://unlicense.org/>
*********************************************************************/
/*********************************************************************
For Further Information on KDIS:
http://p.sf.net/kdis/UserGuide
This example is the same as PDU Factory example 1 however it uses some of the new features provided by the Connection class.
https://sourceforge.net/p/kdis/wiki/PDU_Factory2/
*********************************************************************/
#include <iostream>
#include "KDIS/Extras/PDU_Factory.h"
#include "KDIS/Network/Connection.h" // A cross platform connection class.
#include "KDIS/Network/ConnectionSubscriber.h"
using namespace std;
using namespace KDIS;
using namespace DATA_TYPE;
using namespace PDU;
using namespace ENUMS;
using namespace UTILS;
using namespace NETWORK;
//
// This is our example subscriber class. It simply prints out the senders IP address and the contents of the PDU.
//
class ExampleSubscriber : public ConnectionSubscriber
{
public:
ExampleSubscriber()
{
};
~ExampleSubscriber()
{
};
// Our overloaded Data Received function
virtual KBOOL OnDataReceived( const KOCTET * Data, KUINT32 DataLength, const KString & SenderIp )
{
cout << "Received " << DataLength << " bytes from " << SenderIp << endl;
// We return true here, if we return false then the data will be discarded by the connection class.
// This means an IP address based filter could be implemented here.
return true;
};
// Our overloaded PDU Received function
virtual void OnPDUReceived( const Header * H )
{
// Print out the contents of the PDU.
cout << H->GetAsString();
cout << "*****************************************************************\n\n" << endl;
};
};
int main()
{
try
{
// Note this multi cast address will probably be different for your network however
// port 3000 is the assigned number by IANA(Internet Assigned Numbers Authority) for DIS simulations.
Connection conn( "192.168.86.255" );
// Lets apply a filter to the factory so it only lets through PDU that have an exercise ID of 1.
conn.GetPDU_Factory()->AddFilter( new FactoryFilterExerciseID( 1 ) );
// Add our subscriber
conn.AddSubscriber( new ExampleSubscriber );
while( true )
{
try
{
// Note: GetNextPDU supports PDU Bundling, which Receive does not.
conn.GetNextPDU();
}
catch( exception & e )
{
// KDIS error, should be safe to carry on.
cout << e.what() << endl;
}
}
}
catch( exception & e )
{
// Socket/Connection error, better stop.
cout << e.what() << endl;
}
return 0;
}
| 34.677686
| 124
| 0.630839
|
TangramFlex
|
9904e948ada36e1a76f79b99d594615cf2c506ca
| 1,170
|
hpp
|
C++
|
opt/nomad/src/Attribute/cacheAttributesDefinition.hpp
|
scikit-quant/scikit-quant
|
397ab0b6287f3815e9bcadbfadbe200edbee5a23
|
[
"BSD-3-Clause-LBNL"
] | 31
|
2019-02-05T16:39:18.000Z
|
2022-03-11T23:14:11.000Z
|
opt/nomad/src/Attribute/cacheAttributesDefinition.hpp
|
scikit-quant/scikit-quant
|
397ab0b6287f3815e9bcadbfadbe200edbee5a23
|
[
"BSD-3-Clause-LBNL"
] | 20
|
2020-04-13T09:22:53.000Z
|
2021-08-16T16:14:13.000Z
|
opt/nomad/src/Attribute/cacheAttributesDefinition.hpp
|
scikit-quant/scikit-quant
|
397ab0b6287f3815e9bcadbfadbe200edbee5a23
|
[
"BSD-3-Clause-LBNL"
] | 6
|
2020-04-21T17:43:47.000Z
|
2021-03-10T04:12:34.000Z
|
//////////// THIS FILE MUST BE CREATED BY EXECUTING WriteAttributeDefinitionFile ////////////
//////////// DO NOT MODIFY THIS FILE MANUALLY ///////////////////////////////////////////////
#ifndef __NOMAD_4_0_CACHEATTRIBUTESDEFINITION__
#define __NOMAD_4_0_CACHEATTRIBUTESDEFINITION__
_definition = {
{ "CACHE_FILE", "std::string", "", " Cache file name ", " \n \n . Cache file. If the specified file does not exist, it will be created. \n \n . Argument: one string. \n \n . If the string is empty, no cache file will be created. \n \n . Points already in the cache file will not be reevaluated. \n \n . Example: CACHE_FILE cache.txt \n \n . Default: Empty string.\n\n", " basic cache file " , "false" , "false" , "true" },
{ "CACHE_SIZE_MAX", "size_t", "INF", " Maximum number of evaluation points to be stored in the cache ", " \n \n . The cache will be purged from older points if it reaches this number \n of evaluation points. \n \n . Argument: one positive integer (expressed in number of evaluation points). \n \n . Example: CACHE_SIZE_MAX 10000 \n \n . Default: INF\n\n", " advanced cache " , "false" , "false" , "true" } };
#endif
| 97.5
| 436
| 0.64359
|
scikit-quant
|
990c981deab8ee1f973aa8b79fd4541113777dc6
| 4,568
|
cpp
|
C++
|
main.cpp
|
Arc-N/DLL-Implementation
|
f366ad19eef76f7b52158e71107a32a6bbcdae24
|
[
"MIT"
] | null | null | null |
main.cpp
|
Arc-N/DLL-Implementation
|
f366ad19eef76f7b52158e71107a32a6bbcdae24
|
[
"MIT"
] | null | null | null |
main.cpp
|
Arc-N/DLL-Implementation
|
f366ad19eef76f7b52158e71107a32a6bbcdae24
|
[
"MIT"
] | null | null | null |
//Arman Arakelyan
#include "helperFunctions.hpp"
int main()
{
int lengthOfSimulation = 0, numberOfRegisters = 0, maximumLineLength = 0;
char arrangmentSelector = '\0';
std::cin >> lengthOfSimulation >> numberOfRegisters >> maximumLineLength;
std::cin >> arrangmentSelector;
//==================================================Single Line==============================================
if (arrangmentSelector == 'S')
{
statistics statsInformation{0};
DoublyLinkedList<customerInfo> cInfo;
std::vector<registerInfo> registers(numberOfRegisters);
//fill in registers with their service time
for (int i = 0; i < numberOfRegisters; ++i)
{
std::cin >> registers[i].time;
registers[i].empty = true;
registers[i].ptime = lengthOfSimulation * 60;
}
//fill in customer information into corresponding linked list.
customerInfo temp;
std::cin >> temp.numberOfCustomersEntered >> temp.timeOfCustomersEntered;
cInfo.addToEnd(temp);
//read customer input untill END
while (!std::cin.fail())
{
std::cin >> temp.numberOfCustomersEntered >> temp.timeOfCustomersEntered;
cInfo.addToEnd(temp);
}
//Start log
std::cout << "\nLOG" << std::endl;
std::cout << "0 start" << std::endl;
for (int t = 0; t < lengthOfSimulation * 60; ++t)
{
if (t == cInfo.first().timeOfCustomersEntered)
{
for (int j = 0; j < cInfo.first().numberOfCustomersEntered; ++j)
{
if (registers[0].queueSize != maximumLineLength)
{
registers[0].line.enqueue(registers[0].queueSize);
registers[0].queueSize++;
registers[0].waitTime.addToEnd(t);
std::cout << t << " entered line 1 length " << registers[0].queueSize << std::endl;
statsInformation.enteredLine++;
}
else if (registers[0].queueSize == maximumLineLength)
{
std::cout << t << " lost" <<std::endl;
statsInformation.lost++;
}
}
cInfo.removeFromStart();
}
if (registers[0].queueSize != 0)
{
moveCustomersToEmptyRegisters(registers, t, statsInformation);
}
isAnyRegisterExiting(registers, t, lengthOfSimulation, statsInformation);
}
std::cout << lengthOfSimulation*60 << " end" << std::endl;
printStatistics(registers, statsInformation);
}
//==================================================Multi Line==============================================
else
{
statistics statsInformation{0};
int numberOfEmptyRegisters = numberOfRegisters;
DoublyLinkedList<customerInfo> cInfo;
std::vector<registerInfo> registers(numberOfRegisters);
//fill in registers with their service time
for (int i = 0; i < numberOfRegisters; ++i)
{
std::cin >> registers[i].time;
registers[i].empty = true;
registers[i].ptime = lengthOfSimulation * 60;
}
//push customer info into linked list cInfo
customerInfo temp;
std::cin >> temp.numberOfCustomersEntered >> temp.timeOfCustomersEntered;
cInfo.addToEnd(temp);
//read input untill END
while (!std::cin.fail())
{
std::cin >> temp.numberOfCustomersEntered >> temp.timeOfCustomersEntered;
cInfo.addToEnd(temp);
}
//start LOG
std::cout << "\nLOG" << std::endl;
std::cout << "0 start" << std::endl;
for (int t = 0; t < lengthOfSimulation * 60; ++t)
{
if (t == cInfo.first().timeOfCustomersEntered)
{
for (int j = 0; j < cInfo.first().numberOfCustomersEntered; ++j)
{
int shortestLineIndex = getShortestLineIndex(registers);
if (registers[shortestLineIndex].queueSize != maximumLineLength)
{
registers[shortestLineIndex].line.enqueue(registers[shortestLineIndex].queueSize);
registers[shortestLineIndex].queueSize++;
registers[shortestLineIndex].waitTime.addToEnd(t);
std::cout << t << " entered line " << shortestLineIndex+1 << " length " << registers[shortestLineIndex].queueSize << std::endl;
statsInformation.enteredLine++;
}
else if (registers[shortestLineIndex].queueSize == maximumLineLength)
{
std::cout << t << " lost" << std::endl;
statsInformation.lost++;
}
}
cInfo.removeFromStart();
}
if(numberOfEmptyRegisters) //if there are not empty registers don't bother trying to move customers into empty registers.
{
moveCustomersToEmptyRegisters(registers, t, numberOfEmptyRegisters, statsInformation);
}
isAnyRegisterExiting(registers, t, lengthOfSimulation, numberOfEmptyRegisters, statsInformation); //Check if any registers are going to finish at t
}
std::cout << lengthOfSimulation*60 << " end" << std::endl;
printStatistics(registers, statsInformation);
}
return 0;
}
| 35.968504
| 150
| 0.652583
|
Arc-N
|
99120f71365de278ae23671cd007a867bc94f843
| 556
|
hpp
|
C++
|
headers/event.hpp
|
bdomitil/irc-server
|
16ea347ea3d1a79fec402a871320cf22d5ef5a2f
|
[
"Unlicense"
] | null | null | null |
headers/event.hpp
|
bdomitil/irc-server
|
16ea347ea3d1a79fec402a871320cf22d5ef5a2f
|
[
"Unlicense"
] | null | null | null |
headers/event.hpp
|
bdomitil/irc-server
|
16ea347ea3d1a79fec402a871320cf22d5ef5a2f
|
[
"Unlicense"
] | null | null | null |
#ifndef IRC_EVENT_HPP
#define IRC_EVENT_HPP
#include "irc-server.hpp"
class t_event{
private:
uint32_t len;
int fd;
uint32_t update_len;
struct kevent *event_list;
public:
void update();
void addReadEvent(int fd, void *udata);
void addWriteEvent(int fd, void *udata);
void disableReadEvent(int fd, void *udata);
void disableWriteEvent(int fd, void *udata);
void enableWriteEvent(int fd, void *udata);
void enableReadEvent(int fd, void *udata);
int proc(struct kevent **list);
uint32_t &size(){return update_len;}
t_event();
};
#endif
| 23.166667
| 45
| 0.733813
|
bdomitil
|
9912ad534241b957aeb416a745be3738794589ed
| 1,766
|
cpp
|
C++
|
src/tdme/engine/model/FacesEntity.cpp
|
mahula/tdme2
|
0f74d35ae5d2cd33b1a410c09f0d45f250ca7a64
|
[
"BSD-3-Clause"
] | null | null | null |
src/tdme/engine/model/FacesEntity.cpp
|
mahula/tdme2
|
0f74d35ae5d2cd33b1a410c09f0d45f250ca7a64
|
[
"BSD-3-Clause"
] | null | null | null |
src/tdme/engine/model/FacesEntity.cpp
|
mahula/tdme2
|
0f74d35ae5d2cd33b1a410c09f0d45f250ca7a64
|
[
"BSD-3-Clause"
] | null | null | null |
#include <tdme/engine/model/FacesEntity.h>
#include <vector>
#include <string>
#include <tdme/engine/model/Face.h>
#include <tdme/engine/model/Group.h>
#include <tdme/engine/model/Material.h>
#include <tdme/engine/model/TextureCoordinate.h>
#include <tdme/math/Vector3.h>
using std::vector;
using std::string;
using tdme::engine::model::FacesEntity;
using tdme::engine::model::Face;
using tdme::engine::model::Group;
using tdme::engine::model::Material;
using tdme::engine::model::TextureCoordinate;
using tdme::math::Vector3;
FacesEntity::FacesEntity()
{
this->id = "";
this->group = nullptr;
this->material = nullptr;
this->textureCoordinatesAvailable = false;
this->tangentBitangentAvailable = false;
}
FacesEntity::FacesEntity(Group* group, const string& id)
{
this->id = id;
this->group = group;
this->material = nullptr;
this->textureCoordinatesAvailable = false;
this->tangentBitangentAvailable = false;
}
void FacesEntity::setFaces(const vector<Face>& faces)
{
this->faces.clear();
this->faces.resize(faces.size());
int i = 0;
for (auto& face: faces) {
this->faces[i++] = face;
}
determineFeatures();
}
void FacesEntity::determineFeatures()
{
textureCoordinatesAvailable = false;
tangentBitangentAvailable = false;
for (auto& face: faces) {
auto& vertexIndices = face.getVertexIndices();
if (vertexIndices[0] != -1 && vertexIndices[1] != -1 && vertexIndices[2] != -1) textureCoordinatesAvailable = true;
auto& tangentIndices = face.getTangentIndices();
auto& biTangentIndices = face.getBitangentIndices();
if (tangentIndices[0] != -1 && tangentIndices[1] != -1 && tangentIndices[2] != -1 &&
biTangentIndices[0] != -1 && biTangentIndices[1] != -1 && biTangentIndices[2] != -1) tangentBitangentAvailable = true;
}
}
| 27.169231
| 121
| 0.715742
|
mahula
|
991ebdf78337daca3f78c08db62eded13e83ae73
| 1,688
|
inl
|
C++
|
include/luaBind/object.inl
|
StefanoLanza/LuaBind
|
37b27e8ed54915890a69139826ece9e24d0860d5
|
[
"MIT"
] | null | null | null |
include/luaBind/object.inl
|
StefanoLanza/LuaBind
|
37b27e8ed54915890a69139826ece9e24d0860d5
|
[
"MIT"
] | null | null | null |
include/luaBind/object.inl
|
StefanoLanza/LuaBind
|
37b27e8ed54915890a69139826ece9e24d0860d5
|
[
"MIT"
] | null | null | null |
#pragma once
#include "autoBlock.h"
#include "result.h"
#include "stackUtils.h"
#include <cassert>
namespace Typhoon::LuaBind {
template <typename RetType, typename... ArgTypes>
Result Object::callMethodRet(const char* func, RetType& ret, ArgTypes&&... args) const {
AutoBlock autoBlock(ls);
const auto [validCall, resStackIndex] = beginCall(func);
if (! validCall) {
return Result { false };
}
const int argStackSize[] = { getStackSize<ArgTypes>()..., 0 };
// Push arguments
// Because of C++ rules, by creating an array, push is called in the correct order for each argument
const int dummy[] = { (push(ls, std::forward<ArgTypes>(args)), 1)..., 1 };
(void)dummy;
// Get stack size of all arguments
int narg = 0;
for (size_t i = 0; i < sizeof...(ArgTypes); ++i) {
narg += argStackSize[i];
}
const int nres = getStackSize<RetType>();
const Result res = callMethodImpl(narg, nres);
if (res) {
ret = pop<RetType>(ls, resStackIndex);
}
return res;
}
template <typename... ArgTypes>
Result Object::callMethod(const char* func, ArgTypes&&... args) const {
AutoBlock autoBlock(ls);
const auto [validCall, resStackIndex] = beginCall(func);
if (! validCall) {
return Result { false };
}
const int argStackSize[] = { getStackSize<ArgTypes>()..., 0 };
// Push arguments
// Because of C++ rules, by creating an array, push is called in the correct order for each argument
const int dummy[] = { (push(ls, std::forward<ArgTypes>(args)), 1)..., 1 };
// Get stack size of all arguments
int narg = 0;
for (size_t i = 0; i < sizeof...(ArgTypes); ++i) {
narg += argStackSize[i];
}
return callMethodImpl(narg, 0);
}
} // namespace Typhoon::LuaBind
| 25.969231
| 101
| 0.668246
|
StefanoLanza
|
991f70d987ade5625f8ddbc1269112446000031e
| 5,880
|
cpp
|
C++
|
src/4-CPUArchitecture/cpu_cache_misses.cpp
|
nixiz/advanced_cpp_course
|
acc3cab52cb629ed3eb12cd0fdd9689069e733e7
|
[
"MIT"
] | 1
|
2021-12-09T07:23:06.000Z
|
2021-12-09T07:23:06.000Z
|
src/4-CPUArchitecture/cpu_cache_misses.cpp
|
nixiz/advanced_cpp_course
|
acc3cab52cb629ed3eb12cd0fdd9689069e733e7
|
[
"MIT"
] | null | null | null |
src/4-CPUArchitecture/cpu_cache_misses.cpp
|
nixiz/advanced_cpp_course
|
acc3cab52cb629ed3eb12cd0fdd9689069e733e7
|
[
"MIT"
] | null | null | null |
#include <advanced_cpp_topics.h>
#include <limits>
#include <type_traits>
#include <chrono>
#include <random>
#include <map>
#include <string>
#include <sstream>
#include <iostream>
#include <iomanip>
namespace cpu_cache_misses {
enum class TraversalOrder : unsigned {
RowMajor,
ColumnMajor
};
template <unsigned int size>
struct random_map
{
unsigned int map[size] = { 0 };
random_map()
{
srand(static_cast<unsigned int>(time(NULL)));
std::generate(std::begin(map), std::end(map), [] {
return rand();
});
}
unsigned int operator()() const
{
return map[++indx % size];
}
private:
mutable unsigned int indx = 0;
};
const static random_map<1024> random_numbers;
template <class T>
class Matrix {
public:
typedef typename std::decay<T>::type Type;
explicit Matrix(unsigned long long matrix_size)
{
const unsigned long long matrix_dim = static_cast<unsigned long long>(sqrt(matrix_size));
const auto dim_size = matrix_dim % 2 == 0 ? matrix_dim : matrix_dim + 1;
rowsize = (dim_size / 2);
columnsize = (dim_size - rowsize);
// check if matrix is equal sized
assert(rowsize == columnsize);
//std::default_random_engine generator;
//std::uniform_int_distribution<int> distribution(1, (std::numeric_limits<Type>::max)());
data_ = new Type*[rowsize];
for (unsigned long long i = 0; i < rowsize; i++)
{
data_[i] = new Type[columnsize];
// set initial values
for (unsigned long long j = 0; j < columnsize; j++)
{
// set random initial data
data_[i][j] = static_cast<Type>(random_numbers());
}
}
}
~Matrix()
{
// delete allocated source
for (size_t i = 0; i < rowsize; i++)
{
delete[] data_[i];
}
delete[] data_;
}
unsigned long long rows() const {
return rowsize;
}
unsigned long long columns() const {
return columnsize;
}
Type* operator[](unsigned long long index) {
return data_[index];
}
Type* operator[](unsigned long long index) const {
return data_[index];
}
private:
Type** data_;
unsigned long long rowsize;
unsigned long long columnsize;
};
template <typename T>
unsigned long long sumMatrix(const Matrix<T>& m, TraversalOrder order)
{
unsigned long long sum = 0;
if (order == TraversalOrder::RowMajor) {
for (unsigned long long r = 0; r < m.rows(); ++r) {
for (unsigned long long c = 0; c < m.columns(); ++c) {
sum += m[r][c];
}
}
}
else {
for (unsigned long long c = 0; c < m.columns(); ++c) {
for (unsigned long long r = 0; r < m.rows(); ++r) {
sum += m[r][c];
}
}
}
return sum;
}
class MatrixSumBenchmarkHelper {
public:
using clock = std::chrono::high_resolution_clock;
using duration = std::chrono::duration<double, std::micro>;
explicit MatrixSumBenchmarkHelper(unsigned long long matrix_size) :
mat(matrix_size) { }
std::pair<double, unsigned long long> start(TraversalOrder order) {
unsigned long long sum = 0;
clock::time_point start = clock::now();
sum = sumMatrix(mat, order);
duration elapsed = clock::now() - start;
// return in millisecond resolution
return std::make_pair(elapsed.count() / 1000.0, sum);
}
protected:
Matrix<unsigned char> mat;
};
struct benchmarkresult {
void SetName(std::string name) {
testname = name;
}
void AddSample(unsigned long long matrix_size, double time) {
samplings.push_back(
std::make_pair(matrix_size, time));
}
friend std::ostream& operator<<(std::ostream& os, const benchmarkresult& result);
private:
std::string testname;
std::vector<std::pair<unsigned long long, double>> samplings; // matrix size (mb) - traversal sum time in milliseconds
};
std::ostream& operator<<(std::ostream& os, const benchmarkresult& result) {
os
<< "results of: " << result.testname << "\n"
<< "matrix size (MB)\telapsed time (ms)" << std::setw(5) << "\n";
for (size_t i = 0; i < result.samplings.size(); i++)
{
os << "\t" << result.samplings[i].first / (1024 * 1024) << "\t\t" << result.samplings[i].second << "\n";
}
return os;
}
} // namespace cpu_cache_misses
ELEMENT_CODE(CpuCacheExample) {
using namespace cpu_cache_misses;
constexpr size_t num_of_iter = 100;
// initiate result map
std::map<std::string, benchmarkresult> results;
results["rowmajor"].SetName("rowmajor");
results["columnmajor"].SetName("columnmajor");
for (size_t i = 1; i <= num_of_iter; ++i)
{
unsigned long long matrix_size = (1024 * 1024) * (i * 5);
std::cout
<< "\n------------------benchmark point------------------\n"
<< "Matrix with size : " << matrix_size << std::endl;
MatrixSumBenchmarkHelper benchmarker{ matrix_size };
std::cout
<< "Starting benchmark for row major traversal" << std::endl;
auto benchmark_result = benchmarker.start(TraversalOrder::RowMajor);
results["rowmajor"].AddSample(matrix_size, benchmark_result.first);
std::cout << "sum: " << benchmark_result.second << "\n";
std::cout
<< "Starting benchmark for column major traversal" << std::endl;
auto benchmark_result_column = benchmarker.start(TraversalOrder::ColumnMajor);
results["columnmajor"].AddSample(matrix_size, benchmark_result_column.first);
std::cout << "sum: " << benchmark_result_column.second << "\n";
}
std::cout
<< "\n------------------------------------------------------\n"
<< results["rowmajor"]
<< "\n------------------------------------------------------\n"
<< results["columnmajor"]
<< std::endl;
}
| 28
| 122
| 0.596429
|
nixiz
|
9921d1792e24d504db60756a0857ae644ed51ccc
| 6,762
|
cpp
|
C++
|
src/schedulers/Static.cpp
|
EngineCL/EngineCL
|
28b717317c3d6330385cb3b8f574f2b35f62ad4c
|
[
"MIT"
] | 13
|
2020-10-12T00:08:42.000Z
|
2022-03-31T21:17:12.000Z
|
src/schedulers/Static.cpp
|
EngineCL/EngineCL
|
28b717317c3d6330385cb3b8f574f2b35f62ad4c
|
[
"MIT"
] | null | null | null |
src/schedulers/Static.cpp
|
EngineCL/EngineCL
|
28b717317c3d6330385cb3b8f574f2b35f62ad4c
|
[
"MIT"
] | 3
|
2020-11-19T01:17:57.000Z
|
2021-04-27T03:40:05.000Z
|
/**
* Copyright (c) 2018 ATC (University of Cantabria) <nozalr@unican.es>
* This file is part of EngineCL which is released under MIT License.
* See file LICENSE for full license details.
*/
#include "schedulers/Static.hpp"
#include <tuple>
#include "Device.hpp"
namespace ecl {
void
fnThreadScheduler(StaticScheduler& scheduler)
{
auto time1 = std::chrono::system_clock::now().time_since_epoch();
scheduler.saveDuration(ActionType::schedulerStart);
scheduler.saveDurationOffset(ActionType::schedulerStart);
scheduler.preEnqueueWork();
scheduler.waitCallbacks();
scheduler.saveDuration(ActionType::schedulerEnd);
scheduler.saveDurationOffset(ActionType::schedulerEnd);
}
StaticScheduler::StaticScheduler(WorkSplit wsplit)
: mSema(1)
, mHasWork(false)
, mWorkSplit(wsplit)
{
mMutexDuration = new mutex();
mTimeInit = std::chrono::system_clock::now().time_since_epoch();
mTime = std::chrono::system_clock::now().time_since_epoch();
mDurationActions.reserve(8); // NOTE: improve the reserve
mDurationOffsetActions.reserve(8); // trade-off memory/common usage
}
StaticScheduler::~StaticScheduler()
{
if (mThread.joinable()) {
mThread.join();
}
}
void
StaticScheduler::printStats()
{
auto sum = 0;
auto len = mDevices.size();
for (uint i = 0; i < len; ++i) {
sum += mChunkDone[i];
}
cout << "StaticScheduler:\n";
cout << "chunks: " << sum << "\n";
cout << "duration offsets from init:\n";
for (auto& t : mDurationOffsetActions) {
Inspector::printActionTypeDuration(std::get<1>(t), std::get<0>(t));
}
}
void
StaticScheduler::waitCallbacks()
{
mSema.wait(1);
}
void
StaticScheduler::notifyCallbacks()
{
mSema.notify(1);
}
void
StaticScheduler::setTotalSize(size_t size)
{
mSize = size;
mHasWork = true;
}
void
StaticScheduler::setGws(NDRange gws)
{
mGws = gws;
mHasWork = true;
}
void
StaticScheduler::setLws(size_t lws)
{
mLws = lws;
}
void
StaticScheduler::setOutPattern(uint outWorkitems, uint outPositions)
{
mOutWorkitems = outWorkitems;
mOutPositions = outPositions;
}
void
StaticScheduler::setDevices(vector<Device*>&& devices)
{
mDevices = move(devices);
mNumDevices = mDevices.size();
mChunkTodo = vector<uint>(mNumDevices, 0);
mChunkGiven = vector<uint>(mNumDevices, 0);
mChunkDone = vector<uint>(mNumDevices, 0);
mQueueIdWork.reserve(mNumDevices);
mQueueIdWork = vector<vector<uint>>(mNumDevices, vector<uint>());
mDevicesWorking = 0;
}
void
StaticScheduler::setRawProportions(const vector<float>& props)
{
auto last = mNumDevices - 1;
if (props.size() < last) {
throw runtime_error("proportions < number of devices - 1");
}
if (last == 0) {
mRawProportions = { 1.0f };
} else {
for (auto prop : props) {
if (prop <= 0.0f || prop >= 1.0f) {
throw runtime_error("proportion should be between (0.0f, 1.0f)");
}
}
mRawProportions = move(props);
}
mWorkSplit = WorkSplit::Raw;
}
tuple<size_t, size_t>
StaticScheduler::splitWork(size_t size, float prop, size_t bound)
{
size_t given = bound * (static_cast<size_t>(prop * size) / bound);
size_t rem = size - given;
if ((given % mLws) != 0) {
throw runtime_error("given % lws: " + to_string(given) + " % " + to_string(mLws));
}
return { given, rem };
}
void
StaticScheduler::saveDuration(ActionType action)
{
lock_guard<mutex> lock(*mMutexDuration);
auto t2 = std::chrono::system_clock::now().time_since_epoch();
size_t diffMs = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - mTime).count();
mDurationActions.push_back(make_tuple(diffMs, action));
mTime = t2;
}
void
StaticScheduler::saveDurationOffset(ActionType action)
{
lock_guard<mutex> lock(*mMutexDuration);
auto t2 = std::chrono::system_clock::now().time_since_epoch();
size_t diffMs = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - mTimeInit).count();
mDurationOffsetActions.push_back(make_tuple(diffMs, action));
}
void
StaticScheduler::calcProportions()
{
vector<tuple<size_t, size_t>> proportions;
int len = mNumDevices;
uint last = len - 1;
size_t wsizeGivenAcc = 0;
size_t wsizeGiven = 0;
size_t wsizeRemaining = mSize;
size_t wsizeRestRemaining = 0;
switch (mWorkSplit) {
case WorkSplit::Raw:
for (uint i = 0; i < last; ++i) {
auto prop = mRawProportions[i];
tie(wsizeGiven, wsizeRestRemaining) = splitWork(mSize, prop, mLws);
size_t wsizeOffset = wsizeGivenAcc;
proportions.push_back(make_tuple(wsizeGiven, wsizeOffset));
wsizeGivenAcc += wsizeGiven;
wsizeRemaining -= wsizeGiven;
}
proportions.push_back(make_tuple(wsizeRemaining, wsizeGivenAcc));
break;
case WorkSplit::By_Devices:
for (uint i = 0; i < last; ++i) {
tie(wsizeGiven, wsizeRemaining) = splitWork(wsizeRemaining, 1.0f / len, mLws);
size_t wsizeOffset = wsizeGivenAcc;
proportions.push_back(make_tuple(wsizeGiven, wsizeOffset));
wsizeGivenAcc += wsizeGiven;
}
proportions.push_back(make_tuple(wsizeRemaining, wsizeGivenAcc));
break;
}
mProportions = move(proportions);
}
void
StaticScheduler::start()
{
mThread = thread(fnThreadScheduler, std::ref(*this));
}
void
StaticScheduler::enqueueWork(Device* device)
{
int id = device->getID();
if (mChunkTodo[id] == 0) {
auto prop = mProportions[id];
size_t size, offset;
tie(size, offset) = prop;
uint index;
{
lock_guard<mutex> guard(mMutexWork);
index = mQueueWork.size();
mQueueWork.push_back(Work(id, offset, size, mOutWorkitems, mOutPositions));
}
mQueueIdWork[id].push_back(index);
mChunkTodo[id]++;
}
}
void
StaticScheduler::preEnqueueWork()
{
mDevicesWorking = mNumDevices;
calcProportions();
}
void
StaticScheduler::requestWork(Device* device)
{
enqueueWork(device);
device->notifyWork();
}
void
StaticScheduler::callback(int queueIndex)
{
{
lock_guard<mutex> guard(mMutexWork);
Work work = mQueueWork[queueIndex];
int id = work.mDeviceId;
mChunkDone[id]++;
if (mChunkDone[id] == 1) {
Device* device = mDevices[id];
mDevicesWorking--;
device->notifyWork();
device->notifyEvent();
if (mDevicesWorking == 0) {
notifyCallbacks();
}
}
}
}
int
StaticScheduler::getWorkIndex(Device* device)
{
int id = device->getID();
if (mHasWork) {
if (mChunkGiven[id] == 0) {
uint next = 0;
{
lock_guard<mutex> guard(mMutexWork);
next = mChunkGiven[id]++;
}
return mQueueIdWork[id][next];
} else {
return -1;
}
} else {
return -1;
}
}
Work
StaticScheduler::getWork(uint queueIndex)
{
return mQueueWork[queueIndex];
}
} // namespace ecl
| 23.726316
| 96
| 0.674652
|
EngineCL
|
992588cd7da596b7450205f7a5d167bc136a0e6d
| 1,345
|
cpp
|
C++
|
SERGRID.cpp
|
Marethyu12/SPOJ-solutions
|
10fb3352e0b8818be40f7df2285b0d30a0fdc09c
|
[
"Unlicense"
] | null | null | null |
SERGRID.cpp
|
Marethyu12/SPOJ-solutions
|
10fb3352e0b8818be40f7df2285b0d30a0fdc09c
|
[
"Unlicense"
] | null | null | null |
SERGRID.cpp
|
Marethyu12/SPOJ-solutions
|
10fb3352e0b8818be40f7df2285b0d30a0fdc09c
|
[
"Unlicense"
] | null | null | null |
#include <bits/stdc++.h>
#define MAXN 500
using namespace std;
struct cell
{
int row;
int col;
cell(int row, int col) : row(row), col(col) {}
};
const int dr[] = {-1, 0, 1, 0};
const int dc[] = {0, 1, 0, -1};
int grid[MAXN][MAXN];
bool visited[MAXN][MAXN];
int dist[MAXN][MAXN];
int rows;
int cols;
inline bool inBounds(int row, int col)
{
return (row >= 0 && row < rows) && (col >= 0 && col < cols);
}
int bfs()
{
queue<cell> q;
visited[0][0] = true;
dist[0][0] = 0;
q.push(cell(0, 0));
while (!q.empty())
{
cell c = q.front();
q.pop();
if (c.row == rows - 1 && c.col == cols - 1)
return dist[c.row][c.col];
for (int i = 0; i < 4; ++i)
{
int k = grid[c.row][c.col];
int row = c.row + k * dr[i];
int col = c.col + k * dc[i];
if (inBounds(row, col) && !visited[row][col])
{
visited[row][col] = true;
dist[row][col] = dist[c.row][c.col] + 1;
q.push(cell(row, col));
}
}
}
return -1;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
string s;
cin >> rows >> cols;
cin.ignore(1, '\n');
for (int i = 0; i < rows; ++i)
{
getline(cin, s);
for (int j = 0; j < cols; ++j)
grid[i][j] = s[j] - '0';
}
cout << bfs() << "\n";
return 0;
}
| 15.639535
| 62
| 0.477323
|
Marethyu12
|
99467c61d8423028f19230a664283e93ac49f3ea
| 76,306
|
cpp
|
C++
|
DspAudioHost/DspAudioHostDlg.cpp
|
sjk7/DSPAudioHost
|
f26c4c4b79df2f3cbc7cb93e4341be04a0958f26
|
[
"MIT"
] | null | null | null |
DspAudioHost/DspAudioHostDlg.cpp
|
sjk7/DSPAudioHost
|
f26c4c4b79df2f3cbc7cb93e4341be04a0958f26
|
[
"MIT"
] | null | null | null |
DspAudioHost/DspAudioHostDlg.cpp
|
sjk7/DSPAudioHost
|
f26c4c4b79df2f3cbc7cb93e4341be04a0958f26
|
[
"MIT"
] | null | null | null |
// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++, C#, and Java: http://www.viva64.com
// DspAudioHostDlg.cpp : implementation file
//
#include "pch.h"
#include "framework.h"
#include "DspAudioHost.h"
#include "DspAudioHostDlg.h"
#include "afxdialogex.h"
#include <vector>
#include <thread>
#include <limits>
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// #include "../win32-darkmode/win32-darkmode/ListViewUtil.h"
HWND hwnd_found_plug_config = nullptr;
static inline BOOL CALLBACK find_plug_handle_proc(_In_ HWND hwnd, _In_ LPARAM lParam) {
std::wstring looking_for((wchar_t*)lParam);
std::wstring this_one(MAX_PATH, L'\0');
::GetWindowText(hwnd, this_one.data(), MAX_PATH);
this_one.resize(this_one.find(L'\0'));
if (this_one == looking_for) {
hwnd_found_plug_config = hwnd;
return FALSE;
}
return TRUE;
}
HWND find_plug_window(const std::wstring& txt) {
hwnd_found_plug_config = nullptr;
EnumThreadWindows(GetCurrentThreadId(), &find_plug_handle_proc, (LPARAM)txt.data());
return hwnd_found_plug_config;
}
HWND hwnd_found = nullptr;
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialogEx {
public:
CAboutDlg();
// Dialog Data
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_ABOUTBOX };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX) {}
void CAboutDlg::DoDataExchange(CDataExchange* pDX) {
CDialogEx::DoDataExchange(pDX);
}
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-local-typedef"
#endif
BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// CDspAudioHostDlg dialog
CDspAudioHostDlg* g_dlg = nullptr;
extern void myPaInitCallback(char* info) {
g_dlg->showPaProgress(info);
}
PaInitCallback g_PaInitCallback = &myPaInitCallback;
CDspAudioHostDlg::CDspAudioHostDlg(CWnd* pParent /*=nullptr*/)
: CDialogEx(IDD_DSPAUDIOHOST_DIALOG, pParent) {
BOOL b = ::SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
if (b == FALSE) {
// will succeed if not run as admin, but you get less than realtime.
}
createPortAudio();
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
g_dlg = this;
}
void CDspAudioHostDlg::paSettingsSave() {
saveAPI();
saveInput();
saveOutput();
}
void CDspAudioHostDlg::saveMyPosition() {
WINDOWPLACEMENT mypos = {};
mypos.length = sizeof(mypos);
if (GetWindowPlacement(&mypos)) {
theApp.WriteProfileBinary(
L"DSPHost_MainWindow", L"Position", (LPBYTE)&mypos, sizeof(mypos));
}
}
void CDspAudioHostDlg::paSettingsLoad() {
assert(m_portaudio);
assert(IsWindow(GetSafeHwnd()));
assert(m_portaudio->hasNotification(this));
m_loadingPaSettings = TRUE;
std::string s = GetCommandLineA();
if (s.find("safemode") == std::string::npos) {
m_paSettings.getAll();
} else {
}
CString what;
try {
what = "Restoring API: ";
what += m_paSettings.m_api;
if (!m_paSettings.api().empty()) {
auto api = m_portaudio->findApi(m_paSettings.api());
assert(api);
// throw std::runtime_error("ffs");
m_portaudio->changeApi(api);
}
what = "Restoring input: "; //-V519
what += m_paSettings.m_input;
if (!m_paSettings.input().empty()) {
auto input = m_portaudio->findDevice(m_paSettings.input());
if (!input) {
std::string e("Could not find input device, with name:\n");
e += m_paSettings.input();
throw std::runtime_error(e);
}
m_portaudio->changeDevice(input->index, portaudio_cpp::DeviceTypes::input);
}
what = "Restoring API: ";
what += m_paSettings.m_output;
if (!m_paSettings.output().empty()) {
auto output = m_portaudio->findDevice(m_paSettings.output());
if (!output) {
std::string e("Could not find output device, with name:\n");
e += m_paSettings.output();
throw std::runtime_error(e);
}
m_portaudio->changeDevice(output->index, portaudio_cpp::DeviceTypes::output);
}
what = "Restoring sample rate: ";
what += std::to_string(m_paSettings.samplerate).data();
showSamplerate();
} catch (const std::exception& e) {
CString msg = L"Portaudio settings cannot be applied, for: ";
msg += L"\n";
msg += what;
msg += "\n\n";
msg += e.what();
msg += L"\n\n\nClick Ignore to revert to using defaults?\n";
msg += L"NOTE: you will LOSE your settings if you do this. So if you need, for "
L"example, to plug in a device, do it now and hit retry.";
auto reply = MessageBox(
msg, L"Error restoring saved devices", MB_ABORTRETRYIGNORE | MB_ICONQUESTION);
if (reply == IDRETRY) {
m_portaudio_create_thread_state = 0;
createPortAudio(TRUE);
return;
} else if (reply == IDABORT) {
exit(-1);
} else {
// do nothing, ignore
m_paSettings = std::move(PASettings(false));
m_paSettings.saveAll();
m_portaudio->failsafeDefaults();
showSamplerate();
myShowCurrentDevice(portaudio_cpp::DeviceTypes::input);
myShowCurrentDevice(portaudio_cpp::DeviceTypes::output);
}
}
m_loadingPaSettings = FALSE;
}
CDspAudioHostDlg::~CDspAudioHostDlg() {
this->myfontStore(0, TRUE);
if (m_portaudio && m_portaudio->m_running) {
m_portaudio->Stop();
}
}
void CDspAudioHostDlg::DoDataExchange(CDataExchange* pDX) {
CDialogEx::DoDataExchange(pDX);
DDX_Control(pDX, IDC_COMBO_API, cboAPI);
DDX_Control(pDX, IDC_COMBO_INPUT, cboInput);
DDX_Control(pDX, IDC_COMBO_OUTPUT, cboOutput);
DDX_Control(pDX, IDC_BTNREFRESH, m_btnRefresh);
DDX_Control(pDX, IDC_STATIC_PLUGPATH, lblPluginPath);
DDX_Control(pDX, IDC_BTN_PLUGPATH, btnPluginPath);
DDX_Control(pDX, IDC_LIST_AVAIL, listAvail);
DDX_Control(pDX, IDC_LIST_CUR, listCur);
DDX_Control(pDX, IDC_BTN_UP, btnUp);
DDX_Control(pDX, IDC_BTN_DOWN, btnDown);
DDX_Control(pDX, IDC_BTN_ADD, btnAdd);
DDX_Control(pDX, IDC_BTN_REMOVE, btnRemove);
DDX_Control(pDX, IDC_BTN_CONFIG_PLUG, btnConfigPlug);
DDX_Control(pDX, IDC_BTN_REFRESH_PLUGS, btnRefreshPlugs);
DDX_Control(pDX, IDC_STATIC_INFO, lblState);
DDX_Control(pDX, IDC_STATIC_PAINFO, lblPa);
DDX_Control(pDX, IDC_BTN_STOP, btnStop);
DDX_Control(pDX, IDC_BTN_PLAY, btnPlay);
DDX_Control(pDX, IDC_STATIC_ELAPSED, lblElapsedTime);
DDX_Control(pDX, IDC_SLIDER_VOL, sldVol);
DDX_Control(pDX, IDC_CHK_FORCE_MONO, chkForceMono);
// DDX_Control(pDX, IDC_VUOUTL, vuOutL);
// DDX_Control(pDX, IDC_VU_OUT_R, vuOutR);
DDX_Control(pDX, IDC_SLIDER_VOL_IN, sldVolIn);
DDX_Control(pDX, IDC_CLIP, lblClip);
DDX_Control(pDX, IDC_COMBO_SAMPLERATE, cboSampleRate);
DDX_Control(pDX, IDC_TAB1, tabAvailPlugs);
DDX_Control(pDX, IDC_LIST_AVAIL_VST, listAvailVST);
}
enum class special_chars : wchar_t {
leftArrow = 223,
rightArrow = 224,
upArrow = 225,
downArrow = 226
};
void btnFontChar(CDspAudioHostDlg& dlg, CMFCButton& btn, special_chars c,
int fontSize = 100, CString fontName = L"Wingdings") {
const auto addr = (UINT_PTR)&btn;
CFont* font = dlg.myfontStore(addr);
if (font) {
LOGFONT logFont;
memset(&logFont, 0, sizeof(LOGFONT));
logFont.lfCharSet = DEFAULT_CHARSET;
logFont.lfHeight = fontSize;
logFont.lfWeight = FW_BOLD;
Checked::tcsncpy_s(
logFont.lfFaceName, _countof(logFont.lfFaceName), fontName, _TRUNCATE);
font->CreatePointFontIndirect(&logFont);
wchar_t text[] = {static_cast<wchar_t>(c), 0x0000};
btn.SetFont(font);
btn.SetWindowTextW(text);
btn.SetRedraw(TRUE);
btn.RedrawWindow();
} else {
ASSERT(0);
}
}
template <typename T>
void SetFontSize(T& btn, CDspAudioHostDlg& dlg, int fontSize,
const wchar_t* fontName = L"Segoe UI", const bool bold = true) {
const UINT_PTR addr = (UINT_PTR)&btn;
CFont* font = dlg.myfontStore(addr);
if (font) {
LOGFONT logFont;
memset(&logFont, 0, sizeof(LOGFONT));
btn.GetFont()->GetLogFont(&logFont);
LOGFONT lf = logFont;
lf.lfHeight = fontSize;
if (bold) lf.lfWeight = FW_BOLD;
_tcscpy(lf.lfFaceName, fontName);
font->CreatePointFontIndirect(&lf);
btn.SetFont(font);
btn.SetRedraw(TRUE);
btn.RedrawWindow();
} else {
ASSERT(0);
}
}
void CDspAudioHostDlg::doEvents() {
MSG Msg;
while (PeekMessage(&Msg, NULL, 0, 0, PM_REMOVE)) {
if (!PreTranslateMessage(&Msg)) {
TranslateMessage(&Msg);
DispatchMessage(&Msg);
}
}
}
void CDspAudioHostDlg::waitForPortAudio() {
if (m_portaudio_create_thread_state == 0) {
createPortAudio();
assert(m_portaudio_create_thread_state);
}
unsigned int waited = 0;
btnStop.EnableWindow(FALSE);
btnPlay.EnableWindow(FALSE);
while (m_portaudio_create_thread_state == 2 || m_portaudio_create_thread_state == 1) {
Sleep(10);
doEvents();
waited += 10;
if (waited % 100 == 0 && IsWindow(*this)) CCmdTarget::BeginWaitCursor();
if (waited % 250 == 0) {
std::string msg("Waiting for PortAudio, waited: ");
msg += std::to_string(waited);
msg += " ms ...";
::SetWindowTextA(lblState.GetSafeHwnd(), msg.data());
}
if (waited % 500 == 0 && IsWindow(*this)) {
if (m_btnRefresh.IsWindowEnabled()) {
this->m_btnRefresh.EnableWindow(FALSE);
this->cboAPI.EnableWindow(FALSE);
this->cboInput.EnableWindow(FALSE);
this->cboOutput.EnableWindow(FALSE);
}
}
}
m_portaudio_create_thread_state = 0;
std::string msg("PortAudio enabled in: ");
msg += std::to_string(waited);
msg += " ms. PortAudio ready.";
if (IsWindow(*this)) {
::SetWindowTextA(lblState, msg.data());
SetWindowTextA(lblPa.GetSafeHwnd(), "");
}
afterCreatePortAudio();
if (IsWindow(*this)) {
this->m_btnRefresh.EnableWindow(TRUE);
this->cboAPI.EnableWindow(TRUE);
this->cboInput.EnableWindow(TRUE);
this->cboOutput.EnableWindow(TRUE);
::SetWindowTextA(lblState, msg.data());
SetWindowTextA(lblPa.GetSafeHwnd(), "");
btnStop.EnableWindow(TRUE);
btnPlay.EnableWindow(TRUE);
EnableWindow(TRUE);
SetForegroundWindow();
SetActiveWindow();
CCmdTarget::EndWaitCursor();
} //-V1020
}
void CDspAudioHostDlg::createPortAudio(BOOL wait) {
if (m_portaudio_create_thread_state) {
throw std::runtime_error("Portaudio thread in bad state for creating right now");
}
m_portaudio_create_thread_state = 1;
if (IsWindow(*this)) {
this->m_btnRefresh.EnableWindow(FALSE);
this->cboAPI.EnableWindow(FALSE);
this->cboInput.EnableWindow(FALSE);
this->cboOutput.EnableWindow(FALSE);
}
std::thread t([&]() {
m_portaudio_create_thread_state = 2;
TRACE("Thread\n");
TRACE("Thread agn\n");
m_portaudio = nullptr;
m_portaudio = std::make_unique<portaudio_cpp::PortAudio<CDspAudioHostDlg>>(*this);
m_portaudio_create_thread_state = 3;
});
t.detach();
if (wait) {
this->waitForPortAudio();
}
}
void CDspAudioHostDlg::afterCreatePortAudio() {
while (!IsWindow(GetSafeHwnd())) {
Sleep(1);
doEvents();
}
mypopApis();
using namespace portaudio_cpp;
mypopDevices(DeviceTypes::input);
mypopDevices(DeviceTypes::output);
myShowCurrentDevice(DeviceTypes::input);
myShowCurrentDevice(DeviceTypes::output);
// note: notifications not enabled until AFTER initial setup
m_portaudio->notification_add(this);
paSettingsLoad();
}
void CDspAudioHostDlg::myInitDialog() {
CCmdTarget::BeginWaitCursor();
EnableWindow(FALSE);
HRESULT themed = ::SetWindowTheme(listAvail.GetSafeHwnd(), L"explorer", nullptr);
assert(themed == S_OK);
themed = ::SetWindowTheme(listCur.GetSafeHwnd(), L"explorer", nullptr);
::SetWindowTheme(listAvailVST.GetSafeHwnd(), L"explorer", nullptr);
CRect lstrect;
listAvail.GetWindowRect(&lstrect);
ScreenToClient(lstrect);
listAvailVST.MoveWindow(lstrect);
assert(themed == S_OK);
findAvailDSPs();
showAvailDSPs();
std::string s = GetCommandLineA();
if (s.find("safemode") == std::string::npos) {
settingsGetPlugins(true);
} else {
}
SetForegroundWindow();
this->waitForPortAudio();
{
const auto pos = theApp.GetProfileIntW(L"WinampHost", L"OutVol", 0);
sldVol.SetPos(pos);
sliderMoved(sldVol);
}
{
const auto pos = theApp.GetProfileIntW(L"WinampHost", L"InputVolume", 2500);
sldVolIn.SetPos(pos);
sliderMoved(sldVolIn);
}
if (chkForceMono.GetCheck() == TRUE) {
m_portaudio->monoInputSet(true);
} else {
m_portaudio->monoInputSet(false);
}
EnableWindow(TRUE);
if (m_portaudio->errCode() == 0) {
OnBnClickedBtnPlay();
}
SetTimer(1, 25, nullptr);
SetForegroundWindow();
GetWindowRect(&m_sizeRect);
CCmdTarget::EndWaitCursor();
}
void CDspAudioHostDlg::mypopApis() {
this->cboAPI.Clear();
cboAPI.ResetContent();
for (const auto& api : m_portaudio->apis()) {
CString name(api.name);
cboAPI.AddString(name);
}
CString default_api_name(m_portaudio->m_currentApi.name);
auto api = m_portaudio->findApi("Windows DirectSound");
if (api) {
// DirectSound as default, please
CString tmp(api->name);
default_api_name = tmp;
m_portaudio->changeApi(api);
}
int idx = cboAPI.FindStringExact(0, default_api_name);
assert(idx >= 0 && idx < cboAPI.GetCount());
cboAPI.SetCurSel(idx);
}
void myFillDevices(const portaudio_cpp::DeviceTypes forInOrOut,
const portaudio_cpp::PortAudio<CDspAudioHostDlg>::device_list& devices,
CComboBox* pcbo) {
pcbo->Clear();
pcbo->ResetContent();
for (const auto& d : devices) {
if (forInOrOut == portaudio_cpp::DeviceTypes::output) {
if (d.info.maxOutputChannels > 0) {
const CString name(d.extendedName.data());
pcbo->AddString(name);
}
} else {
if (d.info.maxInputChannels > 0) {
const CString name(d.extendedName.data());
pcbo->AddString(name);
}
}
}
}
void CDspAudioHostDlg::myShowCurrentDevice(const portaudio_cpp::DeviceTypes forInOrOut) {
const auto& cur = m_portaudio->currentDevice(forInOrOut);
const CString inName(cur.extendedName.data());
/*/
const auto& types = cur.get_supported_audio_types();
auto s = cur.to_string(types);
CString ws(s.c_str());
const auto ffs = ws.GetLength();
TRACE(L"ffs\n%s\n", ws.GetBuffer());
/*/
auto* pcbo = &this->cboInput;
if (forInOrOut == portaudio_cpp::DeviceTypes::output) {
pcbo = &this->cboOutput;
} else {
pcbo = &this->cboInput;
}
auto idx = pcbo->FindStringExact(0, inName);
#ifdef DEBUG
const auto how_many = pcbo->GetCount();
assert(idx >= 0 && idx < how_many);
#endif
pcbo->SetCurSel(idx);
}
int CDspAudioHostDlg::myPreparePortAudio(const portaudio_cpp::ChannelsType& chans,
const portaudio_cpp::SampleRateType& samplerate) {
try {
return m_portaudio->preparePlay(samplerate, chans, true);
} catch (const std::exception& e) {
std::string s("Failed to open audio devices:\n\n");
s += e.what();
MessageBoxA(
this->GetSafeHwnd(), s.data(), "Fatal PortAudio Error", MB_OK | MB_ICONSTOP);
throw;
}
}
void CDspAudioHostDlg::showPaProgress(const char* what) {
if (IsWindow(*this)) SetWindowTextA(lblPa.GetSafeHwnd(), what);
}
const winamp_dsp::plugins_type& CDspAudioHostDlg::findAvailDSPs() {
winamp_dsp::Host& host = m_winamp_host;
CString root;
lblPluginPath.GetWindowTextW(root);
CStringA myroot(root);
host.setParent(this->GetSafeHwnd());
host.setFolder(myroot.GetBuffer());
vst::Plugins& plugs = m_vsts;
plugs.scanForPlugs();
tracePlugins();
return host.plugins();
}
void clear_cols(CListCtrl& list) {
if (list.GetHeaderCtrl()) {
int nColumnCount = list.GetHeaderCtrl()->GetItemCount();
// Delete all of the columns.
for (int i = 0; i < nColumnCount; i++) {
list.DeleteColumn(0);
}
}
}
inline void insertListItem(CMFCListCtrl& lst, const plugins_base& d) {
const auto& desc = d.description();
if (!desc.empty()) {
CString wDesc(desc.data());
int cnt = lst.InsertItem(lst.GetItemCount(), wDesc);
auto ptr = (DWORD_PTR)d.description().data();
lst.SetItemData(cnt, ptr);
}
}
void CDspAudioHostDlg::showAvailDSPs() {
const auto& dsps = m_winamp_host.plugins();
const auto& vsts = m_vsts.plugsAvailable();
listAvailVST.DeleteAllItems();
listAvail.DeleteAllItems();
clear_cols(listAvail);
clear_cols(listCur);
clear_cols(listAvailVST);
listAvailVST.InsertColumn(0, L"Plugins available");
listAvail.InsertColumn(0, L"Plugins available");
listCur.InsertColumn(0, L"Active plugins");
assert(listAvail.GetHeaderCtrl());
for (const auto& d : dsps) {
insertListItem(listAvail, d);
}
for (const auto& d : vsts) {
insertListItem(listAvailVST, d);
}
listAvail.SetColumnWidth(0, LVSCW_AUTOSIZE_USEHEADER);
listCur.SetColumnWidth(0, LVSCW_AUTOSIZE_USEHEADER);
listAvailVST.SetColumnWidth(0, LVSCW_AUTOSIZE_USEHEADER);
if (listAvail.GetItemCount() > 0) {
listAvail.SetItemState(0, LVIS_SELECTED, LVIS_SELECTED);
}
listAvail.Sort(0);
listAvail.SetRedraw();
listAvail.UpdateWindow();
listCur.SetRedraw();
listCur.UpdateWindow();
BOOL en = dsps.empty() == false;
btnAdd.EnableWindow(en);
btnRemove.EnableWindow(en);
}
void CDspAudioHostDlg::setUpButtons() {
btnFontChar(*this, btnAdd, special_chars::rightArrow);
btnFontChar(*this, btnRemove, special_chars::leftArrow);
btnFontChar(*this, btnUp, special_chars::upArrow);
btnFontChar(*this, btnDown, special_chars::downArrow);
SetFontSize(lblElapsedTime, *this, 150);
auto icon = (HICON)::LoadImage(
theApp.m_hInstance, MAKEINTRESOURCE(IDI_ICON_SETTINGS), IMAGE_ICON, 16, 16, 0);
btnConfigPlug.SetIcon(icon);
icon = (HICON)::LoadImage(
theApp.m_hInstance, MAKEINTRESOURCE(IDI_ICON_REFRESH), IMAGE_ICON, 16, 16, 0);
btnRefreshPlugs.SetIcon(icon);
icon = (HICON)::LoadImage(theApp.m_hInstance, MAKEINTRESOURCE(IDI_ICON_RELOAD_AUDIO),
IMAGE_ICON, 16, 16, 0);
m_btnRefresh.SetIcon(icon);
icon = (HICON)::LoadImage(
theApp.m_hInstance, MAKEINTRESOURCE(IDI_FLAT_STOP), IMAGE_ICON, 24, 24, 0);
this->btnStop.SetIcon(icon);
icon = (HICON)::LoadImage(
theApp.m_hInstance, MAKEINTRESOURCE(IDI_FLAT_PLAY), IMAGE_ICON, 24, 24, 0);
this->btnPlay.SetIcon(icon);
btnPlay.EnableWindow(FALSE);
btnStop.EnableWindow(FALSE);
}
void CDspAudioHostDlg::mypopDevices(const portaudio_cpp::DeviceTypes forInOrOut) {
// const auto& device = m_portaudio->m_currentDevices[forInOrOut];
auto* pcbo = &this->cboInput;
if (forInOrOut == portaudio_cpp::DeviceTypes::output) {
pcbo = &this->cboOutput;
} else {
pcbo = &this->cboInput;
}
myFillDevices(forInOrOut, m_portaudio->devices(), pcbo);
}
void CDspAudioHostDlg::onApiChanged(const PaHostApiInfo& newApi) noexcept {
CString apiName(newApi.name);
int i = cboAPI.FindStringExact(0, apiName);
assert(i >= 0 && i < cboAPI.GetCount());
cboAPI.SetCurSel(i);
this->mypopAllDevices();
if (!m_loadingPaSettings) {
saveAPI();
}
}
using namespace portaudio_cpp;
void CDspAudioHostDlg::onInputDeviceChanged(
const PaDeviceInfoEx& newInputDevice) noexcept {
(void)newInputDevice;
myShowCurrentDevice(portaudio_cpp::DeviceTypes::input);
if (!m_loadingPaSettings) {
saveInput();
OnBnClickedBtnPlay();
}
}
void CDspAudioHostDlg::onOutputDeviceChanged(
const PaDeviceInfoEx& newOutputDevice) noexcept {
(void)newOutputDevice;
myShowCurrentDevice(portaudio_cpp::DeviceTypes::output);
if (!m_loadingPaSettings) {
saveOutput();
OnBnClickedBtnPlay();
}
}
void CDspAudioHostDlg::onStreamStarted(const PaStreamInfo&) noexcept {}
void CDspAudioHostDlg::onStreamStopped(const PaStreamInfo&) noexcept {}
void CDspAudioHostDlg::onStreamAbort(const PaStreamInfo&) noexcept {}
void CDspAudioHostDlg::mypopInputDevices() {
mypopDevices(portaudio_cpp::DeviceTypes::input);
}
void CDspAudioHostDlg::mypopOutputDevices() {
mypopDevices(portaudio_cpp::DeviceTypes::output);
}
void CDspAudioHostDlg::mypopAllDevices() {
mypopDevices(portaudio_cpp::DeviceTypes::input);
mypopDevices(portaudio_cpp::DeviceTypes::output);
}
void CDspAudioHostDlg::myChangeAPI(CString apiName) {
if (apiName.IsEmpty()) {
cboAPI.GetWindowTextW(apiName);
}
CStringA apiNameN(apiName);
std::string sapi(apiNameN.GetBuffer());
auto ptr = m_portaudio->findApi(sapi);
if (ptr) {
m_portaudio->changeApi(ptr);
if (!m_portaudio->subscribedForNotifications(this)) {
mypopAllDevices();
myShowCurrentDevice(portaudio_cpp::DeviceTypes::input);
myShowCurrentDevice(portaudio_cpp::DeviceTypes::output);
} // otherwise UI is populated from notifications
} else {
CString msg = L"Unable to find api, with name: ";
msg += apiName;
MessageBox(msg, L"Fatal Error", MB_OK);
}
}
#pragma warning(disable : 26454)
// BEGIN_MESSAGE_MAP(CSortMFCListCtrl, CMFCListCtrl)
// ON_NOTIFY_REFLECT_EX(NM_CUSTOMDRAW, &CSortMFCListCtrl::OnCustomDraw)
// END_MESSAGE_MAP()
BEGIN_MESSAGE_MAP(CDspAudioHostDlg, CDialogEx)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_CBN_SELCHANGE(IDC_COMBO_API, &CDspAudioHostDlg::OnSelchangeComboApi)
ON_BN_CLICKED(IDC_BTNREFRESH, &CDspAudioHostDlg::OnBnClickedRefreshPA)
ON_BN_CLICKED(IDC_BTN_PLUGPATH, &CDspAudioHostDlg::OnBnClickedBtnPlugpath)
ON_STN_CLICKED(IDC_STATIC_PLUGPATH, &CDspAudioHostDlg::OnStnClickedStaticPlugpath)
ON_CBN_SELCHANGE(IDC_COMBO_INPUT, &CDspAudioHostDlg::OnSelchangeComboInput)
ON_CBN_SELCHANGE(IDC_COMBO_OUTPUT, &CDspAudioHostDlg::OnCbnSelchangeComboOutput)
ON_BN_CLICKED(IDC_BTN_REFRESH_PLUGS, &CDspAudioHostDlg::OnBnClickedBtnRefreshPlugs)
ON_MESSAGE(WM_FIRST_SHOWN, &CDspAudioHostDlg::OnDialogShown)
ON_BN_CLICKED(IDC_BTN_TEST, &CDspAudioHostDlg::OnBnClickedBtnRefreshPlugs2)
ON_BN_CLICKED(IDC_BTN_ADD, &CDspAudioHostDlg::OnBnClickedBtnAdd)
ON_BN_CLICKED(IDC_BTN_REMOVE, &CDspAudioHostDlg::OnBnClickedBtnRemove)
ON_BN_CLICKED(IDC_BTN_CONFIG_PLUG, &CDspAudioHostDlg::OnBnClickedBtnConfigPlug)
ON_NOTIFY(NM_DBLCLK, IDC_LIST_CUR, &CDspAudioHostDlg::OnDblclkListCur)
ON_NOTIFY(NM_DBLCLK, IDC_LIST_AVAIL, &CDspAudioHostDlg::OnDblclkListAvail)
ON_BN_CLICKED(IDC_BTN_UP, &CDspAudioHostDlg::OnBnClickedBtnUp)
ON_BN_CLICKED(IDC_BTN_DOWN, &CDspAudioHostDlg::OnBnClickedBtnDown)
ON_WM_CLOSE()
ON_WM_TIMER()
ON_BN_CLICKED(IDC_BTN_PLAY, &CDspAudioHostDlg::OnBnClickedBtnPlay)
ON_BN_CLICKED(IDC_BTN_STOP, &CDspAudioHostDlg::OnBnClickedBtnStop)
ON_WM_CTLCOLOR()
ON_NOTIFY(NM_CUSTOMDRAW, IDC_SLIDER_VOL, &CDspAudioHostDlg::OnNMCustomdrawSliderVol)
ON_WM_VSCROLL()
ON_BN_CLICKED(IDC_CHK_FORCE_MONO, &CDspAudioHostDlg::OnBnClickedChkForceMono)
ON_STN_CLICKED(IDC_VU_OUT_R, &CDspAudioHostDlg::OnStnClickedVuOutR)
ON_STN_CLICKED(IDC_CLIP, &CDspAudioHostDlg::OnStnClickedClip)
ON_CBN_SELCHANGE(IDC_COMBO_SAMPLERATE, &CDspAudioHostDlg::OnCbnSelchangeComboSamplerate)
ON_WM_SIZE()
ON_WM_THEMECHANGED()
ON_BN_CLICKED(IDC_BTN_CONFIG_AUDIO, &CDspAudioHostDlg::OnBnClickedBtnConfigAudio)
END_MESSAGE_MAP()
#pragma warning(default : 26454)
RECT my_get_window_position(HWND hwnd) {
RECT rect = {};
WINDOWPLACEMENT wp = {};
wp.length = sizeof(WINDOWPLACEMENT);
ASSERT(IsWindow(hwnd));
::GetWindowPlacement(hwnd, &wp);
rect = wp.rcNormalPosition;
return rect;
}
static bool window_is_offscreen(HWND hwnd) {
// int nScreenWidth = GetSystemMetrics(SM_CXSCREEN);
// int nScreenHeight = GetSystemMetrics(SM_CYSCREEN);
CRect windows_work_area;
RECT rect = my_get_window_position(hwnd);
SystemParametersInfo(SPI_GETWORKAREA, 0, &windows_work_area, 0);
if (rect.bottom > windows_work_area.bottom + 50
|| rect.right > windows_work_area.right + 50
|| rect.left < windows_work_area.left - 50
|| rect.top < windows_work_area.top - 50) {
return true;
}
return false;
}
// CDspAudioHostDlg message handlers
BOOL CDspAudioHostDlg::OnInitDialog() {
CDialogEx::OnInitDialog();
// _CrtSetBreakAlloc(7611);
CStringA tit = "DSPAudioHost (RC) Built at: ";
tit += __TIME__;
tit += " on: ";
tit += __DATE__;
tabAvailPlugs.InsertItem(0, L"VST Plugins");
tabAvailPlugs.InsertItem(0, L"Winamp DSP Plugins");
tabAvailPlugs.SetCurSel(0);
NONCLIENTMETRICS metrics = {};
metrics.cbSize = sizeof(NONCLIENTMETRICS);
::SystemParametersInfo(
SPI_GETNONCLIENTMETRICS, sizeof(NONCLIENTMETRICS), &metrics, 0);
m_windows10Font.CreateFontIndirect(&metrics.lfMessageFont);
SendMessageToDescendants(WM_SETFONT, (WPARAM)m_windows10Font.GetSafeHandle(), 0);
myPropSheet.setFontObject(&m_windows10Font);
CStringW wtit(tit);
SetWindowText(wtit);
BOOL ret = myPropSheet.Create(this, &m_windows10Font);
if (!ret) // Create failed.
AfxMessageBox(L"Error creating Dialog");
myPropSheet.ShowWindow(SW_HIDE);
// auto tabIndex = m_plugs.size();
// myplug = new vst::Plug(&myPropSheet, &myPropSheet.mypage[0], tabIndex);
// const auto& desc = myplug->description();
// CString wt(desc.data());
// myPropSheet.SetPageTitle(0, wt);
// myPropSheet.SetWindowTextW(L"VST Plugins Properties");
// this->addActivatedPlugToUI(*myplug);
doEvents();
sldVol.SetRange(0, 6000, TRUE);
sldVol.SetTicFreq(50);
sldVolIn.SetRange(0, 6000, TRUE);
sldVolIn.SetTicFreq(50);
// Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
/*/
CMFCVisualManagerOffice2007 ::SetStyle(
CMFCVisualManagerOffice2007::Office2007_LunaBlue);
CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(
CMFCVisualManagerOffice2007)); // <--Added to support deviant themes!
/*/
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != nullptr) {
BOOL bNameValid;
CString strAboutMenu;
bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
ASSERT(bNameValid);
if (!strAboutMenu.IsEmpty()) {
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
setUpButtons();
setupMeters();
PostMessage(WM_FIRST_SHOWN);
WINDOWPLACEMENT wp = {};
wp.length = sizeof(wp);
UINT nSize = 0;
LPBYTE pPlacementBytes = NULL;
WINDOWPLACEMENT orig = {};
orig.length = sizeof(orig);
GetWindowPlacement(&orig);
std::string s = GetCommandLineA();
GetWindowRect(&m_sizeRect);
if (s.find("safemode") == std::string::npos) {
if (theApp.GetProfileBinary(
L"DSPHost_MainWindow", L"Position", &pPlacementBytes, &nSize)) {
ASSERT(pPlacementBytes != NULL);
if (pPlacementBytes != NULL) {
ASSERT(nSize == sizeof(WINDOWPLACEMENT));
if (nSize == sizeof(WINDOWPLACEMENT)) {
memcpy(&wp, pPlacementBytes, nSize);
}
delete[] pPlacementBytes;
wp.showCmd = 1;
this->SetWindowPlacement(&wp);
if (window_is_offscreen(m_hWnd)) {
SetWindowPlacement(&orig);
}
}
}
}
GetWindowRect(&m_sizeRect);
return TRUE; // return TRUE unless you set the focus to a control
}
void CDspAudioHostDlg::setupMeters() {
pbar_ctrl_create(TRUE, "Left Input", IDC_VU_IN_L, vuInL, TRUE);
pbar_ctrl_create(TRUE, "Right Input", IDC_VU_IN_R, vuInR, TRUE);
pbar_ctrl_create(TRUE, "Left Output", IDC_VUOUTL, vuOutL, TRUE);
pbar_ctrl_create(TRUE, "Right Output", IDC_VU_OUT_R, vuOutR, TRUE);
CPBar::colorvec_t cv;
cv.reserve(3);
cv.emplace_back(
CPBar::colors(RGB(51, 34, 0), RGB(180, 131, 2), 70)); // off / on colors
cv.emplace_back(
CPBar::colors(RGB(25, 50, 0), RGB(50, 150, 0), 25)); // off / on colors
cv.emplace_back(CPBar::colors(RGB(50, 50, 0), RGB(190, 190, 0), 5));
vuOutL.colors_set(cv);
vuOutR.colors_set(cv);
vuOutL.peak_hold_color_set(RGB(250, 201, 40));
vuOutR.peak_hold_color_set(RGB(250, 201, 40));
vuInL.colors_set(cv);
vuInR.colors_set(cv);
vuInL.peak_hold_color_set(RGB(250, 201, 40));
vuInR.peak_hold_color_set(RGB(250, 201, 40));
}
LRESULT CDspAudioHostDlg::OnDialogShown(WPARAM, LPARAM) {
UpdateWindow();
myInitDialog();
return 0;
}
void CDspAudioHostDlg::OnSysCommand(UINT nID, LPARAM lParam) {
if ((nID & 0xFFF0) == IDM_ABOUTBOX) {
CAboutDlg dlgAbout;
dlgAbout.DoModal();
} else {
if ((nID & 0xFFF0) == SC_CLOSE) {
// if user clicked the "X"
OnClose();
EndDialog(IDOK); // Close the dialog with IDOK (or IDCANCEL)
delete myplug;
} else {
CDialog::OnSysCommand(nID, lParam);
}
}
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CDspAudioHostDlg::OnPaint() {
if (IsIconic()) {
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
} else {
CDialogEx::OnPaint();
}
}
// The system calls this function to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CDspAudioHostDlg::OnQueryDragIcon() {
return static_cast<HCURSOR>(m_hIcon);
}
int findTextInCombo(CString findWhat, CComboBox& cb) {
std::wstring_view vold = findWhat.GetBuffer();
std::wstring_view vnow;
for (int x = 0; x < cb.GetCount(); ++x) {
CString ws;
cb.GetLBText(x, ws);
vnow = ws.GetBuffer();
if (vnow.length() < vold.length()) {
if (vold.find(vnow) != std::string::npos) {
return x;
}
}
}
return -1;
}
void CDspAudioHostDlg::OnSelchangeComboApi() {
CStringW old_input;
CStringW old_output;
PortAudioGlobalIndex old_ip_index;
PortAudioGlobalIndex old_op_index;
portaudio_cpp::AudioFormat old_format;
// bool was_running = m_portaudio->m_running;
int found = 0;
if (m_portaudio) {
const auto& ip = m_portaudio->currentDevice(DeviceTypes::input);
const auto& op = m_portaudio->currentDevice(DeviceTypes::output);
old_input = ip.extendedName.c_str();
old_output = op.extendedName.c_str();
old_format = m_portaudio->currentFormats(DeviceTypes::input);
old_ip_index = ip.globalIndex;
old_op_index = op.globalIndex;
}
this->myChangeAPI(L"");
if (m_portaudio) {
auto i = cboInput.FindStringExact(0, old_input);
if (i < 0) {
i = cboInput.FindString(0, old_input);
}
if (i < 0) {
i = findTextInCombo(old_input, cboInput);
}
if (i >= 0) {
++found;
cboInput.SetCurSel(i);
OnSelchangeComboInput();
}
i = cboOutput.FindStringExact(0, old_output);
if (i < 0) {
i = cboOutput.FindString(0, old_output);
}
if (i < 0) {
i = findTextInCombo(old_output, cboOutput);
}
if (i >= 0) {
++found;
cboOutput.SetCurSel(i);
OnCbnSelchangeComboOutput();
}
if (found == 2) {
try {
if (!old_format.is_empty()) {
OnBnClickedBtnPlay();
}
} catch (const std::exception& e) { //-V565
::MessageBoxA(m_hWnd, e.what(),
"Audio failed to automatically restart after api change",
MB_OK | MB_ICONSTOP);
}
}
}
}
void CDspAudioHostDlg::OnBnClickedRefreshPA() {
CString orig_text;
auto info = m_portaudio->info();
m_btnRefresh.GetWindowTextW(orig_text);
m_btnRefresh.SetWindowTextW(L"Please wait ...");
CCmdTarget::BeginWaitCursor();
myInitDialog();
m_btnRefresh.SetWindowTextW(orig_text);
m_portaudio->restoreInfo(info);
CCmdTarget::EndWaitCursor();
}
void CDspAudioHostDlg::OnBnClickedBtnPlugpath() {
CString strOutFolder;
// note: the application class is derived from CWinAppEx
CShellManager* pShellManager = theApp.GetShellManager();
CString existing_folder;
lblPluginPath.GetWindowTextW(existing_folder);
if (!PathFileExists(existing_folder)) {
const CString default_plug_folder(
L"C:\\Program Files (x86)\\AudioEnhance Sound Router\\plugins\\");
existing_folder = default_plug_folder;
}
if (pShellManager->BrowseForFolder(
strOutFolder, this, existing_folder, L"Choose the plugins folder to use")) {
strOutFolder += L"\\";
lblPluginPath.SetWindowTextW(strOutFolder);
findAvailDSPs();
}
}
void CDspAudioHostDlg::OnStnClickedStaticPlugpath() {
// TODO: Add your control notification handler code here
}
void CDspAudioHostDlg::OnSelchangeComboInput() {
CString name;
const auto idx = cboInput.GetCurSel();
cboInput.GetLBText(idx, name);
CStringA nName(name);
const auto dev = m_portaudio->findDevice(nName.GetBuffer());
if (!dev) {
CString msg(L"Sorry, can't find input device: ");
msg += name;
MessageBox(msg, L"Error: Cannot find input device");
} else {
m_portaudio->changeDevice(*dev, portaudio_cpp::DeviceTypes::input);
}
}
void CDspAudioHostDlg::OnCbnSelchangeComboOutput() {
CString name;
const auto idx = cboOutput.GetCurSel();
cboOutput.GetLBText(idx, name);
CStringA nName(name);
const auto dev = m_portaudio->findDevice(nName.GetBuffer());
if (!dev) {
CString msg(L"Sorry, can't find output device: ");
msg += name;
MessageBox(msg, L"Error: Cannot find output device");
} else {
m_portaudio->changeDevice(*dev, portaudio_cpp::DeviceTypes::output);
}
}
void CDspAudioHostDlg::OnBnClickedBtnRefreshPlugs() {
CCmdTarget::BeginWaitCursor();
EnableWindow(FALSE);
findAvailDSPs();
showAvailDSPs();
EnableWindow(TRUE);
CCmdTarget::EndWaitCursor();
}
void CDspAudioHostDlg::tracePlugins() {
winamp_dsp::Host& host = m_winamp_host;
for (const auto& plug : host.m_enumerator.plugins()) {
TRACE("Plugin found @ %s\n", plug.filePath().data());
TRACE("Plugin has description: %s\n", plug.description().data());
TRACE("\n");
}
TRACE("\n");
}
void CDspAudioHostDlg::showClipped() {
static DWORD last_shown_clip = timeGetTime();
if (m_clipped) {
lblClip.ShowWindow(TRUE);
last_shown_clip = timeGetTime();
} else {
if (timeGetTime() - last_shown_clip > 500) {
lblClip.ShowWindow(FALSE);
}
}
}
void CDspAudioHostDlg::showSamplerate() {
if (cboSampleRate.GetCount() == 0) {
cboSampleRate.AddString(L"192000");
cboSampleRate.AddString(L"128000");
cboSampleRate.AddString(L"96000");
cboSampleRate.AddString(L"48000");
cboSampleRate.AddString(L"44100");
cboSampleRate.AddString(L"22050");
}
auto thing = cboSampleRate.FindStringExact(
0, std::to_wstring(m_paSettings.samplerate).data());
assert(thing >= 0);
cboSampleRate.SetCurSel(thing);
}
void CDspAudioHostDlg::OnBnClickedBtnRefreshPlugs2() {}
void CDspAudioHostDlg::addActivatedPlugToUI(const plugins_base& plug) {
CString ws(plug.description().data());
auto count = listCur.GetItemCount();
listCur.InsertItem(count, ws, 0);
m_plugs.add(&plug);
count++;
setUpDownButtonsState();
listCur.SetItemState(count - 1, LVIS_SELECTED, LVIS_SELECTED);
}
void CDspAudioHostDlg::removeActivatedPlugFromUI(int idx) {
listCur.DeleteItem(idx);
const auto count = listCur.GetItemCount();
setUpDownButtonsState();
if (count > 1) {
listCur.SetItemState(idx - 1, LVIS_SELECTED, LVIS_SELECTED);
} else {
if (count) {
listCur.SetItemState(0, LVIS_SELECTED, LVIS_SELECTED);
}
}
}
BOOL CDspAudioHostDlg::restorePlugWindowPosition(const plugins_base& plugin) {
HWND hwnd = find_plug_window(plugin.configHandleWindowText());
ASSERT(hwnd);
if (!IsWindow(hwnd)) {
hwnd = FindPluginWindow(plugin.description());
}
if (!IsWindow(hwnd)) return FALSE;
WINDOWPLACEMENT wp = {};
wp.length = sizeof(wp);
CString wdesc(plugin.description().data());
UINT nSize = 0;
BOOL ret = FALSE;
LPBYTE pPlacementBytes = NULL;
std::string s = GetCommandLineA();
if (s.find("safemode") == std::string::npos) {
if (theApp.GetProfileBinary(
L"PlugWindowPositions", wdesc, &pPlacementBytes, &nSize)) {
ASSERT(pPlacementBytes != NULL);
if (pPlacementBytes != NULL) {
ASSERT(nSize == sizeof(WINDOWPLACEMENT));
if (nSize == sizeof(WINDOWPLACEMENT)) {
memcpy(&wp, pPlacementBytes, nSize);
}
delete[] pPlacementBytes;
ret = ::SetWindowPlacement(hwnd, &wp);
}
}
}
return ret;
}
void CDspAudioHostDlg::savePlugWindowPositions() {
saveMyPosition();
for (auto&& plug : m_plugs) {
HWND hwnd = plug->configHandle();
if (!IsWindow(hwnd)) { // eg when user closes plugin window altogether
hwnd = find_plug_window(plug->configHandleWindowText());
}
ASSERT(hwnd);
if (!hwnd) {
hwnd = FindPluginWindow(plug->description());
}
ASSERT(hwnd);
if (IsWindow(hwnd)) {
WINDOWPLACEMENT wp = {};
wp.length = sizeof(wp);
BOOL got = ::GetWindowPlacement(hwnd, &wp);
ASSERT(got);
if (got) {
CString wdesc(plug->description().data());
theApp.WriteProfileBinary(
L"PlugWindowPositions", wdesc, (LPBYTE)(&wp), sizeof(wp));
}
} else {
// window closed. So remember it this way
}
}
}
void CDspAudioHostDlg::settingsSavePlugins() {
std::string plugs = m_plugs.getActivePlugsAsString();
CString ws(plugs.data());
theApp.WriteProfileStringW(L"WinampHost", L"ActivePlugs", ws);
savePlugWindowPositions();
BOOL b = FALSE;
if (m_portaudio->m_bMonoInput) {
b = TRUE;
} else {
b = FALSE;
}
{
theApp.WriteProfileInt(L"WinampHost", L"ForceMonoInput", b);
const auto pos = sldVol.GetPos();
theApp.WriteProfileInt(L"WinampHost", L"OutVol", pos);
}
{
const auto pos = sldVolIn.GetPos();
theApp.WriteProfileInt(L"WinampHost", L"InputVolume", pos);
}
}
void CDspAudioHostDlg::settingsGetPlugins(bool apply) {
CString plugs = theApp.GetProfileStringW(L"WinampHost", L"ActivePlugs", L"");
if (!plugs.IsEmpty()) {
if (apply) {
CStringA csa(plugs);
const char sep = *plugins::PLUG_SEP;
auto descriptions = winamp_dsp::my::strings::split(csa.GetBuffer(), sep);
for (const auto& s : descriptions) {
auto ptr = m_winamp_host.findPlug(s);
auto existing = m_plugs.findActivatedPlugByDesc(s);
if (!existing) {
if (ptr) {
myActivatePlug(ptr, true, false);
}
}
}
}
}
const auto b = theApp.GetProfileIntW(L"WinampHost", L"ForceMonoInput", FALSE);
chkForceMono.SetCheck(b);
OnBnClickedChkForceMono();
SetActiveWindow();
}
static inline BOOL CALLBACK EnumWindowsProcFindAllA(_In_ HWND hwnd, _In_ LPARAM lParam) {
auto pthis = (CDspAudioHostDlg*)lParam;
std::wstring str(MAX_PATH, L'\0');
::GetWindowText(hwnd, str.data(), MAX_PATH);
pthis->m_child_windowsA.insert({hwnd, str});
return TRUE;
}
static inline BOOL CALLBACK EnumWindowsProcFindAllB(_In_ HWND hwnd, _In_ LPARAM lParam) {
auto pthis = (CDspAudioHostDlg*)lParam;
std::wstring str(MAX_PATH, L'\0');
::GetWindowText(hwnd, str.data(), MAX_PATH);
pthis->m_child_windowsB.insert({hwnd, str});
return TRUE;
}
plugins_base* CDspAudioHostDlg::manageActivatePlug(plugins_base& plug) {
m_child_windowsA.clear();
m_child_windowsB.clear();
EnumThreadWindows(GetCurrentThreadId(), EnumWindowsProcFindAllA, (LPARAM)this);
plugins_base* pactivated = nullptr;
winamp_dsp::Plugin* pPlug = nullptr;
if (plug.getType() == plugins_base::PlugType::Winamp_dsp) {
pPlug = (winamp_dsp::Plugin*)&plug;
auto& activated = m_winamp_host.activatePlug(*pPlug);
pactivated = &activated;
pactivated->showConfig();
} else {
vst::Plug* pMyPlug = (vst::Plug*)&plug;
pactivated = m_vsts.activatePlug(*pMyPlug);
return pactivated; // return it since we do not need all the find window malarkey
// below
}
doEvents();
EnumThreadWindows(GetCurrentThreadId(), EnumWindowsProcFindAllB, (LPARAM)this);
assert(m_child_windowsB.size() > m_child_windowsA.size());
std::map<HWND, std::wstring> diff;
auto& a = m_child_windowsA;
auto& b = m_child_windowsB;
std::set_symmetric_difference(
a.begin(), a.end(), b.begin(), b.end(), std::inserter(diff, diff.begin()));
const auto this_hwnd = this->m_hWnd;
size_t ctr = 0;
for (const auto& pr : diff) {
ctr++;
auto parent = ::GetParent(pr.first);
if (parent == this_hwnd) {
TRACE(L"Found plug window, with text: %s\n", pr.second.data());
ASSERT(IsWindow(pr.first));
pPlug->configHandleWindowTextSet(pr.second);
pPlug->configHandleWindowSet(pr.first);
break;
}
}
return pactivated;
}
plugins_base* CDspAudioHostDlg::myActivatePlug(
plugins_base* plug, bool addToUI, bool force_show) {
bool was_running = false;
if (m_portaudio && m_portaudio->m_running) {
was_running = true;
m_portaudio->Stop();
}
assert(plug);
if (!plug) {
return plug;
}
try {
auto activated = manageActivatePlug(*plug);
assert(activated != nullptr);
hwnd_found = find_plug_window(activated->configHandleWindowText());
if (activated->getType() == plugins_base::PlugType::Winamp_dsp) {
if (!IsWindow(hwnd_found)) {
hwnd_found = FindPluginWindow(activated->description());
}
if (IsWindow(hwnd_found)) {
// annoying me that plug windows are ALL shown if we are restoring the
// dialog
BOOL set = ::SetWindowLongPtr(
hwnd_found, GWL_HWNDPARENT, (long)::GetDesktopWindow());
ASSERT(set);
(void)set;
restorePlugWindowPosition(*activated);
if (force_show) {
::BringWindowToTop(hwnd_found);
::SetActiveWindow(hwnd_found);
::ShowWindow(hwnd_found, SW_SHOWNORMAL);
}
}
} else {
// VST types are hosting in property sheet and none of the dances above are
// required
}
if (addToUI) {
addActivatedPlugToUI(*activated);
SetForegroundWindow();
}
if (was_running && m_portaudio) {
portaudioStart();
}
return activated;
} catch (const std::exception& e) {
MessageBoxA(m_hWnd, e.what(), "Error loading plugin", MB_OK);
}
return nullptr;
}
std::string desc_find;
int find_level = 0;
static inline BOOL CALLBACK EnumWindowsProcFindPlug(_In_ HWND hwnd, _In_ LPARAM) {
std::string s;
s.resize(256);
::GetWindowTextA(hwnd, &s[0], 256);
s.resize(s.find_first_of('\0'));
if (find_level == 0) {
if (s == desc_find) {
hwnd_found = hwnd;
return FALSE;
}
} else {
if (find_level == 1) {
if (s.find(desc_find) == 0) {
hwnd_found = hwnd;
return FALSE;
}
} else {
if (s.find(desc_find) != std::string::npos) {
hwnd_found = hwnd;
return FALSE;
}
}
}
return TRUE;
}
HWND CDspAudioHostDlg::FindPluginWindow(std::string_view desc) {
if (desc == "Tomass' Limiter V1.0") {
desc = "Tomass Limiter V1.0";
}
desc_find = desc;
find_level = 0;
hwnd_found = nullptr;
EnumThreadWindows(GetCurrentThreadId(), EnumWindowsProcFindPlug, (LPARAM)this);
if (!hwnd_found) { //-V547
find_level = 1;
EnumThreadWindows(GetCurrentThreadId(), EnumWindowsProcFindPlug, (LPARAM)this);
}
if (!hwnd_found) { //-V547
find_level = 2;
EnumThreadWindows(GetCurrentThreadId(), EnumWindowsProcFindPlug, (LPARAM)this);
}
return hwnd_found;
}
void CDspAudioHostDlg::saveAPI() {
cboAPI.GetLBText(cboAPI.GetCurSel(), m_paSettings.m_api);
m_paSettings.saveAll();
}
void CDspAudioHostDlg::saveInput() {
cboInput.GetLBText(cboInput.GetCurSel(), m_paSettings.m_input);
m_paSettings.saveAll();
}
void CDspAudioHostDlg::saveOutput() {
cboOutput.GetLBText(cboOutput.GetCurSel(), m_paSettings.m_output);
m_paSettings.saveAll();
}
void CDspAudioHostDlg::OnBnClickedBtnAdd() {
CCmdTarget::BeginWaitCursor();
POSITION pos = this->listAvail.GetFirstSelectedItemPosition();
if (pos == NULL) {
MessageBox(L"You need to select at least one plugin on the left list first.");
} else {
while (pos) {
int nItem = listAvail.GetNextSelectedItem(pos);
TRACE1("Item %d was selected!\n", nItem);
CString ws = listAvail.GetItemText(nItem, 0);
CStringA wsa(ws);
auto existing = m_winamp_host.findActivatedPlugByDesc(wsa.GetBuffer());
if (existing != nullptr) {
CString msg = L"The plugin: ";
msg += wsa;
msg += L"\nis already loaded\n\nYou cannot load a plugin more than "
L"once\n\n";
msg += L"Do you want to show the window for this plugin? (Bear in mind "
L"it may be minimised)";
int result = SHMessageBoxCheck(this->GetSafeHwnd(), msg,
TEXT("One Instance Of Plugin Warning"), MB_ICONINFORMATION | MB_YESNO,
IDYES, TEXT("{9D5CE92A-2EA9-43A2-A19E-736853BCCBB9}"));
if (result == IDYES) {
existing->showConfig();
auto fnd = FindPluginWindow(existing->description());
if (fnd) { //-V547
centreWindowOnMe(fnd, GetSafeHwnd(), false);
}
}
break;
}
if (!ws.IsEmpty()) {
auto* found = m_winamp_host.findPlug(wsa.GetBuffer());
if (!found) {
MessageBox(L"Unexpected, cannot find plugin");
} else {
if (myActivatePlug(found)) {
settingsSavePlugins();
}
}
}
}
}
CCmdTarget::EndWaitCursor();
}
int getSelectedIndex(CListCtrl& lv) {
POSITION pos = lv.GetFirstSelectedItemPosition();
if (pos == NULL) {
return -1;
}
int nItem = lv.GetNextSelectedItem(pos);
return nItem;
}
void CDspAudioHostDlg::OnBnClickedBtnRemove() {
POSITION pos = this->listCur.GetFirstSelectedItemPosition();
bool was_running = false;
if (this->m_portaudio) {
was_running = m_portaudio->m_running;
m_portaudio->Stop();
}
if (pos == NULL) {
MessageBox(L"You need to select at least one plugin on the right list first.");
} else {
while (pos) {
int nItem = listCur.GetNextSelectedItem(pos);
TRACE1("Item %d was selected!\n", nItem);
CString ws = listCur.GetItemText(nItem, 0);
if (!ws.IsEmpty()) {
const auto&& found = m_plugs.findActivatedPlug(nItem);
if (found == nullptr) { //-V547
MessageBox(L"Unexpected, cannot find activated plugin");
} else {
bool removed = false;
m_plugs.remove(found);
if (found->getType() == plugins_base::PlugType::Winamp_dsp) {
removed = m_winamp_host.removeActivatedPlug(
(winamp_dsp::Plugin*)found);
} else {
// FIXME: vst host needs to remove plug
ASSERT(0);
}
if (removed) {
removeActivatedPlugFromUI(nItem);
settingsSavePlugins();
}
}
}
}
}
if (was_running) {
try {
this->portaudioStart();
} catch (const std::exception&) { //-V565
}
}
}
void CDspAudioHostDlg::myCurListShowConfig(int idx) {
if (idx < 0) {
MessageBox(L"First select a plugin in the active plugin list");
} else {
auto plug = m_plugs.findActivatedPlug(idx);
if (!plug) {
MessageBox(L"Unexpected: could not find the plugin");
} else {
plug->showConfig();
if (plug->getType() == plugins_base::PlugType::Winamp_dsp) {
auto hWnd = find_plug_window(plug->configHandleWindowText());
if (!IsWindow(hWnd)) {
hWnd = FindPluginWindow(plug->description()); //-V1048
}
if (IsWindow(hWnd)) {
centreWindowOnMe(hWnd, GetSafeHwnd());
}
} else {
// not a winamp plug!
if (IsWindow(plug->configHandle())) {
centreWindowOnMe(plug->configHandle(), GetSafeHwnd());
}
}
}
}
}
void CDspAudioHostDlg::OnBnClickedBtnConfigPlug() {
const auto idx = getSelectedIndex(listCur);
myCurListShowConfig(idx);
}
void CDspAudioHostDlg::OnDblclkListCur(NMHDR* pNMHDR, LRESULT* pResult) {
// LPNMITEMACTIVATE pNMItemActivate = reinterpret_cast<LPNMITEMACTIVATE>(pNMHDR);
LPNMITEMACTIVATE pitem = (LPNMITEMACTIVATE)pNMHDR;
int row = pitem->iItem;
myCurListShowConfig(row);
*pResult = 0;
}
void CDspAudioHostDlg::OnDblclkListAvail(NMHDR* pNMHDR, LRESULT* pResult) {
// LPNMITEMACTIVATE pNMItemActivate = reinterpret_cast<LPNMITEMACTIVATE>(pNMHDR);
LPNMITEMACTIVATE pitem = (LPNMITEMACTIVATE)pNMHDR;
int row = pitem->iItem;
if (row > 0) {
CString ws = listAvail.GetItemText(row, 0);
CStringA wsa(ws);
auto plug = m_winamp_host.findPlug(wsa.GetBuffer());
if (!plug) {
MessageBox(L"Unexpected: cannot find plug!");
}
myActivatePlug(plug);
}
*pResult = 0;
}
void CDspAudioHostDlg::myShowActivePlugs() {
listCur.DeleteAllItems();
for (const auto& plug : m_winamp_host.activePlugins()) {
if (!plug.description().empty()) {
// auto p = m_winamp_host.findPlug(plug.description());
CString wcs(plug.description().data());
auto inserted = listCur.InsertItem(listCur.GetItemCount(), wcs, 0);
(void)inserted;
assert(inserted >= 0);
}
};
}
static inline BOOL CenterWindow(HWND hwndWindow, int topOffset = 0) {
HWND hwndParent;
RECT rectWindow, rectParent;
// make the window relative to its parent
if ((hwndParent = GetParent(hwndWindow)) != NULL) {
GetWindowRect(hwndWindow, &rectWindow);
GetWindowRect(hwndParent, &rectParent);
WINDOWPLACEMENT wp = {};
wp.length = sizeof(WINDOWPLACEMENT);
BOOL gotp = ::GetWindowPlacement(hwndWindow, &wp);
ASSERT(gotp);
rectWindow = wp.rcNormalPosition;
int nWidth = rectWindow.right - rectWindow.left;
int nHeight = rectWindow.bottom - rectWindow.top;
int nX = ((rectParent.right - rectParent.left) - nWidth) / 2 + rectParent.left;
int nY = ((rectParent.bottom - rectParent.top) - nHeight) / 2 + rectParent.top;
int nScreenWidth = GetSystemMetrics(SM_CXSCREEN);
int nScreenHeight = GetSystemMetrics(SM_CYSCREEN);
// make sure that the dialog box never moves outside of the screen
if (nX < 0) nX = 0;
if (nY < 0) nY = 0;
if (nX + nWidth > nScreenWidth) nX = nScreenWidth - nWidth;
if (nY + nHeight > nScreenHeight) nY = nScreenHeight - nHeight;
CRect final(nX, nY + topOffset, nX + nWidth, nY + nHeight + topOffset);
// MoveWindow(hwndWindow, nX, nY + topOffset, nWidth, nHeight, FALSE);
wp.rcNormalPosition = final;
gotp = ::SetWindowPlacement(hwndWindow, &wp);
assert(gotp);
return TRUE;
}
return FALSE;
}
// if you don't force then it will only be centred on me when hwnd is off the screen
// partially or completely
void CDspAudioHostDlg::centreWindowOnMe(
HWND hwnd, HWND parent, bool force, int topOffset) {
(void)parent;
if (force) {
::CenterWindow(hwnd, topOffset);
} else {
if (window_is_offscreen(hwnd)) {
::CenterWindow(hwnd, topOffset);
}
}
::ShowWindow(hwnd, SW_SHOWNORMAL);
::BringWindowToTop(hwnd_found);
::SetActiveWindow(hwnd_found);
}
void CDspAudioHostDlg::setUpDownButtonsState() {
int cnt = listCur.GetItemCount();
BOOL en = cnt > 0;
btnUp.EnableWindow(en);
btnDown.EnableWindow(en);
}
void CDspAudioHostDlg::OnBnClickedBtnUp() {
int idxA = getSelectedIndex(listCur);
if (idxA < 0) {
MessageBox(L"Please select an active plugin in the list");
return;
}
int idxB = idxA - 1;
if (idxB < 0) {
// the first one cannot be moved up
return;
}
m_winamp_host.swapPlugins(idxA, idxB);
int selindex = idxB;
myShowActivePlugs();
listCur.SetItemState(selindex, LVIS_SELECTED, LVIS_SELECTED);
setUpDownButtonsState();
settingsSavePlugins();
}
void CDspAudioHostDlg::OnBnClickedBtnDown() {
int idxA = getSelectedIndex(listCur);
const int cnt = listCur.GetItemCount();
if (idxA < 0) {
MessageBox(L"Please select an active plugin in the list");
return;
}
int idxB = idxA + 1;
if (idxB >= cnt) return; // last item cannot be moved down
m_winamp_host.swapPlugins(idxA, idxB);
myShowActivePlugs();
listCur.SetItemState(idxB, LVIS_SELECTED, LVIS_SELECTED);
setUpDownButtonsState();
settingsSavePlugins();
}
void CDspAudioHostDlg::OnClose() {
static bool got_closed = false;
if (got_closed) return;
got_closed = true;
if (m_portaudio) m_portaudio->Stop();
settingsSavePlugins();
m_paSettings.saveAll();
__super::OnClose();
}
void CDspAudioHostDlg::OnTimer(UINT_PTR nIDEvent) {
static bool busy = false;
if (busy) {
return;
}
busy = true;
showMeters();
static std::wstring ws;
if (ws.size() != 1024) ws.resize(1024);
std::wstring sw;
if (m_portaudio) {
if (m_portaudio->m_running) {
double t = m_portaudio->currentTime();
portaudio_cpp::timestring(true, sw, (uint64_t)(t * 1000.0),
portaudio_cpp::time_flags::simple_format, ws.data());
assert(sw.size() == 15);
lblElapsedTime.SetWindowTextW(sw.data());
} else {
portaudio_cpp::timestring(
true, sw, 0, portaudio_cpp::time_flags::simple_format, ws.data());
lblElapsedTime.SetWindowTextW(sw.data());
}
}
__super::OnTimer(nIDEvent);
busy = false;
}
bool CDspAudioHostDlg::myPreparePlay(portaudio_cpp::AudioFormat& fmt) {
bool retval = true;
auto& myfmt = fmt;
myfmt.forInOrOut = DeviceTypes::input;
auto errcode = m_portaudio->isFormatSupported(myfmt);
if (errcode != paFormatIsSupported) {
std::string serr(Pa_GetErrorText(errcode));
serr += "\n";
serr += Pa_GetLastHostErrorInfo()->errorText;
MessageBox(L"The input device does not support the requested input audio format",
L"Bad input device Parameters");
retval = false;
}
if (retval) {
myfmt.forInOrOut = DeviceTypes::output;
errcode = m_portaudio->isFormatSupported(myfmt);
if (errcode == paInvalidChannelCount) {
myfmt.channels = portaudio_cpp::ChannelsType::mono;
errcode = m_portaudio->isFormatSupported(myfmt);
}
if (errcode) {
std::string serr = Pa_GetErrorText(errcode);
serr += "\n";
serr += Pa_GetLastHostErrorInfo()->errorText;
serr += "\n";
}
if (errcode != paFormatIsSupported) {
MessageBox(
L"The output device does not support the requested output audio format",
L"Bad output device Parameters");
retval = false;
}
}
/*/
if (1) {
const auto& d = m_portaudio->currentDevice(portaudio_cpp::DeviceTypes::output);
const auto& id = m_portaudio->currentDevice(portaudio_cpp::DeviceTypes::input);
const auto& sup_out = d.get_supported_audio_types();
const auto& sup_in = id.get_supported_audio_types();
const auto rates_out = d.getSupportedSamplerates();
const auto rates_in = id.getSupportedSamplerates();
TRACE("ffs");
}
/*/
return retval;
}
void CDspAudioHostDlg::OnBnClickedBtnPlay() {
if (!m_portaudio) return;
if (m_portaudio && m_portaudio->m_running) {
m_portaudio->Close();
}
int samplerates[] = {0, 0};
samplerates[0] = (int)m_portaudio->devices()[0].info.defaultSampleRate;
samplerates[1] = (int)m_portaudio->devices()[1].info.defaultSampleRate;
std::string strSamplerates("Input default samplerate = ");
strSamplerates += std::to_string(samplerates[0]);
strSamplerates += "\n";
strSamplerates += "Output default samplerate = ";
strSamplerates += std::to_string(samplerates[1]);
try {
portaudio_cpp::ChannelsType chans; // stereo by default
auto sr = portaudio_cpp::SampleRateType(m_paSettings.samplerate);
auto myfmt = portaudio_cpp::AudioFormat::makeAudioFormat(
portaudio_cpp::DeviceTypes::input, SampleFormat::Float32, sr, chans);
// if (!myPreparePlay(myfmt)) {
// return;
// }
// do this even if errors detected, so that we might find a common samplerate
myPreparePlay(myfmt);
if (1) {
if (myPreparePortAudio(chans, sr) == NOERROR) {
portaudioStart();
std::string sTime;
int l = (int)(m_portaudio->currentLatency() * 1000.0);
sTime += "[Latency] ";
sTime += std::to_string(l);
sTime += " ms. ";
sTime += "Format: ";
sTime += m_portaudio->sampleFormat().to_string();
sTime += " ";
sTime += m_portaudio->sampleRate().to_string();
::SetWindowTextA(lblPa.GetSafeHwnd(), sTime.c_str());
m_paSettings.saveAll();
}
}
} catch (const std::exception& e) {
const auto code = m_portaudio->errCode();
if (code == paInvalidSampleRate || code == paSampleFormatNotSupported) {
auto data = m_portaudio->findCommonSamplerate();
if (data <= 0) {
MessageBox(CStringW(e.what()));
} else {
std::wstringstream ws;
ws << L"Information: these two devices do share a common sample rate "
L"of: ";
ws << data;
ws << L"\n\n Would you like to try that instead?";
CString w(ws.str().c_str());
auto response = MessageBox(
w, L"Try a different sample rate?", MB_YESNO | MB_ICONINFORMATION);
if (response == IDYES) {
std::wstring wsamplerate = std::to_wstring(data);
auto found = cboSampleRate.FindStringExact(0, wsamplerate.c_str());
if (found >= 0) {
cboSampleRate.SetCurSel(found);
OnCbnSelchangeComboSamplerate(); // which calls us again
return;
}
}
}
} else {
MessageBox(CStringW(e.what()));
}
//::ShellExecute(*this, L"rundll32.exe", L"shell32.dll,Control_RunDLL
//: mmsys.cpl,,2",
// L"", L"", SW_SHOWNORMAL);
#pragma warning(disable : 28159)
if (std::string_view(m_portaudio->m_currentApi.name) != "ASIO")
::WinExec(
"rundll32.exe shell32.dll,Control_RunDLL mmsys.cpl,,0", SW_SHOWNORMAL);
}
}
void CDspAudioHostDlg::OnBnClickedBtnStop() {
if (m_portaudio && m_portaudio->m_running) {
m_portaudio->Stop();
}
}
HBRUSH CDspAudioHostDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) {
HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
// this is how you stop flicker in a static text control.
if (CTLCOLOR_STATIC == nCtlColor && pWnd == (CWnd*)&lblElapsedTime) {
if (NULL == m_brush.GetSafeHandle()) {
m_brush.CreateStockObject(NULL_BRUSH);
} else {
return m_brush;
}
} else {
if (CTLCOLOR_STATIC == nCtlColor && pWnd == (CWnd*)&lblClip) {
static CBrush brush(RGB(200, 0, 0));
return brush;
}
}
/*/
if (nCtlColor == CTLCOLOR_LISTBOX) {
COMBOBOXINFO info;
info.cbSize = sizeof(info);
::SendMessage(cboInput.m_hWnd, CB_GETCOMBOBOXINFO, 0, (LPARAM)&info);
COMBOBOXINFO info1;
info1.cbSize = sizeof(info1);
//::SendMessage(hWndComboBox1, CB_GETCOMBOBOXINFO, 0, (LPARAM)&info1);
if (pWnd->GetSafeHwnd() == info.hwndCombo) {
HDC dc = pDC->GetSafeHdc();
SetBkMode(dc, OPAQUE);
SetTextColor(dc, RGB(255, 255, 0));
SetBkColor(dc, 0x383838); // 0x383838
static HBRUSH comboBrush = CreateSolidBrush(0x383838); // global var
return comboBrush;
}
} else if (nCtlColor == WM_CTLCOLOREDIT) {
{
HWND hWnd = pWnd->GetSafeHwnd();
HDC dc = pDC->GetSafeHdc();
if (hWnd == cboInput.GetSafeHwnd()) {
SetBkMode(dc, OPAQUE);
SetTextColor(dc, RGB(255, 0, 255));
SetBkColor(dc, 0x383838); // 0x383838
static HBRUSH comboBrush = CreateSolidBrush(0x383838); // global var
return comboBrush;
}
}
}
constexpr COLORREF darkBkColor = 0x383838;
constexpr COLORREF darkTextColor = 0xFFFFFF;
static HBRUSH hbrBkgnd = nullptr;
if (g_darkModeSupported && g_darkModeEnabled) {
HDC hdc = pDC->GetSafeHdc();
SetTextColor(hdc, darkTextColor);
SetBkColor(hdc, darkBkColor);
if (!hbrBkgnd) hbrBkgnd = CreateSolidBrush(darkBkColor);
return hbrBkgnd;
}
/*/
return hbr;
}
void CDspAudioHostDlg::OnNMCustomdrawSliderVol(NMHDR*, LRESULT* pResult) {
// LPNMCUSTOMDRAW pNMCD = reinterpret_cast<LPNMCUSTOMDRAW>(pNMHDR);
// TODO: Add your control notification handler code here
*pResult = 0;
}
void CDspAudioHostDlg::sliderMoved(CSliderCtrl& which) {
if (&which == &sldVol) {
float pos = -((float)sldVol.GetPos() + std::numeric_limits<float>::epsilon());
pos /= 100.0f; // db
const auto val = portaudio_cpp::db_to_value(-pos);
this->m_volume = val;
} else if (&which == &sldVolIn) {
float pos = -((float)sldVolIn.GetPos() + std::numeric_limits<float>::epsilon());
pos /= 100.0f; // db
pos += 25.0f; // provide some boost on the input
auto val = portaudio_cpp::db_to_value(-pos);
this->m_volumeIn = val;
}
}
void CDspAudioHostDlg::OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar) {
CSliderCtrl* pSlider = reinterpret_cast<CSliderCtrl*>(pScrollBar);
// Check which slider sent the notification
if (TRUE) {
switch (nSBCode) {
case TB_LINEUP:
case TB_LINEDOWN:
case TB_PAGEUP:
case TB_PAGEDOWN:
case TB_THUMBPOSITION: {
sliderMoved(*pSlider); //-V1037
break;
}
case TB_TOP:
case TB_BOTTOM:
case TB_THUMBTRACK: {
sliderMoved(*pSlider);
break;
}
case TB_ENDTRACK:
default: break;
}
}
__super::OnVScroll(nSBCode, nPos, pScrollBar);
}
void CDspAudioHostDlg::OnBnClickedChkForceMono() {
// TODO: Add your control notification handler code here
if (m_portaudio) {
if (chkForceMono.GetCheck() == TRUE) {
m_portaudio->monoInputSet(true);
} else {
m_portaudio->monoInputSet(false);
}
}
}
void CDspAudioHostDlg::OnStnClickedVuOutR() {
// TODO: Add your control notification handler code here
}
void CDspAudioHostDlg::showMeters() {
double left = 0;
double right = 0;
if (m_portaudio && m_portaudio->m_running) {
const auto& env = m_portaudio->m_env_output.m_env;
cpp::audio::envelope_val<double>(left, right, 2, env[0], env[1], 10000L, 80L);
}
vuOutL.value_set(left);
vuOutR.value_set(right);
if (m_portaudio && m_portaudio->m_running) {
const auto& env = m_portaudio->m_env_input.m_env;
cpp::audio::envelope_val<double>(left, right, 2, env[0], env[1], 10000L, 80L);
showClipped();
}
vuInL.value_set(left);
vuInR.value_set(right);
}
void CDspAudioHostDlg::portaudioStart() {
m_portaudio->Start();
if (chkForceMono.GetCheck()) {
m_portaudio->monoInputSet(true);
} else {
m_portaudio->monoInputSet(false);
}
}
void CDspAudioHostDlg::pbar_ctrl_create(BOOL double_buffered, const std::string& name,
const int idctrl, CPBar& pbar, int invert) {
#pragma warning(disable : 4130) // VC wants to complain about my ASSERT statement.
CRect rect;
GetDlgItem(idctrl)->GetWindowRect(&rect);
rect.top += 4;
rect.bottom += 4;
rect.bottom -= 1;
ScreenToClient(&rect);
GetDlgItem(idctrl)->ShowWindow(SW_HIDE);
if (pbar.GetSafeHwnd()) {
ASSERT("You likely screwed up. This pbar already has a window. Are you "
"assigning "
"the wrong one?"
== 0);
}
pbar.Create(name, AfxGetInstanceHandle(), 0, (WS_CHILD | WS_VISIBLE) & (~WS_BORDER),
rect, this, idctrl);
pbar.orientation_set(CPBar::orientation_t::vertical);
pbar.maximum_set(10000);
pbar.smooth_set(false);
pbar.draw_inverted_set(invert);
pbar.double_buffered_set(double_buffered);
}
void CDspAudioHostDlg::OnStnClickedClip() {
// TODO: Add your control notification handler code here
}
void CDspAudioHostDlg::OnCbnSelchangeComboSamplerate() {
afterSamplerateChanged();
}
void CDspAudioHostDlg::afterSamplerateChanged(bool fromUserClick) {
const auto idx = cboSampleRate.GetCurSel();
CString cs;
cboSampleRate.GetLBText(idx, cs);
CStringA csa(cs);
const auto sr = atoi(csa);
if (fromUserClick) {
if (sr != 44100) {
CString msg(
L"Please note that almost all winamp dsp plugins (with the notable "
L"exception of Maximod)\n were never designed for anything other "
L"than "
L"44100 "
L"sample rate.\n\nThey may give silent output, or crash the "
L"application "
L"if "
L"you try to use them with a non-44100 sample rate");
SHMessageBoxCheck(this->GetSafeHwnd(), msg,
TEXT("Non-standard sample rate warning"), MB_ICONINFORMATION | MB_OK,
IDYES, TEXT("{0C44B5F5-F102-4115-B782-7EDC567302B1}"));
}
}
m_paSettings.samplerate = sr;
this->OnBnClickedBtnPlay();
}
void CDspAudioHostDlg::OnSize(UINT nType, int cx, int cy) {
__super::OnSize(nType, cx, cy);
}
LRESULT CDspAudioHostDlg::OnThemeChanged() {
/*/
if (g_darkModeSupported) {
_AllowDarkModeForWindow(*this, g_darkModeEnabled);
RefreshTitleBarThemeColor(*this);
CWnd* pwndChild = GetWindow(GW_CHILD);
while (pwndChild) {
_AllowDarkModeForWindow(*pwndChild, g_darkModeEnabled);
::SendMessageW(*pwndChild, WM_THEMECHANGED, 0, 0);
wchar_t buf[MAX_PATH] = {0};
::GetWindowText(*pwndChild, buf, MAX_PATH);
TRACE(L"setting dark mode (%d) to window: %s\n", (int)g_darkModeEnabled, buf);
pwndChild = pwndChild->GetWindow(GW_HWNDNEXT);
}
UpdateWindow();
}
/*/
return 1;
}
#define WM_WININICHANGE 0x001A
#define WM_SETTINGCHANGE WM_WININICHANGE
BOOL CDspAudioHostDlg::OnWndMsg(
UINT message, WPARAM wParam, LPARAM lParam, LRESULT* pResult) {
switch (message) {
case WM_SIZING: {
RECT* r = (RECT*)lParam;
*r = m_sizeRect;
break;
}
case WM_MOVING:
case WM_SIZE:
case WM_MOVE: {
GetWindowRect(&m_sizeRect);
if (m_portaudio_create_thread_state == 0) {
saveMyPosition();
} else {
// app setting up, wait!
TRACE("Waiting before saving window position\n");
}
break;
}
case WM_VU_CLICKED: {
const auto val = !vuInL.smooth();
vuInL.smooth_set(val);
vuInR.smooth_set(val);
vuOutL.smooth_set(val);
vuOutR.smooth_set(val);
return TRUE;
break;
}
case WM_NOTIFY: {
NMHDR* nmhdr = NULL;
nmhdr = (NMHDR*)lParam;
if (this->tabAvailPlugs.m_hWnd == nmhdr->hwndFrom) {
switch (nmhdr->code) {
case TCN_SELCHANGE: {
int sel = tabAvailPlugs.GetCurSel();
myTabSelChange(tabAvailPlugs, sel);
}
}
}
}
[[fallthrough]];
default:
{
return __super::OnWndMsg(message, wParam, lParam, pResult);
}
};
return __super::OnWndMsg(message, wParam, lParam, pResult);
}
void CDspAudioHostDlg::OnBnClickedBtnConfigAudio() {
::WinExec("rundll32.exe shell32.dll,Control_RunDLL mmsys.cpl,,0", SW_SHOWNORMAL);
}
void CDspAudioHostDlg::OnCancel() {
// TODO: Add your specialized code here and/or call the base class
//__super::OnCancel();
// nope, don't want to close window on enter key, thanks
}
void CDspAudioHostDlg::OnOK() {
// TODO: Add your specialized code here and/or call the base class
// __super::OnOK();
// nope, don't want to close window on enter key, thanks
}
void CDspAudioHostDlg::PreSubclassWindow() {
if (m_hWnd != NULL) {
// we don't want the user to be able to resize us
LONG cs = GetWindowLong(m_hWnd, GWL_STYLE);
cs &= ~WS_EX_CLIENTEDGE;
cs &= (0xFFFFFFFF ^ WS_SIZEBOX);
cs |= WS_BORDER;
cs &= (0xFFFFFFFF ^ WS_MAXIMIZEBOX);
SetWindowLong(m_hWnd, GWL_STYLE, cs);
}
__super::PreSubclassWindow();
}
void CDspAudioHostDlg::myTabSelChange(CTabCtrl& tab, int tabIndex) {
if (tabIndex == 0) {
listAvail.ShowWindow(TRUE);
listAvailVST.ShowWindow(FALSE);
} else {
listAvail.ShowWindow(FALSE);
listAvailVST.ShowWindow(TRUE);
}
}
BOOL CDspAudioHostDlg::OnNotify(WPARAM wParam, LPARAM lParam, LRESULT* pResult) {
// TODO: Add your specialized code here and/or call the base class
NMHDR* pNMHDR = (NMHDR*)lParam;
BOOL callParent = TRUE;
if (pNMHDR->hwndFrom == listAvailVST) {
static bool bHighlighted = TRUE;
LPNMLVCUSTOMDRAW lpLVCustomDraw = reinterpret_cast<LPNMLVCUSTOMDRAW>(pNMHDR);
NMCUSTOMDRAW nmcd = lpLVCustomDraw->nmcd;
*pResult = CDRF_DODEFAULT;
// auto nmh = *pNMHDR;
switch (lpLVCustomDraw->nmcd.dwDrawStage) {
case CDDS_PREPAINT: *pResult = CDRF_NOTIFYITEMDRAW; break;
case CDDS_ITEMPREPAINT: {
// int row = nmcd.dwItemSpec;
// bHighlighted = row % 2 == 0;
if (true) {
lpLVCustomDraw->clrText = RGB(0, 100, 0);
// EnableHighlighting(row, false);
*pResult = CDRF_DODEFAULT | CDRF_NOTIFYPOSTPAINT;
callParent = false;
}
} break;
case CDDS_ITEMPOSTPAINT:
if (bHighlighted) {
// int row = nmcd.dwItemSpec;
// EnableHighlighting(row, true);
callParent = false;
}
*pResult = CDRF_DODEFAULT;
break;
default: break;
}
if (callParent) {
return __super::OnNotify(wParam, lParam, pResult);
}
}
return callParent;
}
| 31.158024
| 90
| 0.615076
|
sjk7
|
994698e8de3948a157175c3a6907ea175f565815
| 521
|
cpp
|
C++
|
abp/GUI/Sciter/demo-apps/sciter-external-behavior/stdafx.cpp
|
pyrroman/au3-boilerplate
|
596a3aa68d4d6b48dd79ed737d1e11604ac9e92f
|
[
"BSD-3-Clause"
] | 8
|
2019-07-02T15:59:30.000Z
|
2021-07-13T05:13:43.000Z
|
abp/GUI/Sciter/demo-apps/sciter-external-behavior/stdafx.cpp
|
pyrroman/au3-boilerplate
|
596a3aa68d4d6b48dd79ed737d1e11604ac9e92f
|
[
"BSD-3-Clause"
] | null | null | null |
abp/GUI/Sciter/demo-apps/sciter-external-behavior/stdafx.cpp
|
pyrroman/au3-boilerplate
|
596a3aa68d4d6b48dd79ed737d1e11604ac9e92f
|
[
"BSD-3-Clause"
] | 1
|
2019-07-02T15:59:31.000Z
|
2019-07-02T15:59:31.000Z
|
// stdafx.cpp : source file that includes just the standard includes
// sciterferry.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
| 23.681818
| 68
| 0.677543
|
pyrroman
|
995286d5bd0fa7419872fcbf0372eaa327924786
| 1,394
|
cpp
|
C++
|
gearoenix/vulkan/image/gx-vk-img-manager.cpp
|
Hossein-Noroozpour/gearoenix
|
c8fa8b8946c03c013dad568d6d7a97d81097c051
|
[
"BSD-Source-Code"
] | 35
|
2018-01-07T02:34:38.000Z
|
2022-02-09T05:19:03.000Z
|
gearoenix/vulkan/image/gx-vk-img-manager.cpp
|
Hossein-Noroozpour/gearoenix
|
c8fa8b8946c03c013dad568d6d7a97d81097c051
|
[
"BSD-Source-Code"
] | 111
|
2017-09-20T09:12:36.000Z
|
2020-12-27T12:52:03.000Z
|
gearoenix/vulkan/image/gx-vk-img-manager.cpp
|
Hossein-Noroozpour/gearoenix
|
c8fa8b8946c03c013dad568d6d7a97d81097c051
|
[
"BSD-Source-Code"
] | 5
|
2020-02-11T11:17:37.000Z
|
2021-01-08T17:55:43.000Z
|
#include "gx-vk-img-manager.hpp"
#ifdef GX_USE_VULKAN
#include "../buffer/gx-vk-buf-buffer.hpp"
#include "../engine/gx-vk-eng-engine.hpp"
#include "gx-vk-img-image.hpp"
gearoenix::vulkan::image::Manager::Manager(engine::Engine* const e) noexcept
: frame_upload_images(e->get_frames_count())
, e(e)
{
}
gearoenix::vulkan::image::Manager::~Manager() noexcept = default;
void gearoenix::vulkan::image::Manager::upload(
std::shared_ptr<Image> img,
std::shared_ptr<buffer::Buffer> buff,
const core::sync::EndCaller<core::sync::EndCallerIgnore>& call) noexcept
{
GX_GUARD_LOCK(upload_images)
upload_images.emplace_back(std::move(img), std::move(buff), call);
}
void gearoenix::vulkan::image::Manager::update(command::Buffer& cmd) noexcept
{
auto& images = frame_upload_images[e->get_frame_number()];
images.clear();
{
GX_GUARD_LOCK(upload_images)
std::swap(upload_images, images);
}
GXTODO
// todo check for sync
for (const auto& img_call : images) {
std::get<0>(img_call)->transit_for_writing(cmd);
}
// todo sync check
for (const auto& img_call : images) {
std::get<0>(img_call)->copy_from_buffer(cmd, *std::get<1>(img_call));
}
// todo sync check
for (const auto& img_call : images) {
std::get<0>(img_call)->transit_for_reading(cmd);
}
// todo sync check
}
#endif
| 28.44898
| 77
| 0.664275
|
Hossein-Noroozpour
|
995dd80a18cf4b99c722d5e75eb51a0d2d672b25
| 1,214
|
hpp
|
C++
|
src/gpu/ocl/ocl_gpu_detect.hpp
|
ImproveMyPhone/mkl-dnn
|
aa13406e8a284495faaddf5396d9090a1d46f1ca
|
[
"Apache-2.0"
] | 4
|
2019-02-01T11:16:59.000Z
|
2020-04-27T17:27:06.000Z
|
src/gpu/ocl/ocl_gpu_detect.hpp
|
ImproveMyPhone/mkl-dnn
|
aa13406e8a284495faaddf5396d9090a1d46f1ca
|
[
"Apache-2.0"
] | 1
|
2020-04-17T22:23:01.000Z
|
2020-04-23T21:11:41.000Z
|
src/gpu/ocl/ocl_gpu_detect.hpp
|
ImproveMyPhone/mkl-dnn
|
aa13406e8a284495faaddf5396d9090a1d46f1ca
|
[
"Apache-2.0"
] | 5
|
2019-02-08T07:36:01.000Z
|
2021-07-14T07:58:50.000Z
|
/*******************************************************************************
* Copyright 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.
*******************************************************************************/
#ifndef GPU_OCL_OCL_GPU_DETECT_HPP
#define GPU_OCL_OCL_GPU_DETECT_HPP
#include <CL/cl.h>
#include "gpu/compute/device_info.hpp"
namespace dnnl {
namespace impl {
namespace gpu {
namespace ocl {
compute::gpu_arch_t detect_gpu_arch(cl_device_id device, cl_context context);
compute::gpu_arch_t detect_gpu_arch_by_device_name(const std::string &name);
} // namespace ocl
} // namespace gpu
} // namespace impl
} // namespace dnnl
#endif // GPU_OCL_OCL_GPU_DETECT_HPP
| 31.947368
| 80
| 0.671334
|
ImproveMyPhone
|
9969170f75bdefe918f39ca2d350e3ca04b0b090
| 586
|
cpp
|
C++
|
Workers/VariableDisplayer.cpp
|
dennistrukhin/C-Virtual-machine
|
644be1f45c0d2804f93bddbfb4728e3d0c9fee5a
|
[
"MIT"
] | null | null | null |
Workers/VariableDisplayer.cpp
|
dennistrukhin/C-Virtual-machine
|
644be1f45c0d2804f93bddbfb4728e3d0c9fee5a
|
[
"MIT"
] | null | null | null |
Workers/VariableDisplayer.cpp
|
dennistrukhin/C-Virtual-machine
|
644be1f45c0d2804f93bddbfb4728e3d0c9fee5a
|
[
"MIT"
] | null | null | null |
//
// Created by Dennis Trukhin on 22/04/2018.
//
#include <iostream>
#include "VariableDisplayer.h"
VariableDisplayer::VariableDisplayer(FileReader *fr, Variables *v) {
reader = fr;
variables = v;
}
void VariableDisplayer::display() {
auto index = reader->getWord().asInt();
auto var = variables->get(index);
std::cout << "=> ";
if (var->isInt()) {
auto value = var->getIntValue();
std::cout << value;
} else if (var->isFloat()) {
auto value = var->getFloatValue();
std::cout << value;
}
std::cout << std::endl;
}
| 22.538462
| 68
| 0.587031
|
dennistrukhin
|
996a8c3d187c620e3814c64c7ab5bcb80ee1b757
| 7,938
|
cpp
|
C++
|
src/voglreplay/replay_tool_compare_hash.cpp
|
kingtaurus/vogl
|
a7317fa38e9d909ada4e941ca7dc2df1e4415b37
|
[
"MIT"
] | 497
|
2015-01-02T19:45:01.000Z
|
2022-03-04T19:22:07.000Z
|
src/voglreplay/replay_tool_compare_hash.cpp
|
kingtaurus/vogl
|
a7317fa38e9d909ada4e941ca7dc2df1e4415b37
|
[
"MIT"
] | 40
|
2015-01-05T21:04:20.000Z
|
2020-03-25T07:01:59.000Z
|
src/voglreplay/replay_tool_compare_hash.cpp
|
kingtaurus/vogl
|
a7317fa38e9d909ada4e941ca7dc2df1e4415b37
|
[
"MIT"
] | 85
|
2015-01-02T22:29:00.000Z
|
2021-11-28T02:42:48.000Z
|
/**************************************************************************
*
* Copyright 2013-2014 RAD Game Tools and Valve Software
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
**************************************************************************/
// File: replay_tool_compare_hash.cpp
#include "vogl_common.h"
#include "vogl_gl_replayer.h"
#include "vogl_file_utils.h"
static command_line_param_desc g_command_line_param_descs_compare_hash_files[] =
{
// compare_hash_files specific
{ "sum_compare_threshold", 1, false, "compare_hash_files: Only report mismatches greater than the specified threshold, use with --sum_hashing" },
{ "sum_hashing", 0, false, "Replay: Use per-component sums, instead of CRC hashing (useful for multisampling)" },
{ "compare_ignore_frames", 1, false, "compare_hash_files: Ignore first X frames" },
{ "compare_expected_frames", 1, false, "compare_hash_files: Fail if the # of frames is not X" },
{ "compare_first_frame", 1, false, "compare_hash_files: First frame to compare to in second hash file" },
{ "ignore_line_count_differences", 0, false, "compare_hash_files: Don't stop if the # of lines differs between the two files" },
};
//----------------------------------------------------------------------------------------------------------------------
// tool_compare_hash_files
//----------------------------------------------------------------------------------------------------------------------
bool tool_compare_hash_files_mode(vogl::vector<command_line_param_desc> *desc)
{
if (desc)
{
desc->append(g_command_line_param_descs_compare_hash_files, VOGL_ARRAY_SIZE(g_command_line_param_descs_compare_hash_files));
return true;
}
dynamic_string src1_filename(g_command_line_params().get_value_as_string_or_empty("", 1));
dynamic_string src2_filename(g_command_line_params().get_value_as_string_or_empty("", 2));
if ((src1_filename.is_empty()) || (src2_filename.is_empty()))
{
vogl_error_printf("Must specify two source filenames!\n");
return false;
}
dynamic_string_array src1_lines;
if (!file_utils::read_text_file(src1_filename.get_ptr(), src1_lines, file_utils::cRTFTrim | file_utils::cRTFIgnoreEmptyLines | file_utils::cRTFIgnoreCommentedLines | file_utils::cRTFPrintErrorMessages))
{
vogl_error_printf("Failed reading source file %s!\n", src1_filename.get_ptr());
return false;
}
vogl_printf("Read 1st source file \"%s\", %u lines\n", src1_filename.get_ptr(), src1_lines.size());
dynamic_string_array src2_lines;
if (!file_utils::read_text_file(src2_filename.get_ptr(), src2_lines, file_utils::cRTFTrim | file_utils::cRTFIgnoreEmptyLines | file_utils::cRTFIgnoreCommentedLines | file_utils::cRTFPrintErrorMessages))
{
vogl_error_printf("Failed reading source file %s!\n", src2_filename.get_ptr());
return false;
}
vogl_printf("Read 2nd source file \"%s\", %u lines\n", src2_filename.get_ptr(), src2_lines.size());
const uint64_t sum_comp_thresh = g_command_line_params().get_value_as_uint64("sum_compare_threshold");
const uint32_t compare_first_frame = g_command_line_params().get_value_as_uint("compare_first_frame");
if (compare_first_frame > src2_lines.size())
{
vogl_error_printf("-compare_first_frame is %u, but the second file only has %u frames!\n", compare_first_frame, src2_lines.size());
return false;
}
const uint32_t lines_to_comp = math::minimum(src1_lines.size(), src2_lines.size() - compare_first_frame);
if (src1_lines.size() != src2_lines.size())
{
// FIXME: When we replay q2, we get 2 more frames vs. tracing. Not sure why, this needs to be investigated.
if ( (!g_command_line_params().get_value_as_bool("ignore_line_count_differences")) && (labs(src1_lines.size() - src2_lines.size()) > 3) )
{
vogl_error_printf("Input files have a different number of lines! (%u vs %u)\n", src1_lines.size(), src2_lines.size());
return false;
}
else
{
vogl_warning_printf("Input files have a different number of lines! (%u vs %u)\n", src1_lines.size(), src2_lines.size());
}
}
const uint32_t compare_ignore_frames = g_command_line_params().get_value_as_uint("compare_ignore_frames");
if (compare_ignore_frames > lines_to_comp)
{
vogl_error_printf("-compare_ignore_frames is too large!\n");
return false;
}
const bool sum_hashing = g_command_line_params().get_value_as_bool("sum_hashing");
if (g_command_line_params().has_key("compare_expected_frames"))
{
const uint32_t compare_expected_frames = g_command_line_params().get_value_as_uint("compare_expected_frames");
if ((src1_lines.size() != compare_expected_frames) || (src2_lines.size() != compare_expected_frames))
{
vogl_warning_printf("Expected %u frames! First file has %u frames, second file has %u frames.\n", compare_expected_frames, src1_lines.size(), src2_lines.size());
return false;
}
}
uint32_t total_mismatches = 0;
uint64_t max_sum_delta = 0;
for (uint32_t i = compare_ignore_frames; i < lines_to_comp; i++)
{
const char *pStr1 = src1_lines[i].get_ptr();
const char *pStr2 = src2_lines[i + compare_first_frame].get_ptr();
uint64_t val1 = 0, val2 = 0;
if (!string_ptr_to_uint64(pStr1, val1))
{
vogl_error_printf("Failed parsing line at index %u of first source file!\n", i);
return false;
}
if (!string_ptr_to_uint64(pStr2, val2))
{
vogl_error_printf("Failed parsing line at index %u of second source file!\n", i);
return false;
}
bool mismatch = false;
if (sum_hashing)
{
uint64_t delta;
if (val1 > val2)
delta = val1 - val2;
else
delta = val2 - val1;
max_sum_delta = math::maximum(max_sum_delta, delta);
if (delta > sum_comp_thresh)
mismatch = true;
}
else
{
mismatch = val1 != val2;
}
if (mismatch)
{
if (sum_hashing)
vogl_error_printf("Mismatch at frame %u: %" PRIu64 ", %" PRIu64 "\n", i, val1, val2);
else
vogl_error_printf("Mismatch at frame %u: 0x%" PRIX64 ", 0x%" PRIX64 "\n", i, val1, val2);
total_mismatches++;
}
}
if (sum_hashing)
vogl_printf("Max sum delta: %" PRIu64 "\n", max_sum_delta);
if (!total_mismatches)
vogl_printf("No mismatches\n");
else
{
vogl_error_printf("%u total mismatches!\n", total_mismatches);
return false;
}
return true;
}
| 42.677419
| 206
| 0.642857
|
kingtaurus
|
996b2ed2bdca65c59049fb1d0cb5f6f88fd32700
| 6,865
|
cpp
|
C++
|
Src/Vulkan/Core/VulkanDriver.cpp
|
StavrosBizelis/NetworkDistributedDeferredShading
|
07c03ce9b13bb5adb164cd4321b2bba284e49b4d
|
[
"MIT"
] | null | null | null |
Src/Vulkan/Core/VulkanDriver.cpp
|
StavrosBizelis/NetworkDistributedDeferredShading
|
07c03ce9b13bb5adb164cd4321b2bba284e49b4d
|
[
"MIT"
] | null | null | null |
Src/Vulkan/Core/VulkanDriver.cpp
|
StavrosBizelis/NetworkDistributedDeferredShading
|
07c03ce9b13bb5adb164cd4321b2bba284e49b4d
|
[
"MIT"
] | null | null | null |
#define ZR_EXPORT 1 // export this class to dll
#include <Vulkan/Core/VulkanDriver.h>
// #include <VulkanDriver/VulkanRenderPassFactory.h>
#include <Common/Core/MyUtilities.h>
#include <Vulkan/Core/VulkanValidationLayerEnabler.h>
VkResult CreateDebugReportCallbackEXT(VkInstance instance, const VkDebugReportCallbackCreateInfoEXT* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDebugReportCallbackEXT* pCallback) {
auto func = (PFN_vkCreateDebugReportCallbackEXT) vkGetInstanceProcAddr(instance, "vkCreateDebugReportCallbackEXT");
if (func != nullptr) {
return func(instance, pCreateInfo, pAllocator, pCallback);
} else {
return VK_ERROR_EXTENSION_NOT_PRESENT;
}
}
void DestroyDebugReportCallbackEXT(VkInstance instance, VkDebugReportCallbackEXT callback, const VkAllocationCallbacks* pAllocator) {
auto func = (PFN_vkDestroyDebugReportCallbackEXT) vkGetInstanceProcAddr(instance, "vkDestroyDebugReportCallbackEXT");
if (func != nullptr) {
func(instance, callback, pAllocator);
}
}
VulkanDriver::VulkanDriver( const std::vector<const char*>& a_requiredInstanceExtensions )
{
// init required extensions before anything
m_requiredInstanceExtensions = a_requiredInstanceExtensions;
if( g_enableValidationLayers ) m_requiredInstanceExtensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
CreateVulkanInstance();
if( g_enableValidationLayers ) SetupDebugCallback();
}
VulkanDriver::~VulkanDriver()
{
Shutdown();
}
void VulkanDriver::Init(const glm::vec2& a_windowSize )
{
m_windowSize = a_windowSize;
m_logicalDeviceMan = std::make_shared<VulkanLogicalDeviceManager>();
// choose physical device
std::map<int, VkPhysicalDevice> l_physicalDevices = m_physicalDeviceMan.GetSuitablePhysicalDevices( m_instance, m_surface, m_windowSize.x, m_windowSize.y);
if( l_physicalDevices.size() == 0 )
throw std::runtime_error("failed to find a suitable GPU!");
m_chosenPhysicalDevice = l_physicalDevices.begin()->second;
VkPhysicalDeviceProperties l_prop;
vkGetPhysicalDeviceProperties(m_chosenPhysicalDevice, &l_prop);
IFDBG( std::cout << "Best Suitable device: " << l_prop.deviceName << std::endl; );
// create logical device, swap chain and Image views for this swap chain
SwapChainSupportDetails l_swapChainDetails = m_physicalDeviceMan.GetSwapChainSupportDetails(m_chosenPhysicalDevice, m_surface, m_windowSize.x, m_windowSize.y);
VkPhysicalDeviceFeatures l_features;
vkGetPhysicalDeviceFeatures(m_chosenPhysicalDevice,&l_features);
m_logicalDeviceMan->Init(m_chosenPhysicalDevice, m_surface, m_physicalDeviceMan.FindQueueFamilies(m_chosenPhysicalDevice, m_surface) , l_features, m_physicalDeviceMan.GetDeviceExtensions());
// setup memory
VkDeviceSize l_stagingMemorySize = 1048576 * 200; // 200mb
VkDeviceSize l_vertexMemorySize = 1048576 * 40; // 40mb
VkDeviceSize l_indexMemorySize = 1048576 * 40; // 40mb
VkDeviceSize l_uniformBufferMemorySize = 1048576 * 100; // 100mb
VkDeviceSize l_mixBufferMemorySize = 1048576 * 4; // 4mb
VkDeviceSize l_shaderImagesSize = 1048576 * 200; // 200mb
VkDeviceSize l_colourAttachmentsSize = 1048576 * 120; // 120mb
VkDeviceSize l_downloadingColourAttachmentsSize = 1048576 * 120; // 120mb
VkDeviceSize l_depthStencilAttachmentsSize = 1048576 * 80; // 80mb
m_logicalDeviceMan->GetMemoryManager()->Init(l_stagingMemorySize, l_vertexMemorySize, l_indexMemorySize, l_uniformBufferMemorySize, l_mixBufferMemorySize,
l_shaderImagesSize, l_colourAttachmentsSize, l_downloadingColourAttachmentsSize, l_depthStencilAttachmentsSize);
// error in CreateSwapChain
IFDBG( std::cout << "Initialized memory \n"; );
m_logicalDeviceMan->CreateSwapChain( l_swapChainDetails );
IFDBG( std::cout << "Created swapchain\n"; );
m_logicalDeviceMan->CreateImageViews();
IFDBG( std::cout << "Created image views\n"; );
// VulkanRenderPassFactory l_factory(m_logicalDeviceMan);
// m_logicalDeviceMan->SetRenderPass( l_factory.CreateColorRenderPass(true) );
// // // // // // // VkPhysicalDeviceProperties l_props;
// // // // // // // vkGetPhysicalDeviceProperties(m_chosenPhysicalDevice, &l_props);
// // // // // // // std::cout << "maxDescriptorSetUniformBuffers" << l_props.limits.maxDescriptorSetUniformBuffers << std::endl;
// // // // // // // std::cout << "maxBoundDescriptorSets" << l_props.limits.maxBoundDescriptorSets << std::endl;
}
// void VulkanDriver::Update(){ m_logicalDeviceMan->Update(); }
VulkanPhysicalDeviceSelector& VulkanDriver::GetPhysicalDeviceSelector() { return m_physicalDeviceMan; }
VkPhysicalDevice VulkanDriver::GetSelectedPhysicalDevice(){ return m_chosenPhysicalDevice; }
std::shared_ptr<VulkanLogicalDeviceManager> VulkanDriver::GetLogicalDeviceManager() { return m_logicalDeviceMan; }
void VulkanDriver::Shutdown()
{
// destroy image views
// destroy swapchain
// destroys logical device
// m_logicalDeviceMan->Shutdown();
DestroyDebugReportCallbackEXT(m_instance, m_callback, nullptr);
if( m_surface )
vkDestroySurfaceKHR(m_instance, m_surface, nullptr);
vkDestroyInstance(m_instance, nullptr);
}
void VulkanDriver::CreateVulkanInstance()
{
m_surface = 0;
VkApplicationInfo l_appInfo;
l_appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
l_appInfo.pApplicationName = "";
l_appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
l_appInfo.pEngineName = "";
l_appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
l_appInfo.apiVersion = VK_API_VERSION_1_0;
VkInstanceCreateInfo l_createInfo = {};
l_createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
l_createInfo.pApplicationInfo = &l_appInfo;
l_createInfo.enabledExtensionCount = static_cast<uint32_t>(m_requiredInstanceExtensions.size());
l_createInfo.ppEnabledExtensionNames = m_requiredInstanceExtensions.data();
if( g_enableValidationLayers )
{
std::cout << "Enable Validation Layers\n";
l_createInfo.enabledLayerCount = static_cast<uint32_t>(g_validationLayers.size());
l_createInfo.ppEnabledLayerNames = g_validationLayers.data();
}
else l_createInfo.enabledLayerCount = 0;
if (vkCreateInstance(&l_createInfo, nullptr, &m_instance) != VK_SUCCESS) {
throw std::runtime_error("failed to create instance!");
}
}
void VulkanDriver::SetupDebugCallback()
{
VkDebugReportCallbackCreateInfoEXT l_createInfo = {};
l_createInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT;
l_createInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT;
l_createInfo.pfnCallback = DebugCallback;
if (CreateDebugReportCallbackEXT(m_instance, &l_createInfo, nullptr, &m_callback) != VK_SUCCESS) {
throw std::runtime_error("failed to set up debug callback!");
}
}
| 39.682081
| 193
| 0.766934
|
StavrosBizelis
|
997351e4aaf176cf496a09eb99e3d0c5bcf87460
| 1,190
|
cpp
|
C++
|
JetEngine/Graphics/Renderable.cpp
|
matt-attack/Jet-Engine
|
4b86ae2b7b60a326a7a329942d2c8f656ed2bd9f
|
[
"MIT"
] | 1
|
2018-07-29T20:51:12.000Z
|
2018-07-29T20:51:12.000Z
|
JetEngine/Graphics/Renderable.cpp
|
matt-attack/Jet-Engine
|
4b86ae2b7b60a326a7a329942d2c8f656ed2bd9f
|
[
"MIT"
] | 12
|
2017-07-29T20:33:15.000Z
|
2018-08-11T23:29:16.000Z
|
JetEngine/Graphics/Renderable.cpp
|
matt-attack/Jet-Engine
|
4b86ae2b7b60a326a7a329942d2c8f656ed2bd9f
|
[
"MIT"
] | 1
|
2018-07-30T12:55:20.000Z
|
2018-07-30T12:55:20.000Z
|
#include "Renderable.h"
#include "../IMaterial.h"
#include "CVertexBuffer.h"
void BasicRenderable::SetMeshEasy(const std::string& material_name, const std::string& image_name, const EzVert* vertex, int count)
{
auto mat = new IMaterial(material_name.c_str());
mat->alpha = false;
//ok, this is eww, but fine for now
std::string mname = image_name;
if (mname.length() > 0 && mname[mname.length() - 1] != 'g')
mname = mname + ".png";//.tga
//need to change this to not always be set to skinned, for example for trees
mat->skinned = false;
mat->shader_name = "Shaders/ubershader.txt";
mat->shader_builder = true;
//temporary test values
//mat->normal = "brick.jpg";
//mat->alphatest = true;
mat->diffuse = mname;
mat->Update(renderer);//load any associated textures
material = mat;
my_vb = CVertexBuffer(VertexBufferUsage::Static);
VertexElement elm7[] = { { ELEMENT_FLOAT3, USAGE_POSITION },
{ ELEMENT_FLOAT3, USAGE_NORMAL },
{ ELEMENT_FLOAT3, USAGE_TANGENT },
{ ELEMENT_FLOAT2, USAGE_TEXCOORD } };
my_vb.SetVertexDeclaration(renderer->GetVertexDeclaration(elm7, 4));
my_vb.Data(vertex, count * sizeof(EzVert), sizeof(EzVert));
vcount = count;
vb = &my_vb;
}
| 30.512821
| 131
| 0.709244
|
matt-attack
|
99745d53c62d84b5a215125f22724225dbb69852
| 5,855
|
cpp
|
C++
|
third_party_src/ksqueezedtextlabel/kde_460_kdeui/src/ksqueezedtextlabel.cpp
|
CoSoSys/cppdevtk
|
99d6c3d328c05a55dae54e82fcbedad93d0cfaa0
|
[
"BSL-1.0",
"Apache-2.0"
] | null | null | null |
third_party_src/ksqueezedtextlabel/kde_460_kdeui/src/ksqueezedtextlabel.cpp
|
CoSoSys/cppdevtk
|
99d6c3d328c05a55dae54e82fcbedad93d0cfaa0
|
[
"BSL-1.0",
"Apache-2.0"
] | null | null | null |
third_party_src/ksqueezedtextlabel/kde_460_kdeui/src/ksqueezedtextlabel.cpp
|
CoSoSys/cppdevtk
|
99d6c3d328c05a55dae54e82fcbedad93d0cfaa0
|
[
"BSL-1.0",
"Apache-2.0"
] | null | null | null |
/* This file is part of the KDE libraries
Copyright (C) 2000 Ronny Standtke <Ronny.Standtke@gmx.de>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 as published by the Free Software Foundation.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "ksqueezedtextlabel.h"
#include <kdebug.h>
#include <klocale.h>
#include <QContextMenuEvent>
#include <kaction.h>
#include <QMenu>
#include <QClipboard>
#include <QApplication>
#include <QMimeData>
#include <kglobalsettings.h>
class KSqueezedTextLabelPrivate
{
public:
void _k_copyFullText() {
QApplication::clipboard()->setText(fullText);
}
QString fullText;
Qt::TextElideMode elideMode;
};
KSqueezedTextLabel::KSqueezedTextLabel(const QString &text , QWidget *parent)
: QLabel (parent),
d(new KSqueezedTextLabelPrivate)
{
setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed));
d->fullText = text;
d->elideMode = Qt::ElideMiddle;
squeezeTextToLabel();
}
KSqueezedTextLabel::KSqueezedTextLabel(QWidget *parent)
: QLabel (parent),
d(new KSqueezedTextLabelPrivate)
{
setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed));
d->elideMode = Qt::ElideMiddle;
}
KSqueezedTextLabel::~KSqueezedTextLabel()
{
delete d;
}
void KSqueezedTextLabel::resizeEvent(QResizeEvent *)
{
squeezeTextToLabel();
}
QSize KSqueezedTextLabel::minimumSizeHint() const
{
QSize sh = QLabel::minimumSizeHint();
sh.setWidth(-1);
return sh;
}
QSize KSqueezedTextLabel::sizeHint() const
{
int maxWidth = KGlobalSettings::desktopGeometry(this).width() * 3 / 4;
QFontMetrics fm(fontMetrics());
int textWidth = fm.width(d->fullText);
if (textWidth > maxWidth) {
textWidth = maxWidth;
}
return QSize(textWidth, QLabel::sizeHint().height());
}
void KSqueezedTextLabel::setText(const QString &text)
{
d->fullText = text;
squeezeTextToLabel();
}
void KSqueezedTextLabel::clear()
{
d->fullText.clear();
QLabel::clear();
}
void KSqueezedTextLabel::squeezeTextToLabel()
{
QFontMetrics fm(fontMetrics());
int labelWidth = size().width();
QStringList squeezedLines;
bool squeezed = false;
Q_FOREACH(const QString& line, d->fullText.split('\n')) {
int lineWidth = fm.width(line);
if (lineWidth > labelWidth) {
squeezed = true;
squeezedLines << fm.elidedText(line, d->elideMode, labelWidth);
} else {
squeezedLines << line;
}
}
if (squeezed) {
QLabel::setText(squeezedLines.join("\n"));
setToolTip(d->fullText);
} else {
QLabel::setText(d->fullText);
setToolTip(QString());
}
}
void KSqueezedTextLabel::setAlignment(Qt::Alignment alignment)
{
// save fullText and restore it
QString tmpFull(d->fullText);
QLabel::setAlignment(alignment);
d->fullText = tmpFull;
}
Qt::TextElideMode KSqueezedTextLabel::textElideMode() const
{
return d->elideMode;
}
void KSqueezedTextLabel::setTextElideMode(Qt::TextElideMode mode)
{
d->elideMode = mode;
squeezeTextToLabel();
}
QString KSqueezedTextLabel::fullText() const
{
return d->fullText;
}
void KSqueezedTextLabel::contextMenuEvent(QContextMenuEvent* ev)
{
// We want to reimplement "Copy" to include the elided text.
// But this means reimplementing the full popup menu, so no more
// copy-link-address or copy-selection support anymore, since we
// have no access to the QTextDocument.
// Maybe we should have a boolean flag in KSqueezedTextLabel itself for
// whether to show the "Copy Full Text" custom popup?
// For now I chose to show it when the text is squeezed; when it's not, the
// standard popup menu can do the job (select all, copy).
const bool squeezed = text() != d->fullText;
const bool showCustomPopup = squeezed;
if (showCustomPopup) {
QMenu menu(this);
KAction* act = new KAction(i18n("&Copy Full Text"), this);
connect(act, SIGNAL(triggered()), this, SLOT(_k_copyFullText()));
menu.addAction(act);
ev->accept();
menu.exec(ev->globalPos());
} else {
QLabel::contextMenuEvent(ev);
}
}
void KSqueezedTextLabel::mouseReleaseEvent(QMouseEvent* ev)
{
#if QT_VERSION >= 0x040700
if (QApplication::clipboard()->supportsSelection() &&
textInteractionFlags() != Qt::NoTextInteraction &&
ev->button() == Qt::LeftButton &&
!d->fullText.isEmpty() &&
hasSelectedText()) {
// Expand "..." when selecting with the mouse
QString txt = selectedText();
const QChar ellipsisChar(0x2026); // from qtextengine.cpp
const int dotsPos = txt.indexOf(ellipsisChar);
if (dotsPos > -1) {
// Ex: abcde...yz, selecting de...y (selectionStart=3)
// charsBeforeSelection = selectionStart = 2 (ab)
// charsAfterSelection = 1 (z)
// final selection length= 26 - 2 - 1 = 23
const int start = selectionStart();
const int charsAfterSelection = text().length() - start - selectedText().length();
txt = d->fullText.mid(selectionStart(), d->fullText.length() - start - charsAfterSelection);
}
QApplication::clipboard()->setText(txt, QClipboard::Selection);
} else
#endif
{
QLabel::mouseReleaseEvent(ev);
}
}
#include "ksqueezedtextlabel.moc"
| 28.42233
| 104
| 0.686422
|
CoSoSys
|
99758b5311eff1a96c57c9951983f47a2841426d
| 414
|
cpp
|
C++
|
Example/datetime_11/main.cpp
|
KwangjoJeong/Boost
|
29c4e2422feded66a689e3aef73086c5cf95b6fe
|
[
"MIT"
] | null | null | null |
Example/datetime_11/main.cpp
|
KwangjoJeong/Boost
|
29c4e2422feded66a689e3aef73086c5cf95b6fe
|
[
"MIT"
] | null | null | null |
Example/datetime_11/main.cpp
|
KwangjoJeong/Boost
|
29c4e2422feded66a689e3aef73086c5cf95b6fe
|
[
"MIT"
] | null | null | null |
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <iostream>
using namespace boost::posix_time;
int main()
{
ptime pt = second_clock::universal_time();
std::cout << pt.date() << '\n';
std::cout << pt.time_of_day() << '\n';
pt = from_iso_string("20140512T120000");
std::cout << pt.date() << '\n';
std::cout << pt.time_of_day() << '\n';
}
| 25.875
| 52
| 0.657005
|
KwangjoJeong
|
9976b281873b3248d258667a42ba6f1e377e6db3
| 1,946
|
cpp
|
C++
|
aws-cpp-sdk-migrationhubstrategy/source/model/NetworkInfo.cpp
|
perfectrecall/aws-sdk-cpp
|
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
|
[
"Apache-2.0"
] | 1
|
2022-02-12T08:09:30.000Z
|
2022-02-12T08:09:30.000Z
|
aws-cpp-sdk-migrationhubstrategy/source/model/NetworkInfo.cpp
|
perfectrecall/aws-sdk-cpp
|
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
|
[
"Apache-2.0"
] | 1
|
2022-01-03T23:59:37.000Z
|
2022-01-03T23:59:37.000Z
|
aws-cpp-sdk-migrationhubstrategy/source/model/NetworkInfo.cpp
|
ravindra-wagh/aws-sdk-cpp
|
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
|
[
"Apache-2.0"
] | 1
|
2021-11-09T11:58:03.000Z
|
2021-11-09T11:58:03.000Z
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/migrationhubstrategy/model/NetworkInfo.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace MigrationHubStrategyRecommendations
{
namespace Model
{
NetworkInfo::NetworkInfo() :
m_interfaceNameHasBeenSet(false),
m_ipAddressHasBeenSet(false),
m_macAddressHasBeenSet(false),
m_netMaskHasBeenSet(false)
{
}
NetworkInfo::NetworkInfo(JsonView jsonValue) :
m_interfaceNameHasBeenSet(false),
m_ipAddressHasBeenSet(false),
m_macAddressHasBeenSet(false),
m_netMaskHasBeenSet(false)
{
*this = jsonValue;
}
NetworkInfo& NetworkInfo::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("interfaceName"))
{
m_interfaceName = jsonValue.GetString("interfaceName");
m_interfaceNameHasBeenSet = true;
}
if(jsonValue.ValueExists("ipAddress"))
{
m_ipAddress = jsonValue.GetString("ipAddress");
m_ipAddressHasBeenSet = true;
}
if(jsonValue.ValueExists("macAddress"))
{
m_macAddress = jsonValue.GetString("macAddress");
m_macAddressHasBeenSet = true;
}
if(jsonValue.ValueExists("netMask"))
{
m_netMask = jsonValue.GetString("netMask");
m_netMaskHasBeenSet = true;
}
return *this;
}
JsonValue NetworkInfo::Jsonize() const
{
JsonValue payload;
if(m_interfaceNameHasBeenSet)
{
payload.WithString("interfaceName", m_interfaceName);
}
if(m_ipAddressHasBeenSet)
{
payload.WithString("ipAddress", m_ipAddress);
}
if(m_macAddressHasBeenSet)
{
payload.WithString("macAddress", m_macAddress);
}
if(m_netMaskHasBeenSet)
{
payload.WithString("netMask", m_netMask);
}
return payload;
}
} // namespace Model
} // namespace MigrationHubStrategyRecommendations
} // namespace Aws
| 18.533333
| 69
| 0.725591
|
perfectrecall
|
9979e35b635eb9481593e6fe7a5e1cc891d656d8
| 1,094
|
cpp
|
C++
|
ABC/ABC086/C.cpp
|
rajyan/AtCoder
|
2c1187994016d4c19b95489d2f2d2c0eab43dd8e
|
[
"MIT"
] | 1
|
2021-06-01T17:13:44.000Z
|
2021-06-01T17:13:44.000Z
|
ABC/ABC086/C.cpp
|
rajyan/AtCoder
|
2c1187994016d4c19b95489d2f2d2c0eab43dd8e
|
[
"MIT"
] | null | null | null |
ABC/ABC086/C.cpp
|
rajyan/AtCoder
|
2c1187994016d4c19b95489d2f2d2c0eab43dd8e
|
[
"MIT"
] | null | null | null |
//#include <cassert>
//#include <cstdio>
//#include <cmath>
//#include <iostream>
//#include <sstream>
//#include <string>
//#include <vector>
//#include <map>
//#include <queue>
//#include <algorithm>
//
//#ifdef _DEBUG
//#define DMP(x) cerr << #x << ": " << x << "\n"
//#else
//#define DMP(x) ((void)0)
//#endif
//
//const int MOD = 1000000007, INF = 1111111111;
//using namespace std;
//using lint = long long;
//
//int main() {
//
// cin.tie(nullptr);
// ios::sync_with_stdio(false);
//
// int N;
// cin >> N;
//
// struct deer {
// int t, x, y;
// deer(int t, int x, int y) :t(t), x(x), y(y) {}
// deer() :t(0), x(0), y(0) {}
// };
//
// vector<deer> plan(N+1);
// for (int i = 1; i <= N; i++) cin >> plan[i].t >> plan[i].x >> plan[i].y;
//
// int cost, time;
// bool flag = true;
// for (int i = 1; i <= N; i++) {
//
// cost = abs(plan[i].x - plan[i - 1].x) + abs(plan[i].y - plan[i - 1].y);
// time = plan[i].t - plan[i - 1].t;
// if (cost > time || ((cost ^ time) & 1)) flag = false;
// }
//
// if (flag) cout << "Yes" << "\n";
// else cout << "No" << "\n";
//
// return 0;
//}
| 21.038462
| 75
| 0.499086
|
rajyan
|
5f5378c04bea77861bb75554ba01c2d796321c99
| 227
|
hpp
|
C++
|
PP/find.hpp
|
Petkr/PP
|
646cc156603a6a9461e74d8f54786c0d5a9c32d2
|
[
"MIT"
] | 3
|
2019-07-12T23:12:24.000Z
|
2019-09-05T07:57:45.000Z
|
PP/find.hpp
|
Petkr/PP
|
646cc156603a6a9461e74d8f54786c0d5a9c32d2
|
[
"MIT"
] | null | null | null |
PP/find.hpp
|
Petkr/PP
|
646cc156603a6a9461e74d8f54786c0d5a9c32d2
|
[
"MIT"
] | null | null | null |
#pragma once
#include <PP/view/concept.hpp>
namespace PP
{
constexpr auto find(concepts::view auto&& v, auto&& p)
{
auto i = view::begin_(v);
for (; i != view::end_(v) && !PP_F(p)(*i); ++i)
;
return i;
}
}
| 16.214286
| 54
| 0.555066
|
Petkr
|
5f5c30c6d16d8f44838f6926d883ca06dd8b4359
| 1,368
|
cpp
|
C++
|
OpenGLTriangleIntersection/Renderer.cpp
|
uysalaltas/Opengl_Triangle_Point_Intersection
|
a310bf459e5a6c24794d9c354d2f2b771e97dae3
|
[
"MIT"
] | null | null | null |
OpenGLTriangleIntersection/Renderer.cpp
|
uysalaltas/Opengl_Triangle_Point_Intersection
|
a310bf459e5a6c24794d9c354d2f2b771e97dae3
|
[
"MIT"
] | null | null | null |
OpenGLTriangleIntersection/Renderer.cpp
|
uysalaltas/Opengl_Triangle_Point_Intersection
|
a310bf459e5a6c24794d9c354d2f2b771e97dae3
|
[
"MIT"
] | null | null | null |
#include "Renderer.h"
#include <glm/gtx/string_cast.hpp>
Renderer::Renderer(std::vector<Vertex>& vertices, std::vector<GLuint>& indices)
: m_vertices(vertices)
, m_indices(indices)
{
std::cout << "Renderer Constructor" << std::endl;
va.Bind();
for (int i = 0; i < m_indices.size(); i++)
{
Point a = m_vertices[m_indices[i]].position;
Vertex& aV = m_vertices[m_indices[i]];
i++;
Point b = m_vertices[m_indices[i]].position;
Vertex& bV = m_vertices[m_indices[i]];
i++;
Point c = m_vertices[m_indices[i]].position;
Vertex& cV = m_vertices[m_indices[i]];
Triangle tri = { a, b, c, aV, bV, cV };
m_triangles.push_back(tri);
}
vb = new VertexBuffer(m_vertices);
ib = new IndexBuffer(m_indices);
va.AddBuffer(*vb, 0, 3, sizeof(Vertex), (void*)0);
va.AddBuffer(*vb, 1, 3, sizeof(Vertex), (void*)(3 * sizeof(float)));
va.AddBuffer(*vb, 2, 3, sizeof(Vertex), (void*)(6 * sizeof(float)));
va.Unbind();
vb->Unbind();
ib->Unbind();
}
void Renderer::DrawLine(Shader& shader)
{
va.Bind();
shader.Bind();
glDrawElements(GL_LINES, m_indices.size(), GL_UNSIGNED_INT, 0);
}
void Renderer::DrawTriangle(Shader& shader)
{
shader.Bind();
va.Bind();
vb->BufferDataModification(m_vertices);
glDrawElements(GL_TRIANGLES, m_indices.size(), GL_UNSIGNED_INT, 0);
}
void Renderer::Clear()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
| 24.428571
| 79
| 0.677632
|
uysalaltas
|
5f5cf92597fbb65c11cfcefeb8d3f75b4696f89e
| 7,531
|
cpp
|
C++
|
OpenC2X/dcc/src/ChannelProber.cpp
|
zdzaz/e-c-its
|
dbe4f191d6d5e7dd50a28e4fcffd3123a64c0372
|
[
"MIT"
] | null | null | null |
OpenC2X/dcc/src/ChannelProber.cpp
|
zdzaz/e-c-its
|
dbe4f191d6d5e7dd50a28e4fcffd3123a64c0372
|
[
"MIT"
] | null | null | null |
OpenC2X/dcc/src/ChannelProber.cpp
|
zdzaz/e-c-its
|
dbe4f191d6d5e7dd50a28e4fcffd3123a64c0372
|
[
"MIT"
] | null | null | null |
// This file is part of OpenC2X.
//
// OpenC2X is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// OpenC2X is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with OpenC2X. If not, see <http://www.gnu.org/licenses/>.
//
// Authors:
// Sven Laux <slaux@mail.uni-paderborn.de>
// Gurjashan Singh Pannu <gurjashan.pannu@ccs-labs.org>
// Stefan Schneider <stefan.schneider@ccs-labs.org>
// Jan Tiemann <janhentie@web.de>
#define ELPP_THREAD_SAFE
#define ELPP_NO_DEFAULT_LOG_FILE
#include "ChannelProber.h"
#include <unistd.h>
#include <string>
#include <iostream>
#include <linux/nl80211.h>
#include <net/if.h>
using namespace std;
int ChannelProber::mNl80211Id;
ChannelProber::ChannelProber(string ifname, double probeInterval, boost::asio::io_service* io, int expNo, string loggingConf, string statisticConf) {
mProbeInterval = probeInterval;
mIfname = ifname;
mIoService = io;
mLogger = new LoggingUtility("ChannelProber", expNo, loggingConf, statisticConf);
mTimer = new boost::asio::deadline_timer(*mIoService, boost::posix_time::millisec(probeInterval * 1000));
}
ChannelProber::~ChannelProber() {
mTimer->cancel();
delete mTimer;
free(mWifi);
nl_socket_modify_cb(mSocket, NL_CB_VALID, NL_CB_CUSTOM,
NULL, NULL);
nl_socket_free(mSocket);
mSocket = NULL;
}
void ChannelProber::init() {
int ret;
mWifi = (netinterface*) calloc(1, sizeof(netinterface));
mWifi->ifindex = if_nametoindex(mIfname.c_str());
if (mWifi->ifindex == 0) {
mLogger->logError("Error getting interface index for : " + mIfname );
mWifi->ifindex = -1;
mWifi->channel = -1;
exit(1);
}
mWifi->load.load = -1;
mWifi->load.totalTimeLast = 0;
mWifi->load.busyTimeLast = 0;
// initialize socket now
mSocket = nl_socket_alloc();
if (mSocket == NULL) {
mLogger->logError("Could not allocate netlink socket");
exit(1);
}
// disable sequence number checking. We want to receive notifications.
nl_socket_disable_seq_check(mSocket);
ret = nl_socket_modify_cb(mSocket, NL_CB_VALID, NL_CB_CUSTOM,
ChannelProber::receivedNetlinkMsg, this);
if(ret != 0) {
mLogger->logError("Failed to modify the callback");
exit(1);
}
// connect socket. Protocol: generic netlink
ret = genl_connect(mSocket);
if (ret != 0) {
mLogger->logError("Connection to netlink socket failed");
exit(1);
}
// resolve mNl80211Id
mNl80211Id = genl_ctrl_resolve(mSocket, "nl80211");
if (mNl80211Id < 0) {
mLogger->logError("Could not get NL80211 id");
exit(1);
}
mTimer->async_wait(boost::bind(&ChannelProber::probe, this, boost::asio::placeholders::error));
}
int ChannelProber::receivedNetlinkMsg(nl_msg *msg, void *arg) {
ChannelProber* cp = (ChannelProber*) arg;
struct nlattr *tb[NL80211_ATTR_MAX + 1];
struct genlmsghdr *gnlh = (genlmsghdr*) nlmsg_data(nlmsg_hdr(msg));
struct nlattr *sinfo[NL80211_SURVEY_INFO_MAX + 1];
char dev[20];
uint64_t total_time = 0, busy_time = 0;
uint32_t channel = 0;
int8_t noise;
nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
genlmsg_attrlen(gnlh, 0), NULL);
if_indextoname(nla_get_u32(tb[NL80211_ATTR_IFINDEX]), dev);
if (!tb[NL80211_ATTR_SURVEY_INFO]) {
cp->mLogger->logInfo("ChannelProber: survey data missing!");
return NL_SKIP;
}
static struct nla_policy survey_policy[NL80211_SURVEY_INFO_MAX + 1] = { };
if (nla_parse_nested(sinfo, NL80211_SURVEY_INFO_MAX,
tb[NL80211_ATTR_SURVEY_INFO], survey_policy)) {
cp->mLogger->logInfo("Failed to parse nested attributes");
return NL_SKIP;
}
// If this info is not about the channel in use, then skip
if (!sinfo[NL80211_SURVEY_INFO_IN_USE]) {
return NL_SKIP;
}
// Current channel in use
if (sinfo[NL80211_SURVEY_INFO_FREQUENCY]) {
channel = nla_get_u32(sinfo[NL80211_SURVEY_INFO_FREQUENCY]);
}
// Noise
if (sinfo[NL80211_SURVEY_INFO_NOISE]) {
noise = (int8_t) nla_get_u8(sinfo[NL80211_SURVEY_INFO_NOISE]);
}
// Total active time
if (sinfo[NL80211_SURVEY_INFO_CHANNEL_TIME]) {
total_time = nla_get_u64(sinfo[NL80211_SURVEY_INFO_CHANNEL_TIME]);
}
// Total busy time
if (sinfo[NL80211_SURVEY_INFO_CHANNEL_TIME_BUSY]) {
busy_time = nla_get_u64(sinfo[NL80211_SURVEY_INFO_CHANNEL_TIME_BUSY]);
}
// Do we need info about extension channel?
if (sinfo[NL80211_SURVEY_INFO_CHANNEL_TIME_EXT_BUSY]) {
// cout << "\textension channel busy time:\t"
// << nla_get_u64(sinfo[NL80211_SURVEY_INFO_CHANNEL_TIME_EXT_BUSY])
// << " ms" << endl;
}
// Total receiving time
if (sinfo[NL80211_SURVEY_INFO_CHANNEL_TIME_RX]) {
//cout << "\tchannel receive time:\t\t"
// << nla_get_u64(sinfo[NL80211_SURVEY_INFO_CHANNEL_TIME_RX])
// << " ms" << endl;
}
// Total transmitting time
if (sinfo[NL80211_SURVEY_INFO_CHANNEL_TIME_TX]) {
//cout << "\tchannel transmit time:\t\t"
// << nla_get_u64(sinfo[NL80211_SURVEY_INFO_CHANNEL_TIME_TX])
// << " ms" << endl;
}
// Update statistics
uint64_t busy_time_diff = busy_time - cp->mWifi->load.busyTimeLast;
uint64_t total_time_diff = total_time - cp->mWifi->load.totalTimeLast;
double load = ((100 * busy_time_diff) / total_time_diff) / 100.0;
cp->mWifi->load.mutexChannelLoad.lock();
cp->mWifi->load.load = load;
cp->mWifi->load.totalTimeLast = total_time;
cp->mWifi->load.busyTimeLast = busy_time;
cp->mWifi->load.noise = noise;
cp->mWifi->load.mutexChannelLoad.unlock();
//cp->mLogger->logStats(to_string(channel) + "\t" + to_string(busy_time_diff) + "\t" + to_string(total_time_diff) + "\t" + to_string(load));
return NL_SKIP;
}
void ChannelProber::probe(const boost::system::error_code &ec) {
sendNl80211(NL80211_CMD_GET_SURVEY, &mWifi->ifindex,
sizeof(mWifi->ifindex), NL80211_ATTR_IFINDEX, NL_AUTO_SEQ,
NLM_F_DUMP);
nl_recvmsgs_default(mSocket);
mTimer->expires_from_now(boost::posix_time::millisec(mProbeInterval * 1000));
mTimer->async_wait(boost::bind(&ChannelProber::probe, this, boost::asio::placeholders::error));
}
int ChannelProber::sendNl80211(uint8_t msgCmd, void *payload,
unsigned int length, int payloadType, unsigned int seq, int flags) {
return send(msgCmd, payload, length, payloadType, seq, mNl80211Id, flags,
0x01);
}
int ChannelProber::send(uint8_t msgCmd, void *payload, unsigned int length,
int attrType, unsigned int seq, int protocolId, int flags,
uint8_t protocolVersion) {
int ret = 0;
// create a new Netlink message
nl_msg *msg = nlmsg_alloc();
// create message header
if (genlmsg_put(msg, 0, seq, protocolId, 0, flags, msgCmd,
protocolVersion) == NULL) {
mLogger->logError("Failed to create netlink header for the message");
return -1;
}
// add message attributes (=payload)
if (length > 0) {
ret = nla_put(msg, attrType, length, payload);
if (ret < 0) {
mLogger->logError("Error when adding attributes");
return ret;
}
}
ret = nl_send_auto(mSocket, msg);
if (ret < 0) {
mLogger->logError("Error when sending the message");
}
nlmsg_free(msg);
return ret;
}
double ChannelProber::getChannelLoad() {
float load;
mWifi->load.mutexChannelLoad.lock();
load = mWifi->load.load;
mWifi->load.mutexChannelLoad.unlock();
return (double) load;
}
| 30.489879
| 149
| 0.727925
|
zdzaz
|
5f5e9fd25cd59621fe6a511bd6dbd83d414be0ca
| 2,799
|
cpp
|
C++
|
lambda/src/Lambda/core/io/EventLoop.cpp
|
lambda-sh/lambda
|
c96de4f2bd370718c6d14d7788444660b1a7838b
|
[
"MIT"
] | 5
|
2021-01-05T20:48:10.000Z
|
2021-11-03T02:11:02.000Z
|
lambda/src/Lambda/core/io/EventLoop.cpp
|
lambda-sh/lambda
|
c96de4f2bd370718c6d14d7788444660b1a7838b
|
[
"MIT"
] | 15
|
2021-01-05T20:41:57.000Z
|
2021-12-21T16:46:54.000Z
|
lambda/src/Lambda/core/io/EventLoop.cpp
|
lambda-sh/lambda
|
c96de4f2bd370718c6d14d7788444660b1a7838b
|
[
"MIT"
] | 2
|
2021-08-02T11:56:27.000Z
|
2021-08-15T09:48:40.000Z
|
#include <Lambda/core/io/EventLoop.h>
#include <Lambda/lib/Time.h>
namespace lambda::core::io {
/// @todo (C3NZ): Investigate into the amount of time needed to sleep by the
/// thread that this loop is running in.
/// @todo (C3NZ): Is this as performant as it can possibly be?
/// @todo (C3NZ): There is no way to currently turn this off when there should
/// be. Especially if this is running in another thread.
void EventLoop::Run() {
while (running_) {
std::this_thread::sleep_for(lib::Milliseconds(50));
UniqueAsyncTask next_task;
if (const bool has_next = event_queue_.try_dequeue(next_task); !has_next) {
continue;
}
const AsyncStatus task_status = next_task->GetStatus();
// Callback has expired.
if (task_status == AsyncStatus::Expired) {
LAMBDA_CORE_TRACE("Task [{0}] has expired", next_task->GetName());
continue;
}
// Still waiting to execute.
if (task_status == AsyncStatus::Deferred) {
const bool has_space = event_queue_.enqueue(std::move(next_task));
LAMBDA_CORE_ASSERT(
has_space,
"The Event loop has run out of space with {} nodes",
size_);
continue;
}
// Handle failure.
if (const AsyncResult result = next_task->Execute();
result == AsyncResult::Failure) {
LAMBDA_CORE_ERROR(
"Task [{}] has failed to execute.",
next_task->GetName());
continue;
}
LAMBDA_CORE_TRACE("Task [{0}] has completed.", next_task->GetName());
}
}
bool EventLoop::SetTimeout(
AsyncCallback callback, const uint32_t milliseconds) {
UniqueAsyncTask task = memory::CreateUnique<AsyncTask>(
std::move(callback),
lib::Time::Now(),
lib::Time::MillisecondsFromNow(milliseconds));
return Dispatch(std::move(task));
}
bool EventLoop::SetInterval(
AsyncCallback callback, const uint32_t milliseconds) {
UniqueAsyncTask task = memory::CreateUnique<AsyncTask>(
std::move(callback),
lib::Time::Now(),
lib::Time::MillisecondsFromNow(milliseconds));
return Dispatch(std::move(task));
}
bool EventLoop::Dispatch(
AsyncCallback callback, lib::Time execute_at, lib::Time expire_at) {
UniqueAsyncTask task = memory::CreateUnique<AsyncTask>(
std::move(callback), execute_at, expire_at);
return Dispatch(std::move(task));
}
/// TODO(C3NZ): Do we need to use std::move since objects with well
/// defined move semantics are copyable into the queue?
///
/// Private dispatch for putting the task into the queue.
bool EventLoop::Dispatch(UniqueAsyncTask task) {
const bool has_space = event_queue_.enqueue(std::move(task));
LAMBDA_CORE_ASSERT(
has_space, "The Event loop has run out of space with {} nodes", size_);
return has_space;
}
} // namespace lambda::core::io
| 31.449438
| 79
| 0.677385
|
lambda-sh
|
5f61743a147a6e425a8084d011ee0535e81958c5
| 3,213
|
cpp
|
C++
|
src/lib/classification/poset_classification/poset_classification_report_options.cpp
|
abetten/orbiter
|
5994d0868a26c37676d6aadfc66a1f1bcb715c4b
|
[
"RSA-MD"
] | 15
|
2016-10-27T15:18:28.000Z
|
2022-02-09T11:13:07.000Z
|
src/lib/classification/poset_classification/poset_classification_report_options.cpp
|
abetten/orbiter
|
5994d0868a26c37676d6aadfc66a1f1bcb715c4b
|
[
"RSA-MD"
] | 4
|
2019-12-09T11:49:11.000Z
|
2020-07-30T17:34:45.000Z
|
src/lib/classification/poset_classification/poset_classification_report_options.cpp
|
abetten/orbiter
|
5994d0868a26c37676d6aadfc66a1f1bcb715c4b
|
[
"RSA-MD"
] | 15
|
2016-06-10T20:05:30.000Z
|
2020-12-18T04:59:19.000Z
|
/*
* poset_classification_report_options.cpp
*
* Created on: Jul 31, 2021
* Author: betten
*/
#include "foundations/foundations.h"
#include "group_actions/group_actions.h"
#include "classification/classification.h"
using namespace std;
namespace orbiter {
namespace classification {
poset_classification_report_options::poset_classification_report_options()
{
f_select_orbits_by_level = FALSE;
select_orbits_by_level_level = 0;
f_select_orbits_by_stabilizer_order = FALSE;
select_orbits_by_stabilizer_order_so = 0;
f_select_orbits_by_stabilizer_order_multiple_of = FALSE;
select_orbits_by_stabilizer_order_so_multiple_of = 0;
f_include_projective_stabilizer = FALSE;
}
poset_classification_report_options::~poset_classification_report_options()
{
}
int poset_classification_report_options::read_arguments(
int argc, std::string *argv,
int verbose_level)
{
int i;
int f_v = (verbose_level >= 1);
if (f_v) {
cout << "poset_classification_report_options::read_arguments" << endl;
}
for (i = 0; i < argc; i++) {
if (stringcmp(argv[i], "-select_orbits_by_level") == 0) {
f_select_orbits_by_level = TRUE;
select_orbits_by_level_level = strtoi(argv[++i]);
}
else if (stringcmp(argv[i], "-select_orbits_by_stabilizer_order") == 0) {
f_select_orbits_by_stabilizer_order = TRUE;
select_orbits_by_stabilizer_order_so = strtoi(argv[++i]);
}
else if (stringcmp(argv[i], "-select_orbits_by_stabilizer_order_multiple_of") == 0) {
f_select_orbits_by_stabilizer_order_multiple_of = TRUE;
select_orbits_by_stabilizer_order_so_multiple_of = strtoi(argv[++i]);
}
else if (stringcmp(argv[i], "-include_projective_stabilizer") == 0) {
f_include_projective_stabilizer = TRUE;
}
else if (stringcmp(argv[i], "-end") == 0) {
if (f_v) {
cout << "-end" << endl;
}
break;
}
else {
cout << "poset_classification_report_options::read_arguments "
"unrecognized option " << argv[i] << endl;
exit(1);
}
} // next i
if (f_v) {
cout << "poset_classification_report_options::read_arguments done" << endl;
}
return i + 1;
}
void poset_classification_report_options::print()
{
//cout << "poset_classification_report_options::print:" << endl;
if (f_select_orbits_by_level) {
cout << "-select_orbits_by_level " << select_orbits_by_level_level << endl;
}
if (f_select_orbits_by_stabilizer_order) {
cout << "-select_orbits_by_stabilizer_order " << select_orbits_by_stabilizer_order_so << endl;
}
if (f_select_orbits_by_stabilizer_order_multiple_of) {
cout << "-select_orbits_by_stabilizer_order_multiple_of " << select_orbits_by_stabilizer_order_so_multiple_of << endl;
}
if (f_include_projective_stabilizer) {
cout << "-include_projective_stabilizer" << endl;
}
}
int poset_classification_report_options::is_selected_by_group_order(long int so)
{
if (f_select_orbits_by_stabilizer_order) {
if (select_orbits_by_stabilizer_order_so == so) {
return TRUE;
}
else {
return FALSE;
}
}
else if (f_select_orbits_by_stabilizer_order_multiple_of) {
if ((so % select_orbits_by_stabilizer_order_so_multiple_of) == 0) {
return TRUE;
}
else {
return FALSE;
}
}
else {
return TRUE;
}
}
}}
| 24.340909
| 120
| 0.73794
|
abetten
|
5f61d22453b8957c45e9a34d83111592934ea31f
| 2,041
|
cpp
|
C++
|
caffe_zyyszj/src/caffe/layers/split_data_layer.cpp
|
ZYYSzj/Selective-Joint-Fine-tuning
|
7dc6c30cd4768b526201986afef9b131bb94da81
|
[
"BSD-2-Clause"
] | 69
|
2017-04-18T03:50:16.000Z
|
2018-12-11T09:09:12.000Z
|
caffe_zyyszj/src/caffe/layers/split_data_layer.cpp
|
ZYYSzj/Selective-Joint-Fine-tuning
|
7dc6c30cd4768b526201986afef9b131bb94da81
|
[
"BSD-2-Clause"
] | 5
|
2017-08-14T14:47:29.000Z
|
2018-07-18T03:45:33.000Z
|
selective_joint_ft/additional_layers/split_data_layer.cpp
|
ZYYSzj/Selective-Joint-Fine-tuning
|
7dc6c30cd4768b526201986afef9b131bb94da81
|
[
"BSD-2-Clause"
] | 17
|
2017-05-02T06:47:48.000Z
|
2018-08-09T04:12:31.000Z
|
#include <cfloat>
#include <vector>
#include <fstream>
#include <sstream>
#include <iostream>
#include <opencv2/opencv.hpp>
#include "caffe/layers/split_data_layer.hpp"
#include "caffe/util/math_functions.hpp"
namespace caffe {
template <typename Dtype>
void SplitDataLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
split_num_ = this->layer_param_.split_data_param().split_num();
CHECK_LT(split_num_,bottom[0]->num());
CHECK_GT(split_num_,0);
}
template <typename Dtype>
void SplitDataLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
top[0]->Reshape({split_num_, bottom[0]->channels(), bottom[0]->height(), bottom[0]->width()});
top[1]->Reshape({(bottom[0]->num()-split_num_), bottom[0]->channels(), bottom[0]->height(), bottom[0]->width()});
}
template <typename Dtype>
void SplitDataLayer<Dtype>::Forward_cpu(
const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) {
int dim=bottom[0]->channels()*bottom[0]->height()*bottom[0]->width();
caffe_cpu_scale(split_num_*dim, Dtype(1.0), bottom[0]->cpu_data(), top[0]->mutable_cpu_data());
caffe_cpu_scale((bottom[0]->num()-split_num_)*dim, Dtype(1.0), bottom[0]->cpu_data()+split_num_*dim, top[1]->mutable_cpu_data());
}
template <typename Dtype>
void SplitDataLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {
int dim=bottom[0]->channels()*bottom[0]->height()*bottom[0]->width();
CHECK_EQ(split_num_*dim,top[0]->count());
CHECK_EQ((bottom[0]->num()-split_num_)*dim,top[1]->count());
caffe_cpu_scale(split_num_*dim, Dtype(1.0), top[0]->cpu_diff(), bottom[0]->mutable_cpu_diff());
caffe_cpu_scale((bottom[0]->num()-split_num_)*dim, Dtype(1.0), top[1]->cpu_diff(), bottom[0]->mutable_cpu_diff()+split_num_*dim);
}
#ifdef CPU_ONLY
STUB_GPU(SplitDataLayer);
#endif
INSTANTIATE_CLASS(SplitDataLayer);
REGISTER_LAYER_CLASS(SplitData);
} // namespace caffe
| 38.509434
| 131
| 0.709946
|
ZYYSzj
|
5f67e0c27ec38f883700e642b2d5e71605601ff2
| 712
|
cpp
|
C++
|
test/io/load_libsvm_subsampling.cpp
|
husk214/libsdm
|
7e4e72a60b0e37e6cceaa32c09b839a3895bfa40
|
[
"BSL-1.0"
] | 4
|
2017-01-15T14:57:26.000Z
|
2022-02-24T08:12:45.000Z
|
test/io/load_libsvm_subsampling.cpp
|
husk214/libsdm
|
7e4e72a60b0e37e6cceaa32c09b839a3895bfa40
|
[
"BSL-1.0"
] | null | null | null |
test/io/load_libsvm_subsampling.cpp
|
husk214/libsdm
|
7e4e72a60b0e37e6cceaa32c09b839a3895bfa40
|
[
"BSL-1.0"
] | 3
|
2017-01-26T01:29:16.000Z
|
2018-06-23T16:49:26.000Z
|
#include "io.hpp"
using namespace sdm;
using namespace Eigen;
using namespace std;
int main(int argc, char const *argv[]) {
if (argc > 4) {
std::string file_name = argv[1];
int sub_num_ins = atof(argv[2]);
int sub_num_fea = atof(argv[3]);
bool random_seed_flag = static_cast<bool>(atoi(argv[4]));
std::string output_file =
file_name + "_" + to_string(sub_num_ins) + "_" + to_string(sub_num_fea);
if (argc > 5)
output_file = (argv[5]);
Eigen::SparseMatrix<double, 1> sx;
Eigen::ArrayXd y;
load_libsvm_subsampling(sx, y, file_name, sub_num_ins, sub_num_fea,
random_seed_flag);
save_libsvm(sx, y, output_file);
}
return 0;
}
| 28.48
| 80
| 0.632022
|
husk214
|
5f70ba139aa3db79fce82817e042a9f16a76d476
| 712
|
cpp
|
C++
|
FastWindows.UI.Composition/CompositionMaskBrush.cpp
|
kennykerr/Minesweeper
|
6f28abab141d80725beb746073d994833075b862
|
[
"MIT"
] | 2
|
2019-06-13T16:29:07.000Z
|
2019-12-17T18:06:59.000Z
|
FastWindows.UI.Composition/CompositionMaskBrush.cpp
|
kennykerr/Minesweeper
|
6f28abab141d80725beb746073d994833075b862
|
[
"MIT"
] | null | null | null |
FastWindows.UI.Composition/CompositionMaskBrush.cpp
|
kennykerr/Minesweeper
|
6f28abab141d80725beb746073d994833075b862
|
[
"MIT"
] | 2
|
2019-09-21T13:15:58.000Z
|
2020-08-30T06:48:59.000Z
|
#include "pch.h"
#include "CompositionMaskBrush.h"
#include "CompositionMaskBrush.g.cpp"
namespace winrt::FastWindows::UI::Composition::implementation
{
FastWindows::UI::Composition::CompositionBrush CompositionMaskBrush::Mask()
{
throw hresult_not_implemented();
}
void CompositionMaskBrush::Mask(FastWindows::UI::Composition::CompositionBrush value)
{
throw hresult_not_implemented();
}
FastWindows::UI::Composition::CompositionBrush CompositionMaskBrush::Source()
{
throw hresult_not_implemented();
}
void CompositionMaskBrush::Source(FastWindows::UI::Composition::CompositionBrush value)
{
throw hresult_not_implemented();
}
}
| 29.666667
| 91
| 0.719101
|
kennykerr
|
5f71705e747482196f9be6a0ba892b3b2e48d97e
| 2,386
|
cpp
|
C++
|
src/test/demo_http.cpp
|
Harrand/Amethyst
|
0e107bbddf9ca85025fe7ff4b2a5cd684f9cac5d
|
[
"MIT"
] | null | null | null |
src/test/demo_http.cpp
|
Harrand/Amethyst
|
0e107bbddf9ca85025fe7ff4b2a5cd684f9cac5d
|
[
"MIT"
] | null | null | null |
src/test/demo_http.cpp
|
Harrand/Amethyst
|
0e107bbddf9ca85025fe7ff4b2a5cd684f9cac5d
|
[
"MIT"
] | null | null | null |
//
// Created by Harrand on 14/12/2018.
//
#include "socket.hpp"
#include "amethyst.hpp"
int main()
{
am::initialise();
using namespace am::net;
// UDP Example
/*
Socket socketA{{transmission::protocol::UDP, internet::protocol::IPV4}};
socketA.bind(80);
Socket socketB{{transmission::protocol::UDP, internet::protocol::IPV4}};
socketB.connect("127.0.0.1", 80);
while(1)
{
socketB.send("hi my name is harrand and this is a message whose size i cannot be bothered to calculate. i hope that the receiving socket is able to determine the correct size of this message so that they allocate enough size to see the true message within: ducks.");
std::cout << "socket A data received size = " << socketA.peek_receive_size() << "\n";
std::string received = socketA.receive_boundless().value_or("invalid data");
std::cout << received;
if(received != "invalid data")
break;
}
socketA.unbind();
socketB.unbind();
*/
// End UDP Example
// Connection Awaiting Example
Socket webserver{{}};
webserver.bind(80);
webserver.listen();
while(1)
{
auto conn = webserver.accept();
if(conn.has_value())
{
std::cout << "found connection.\n";
std::string rcv = webserver.receive_boundless().value_or("invalid");
std::cout << "data received:\n" << rcv << "\n";
break;
}
}
webserver.unbind();
// End Connection Awaiting Example
// TCP Example
/*
Socket socketA{{transmission::protocol::TCP, internet::protocol::IPV4}};
socketA.bind(80);
socketA.listen();
Socket socketB{{transmission::protocol::TCP, internet::protocol::IPV4}};
while(1)
{
socketB.connect("127.0.0.1", 80);
socketB.send("hello. this is some data, except that this data is being sent via TCP. pretty cool eh?");
std::optional<Address> possible_connection = socketA.accept();
if(possible_connection.has_value())
{
std::cout << "found connection!\n";
std::string received = socketA.receive_boundless().value_or("invalid data");
std::cout << "data received: " << received << "\n";
break;
}
}
socketA.unbind();
socketB.unbind();
*/
// End TCP Example
am::terminate();
}
| 33.605634
| 274
| 0.598491
|
Harrand
|
5f7bc0933e673eaa4dab2f2d05b26c0f54a16a68
| 1,768
|
cpp
|
C++
|
VkTest/VkTest/src/Core/KeyboardController.cpp
|
Yank1n/VkTest
|
1c7354bc694f35a21d65dcbe39fa4b1e6fc4eef9
|
[
"MIT"
] | null | null | null |
VkTest/VkTest/src/Core/KeyboardController.cpp
|
Yank1n/VkTest
|
1c7354bc694f35a21d65dcbe39fa4b1e6fc4eef9
|
[
"MIT"
] | null | null | null |
VkTest/VkTest/src/Core/KeyboardController.cpp
|
Yank1n/VkTest
|
1c7354bc694f35a21d65dcbe39fa4b1e6fc4eef9
|
[
"MIT"
] | null | null | null |
#include "KeyboardController.h"
void KeyboardController::Move(GLFWwindow* window, float dt, GameObject& gameObject) {
glm::vec3 rotate{ 0.0f };
if (glfwGetKey(window, m_Key.lookRight) == GLFW_PRESS) rotate.y += 1.0f;
if (glfwGetKey(window, m_Key.lookLeft) == GLFW_PRESS) rotate.y -= 1.0f;
if (glfwGetKey(window, m_Key.lookUp) == GLFW_PRESS) rotate.x += 1.0f;
if (glfwGetKey(window, m_Key.lookDown) == GLFW_PRESS) rotate.x -= 1.0f;
if (glm::dot(rotate, rotate) > std::numeric_limits<float>::epsilon()) {
gameObject.transform.rotation += m_LookSpeed * dt * glm::normalize(rotate);
}
gameObject.transform.rotation.x = glm::clamp(gameObject.transform.rotation.x, -1.5f, 1.5f);
gameObject.transform.rotation.y = glm::mod(gameObject.transform.rotation.y, glm::two_pi<float>());
float yaw = gameObject.transform.rotation.y;
const glm::vec3 forwardDir{ sin(yaw), 0.0f, cos(yaw) };
const glm::vec3 rightDir{ forwardDir.z, 0.0f, -forwardDir.x };
const glm::vec3 upDir{ 0.0f, -1.0f, 0.0f };
glm::vec3 moveDir{ 0.0f };
if (glfwGetKey(window, m_Key.moveForward) == GLFW_PRESS) moveDir += forwardDir;
if (glfwGetKey(window, m_Key.moveBackward) == GLFW_PRESS) moveDir -= forwardDir;
if (glfwGetKey(window, m_Key.moveRight) == GLFW_PRESS) moveDir += rightDir;
if (glfwGetKey(window, m_Key.moveLeft) == GLFW_PRESS) moveDir -= rightDir;
if (glfwGetKey(window, m_Key.moveUp) == GLFW_PRESS) moveDir += upDir;
if (glfwGetKey(window, m_Key.moveDown) == GLFW_PRESS) moveDir -= upDir;
if (glm::dot(moveDir, moveDir) > std::numeric_limits<float>::epsilon()) {
gameObject.transform.translation += m_MoveSpeed * dt * glm::normalize(moveDir);
}
}
| 52
| 103
| 0.667986
|
Yank1n
|
5f7d4ca5b2a12aad2d012a1d3d5e917d5eb15f8d
| 119,934
|
cpp
|
C++
|
src/vedaEMailClient/vedaEMailClient.cpp
|
vedatech/Veda_platform
|
5592cb0e43666b04df12eed1849a2a655de6feff
|
[
"MIT"
] | null | null | null |
src/vedaEMailClient/vedaEMailClient.cpp
|
vedatech/Veda_platform
|
5592cb0e43666b04df12eed1849a2a655de6feff
|
[
"MIT"
] | null | null | null |
src/vedaEMailClient/vedaEMailClient.cpp
|
vedatech/Veda_platform
|
5592cb0e43666b04df12eed1849a2a655de6feff
|
[
"MIT"
] | null | null | null |
#include "vedaEMailClient.h"
#include "ui_vedaEMailClient.h"
vedaEMailClient::vedaEMailClient(QWidget *parent) :
QWidget(parent),
ui(new Ui::vedaEMailClient)
{
ui->setupUi(this);
setWindowTitle("VEDA EMail client");
setWindowIcon(QIcon(":/Resources/veda-icon-512.png"));
//#ifdef MACOS
// setWindowIcon(QIcon(":/Resources/ico-coin.png"));
//#else
//#endif
if (LIBVEDAWALLET_NOERROR != veda_wallet_init_library(engine)){
exit(-1);
}
mainWindow = new (std::nothrow) MainWindow(this);
if (nullptr == mainWindow) exit(-1);
ui->AppLayout->addWidget(mainWindow);
connect_widgets();
init_server_thread();
connect_server_thread();
//QCoreApplication::applicationDirPath();
// QDir::setCurrent(executable_path);
read_ini_file();
error_timer = new (std::nothrow) QTimer(this);
error_timer->setSingleShot(true);
error_timer->setInterval(ERROR_INTERVAL);
connect(error_timer, SIGNAL(timeout()),
this, SLOT(error_timeout()));
autorenew_timer = new (std::nothrow) QTimer(this);
autorenew_timer->setSingleShot(true);
connect(autorenew_timer, SIGNAL(timeout()),
this, SLOT(on_refresh_Button_clicked()));
autoLogOutTimer = new (std::nothrow) QTimer(this);
autoLogOutTimer->setSingleShot(true);
connect(autoLogOutTimer, SIGNAL(timeout()),
this, SLOT(autoLogOut()));
}
vedaEMailClient::~vedaEMailClient()
{
// saveReadMessageList();
delete ui;
delete server;
server_thread->exit();
server_thread->deleteLater();
if (0 != wstk) veda_wallet_free(wstk);
veda_wallet_stop_library(engine);
}
void vedaEMailClient::connect_widgets()
{
qRegisterMetaType<GetMailByWIDType>("GetMailByWIDType");
connect(this, SIGNAL( get_email_by_wid(const std::string, const int, GetMailByWIDType)),
this, SLOT(email_by_wid_getter(const std::string, const int, GetMailByWIDType)));
connect(this, SIGNAL(got_email_locally(QString, const int, GetMailByWIDType, bool)),
this, SLOT(email_by_wid_placer(QString, const int, GetMailByWIDType, bool)));
connect(this, SIGNAL(allIncomingEmailsPlaced()),
this, SLOT(recipientCompleterRefresher()));
connect(this, SIGNAL(allOutcomingEmailsPlaced()),
this, SLOT(recipientCompleterRefresher()));
connect(mainWindow->ui->register_Button, SIGNAL(clicked()),
this, SLOT(begin_form_register_ButtonClicked()));
connect(mainWindow->ui->back_Button_3, SIGNAL(clicked()),
this, SLOT(registration_form_back_ButtonClicked()));
connect(mainWindow->ui->logOut_Button, SIGNAL(clicked()),
this, SLOT(on_logOut_Button_clicked()));
connect(mainWindow->ui->new_Button, SIGNAL(clicked()),
this, SLOT(main_menu_form_new_ButtonClicked()));
connect(mainWindow->ui->incoming_Button, SIGNAL(clicked()),
this, SLOT(main_menu_form_incoming_ButtonClicked()));
connect(mainWindow->ui->outcoming_Button, SIGNAL(clicked()),
this, SLOT(main_menu_form_outcoming_ButtonClicked()));
connect(mainWindow->ui->settings_Button, SIGNAL(clicked()),
this, SLOT(on_settings_Button_clicked()));
connect(mainWindow->ui->back_Button_4, SIGNAL(clicked()),
this, SLOT(settings_form_back_ButtonClicked()));
connect(mainWindow->ui->balance_Button, SIGNAL(clicked()),
this, SLOT(on_balance_Button_clicked()));
connect(mainWindow->ui->back_Button, SIGNAL(clicked()),
this, SLOT(balance_form_back_ButtonClicked()));
connect(mainWindow->ui->sign_up_Button, SIGNAL(clicked()),
this, SLOT(registration_form_sign_up_ButtonClicked()));
connect(mainWindow->ui->signIn_Button, SIGNAL(clicked()),
this, SLOT(begin_form_signIn_ButtonClicked()));
mainWindow->ui->login_lineEdit->installEventFilter(&dblClickFilter);
connect(&dblClickFilter, SIGNAL(doubleClick()),
this, SLOT(doubleClicked()));
connect(mainWindow->ui->login_lineEdit, SIGNAL(textChanged(const QString&)),
this, SLOT(begin_form_login_lineEdit_textChanged(const QString&)));
connect(mainWindow->ui->GetMoreMessagesButton, SIGNAL(clicked()),
this, SLOT(balance_form_getMoreMessages_ButtonClicked()));
connect(mainWindow->ui->decryptButton, SIGNAL(clicked()),
this, SLOT(read_letter_form_decrypt_ButtonClicked()));
connect(mainWindow->ui->button1Page8, SIGNAL(clicked()),
this, SLOT(read_letter_form_reply_ButtonClicked()));
connect(mainWindow->ui->button0Page6, SIGNAL(clicked()),
this, SLOT(new_letter_form_send_ButtonClicked()));
mainWindow->ui->lineEditPage6->installEventFilter(&dblClickFilter);
//button4-7Page3
connect(mainWindow->ui->button4Page3, SIGNAL(clicked()),
this, SLOT(incoming_message_list_form_first_ButtonClicked()));
connect(mainWindow->ui->button5Page3, SIGNAL(clicked()),
this, SLOT(incoming_message_list_form_prev_ButtonClicked()));
connect(mainWindow->ui->button6Page3, SIGNAL(clicked()),
this, SLOT(incoming_message_list_form_next_ButtonClicked()));
connect(mainWindow->ui->button7Page3, SIGNAL(clicked()),
this, SLOT(incoming_message_list_form_last_ButtonClicked()));
connect(mainWindow->ui->button0Page10, SIGNAL(clicked()),
this, SLOT(autoLogOutSettingsChanged()));
connect(mainWindow->ui->button1Page10, SIGNAL(clicked()),
this, SLOT(autoLogOutSettingsChanged()));
connect(mainWindow->ui->button2Page10, SIGNAL(clicked()),
this, SLOT(autoLogOutSettingsChanged()));
connect(mainWindow->ui->button3Page10, SIGNAL(clicked()),
this, SLOT(autoLogOutSettingsChanged()));
connect(mainWindow->ui->refresh_Button, SIGNAL(clicked()),
this, SLOT(on_refresh_Button_clicked()));
connect(mainWindow->ui->newLetterAttachButton, SIGNAL(clicked()),
this, SLOT(newLetterAttachButtonClicked()));
connect(mainWindow->ui->button2Page8, SIGNAL(clicked()),
this, SLOT(readMessageFormDeleteButtonClicked()));
// connect(mainWindow->ui->button0Page8, SIGNAL(clicked()),
// this, SLOT(fileToSaveChoosen()));
connect(mainWindow->ui->reg2ConfirmButton, SIGNAL(clicked()),
this, SLOT(reg2ConfirmButtonClicked()));
connect(mainWindow->ui->reg2BackButton, SIGNAL(clicked()),
this, SLOT(reg2BackButtonClicked()));
connect(mainWindow->ui->setPreferredNodeButton, SIGNAL(clicked()),
this, SLOT(setPreferredNodeButtonClicked()));
connect(mainWindow->ui->beginSettingsButton, SIGNAL(clicked()),
this, SLOT(beginSettingsButtonClicked()));
}
void vedaEMailClient::toggle_loading_screen(int index, bool on)
{
mainWindow->toggleLoadingScreen(index, on);
}
void vedaEMailClient::updateUnknownWalletsEverywhere()
{
//1. Подсказки вначале
fillBeginFormCompleter();
//2. Почта во внутреннюю переменную и на description label
fillDescriptionLabelMail();
}
void vedaEMailClient::init_server_thread()
{
server = new (std::nothrow) server_functions();
if (nullptr == server) exit(-1);
server_thread = new (std::nothrow) QThread(this);
if (nullptr == server_thread) exit(-1);
server->moveToThread(server_thread);
server_thread->start();
}
void vedaEMailClient::connect_server_thread()
{
qRegisterMetaType<uint64_t>("uint64_t");
qRegisterMetaType<json>("json");
connect(this, SIGNAL(server_reg_1(uint64_t, char *, char *, char *, int, char *, int, char *, int, char *)),
server, SLOT( reg_1(uint64_t, char *, char *, char *, int, char *, int, char *, int, char *)));
connect(server, SIGNAL( reg_1_res(int, bool, uint64_t)),
this, SLOT(server_from_reg_1(int, bool, uint64_t)));
connect(this, SIGNAL(server_reg_2(char *, int)),
server, SLOT(reg_2(char *, int)));
connect(server, SIGNAL(reg_2_res(int)),
this, SLOT(server_from_reg_2(int)));
connect(this, SIGNAL(server_auth(uint64_t, char *, char *, char *, int, char *, int, char *, int)),
server, SLOT( auth(uint64_t, char *, char *, char *, int, char *, int, char *, int)));
connect(server, SIGNAL( auth_res(uint64_t, int, char *, uint64_t, char *, uint64_t, uint64_t, char *, int)),
this, SLOT(server_from_auth(uint64_t, int, char *, uint64_t, char *, uint64_t, uint64_t, char *, int)));
connect(this, SIGNAL(server_get_tokens(uint64_t, bool)),
server, SLOT(get_tokens(uint64_t, bool)));
connect(server, SIGNAL(get_tokens_res(int, char *)),
this, SLOT(server_from_get_tokens(int, char *)));
connect(this, SIGNAL(server_send_tokens(uint64_t, int, char *, char *, uint64_t, char *, uint64_t, char *, uint64_t)),
server, SLOT( send_tokens(uint64_t, int, char *, char *, uint64_t, char *, uint64_t, char *, uint64_t)));
connect(server, SIGNAL( send_tokens_res(int)),
this, SLOT(server_from_send_tokens(int)));
connect(this, SIGNAL(server_get_email(uint64_t, char *, const int, GetMailByWIDType)),
server, SLOT( get_email(uint64_t, char *, const int, GetMailByWIDType)));
connect(server, SIGNAL( get_email_res(QString, const int, GetMailByWIDType, bool)),
this, SLOT(email_by_wid_placer(QString, const int, GetMailByWIDType, bool)));
connect(this, SIGNAL(decrementEmailsGotByWIDsCount()),
this, SLOT(emailByWIDIniFileDecrementer()));
connect(this, SIGNAL(server_get_wid_list_by_email(uint64_t, char *)),
server, SLOT( get_wid_list_by_email(uint64_t, char *)));
connect(server, SIGNAL( get_wid_list_by_email_res(json, int)),
this, SLOT(server_from_get_wid_list_by_email(json, int)));
connect(this, SIGNAL(server_create_empty_messages(uint64_t, char *, int, char *, char *, int)),
server, SLOT(create_empty_messages(uint64_t, char *, int, char *, char *, int)));
connect(server, SIGNAL(create_empty_messages_res(int)),
this, SLOT(server_from_create_empty_messages(int)));
connect(this, SIGNAL(server_nulify_wstk()), server, SLOT(nulify_wstk()));
}
void vedaEMailClient::read_ini_file()
{
if (readIniFileFirstTime){
executable_path = QStandardPaths::standardLocations(QStandardPaths::AppLocalDataLocation)[0];
// qDebug()<<"work dir path is " << executable_path;
if (!dir.cd(executable_path)){
dir.mkdir(executable_path);
dir.cd(executable_path);
}
if (!dir.cd(PATH_TO_VERSIONS_FOLDER)){
dir.mkdir(PATH_TO_VERSIONS_FOLDER);
dir.cd(PATH_TO_VERSIONS_FOLDER);
}
if (!dir.cd(PATH_TO_CURRENT_VERSION_FOLDER)){
dir.mkdir(PATH_TO_CURRENT_VERSION_FOLDER);
dir.cd(PATH_TO_CURRENT_VERSION_FOLDER);
}
if (!dir.cd(PATH_TO_BIN)){
dir.mkdir(PATH_TO_BIN);
dir.cd(PATH_TO_BIN);
}
executable_path = dir.absolutePath();
dir.setCurrent(executable_path);
if (!dir.cd(PATH_TO_ETC)){
dir.mkdir(PATH_TO_ETC);
}
dir.cd(executable_path);
if (!dir.cd(PATH_TO_WALLETS_DIR)){
dir.mkdir(PATH_TO_WALLETS_DIR);
}
dir.cd(executable_path);
readIniFileFirstTime = false;
}
if (nullptr == iniWrapper){
iniWrapper = new (std::nothrow) VedaIniWrapper(PATH_TO_INI_FILE, true);
}
verifyIniFile();
read_wallets();
read_address_book(true);
read_current_node();
readAutoLogOutSettings();
// read_start_money();
///\todo отсортировать адресную книгу, а также проверить ее содержимое на хуйню
}
void vedaEMailClient::verifyIniFile()
{
sortIniFile();
removeIniDuplicates();
///\todo другие необходимые проверки
iniWrapper->writeConfigFile();
}
void vedaEMailClient::sortIniFile()
{
QVector<std::string> sections;
sections << INI_FILE_CURRENT_NODE_SECTION;
sections << INI_FILE_AUTO_LOG_OUT_SECTION;
sections << INI_FILE_ADDRESS_BOOK_SECTION;
sections << INI_FILE_WALLETS_SECTION;
QVector<uint64_t> section_indexes;
for (int sectCount = 0, sectLimit = sections.size(); sectCount < sectLimit; sectCount++){
//1. Узнать, требуется ли сортировка
bool needToSort = false;
section_indexes.clear();
for (uint64_t i = 0, limit = iniWrapper->datas.size(); i < limit; i++) {
if (iniWrapper->datas[i].index == sections[sectCount]){
section_indexes << i;
}
}
if (1 == section_indexes.size() || 0 == section_indexes.size()) continue;
for (int i = 0, limit = section_indexes.size() - 1; i < limit; i++) {
if ((section_indexes[i + 1] - section_indexes[i]) > 1){
needToSort = true;
break;
}
}
if (!needToSort) continue;
else {
//2. Если сортировка требуется, отсортировать по месту первого нахождения элемента этой секции в инишнике
VedaIniEntry temp;
auto itBegin = iniWrapper->datas.begin();
for (int i = 1, limit = section_indexes.size(); i < limit; i++) {
if ((section_indexes[i] - section_indexes[i - 1]) > 1){ //место, в котором разрыв секции
temp.clear();
temp = iniWrapper->datas[section_indexes[i]];
iniWrapper->datas.erase(itBegin + section_indexes[i]);
iniWrapper->datas.insert(itBegin + section_indexes[i - 1] + 1, temp);
section_indexes[i] = section_indexes[i - 1] + 1;
}
}
}
}
}
void vedaEMailClient::removeIniDuplicates()
{
if (!iniWrapper->datas.empty()){
std::string name, value;
//секции считаются отсортированными, так что при смене секции цикл должен завершаться
std::string sectionName;
for (int i = 0, limit = iniWrapper->datas.size(); i < limit; i++){
name = iniWrapper->datas[i].name;
value = iniWrapper->datas[i].value;
sectionName = iniWrapper->datas[i].index;
for (int j = i + 1; j < iniWrapper->datas.size();) {
if (iniWrapper->datas[j].index != sectionName) break;
if ((name == iniWrapper->datas[j].name) && (value == iniWrapper->datas[j].value)){
limit--;
iniWrapper->datas.erase(iniWrapper->datas.begin() + j);
}
else j++;
}
}
}
}
void vedaEMailClient::read_wallets()
{
//1. Считать данные ini - уже считаны при открытии ini файла
//2. Считать реальные файлы в папке
if (dir.cd(PATH_TO_WALLETS_DIR)){
QStringList dirList = dir.entryList(QDir::Files | QDir::NoDotAndDotDot | QDir::NoSymLinks);
clear_dir_files_list(dirList);
dir.cd(executable_path);
//3. Удалить из ini несуществующие
//3.5. Также переименовать в unknown адреса, не соответствующие шаблону почты
if (!iniWrapper->datas.empty()){
bool found_first = false;
for (int i = 0, limit = iniWrapper->datas.size(); i < limit;){
if (0 == strcmp(INI_FILE_WALLETS_SECTION,iniWrapper->datas[i].index.c_str())){
found_first = true;
if (!dirList.contains(QString::fromStdString(iniWrapper->datas[i].value))){
limit--;
iniWrapper->datas.erase(iniWrapper->datas.begin() + i);
}
else {
if (!isEmailValidAddress(iniWrapper->datas[i].name)){
iniWrapper->datas[i].name = INI_FILE_UNKNOWN_MAIL;
}
//превентивно чистить dirList чтобы оставить только неучтенные в ini
dirList.removeOne(QString::fromStdString(iniWrapper->datas[i].value));
i++;
}
}
else if (found_first){
break;
}
else {
i++;
}
}
}
//4. удалить дубликаты - сделано в другом месте
//5. Добавить в ini неучтенные как unknown (WID)
if (!dirList.isEmpty()){
//5.1. Найти индекс вставки
int insertPlace = 0;
if (!iniWrapper->datas.empty()) {
bool section_found = false;
for (; insertPlace < iniWrapper->datas.size(); insertPlace++){
if (0 != strcmp(INI_FILE_WALLETS_SECTION, iniWrapper->datas[insertPlace].index.c_str())){
if (section_found) {
break;
}
else {
continue;
}
}
else {
section_found = true;
}
}
}
auto it = iniWrapper->datas.begin();
std::advance(it, insertPlace);
VedaIniEntry temp;
temp.index = INI_FILE_WALLETS_SECTION;
temp.name = INI_FILE_UNKNOWN_MAIL;
for (int i = 0; i < dirList.size(); i++){
temp.value = dirList[i].toLocal8Bit().data();
if (iniWrapper->datas.empty()
||
(insertPlace == iniWrapper->datas.size()) //если секции не было
)
{
iniWrapper->datas.push_back(temp);
insertPlace++;
}
else {
iniWrapper->datas.insert(it++, temp);
}
}
}
}
//6. Отсортировать ini по одинаковым Email'ам:
// if (!iniWrapper->datas.empty()){
// std::string mail;
// int size = iniWrapper->datas.size();
// int same_name_entries = 0;
// for (int i = 0; i < size; i += (1 + same_name_entries)){
// if (0 == strcmp(INI_FILE_WALLETS_SECTION, iniWrapper->datas[i].index.c_str())){
// mail = iniWrapper->datas[i].name;
// same_name_entries = 0;
// for (int j = i + 1; j < size; j++){
// if (0 != strcmp(INI_FILE_WALLETS_SECTION, iniWrapper->datas[j].index.c_str())) break;
// if (iniWrapper->datas[j].name == mail){
// if ((j - i) > ++same_name_entries){
// iniWrapper->datas.insert(iniWrapper->datas.begin() + i + 1 + same_name_entries,
// iniWrapper->datas[j]);
// iniWrapper->datas.erase(iniWrapper->datas.begin() + j + 1);
// j++;
// }
// }
// }
// }
// }
// }
sortSection(std::string(INI_FILE_WALLETS_SECTION));
//7. Перезаписать ini
iniWrapper->writeConfigFile();
//8. Заполнить completer
fillBeginFormCompleter();
}
void vedaEMailClient::read_address_book(bool withEMailsVerification)
{
//1. Считать ini - считано конструктором ini
if (withEMailsVerification){
//2. Удалить лажу
if (!iniWrapper->datas.empty()){
bool needToWrite = false;
for (int i = 0;i < iniWrapper->datas.size(); i++){
if (0 == strcmp(INI_FILE_ADDRESS_BOOK_SECTION, iniWrapper->datas[i].index.c_str())){
//лажа - если имя - не email или соответствующий адрес - не адрес
if (!isEmailValidAddress(iniWrapper->datas[i].name) ||
!wallet_file_name_is_valid(QString::fromStdString(iniWrapper->datas[i].value))){
iniWrapper->datas.erase(iniWrapper->datas.begin() + i);
needToWrite = true;
}
}
}
if (needToWrite){
iniWrapper->writeConfigFile();
}
}
}
//отсортировать по одинаковым email'ам
if (sortSection(std::string(INI_FILE_ADDRESS_BOOK_SECTION))){
iniWrapper->writeConfigFile();
}
//доставить completer в создание сообщения
recipientLineEditCompletions.clear();
std::vector<VedaIniEntry> entries;
if (0 < iniWrapper->getAllEntrysByName(INI_FILE_ADDRESS_BOOK_SECTION, entries)){
std::string lastEMail;
int toCompleterLastIndex = -1;
for (uint64_t i = 0, limit = entries.size(); i < limit; i++) {
if (entries[i].name == lastEMail){//найдена почта с более чем одним адресом
recipientLineEditCompletions[toCompleterLastIndex++] = QString::fromStdString(
entries[i - 1].name + " (" + entries[i - 1].value + ")"
);
recipientLineEditCompletions.push_back(QString::fromStdString(
entries[i].name + " (" + entries[i].value + ")"
));
}
else {
lastEMail = entries[i].name;
recipientLineEditCompletions.push_back(QString::fromStdString(
entries[i].name
));
toCompleterLastIndex++;
}
}
}
mainWindow->setCompleterOnRecipientLineEdit(recipientLineEditCompletions);
}
void vedaEMailClient::addWIDListToAddressBook(bool withVerification)
{
int i = 0;
int limit = iniWrapper->datas.size();
if (withVerification){
if (!iniWrapper->datas.empty()){
bool section_found = false;
for (;
(i < limit) && (!WIDsByMail.isEmpty());
i++) {
if (0 == strcmp(INI_FILE_ADDRESS_BOOK_SECTION, iniWrapper->datas[i].index.c_str())){
section_found = true;
//вставлять в inifile нужно только новые аккаунты
WIDsByMail.removeOne(iniWrapper->datas[i].value);
}
else if (section_found) {
break;
}
}
}
if (WIDsByMail.isEmpty()){
//не нужно ничего вставлять
return;
}
}
//1. Найти секцию
for (i = 0; i < limit; i++) {
if (0 == strcmp(iniWrapper->datas[i].index.c_str(), INI_FILE_ADDRESS_BOOK_SECTION)){
break;
}
}
if (!withVerification) {
//проверить тот случай, когда на самом деле нужная запись уже легла другим способом
}
//2. Вставить
VedaIniEntry temp;
temp.index = INI_FILE_ADDRESS_BOOK_SECTION;
temp.name = mainWindow->ui->lineEditPage6->text().toLocal8Bit().data();
if (i == limit){//секции не было
for (int j = 0, toInsert = WIDsByMail.size(); j < toInsert; j++) {
temp.value = WIDsByMail[j];
iniWrapper->datas.push_back(temp);
}
}
else {//секция была
//0. Найти место внутри секции для вставки
for (;
(i < limit)
&&
(0 == strcmp(INI_FILE_ADDRESS_BOOK_SECTION, iniWrapper->datas[i].index.c_str()));
i++) {
if (iniWrapper->datas[i].name < temp.name) continue;
else break;
}
//1. Вставить
auto it = iniWrapper->datas.begin();
for (int j = 0, toInsert = WIDsByMail.size(); j < toInsert; j++) {
temp.value = WIDsByMail[j];
if (i == limit){
iniWrapper->datas.push_back(temp);
}
else {
iniWrapper->datas.insert(it + i++, temp);
}
}
}
iniWrapper->writeConfigFile();
}
void vedaEMailClient::read_current_node()
{
std::vector<VedaIniEntry> vect;
int res;
if (1 != (res = iniWrapper->getAllEntrysByName(INI_FILE_CURRENT_NODE_SECTION, vect))){
if (1 < res){
bool ignore_first = true;
for (int i = 0, limit = iniWrapper->datas.size(); i < limit; i++){
if (0 == strcmp(INI_FILE_CURRENT_NODE_SECTION, iniWrapper->datas[i].index.c_str())){
if (!ignore_first){
iniWrapper->datas.erase(iniWrapper->datas.begin() + i--);
}
else {
ignore_first = false;
current_node = QString::fromStdString(vect[1].name);
}
}
}
}
else {
current_node = INI_FILE_CURRENT_NODE_GERMAN_IP; //INI_FILE_CURRENT_NODE_LOCAL_IP
VedaIniEntry temp;
temp.index = INI_FILE_CURRENT_NODE_SECTION;
temp.name = temp.value = INI_FILE_CURRENT_NODE_GERMAN_IP;
iniWrapper->datas.push_back(temp);
}
iniWrapper->writeConfigFile();
}
else {
current_node = QString::fromStdString(vect[0].name);
}
QStringList nums = current_node.split(".");
if (nums.size() != 4) return;
mainWindow->ui->preferredNodeLineEdit1->setText(nums[0]);
mainWindow->ui->preferredNodeLineEdit2->setText(nums[1]);
mainWindow->ui->preferredNodeLineEdit3->setText(nums[2]);
mainWindow->ui->preferredNodeLineEdit4->setText(nums[3]);
}
void vedaEMailClient::readAutoLogOutSettings()
{
if (!iniWrapper->datas.empty()){
bool First = true;
bool only = true;
for (int i = 0, limit = iniWrapper->datas.size(); i < limit; i++) {
if (0 == strcmp(INI_FILE_AUTO_LOG_OUT_SECTION, iniWrapper->datas[i].index.c_str())){
if (First){
First = false;
autoLogOutTimerMinuteRange = QString::fromStdString(iniWrapper->datas[i].value).toInt();
}
else {
only = false;
iniWrapper->datas.erase(iniWrapper->datas.begin() + i--);
limit--;
}
}
else if (!First) {
break;
}
}
if (First){
autoLogOutTimerMinuteRange = 0;
}
if (!only){
iniWrapper->writeConfigFile();
}
}
else {
autoLogOutTimerMinuteRange = 0;
}
if (0 == autoLogOutTimerMinuteRange){
mainWindow->ui->button0Page10->setChecked(true);
}
else if (1 == autoLogOutTimerMinuteRange){
mainWindow->ui->button1Page10->setChecked(true);
}
else if (2 == autoLogOutTimerMinuteRange){
mainWindow->ui->button2Page10->setChecked(true);
}
else {
mainWindow->ui->button3Page10->setChecked(true);
}
}
void vedaEMailClient::saveAutoLogOutSettings()
{
//считаем что запись одна, так как лишние были удалены при запуске программы
//секции отсортированы
//0. Найти место для вставки
int insertIndex = 0;
if (!iniWrapper->datas.empty()){
for (int limit = iniWrapper->datas.size(); insertIndex < limit; insertIndex++) {
if (0 == strcmp(INI_FILE_AUTO_LOG_OUT_SECTION, iniWrapper->datas[insertIndex].index.c_str())){
break;
}
}
}
//1. Вставить
if (insertIndex == iniWrapper->datas.size()){
VedaIniEntry temp;
temp.index = INI_FILE_AUTO_LOG_OUT_SECTION;
temp.name = INI_FILE_AUTO_LOG_OUT_NAME_FIELD;
temp.value = QString::number(autoLogOutTimerMinuteRange).toLocal8Bit().data();
iniWrapper->datas.push_back(temp);
}
else {
iniWrapper->datas[insertIndex].value = QString::number(autoLogOutTimerMinuteRange).toLocal8Bit().data();
}
iniWrapper->writeConfigFile();
}
void vedaEMailClient::fillBeginFormCompleter()
{
if (!iniWrapper->datas.empty()){
QStringList completions;
QString last;
bool first_same_mail = true;
for (int i = 0; i < iniWrapper->datas.size(); i++){
if (0 == strcmp(INI_FILE_WALLETS_SECTION, iniWrapper->datas[i].index.c_str())){
completions << QString::fromStdString(iniWrapper->datas[i].name);
if (last == completions.last()){
if (first_same_mail){
completions[completions.size() - 2] = last + " (" +
QString::fromStdString(iniWrapper->datas[i - 1].value) + ")";
first_same_mail = false;
}
completions.last() += " (" +
QString::fromStdString(iniWrapper->datas[i].value) + ")";
}
else if (QString(INI_FILE_UNKNOWN_MAIL) == completions.last()) {
completions.last() += " (" +
QString::fromStdString(iniWrapper->datas[i].value) + ")";
}
else {
last = completions.last();
first_same_mail = true;
}
}
}
mainWindow->setCompleterOnLoginLineEdit(completions);
}
}
void vedaEMailClient::fillDescriptionLabelMail()
{
std::string stdWID = current_wid.toLocal8Bit().data();
for (int i = 0; i < iniWrapper->datas.size(); i++){
if (0 == strcmp(INI_FILE_WALLETS_SECTION, iniWrapper->datas[i].index.c_str())){
if (iniWrapper->datas[i].value == stdWID){
current_mail_address = QString::fromStdString(
iniWrapper->datas[i].name
);
mainWindow->ui->mainMenuMaillabel->setText(current_mail_address);
mainWindow->ui->label11Page10->setText(current_mail_address);
}
}
}
}
void vedaEMailClient::save_wallets(QString mail_address, QString wallet)
{
if (wallet.isEmpty()) return;
//1. Найти место для вставки
int i = 0;
//Вставить в конец секции
for (; i < iniWrapper->datas.size(); i++){
if (0 == strcmp(INI_FILE_WALLETS_SECTION, iniWrapper->datas[i].index.c_str())) break;
}
for (; i < iniWrapper->datas.size(); i++){
if (0 != strcmp(INI_FILE_WALLETS_SECTION, iniWrapper->datas[i].index.c_str())) break;
}
VedaIniEntry temp;
temp.name = mail_address.toLocal8Bit().data();
temp.value = wallet.toLocal8Bit().data();
temp.index = INI_FILE_WALLETS_SECTION;
if (i == iniWrapper->datas.size()){
iniWrapper->datas.push_back(temp);
}
else {
iniWrapper->datas.insert(iniWrapper->datas.begin() + i, temp);
}
iniWrapper->writeConfigFile();
}
QString vedaEMailClient::find_new_wid()
{
if (!dir.cd(PATH_TO_WALLETS_DIR)) return "";
QStringList dirList = dir.entryList(QDir::Files | QDir::NoDotAndDotDot | QDir::NoSymLinks);
clear_dir_files_list(dirList);
dir.cd(executable_path);
//найти WID, не существующий в ini
QString WID;
for (int i = 0; i < iniWrapper->datas.size(); i++) {
if (0 == strcmp(INI_FILE_WALLETS_SECTION, iniWrapper->datas[i].index.c_str())){
WID = QString::fromStdString(iniWrapper->datas[i].value);
if (dirList.contains(WID)){
dirList.removeOne(WID);
}
}
}
if (1 == dirList.size()){//условие правильного нахождения несуществующего WID
return dirList[0];
}
else{
return "";
}
}
void vedaEMailClient::show_error_label(QLabel *error_label, QString error_text, bool error)
{
if (!errorLabels.contains(error_label)){
errorLabels << error_label;
}
if (error){
error_label->setText("<FONT COLOR=#F00000>" +
error_text +
"</FONT>");
}
else {
error_label->setText("<FONT COLOR=#00F000>" +
error_text +
"</FONT>");
}
error_timer->start();
}
char *vedaEMailClient::QString_to_char_array(QString str, int *len)
{
if (str.isEmpty())
return NULL;
int *l;
int ll;
if (nullptr == len){
l = ≪
}
else {
l = len;
}
*l = str.toLocal8Bit().size();
char *ret = (char *)malloc(*l + 1);
if (!ret)
return NULL;
memset(ret, 0x0, *l + 1);
memcpy(ret, str.toLocal8Bit().data(), *l);
return ret;
}
char *vedaEMailClient::std_string_to_char_array(string str, int *len)
{
if (str.empty()){
return NULL;
}
int *l;
int ll;
if (nullptr == len){
l = ≪
}
else {
l = len;
}
*l = str.size();
char *ret = (char *)malloc(*l + 1);
if (!ret){
return NULL;
}
memset(ret, 0x0, *l + 1);
memcpy(ret, str.c_str(), *l);
return ret;
}
char *vedaEMailClient::jsonToCharArray(json j, int *len)
{
return std_string_to_char_array(j.dump(), len);
}
char *vedaEMailClient::make_certificate(char *&mailToCheck, int *len)
{
char *res = NULL;
std::string temp;
int *l;
int ll;
json j;
if (nullptr == len){
l = ≪
}
else {
l = len;
}
mailToCheck = QString_to_char_array(
QString::fromStdString(std::string(mainWindow->ui->MailLineEdit1->text().toLocal8Bit().data()) +
std::string(mainWindow->ui->MailDogLineEdit->text().toLocal8Bit().data()) +
std::string(mainWindow->ui->MailLineEdit2->text().toLocal8Bit().data()) +
std::string(mainWindow->ui->MailDotLineEdit1->text().toLocal8Bit().data()) +
std::string(mainWindow->ui->MailLineEdit3->text().toLocal8Bit().data()))
);
if (NULL == mailToCheck){
return NULL;
}
j[JSON_CERT_FIO] = std::string(mainWindow->ui->first_name_lineEdit->text().toLocal8Bit().data()) +
std::string(" ") +
std::string(mainWindow->ui->last_name_lineEdit->text().toLocal8Bit().data());
j[JSON_CERT_CITY] = std::string(" ");
j[JSON_CERT_STATE] = std::string(" ");
j[JSON_CERT_COUNTRY] = std::string(mainWindow->ui->country_comboBox->currentText().toLocal8Bit().data());
j[JSON_CERT_EMAIL] = mailToCheck;
j[JSON_CERT_ORG] = std::string(" ");
j[JSON_CERT_ORG_UNIT] = std::string(" ");
temp = j.dump();
*l = temp.size();
res = (char *)malloc(*l + 1);
if (!res) return res;
memcpy(res, temp.c_str(), *l);
res[*l] = 0x0;
return res;
}
bool vedaEMailClient::wallet_file_name_is_valid(QString name)
{
return (DEFAULT_WID_SIZE == name.size());
}
void vedaEMailClient::fill_token_indexes_vectors()
{
incoming_letters_indexes.clear();
clear_letters_indexes.clear();
tokens_indexes.clear();
unReadIncomingMessages = 0;
int index = -1;
bool status = false;
// incoming_letters_indexes.fill(0, TIDsNTimes.size());
#ifndef VEDA_PROTO_BUF
json j;
#else
TokenPb::Token token;
#endif
std::string color_name;
std::string empty_token_compare_pattern = EMPTY_TOKEN_COLOR_NAME;
std::string empty_token_compare_pattern_2 = EMPTY_TOKEN_COLOR_NAME_2;
QString TID;
QMap<QString, int> RawTimesNIndexes;
// int indexToRemove;
for (auto it = j_tokens[JSON_BALANCE_MASS].begin(); it != j_tokens[JSON_BALANCE_MASS].end(); ++it){
index++;
try {
status = j_tokens[JSON_BALANCE_MASS][it.key()][JSON_BALANCE_STATUS].get<bool>();
} catch (...) {
qDebug()<<"json parse exception";
continue;
}
if (!status) {
continue;
}
try {
#ifndef VEDA_PROTO_BUF
j = get_token_json_by_vid(it.key());
if (j.empty()){
qDebug()<<"parse json failure";
continue;
}
#else
token = get_token_pb_by_vid(it.key());
if (!token.has_user() || !token.has_genesis()){
qDebug()<<"protobuf parse exception";
continue;
}
#endif
if (j_tokens[JSON_BALANCE_MASS][it.key()][JSON_BALANCE_TYPE].get<int>() == 0) {
tokens_indexes << index;
}
else {
#ifndef VEDA_PROTO_BUF
color_name = j[JSON_TOKEN_GENESIS][JSON_TOKEN_GENESIS_COLOR_NAME].get<std::string>();
#else
color_name = token.genesis().color_text();
#endif
if ((color_name == empty_token_compare_pattern) ||
(color_name == empty_token_compare_pattern_2)){
clear_letters_indexes << index;
}
else {
TID = QString::fromStdString(
#ifndef VEDA_PROTO_BUF
j[JSON_TOKEN_USER][JSON_TOKEN_USER_TID].get<std::string>()
#else
token.user().tid()
#endif
);
RawTimesNIndexes.insert(TIDsNRawTimes[TID], index);
// incoming_letters_indexes << index;
if (!currentReadVIDs.contains(it.key())){
unReadIncomingMessages++;
}
}
}
}
catch(...){
qDebug()<<"json parse exception";
continue;
}
}
//сделать список входящих отсортированным по убыванию времени
for (auto it = RawTimesNIndexes.begin(); it != RawTimesNIndexes.end(); it++) {
incoming_letters_indexes.push_front(it.value());
}
incoming_pages_num = incoming_letters_indexes.size() / LETTERS_PER_PAGE;
if (0 < (LastPageLetterCount = incoming_letters_indexes.size() % LETTERS_PER_PAGE)) {
incoming_pages_num++;
}
else {
LastPageLetterCount = LETTERS_PER_PAGE;
}
//IncomingButton text
updateIncomingButtonText();
}
void vedaEMailClient::show_current_balance_everywhere()
{
messagesAvailable = MIN(clear_letters_indexes.size(), tokens_indexes.size());
mainWindow->ui->message_available_count_label->setText(QString::number(messagesAvailable));
///\todo минимальное из количества комиссионных токенов и количества болванок
if (0 == messagesAvailable){
mainWindow->ui->new_Button->setDisabled(true);
}
else {
mainWindow->ui->new_Button->setEnabled(true);
}
if ((MESSAGES_AVAILABLE_MINIMUM_COUNT_TO_ALLOW_GET_MORE > messagesAvailable)
&&
(tokens_indexes.size() > (messagesAvailable + 1))
&&
(MAX_GET_MORE_MSGS_BTN_PRESSES > getMoreTokensButtonClickCount))//чтобы в результате возможных сообщений не стало меньше
{
mainWindow->ui->GetMoreMessagesButton->setEnabled(true);
}
else {
mainWindow->ui->GetMoreMessagesButton->setDisabled(true);
}
mainWindow->ui->label2Page2->setText(makeVDNFromNum(balance));
mainWindow->ui->label6Page10->setText(makeVDNFromNum(balance));
mainWindow->ui->label6Page2->setText(QString::number(messagesAvailable));
mainWindow->ui->label8Page2->setText(VDN_PER_MSG);
mainWindow->ui->label10Page2->setText(current_wid);
//settings
mainWindow->ui->label11Page10->setText(current_mail_address);
//m sent
mainWindow->ui->label2Page10->setText(QString::number(outcoming_message_list.size()));
//m recieved
mainWindow->ui->label4Page10->setText(QString::number(incoming_letters_indexes.size()));
}
void vedaEMailClient::fill_incoming_message_list()
{
ini_file_address_book_section_replaces_count_by_incoming = 0;
ini_file_address_book_section_replaces_by_incoming_was_from_server = false;
allIncomingQueryiesEnded = false;
//удалить предыдущие
message_list_item *temp;
if (!incoming_message_list.isEmpty()){
for(int i = 0, limit = incoming_message_list.size(); i < limit; i++){
temp = incoming_message_list.last();
incoming_message_list.removeLast();
delete temp;
}
}
//заполнить новыми
if (incoming_letters_indexes.isEmpty()){
allIncomingQueryiesEnded = true;
return;
}
json::iterator it;
#ifndef VEDA_PROTO_BUF
json token_j;
#else
TokenPb::Token token;
#endif
std::string author;
QString TID;
QString time;
QString rawTime;
// std::string color;
int attachmentsSize;
for(int i = 0; i < lettersToShow; i++){
it = j_tokens[JSON_BALANCE_MASS].begin();
std::advance(it, incoming_letters_indexes[current_first_incoming_letter + i]);
#ifndef VEDA_PROTO_BUF
token_j = get_token_json_by_vid(it.key());
if (token_j.empty()){
qDebug()<<"parse json failure";
continue;
}
#else
token = get_token_pb_by_vid(it.key());
if (!token.has_user() || !token.has_genesis()){
qDebug()<<"parse protobuf failure";
continue;
}
#endif
try {
#ifndef VEDA_PROTO_BUF
author = token_j[JSON_TOKEN_GENESIS][JSON_TOKEN_GENESIS_AUTHOR_ID].get<std::string>();
#else
author = token.genesis().author_id();
#endif
TID = QString::fromStdString(
#ifndef VEDA_PROTO_BUF
token_j[JSON_TOKEN_USER][JSON_TOKEN_USER_TID].get<std::string>()
#else
token.user().tid()
#endif
);
if (!TID.isEmpty()){
time = TIDsNTimes[TID];
rawTime = TIDsNRawTimes[TID];
}
#ifndef VEDA_PROTO_BUF
color = token_j[JSON_TOKEN_GENESIS][JSON_TOKEN_GENESIS_COLOR_NAME].get<std::string>();
#else
// color = token.genesis().color_text();
attachmentsSize = 0;
attachmentsSize += token.genesis().color_text_cnt();
for (int i = 0, limit = token.genesis().color_file_size(); i < limit; i++) {
attachmentsSize += token.genesis().color_file(i).len();
}
#endif
// colorSize = color.size();
} catch (...) {
qDebug()<<"parse json exception";
continue;
}
temp = new (std::nothrow) message_list_item(INI_FILE_UNKNOWN_MAIL,
time/* + "index in vector: " + QString::number(current_letters_vector_index - 1)*/,
rawTime,
sizeFromNum(attachmentsSize),
current_first_incoming_letter + i,
true,
mainWindow->ui->IncomingscrollAreaWidgetContents);
temp->set_wid(author);
if (currentReadVIDs.contains(it.key())){
temp->unsetBold();
}
mainWindow->addIncomingListItem(temp);
incoming_message_list << temp;
ini_file_address_book_section_replaces_count_by_incoming++;
connect(temp, SIGNAL(clicked()), this, SLOT(message_list_itemClicked()));
}
for (int i = 0, limit = incoming_message_list.size(); i < limit; i++) {
emit get_email_by_wid(incoming_message_list[i]->get_wid(), i, Incoming);
}
if (incoming_message_list.isEmpty()){
allIncomingQueryiesEnded = true;
}
}
void vedaEMailClient::fillOutcomingMessageList()
{
ini_file_address_book_section_replaces_count_by_outcoming = 0;
ini_file_address_book_section_replaces_by_outcoming_was_from_server = false;
allOutcomingQueryiesEnded = false;
//удалить предыдущие
message_list_item *temp;
if (!outcoming_message_list.isEmpty()){
for (int i = 0, limit = outcoming_message_list.size(); i < limit; i++){
temp = outcoming_message_list.last();
outcoming_message_list.removeLast();
delete temp;
}
}
TIDsNTimes.clear();
TIDsNRawTimes.clear();
//заполнить новыми
int i = 0;
int outcoming_index = 0;
auto it = j_trns.begin();
QString wid_sender;
QString wid_recipient;
std::string rawTime;
QString time;
QString TID;
for (; it != j_trns.end(); it++, i++){
try {
//определить что исходящая
wid_sender = QString::fromStdString(
it.value()[JSON_TRANSACTION_BODY][JSON_TRANSACTION_BODY_SENDER].get<std::string>()
);
wid_recipient = QString::fromStdString(
it.value()[JSON_TRANSACTION_BODY][JSON_TRANSACTION_BODY_RECIPIENT].get<std::string>()
);
rawTime = it.value()[JSON_TRANSACTION_BODY][JSON_TRANSACTION_BODY_TIME].get<std::string>();
time = getTimeFromTransaction(rawTime);
//если входящая - заполнить вектор времен
if (wid_sender != current_wid
||
wid_sender == wid_recipient) //если сам себе
{
TID = QString::fromStdString(
it.value()[JSON_TRANSACTION_BODY][JSON_TRANSACTION_BODY_TID].get<std::string>()
);
TIDsNTimes.insert(TID, time);
TIDsNRawTimes.insert(TID, QString::fromStdString(rawTime));
// RawTimesNTIDs.insert(QString::fromStdString(rawTime), TID);
// if (wid_sender != wid_recipient){
// //если не сам себе, не надо заполнять как исходящую
// continue;
// }
continue;
}
// else {
// }
// time = getTimeFromTransaction(it.value()[JSON_TRANSACTION_BODY][JSON_TRANSACTION_BODY_TIME].get<std::string>());
} catch (...) {
qDebug()<<"json exception";
continue;
}
temp = new (std::nothrow) message_list_item(INI_FILE_UNKNOWN_MAIL,
time,
QString::fromStdString(rawTime),
"",
-1,
false,
mainWindow->ui->OutcomingscrollAreaWidgetContents);
// temp->setStyleSheet("border: 2px solid lightgreen;");
temp->set_wid(
std::string(
wid_recipient.toLocal8Bit().data(), wid_recipient.toLocal8Bit().size()));
temp->unsetBold();
mainWindow->addOutcomingListItem(temp);
outcoming_message_list << temp;
ini_file_address_book_section_replaces_count_by_outcoming++;
// emit get_email_by_wid(wid_recipient, outcoming_index++, Outcoming);
}
sortMessageListByTime(Outcoming);
for (int i = 0, limit = outcoming_message_list.size(); i < limit; i++) {
emit get_email_by_wid(outcoming_message_list[i]->get_wid(), i, Outcoming);
}
if (0 == outcoming_index){
allOutcomingQueryiesEnded = true;
}
}
//int vedaEMailClient::get_current_open_wallet_index(QString mail_str)
//{
// QString address;
// //Если описание расширенное
// if (mail_str.contains("(")){
// address = mail_str.split("(")[1]; //взять все после "("
// address.chop(1); //удалить ")"
// std::string add(address.toStdString());
// for (int i = 0; i < mail_wallet_pairs.size(); i++){
// if (add == mail_wallet_pairs[i].value){
// return i;
// }
// }
// return -1;
// }
// else {
// std::string ml(mail_str.toStdString());
// for (int i = 0; i < mail_wallet_pairs.size(); i++){
// if (ml == mail_wallet_pairs[i].name){
// return i;
// }
// }
// return -1;
// }
//}
bool vedaEMailClient::isEmailValidAddress(std::string str)
{
QRegExp EmailRegExp("^[0-9a-zA-Z]+([0-9a-zA-Z]*[-._+])*[0-9a-zA-Z]+@[0-9a-zA-Z]+([-.][0-9a-zA-Z]+)*([0-9a-zA-Z]*[.])[a-zA-Z]{2,6}$");
return QString::fromStdString(str).contains(EmailRegExp);
}
bool vedaEMailClient::isWord(QString str, int minimumSize)
{
QRegExp wordRegExp("\\w");
if (0 != minimumSize){
if (str.size() < minimumSize) return false;
}
return str.contains(wordRegExp);
}
QString vedaEMailClient::get_WID_from_begin(int *index)
{
std::string temp;
QString login_string = mainWindow->ui->login_lineEdit->text();
if (login_string.contains("(")){//логин содержит WID в скобках
login_string.chop(1);
temp = login_string.split("(")[1].toLocal8Bit().data();
if (nullptr != index){
for (int i = 0;i < iniWrapper->datas.size(); i++) {
if (temp == iniWrapper->datas[i].value){
*index = i;
return QString::fromStdString(temp);
}
}
return QString();
}
}
else {//логин содержит только mail адрес
temp = login_string.toLocal8Bit().data();
int i = 0;
for (; i < iniWrapper->datas.size(); i++) {
if (0 == strcmp(INI_FILE_WALLETS_SECTION, iniWrapper->datas[i].index.c_str())){
if (temp == iniWrapper->datas[i].name){
if (nullptr != index) {
*index = i;
break;
}
}
}
}
if (i == iniWrapper->datas.size()){
//не было найдено совпадения
///\todo возможно, стоит попробовать обратиться к серверу чтобы получить адрес
return "";
}
else {
return QString::fromStdString(iniWrapper->datas[i].value);
}
}
}
void vedaEMailClient::clear_dir_files_list(QStringList &list)
{
for (int i = 0; i < list.size();){
if ((DEFAULT_WID_SIZE_WITH_P == list[i].size())
&& (list[i].contains("_p"))){
list[i].chop(2);
i++;
}
else {
list.removeAt(i);
}
}
}
char *vedaEMailClient::get_token_buffer_by_vid(const string &vid, int &len)
{
char *vid_ch = NULL;
int vid_ch_len = vid.size() + 1;
vid_ch = (char *)malloc(vid_ch_len);
if (!vid_ch){
return NULL;
}
memset(vid_ch, 0x0, vid_ch_len);
memcpy(vid_ch, vid.c_str(), vid_ch_len - 1);
char *token_ch = NULL;
if (LIBVEDAWALLET_NOERROR != veda_wallet_get_token_json_by_id(wstk,
vid_ch,
&token_ch,
len)){
qDebug()<<"cannot get token info";
free(vid_ch);
return NULL;
}
else {
free(vid_ch);
return token_ch;
}
}
#ifndef VEDA_PROTO_BUF
json vedaEMailClient::get_token_json_by_vid(const string &vid)
{
char *token_ch = get_token_buffer_by_vid(vid);
if (NULL == token_ch){
return json();
}
else {
json j = json::parse(std::string(token_ch));
free(token_ch);
return j;
}
}
#else
TokenPb::Token vedaEMailClient::get_token_pb_by_vid(const string &vid)
{
TokenPb::Token ret;
int bufLen = 0;
char *token_ch = get_token_buffer_by_vid(vid, bufLen);
if (NULL != token_ch){
ret.ParseFromArray(token_ch, bufLen);
free(token_ch);
}
return ret;
// serialize:
// ret.ByteSizeLong() потому что надо сразу выделить память
// ret.SerializeToArray()
//verify field existence
// ret.genesis().color_name().empty();
//setter:
// ret.mutable_user()->set_tid()
//getter:
// ret.user().tid()
}
#endif
char *vedaEMailClient::form_token_mas_by_index(int index, int *len)
{
if (j_tokens.empty()){
return NULL;
}
auto it = j_tokens[JSON_BALANCE_MASS].begin();
std::advance(it, index);
std::string vid = it.key();
#ifndef VEDA_PROTO_BUF
json j;
#else
TokenPb::Token token;
#endif
#ifndef VEDA_PROTO_BUF
j = get_token_json_by_vid(vid);
if (j.empty()){
qDebug()<<"Get token failure";
return NULL;
}
#else
token = get_token_pb_by_vid(vid);
if (!token.has_user() || !token.has_genesis()){
qDebug()<<"parse protobuf failure";
return NULL;
}
#endif
json j_buf;
#ifndef VEDA_PROTO_BUF
j_buf[vid][JSON_TRN_TOKEN_IN_NOMINAL] = j[JSON_TOKEN_GENESIS][JSON_TOKEN_GENESIS_NOMINAL];
j_buf[vid][JSON_TRN_TOKEN_IN_TID_TRN] = j[JSON_TOKEN_USER][JSON_TOKEN_USER_TID];
j_buf[vid][JSON_TRN_TOKEN_IN_HASH_TRN] = j[JSON_TOKEN_USER][JSON_TOKEN_USER_TID_HASH];
#else
j_buf[vid][JSON_TRN_TOKEN_IN_NOMINAL] = token.genesis().nominal();
j_buf[vid][JSON_TRN_TOKEN_IN_TID_TRN] = token.user().tid();
j_buf[vid][JSON_TRN_TOKEN_IN_HASH_TRN] = token.user().tid_hash();
#endif
vid = j_buf.dump();
return std_string_to_char_array(vid, len);
}
char *vedaEMailClient::get_vid_by_index(int index)
{
auto it = j_tokens[JSON_BALANCE_MASS].begin();
std::advance(it, index);
return std_string_to_char_array(it.key());
}
bool vedaEMailClient::get_wid_by_email_locally(QString email)
{
std::vector<VedaIniEntry> list;
if (0 == iniWrapper->getAllEntrysByName(INI_FILE_ADDRESS_BOOK_SECTION, list)){
return false;
}
else {
std::string emailString = email.toLocal8Bit().data();
WIDsByMail.clear();
for (uint64_t i = 0; i < list.size(); i++){
if (emailString == list[i].name){
WIDsByMail << list[i].value;
}
}
return !WIDsByMail.isEmpty();
// if (!WIDsByMail.isEmpty()) return true;
// return false;
}
}
void vedaEMailClient::finish_sending_message()
{
//0. Пресечь попытку отправить самому себе
if (recipient_wid == current_wid){
show_error_label(mainWindow->ui->NewLetterErrLabel, "Recipient must be another Veda User");
return;
}
//изменить COLOR_NAME
char *vid = get_vid_by_index(clear_letters_indexes[0]);
if (NULL == vid){
qDebug()<<"Low memory";
return;
}
//для того, чтобы адресат расшифровал, надо передать его WID
char *WIDr = NULL;
WIDr = QString_to_char_array(recipient_wid);
if (NULL == WIDr){
qDebug()<<"Low memory";
return;
}
// qDebug()<<"WIDr is set to " << WIDr << " " << strlen(WIDr);
char *jfileList = NULL;
int jfileListLen = 0;
if (0 < overallAttachmentsSize){
// json file, filesInfo;
// file[JSON_FILE_NAME] = std::string(
// fileToAttachName.toLocal8Bit().data()
// );
// filesInfo.push_back(file);
// jfileList = jsonToCharArray(filesInfo, &jfileListLen);
json file, filesInfo;
for (int i = 0, limit = outcomingFileButtons.size(); i < limit; i++){
file[JSON_FILE_NAME] = std::string(
outcomingFileButtons[i]->getFileNameWithPath().toLocal8Bit().data()
);
filesInfo.push_back(file);
jfileList = jsonToCharArray(filesInfo, &jfileListLen);
}
}
// else {//text
int color_name_len = 0;
char *color_name = NULL;
if (mainWindow->ui->newLetterPlainTextEdit->toPlainText().isEmpty()){
// color_name = QString_to_char_array("Attachments\n ↓", &color_name_len);
}
else {
color_name = QString_to_char_array(mainWindow->ui->newLetterPlainTextEdit->toPlainText(), &color_name_len);
if (NULL == color_name){
free(WIDr);
free(vid);
qDebug()<<"Low memory";
return;
}
}
if (LIBVEDAWALLET_NOERROR != veda_wallet_edit_marked_token_by_id(wstk,
vid,
WIDr,
color_name,
color_name_len,
jfileList,
jfileListLen)){
free(color_name);
free(WIDr);
free(vid);
if (jfileList) free(jfileList);
qDebug()<<"Error editing letter text";
return;
}
else {
free(color_name);
free(vid);
if (jfileList) free(jfileList);
}
// qDebug()<<"WIDr after editing is " << WIDr << " " << strlen(WIDr);
// }
//отправить
int token_mas_len = 0;
char *token_mas = form_token_mas_by_index(clear_letters_indexes[0], &token_mas_len);
if (NULL == token_mas){
free(WIDr);
qDebug()<<"Low memory";
return;
}
int com_mas_len = 0;
char *com_mas = form_token_mas_by_index(tokens_indexes[0], &com_mas_len);
if (NULL == com_mas){
free(token_mas);
free(WIDr);
qDebug()<<"Low memory";
return;
}
// qDebug()<<"WIDr before sending is " << WIDr << " " << strlen(WIDr);
emit server_send_tokens(wstk,
TRN_TRANSFER, ///\todo определить на свой ли кошелек идет отправка
WIDr,
token_mas,
token_mas_len,
com_mas,
com_mas_len);
startAutoRenewTimer();
startAutoLogOutTimer();
toggle_loading_screen(3, true);
}
QString vedaEMailClient::getTimeFromTransaction(string str_time)
{
QString raw = QString::fromStdString(str_time);
QStringList raw_list = raw.split(".");
if (0 == raw_list.size()){
return QString("");
}
else if (2 > raw_list.size()) {
raw_list << QString::number(0);
}
bool ok = false;
unsigned long secs = raw_list[0].toULong(&ok);
if (!ok) return QString("");
unsigned long msecs = raw_list[1].toULong(&ok);
if (!ok) return QString("");
struct tm *ptm;
ptm = localtime((time_t*)&secs);
char c_time[40] = {0x0};
strftime(c_time, sizeof(c_time), "%Y-%m-%d %H:%M:%S", ptm);
msecs /= 1000;
char c_ret[128] = {0x0};
sprintf(c_ret,"%s.%ld ", c_time, (long)msecs);
raw = c_ret;
//может в итоге не будет нужно, но сейчас есть:
//удаление миллисекунд
raw.chop(raw.size() - raw.lastIndexOf("."));
return raw;
}
void vedaEMailClient::get_mails_for_wallets_section()
{
//дойти до секции
int i = 0;
for (; i < iniWrapper->datas.size(); i++) {
if (0 == strcmp(INI_FILE_WALLETS_SECTION, iniWrapper->datas[i].index.c_str())) break;
}
if (i < iniWrapper->datas.size()){//секция есть
int section_begin = i;
//сосчитать, сколько замен требуется, они понадобятся для сигнала об окончании замен
QVector<int> indexesToEmit;
ini_file_wallets_section_replaces_count = 0;
for (; i < iniWrapper->datas.size(); i++){
if (0 == strcmp(INI_FILE_WALLETS_SECTION, iniWrapper->datas[i].index.c_str())){
if (0 == strcmp(INI_FILE_UNKNOWN_MAIL, iniWrapper->datas[i].name.c_str())){
ini_file_wallets_section_replaces_count++;
indexesToEmit << i;
}
}
else break;
}
//теперь отправить сигналы запроса почтового адреса
int limit = indexesToEmit.size();
if (0 < limit){
for (i = 0; i < limit; i++){
emit get_email_by_wid(iniWrapper->datas[indexesToEmit[i]].value, indexesToEmit[i], IniFileWalletsSection);
}
}
}
}
bool vedaEMailClient::hasStartMoney()
{
return walletsRecievedStartMoney.contains(current_wid);
}
void vedaEMailClient::startAutoRenewTimer()
{
// qDebug()<<"autorenew timer started";
autorenew_timer->start(AUTO_RENEW_TIMER_PERIOD);
}
QString vedaEMailClient::makeVDNFromNum(uint64_t num)
{
QString ret = QString::number(num);
// QString rret = ret.insert(ret.size() - 6, ",");
if (ret.size() <= 6){
return QString::number(0);
}
else {
ret.chop(6);
return ret;
}
}
void vedaEMailClient::renew_frontend()
{
fillOutcomingMessageList();
fill_token_indexes_vectors();
if (1 == incoming_pages_num || 0 == incoming_pages_num){
mainWindow->ui->button4Page3->hide();
mainWindow->ui->button5Page3->hide();
mainWindow->ui->button6Page3->hide();
mainWindow->ui->button7Page3->hide();
}
else {
mainWindow->ui->button4Page3->show();
mainWindow->ui->button5Page3->show();
mainWindow->ui->button6Page3->show();
mainWindow->ui->button7Page3->show();
}
incoming_message_list_form_first_ButtonClicked();
show_current_balance_everywhere();
}
void vedaEMailClient::startAutoLogOutTimer()
{
if (0 < autoLogOutTimerMinuteRange){
// qDebug()<<"autologout started for " << autoLogOutTimerMinuteRange << " minutes";
autoLogOutTimer->start(1000 * 60 * autoLogOutTimerMinuteRange);
}
else {
// qDebug()<<"autologout turned off";
autoLogOutTimer->stop();
}
}
bool vedaEMailClient::parseWIDsByMail()
{
if (1 == WIDsByMail.size()){
recipient_wid = QString::fromStdString(WIDsByMail[0]);
return true;
}
else if (1 < WIDsByMail.size()) {
// вставить в completions для newletter
QString strToFind = mainWindow->ui->lineEditPage6->text();
if (recipientLineEditCompletions.contains(strToFind)){
recipientLineEditCompletions.removeOne(strToFind);
}
QString strToInsert;
for (int i = 0; i < WIDsByMail.size(); i++) {
strToInsert = strToFind + " (" + QString::fromStdString(WIDsByMail[i]) + ")";
if (!recipientLineEditCompletions.contains(strToInsert)){
recipientLineEditCompletions.push_back(strToInsert);
}
}
mainWindow->setCompleterOnRecipientLineEdit(recipientLineEditCompletions);
show_error_label(mainWindow->ui->NewLetterErrLabel, "This Veda account have more than one adresses, choose one");
mainWindow->CompleteOnRecipientLineEdit();
// read_address_book(false);
}
else { //нет аккаунтов с таким email'ом
show_error_label(mainWindow->ui->NewLetterErrLabel, "This Veda account does not exist");
}
/*
show_error_label(mainWindow->ui->NewLetterErrLabel, "This Veda account have more than one adresses, choose one");
mainWindow->CompleteOnRecipientLineEdit();
*/
return false;
}
void vedaEMailClient::sortMessageListByTime(GetMailByWIDType type)
{
//выбрать список
QVector<message_list_item*> &list = Incoming == type ? incoming_message_list : outcoming_message_list;
//отсортировать по времени в порядке возрастания
QMap<QString, int> map;
for (int i = 0, limit = list.size(); i < limit; i++) {
map.insert(list[i]->getRawTime(), i);
}
//переставить
QVector<message_list_item*> newList;
message_list_item* temp;
while (!map.isEmpty()){
temp = list[map.last()];
newList << temp;
map.remove(map.lastKey());
Incoming == type ?
mainWindow->removeIncomingListItem(temp) :
mainWindow->removeOutomingListItem(temp);
}
list = newList;
for (int i = 0, limit = list.size(); i < limit; i++) {
Incoming == type ?
mainWindow->addIncomingListItem(list[i]) :
mainWindow->addOutcomingListItem(list[i]);
}
}
void vedaEMailClient::readReadMessageList()
{
if (nullptr != currentReadMessageStorage){
delete currentReadMessageStorage;
currentReadMessageStorage = nullptr;
}
char *fileName = QString_to_char_array(QString(PATH_TO_WALLETS_DIR) + "/" + current_wid + ".tmp");
currentReadMessageStorage = new (std::nothrow) VedaIniWrapper(fileName);
free(fileName);
currentReadVIDs.clear();
for (uint64_t i = 0, limit = currentReadMessageStorage->datas.size(); i < limit; i++) {
currentReadVIDs << currentReadMessageStorage->datas[i].name;
}
}
void vedaEMailClient::addMessageToReadMessageList(const std::string &vid)
{
currentReadVIDs << vid;
VedaIniEntry temp;
temp.index = READ_MESSAGE_LIST_SECTION;
temp.value = READ_MESSAGE_LIST_VALUE;
temp.name = vid;
int placeToInsert = 0;
for (uint64_t limit = currentReadMessageStorage->datas.size(); placeToInsert < limit; placeToInsert++) {
if (currentReadMessageStorage->datas[placeToInsert].name < vid){
continue;
}
else if (currentReadMessageStorage->datas[placeToInsert].name == vid){
placeToInsert = -1;
break;
}
else {
break;
}
}
if (-1 == placeToInsert) {
return;
}
else if (placeToInsert == currentReadMessageStorage->datas.size()){
currentReadMessageStorage->datas.push_back(temp);
}
else {
auto it = currentReadMessageStorage->datas.begin();
currentReadMessageStorage->datas.insert(it + placeToInsert, temp);
}
//только если сообщение было новым
//1. Сразу учесть это в файле
currentReadMessageStorage->writeConfigFile();
//2. Учесть это в кнопке
unReadIncomingMessages--;
updateIncomingButtonText();
}
void vedaEMailClient::saveReadMessageList()
{
if (nullptr != currentReadMessageStorage){
currentReadMessageStorage->writeConfigFile();
}
}
void vedaEMailClient::updateIncomingButtonText()
{
if (0 < unReadIncomingMessages){
mainWindow->ui->incoming_Button->setText(QString(INCOMING_BUTTON_DEFAULT_TEXT)
+ " ("
+ QString::number(unReadIncomingMessages)
+ ")");
}
else {
mainWindow->ui->incoming_Button->setText(INCOMING_BUTTON_DEFAULT_TEXT);
}
}
QString vedaEMailClient::sizeFromNum(int num)
{
if (0 > num) return QString("");
QString ret;
uint64_t s = num;
if (0 == (s >> 10)){
ret = QString::number(s) + " B";
return ret;
}
s >>= 10;
if (0 == (s >> 10)){
ret = QString::number(s) + " KB";
return ret;
}
s >>= 10;
if (0 == (s >> 10)){
ret = QString::number(s) + " MB";
return ret;
}
s >>= 10;
if (0 == (s >> 10)){
ret = QString::number(s) + " GB";
return ret;
}
s >>= 10;
if (0 == (s >> 10)){
ret = QString::number(s) + " TB";
return ret;
}
return QString("");
}
//QString vedaEMailClient::sizeFromColor(string str)
//{
// QString ret;
// uint64_t s = str.size();
// if (0 == (s >> 10)){
// ret = QString::number(s) + " B";
// return ret;
// }
// s >>= 10;
// if (0 == (s >> 10)){
// ret = QString::number(s) + " KB";
// return ret;
// }
// s >>= 10;
// if (0 == (s >> 10)){
// ret = QString::number(s) + " MB";
// return ret;
// }
// s >>= 10;
// if (0 == (s >> 10)){
// ret = QString::number(s) + " GB";
// return ret;
// }
// s >>= 10;
// if (0 == (s >> 10)){
// ret = QString::number(s) + " TB";
// return ret;
// }
// return QString("");
//}
QString vedaEMailClient::cutFileName(const QString &fileName)
{
return fileName.split("/").last();
}
void vedaEMailClient::deleteUncompletedBox()
{
veda_wallet_CryptoBoxDropBox(wstk);
veda_wallet_CryptoBoxFree(wstk);
emit server_nulify_wstk();
}
bool vedaEMailClient::sortSection(string sectionName)
{
if (!iniWrapper->datas.empty()){
bool wasSorted = false;
std::string mail;
int size = iniWrapper->datas.size();
int same_name_entries = 0;
for (int i = 0; i < size; i += (1 + same_name_entries)){
if (0 == strcmp(sectionName.c_str(), iniWrapper->datas[i].index.c_str())){
mail = iniWrapper->datas[i].name;
same_name_entries = 0;
for (int j = i + 1; j < size; j++){
if (0 != strcmp(sectionName.c_str(), iniWrapper->datas[j].index.c_str())) break;
if (iniWrapper->datas[j].name == mail){
if ((j - i) > ++same_name_entries){
iniWrapper->datas.insert(iniWrapper->datas.begin() + i + same_name_entries,
iniWrapper->datas[j]);
iniWrapper->datas.erase(iniWrapper->datas.begin() + j + 1);
// j--;
wasSorted = true;
}
}
}
}
}
return wasSorted;
}
else {
return false;
}
}
void vedaEMailClient::savePreferredNode(QString IP)
{
int index = 0;
int limit = 0;
if (0 < (limit = iniWrapper->datas.size())){
while (index < limit) {
if (0 == strcmp(iniWrapper->datas[index].index.c_str(), INI_FILE_CURRENT_NODE_SECTION))
break;
}
}
VedaIniEntry temp;
temp.index = INI_FILE_CURRENT_NODE_SECTION;
temp.name = temp.value = IP.toLocal8Bit().data();
if (index == limit){
iniWrapper->datas.push_back(temp);
}
else {
iniWrapper->datas[index].name = iniWrapper->datas[index].value = temp.name;
}
iniWrapper->writeConfigFile();
}
void vedaEMailClient::begin_form_signIn_ButtonClicked()
{
if (mainWindow->ui->login_lineEdit->text().isEmpty()){
show_error_label(mainWindow->ui->BeginErrLabel, "Login is empty");
return;
}
if (PASS_MIN_LEN > mainWindow->ui->password_lineEdit->text().size()){
show_error_label(mainWindow->ui->BeginErrLabel, "Password is too short");
return;
}
if (SECRET_MIN_LEN > mainWindow->ui->secret_lineEdit->text().size()){
show_error_label(mainWindow->ui->BeginErrLabel, "Secret phrase is too short");
return;
}
char *curnode = QString_to_char_array(current_node);
if (NULL == curnode){
qDebug()<<"low memory";
return;
}
current_wid = get_WID_from_begin(¤t_opened_wallet);
if (current_wid.isEmpty()){
free(curnode);
qDebug()<<"cannot recieve wallet address";
return;
}
int cryptobox_name_len;
char *cryptobox_name = QString_to_char_array(current_wid, &cryptobox_name_len);
if (NULL == cryptobox_name){
free(curnode);
qDebug()<<"low memory";
return;
}
int pass_len;
char *pass = QString_to_char_array(mainWindow->ui->password_lineEdit->text(), &pass_len);
if (NULL == pass){
free(cryptobox_name);
free(curnode);
qDebug()<<"low memory";
return;
}
int secret_len;
char *secret = QString_to_char_array(mainWindow->ui->secret_lineEdit->text(), &secret_len);
if (NULL == secret){
free(pass);
free(cryptobox_name);
free(curnode);
qDebug()<<"low memory";
return;
}
toggle_loading_screen(0, true);
emit server_auth(engine,
PATH_TO_WALLETS_DIR,
curnode,
cryptobox_name,
cryptobox_name_len,
pass,
pass_len,
secret,
secret_len);
startAutoRenewTimer();
startAutoLogOutTimer();
}
void vedaEMailClient::begin_form_register_ButtonClicked()
{
mainWindow->ui->stackedWidget->setCurrentIndex(9);
}
void vedaEMailClient::registration_form_sign_up_ButtonClicked()
{
// if (!isWord(mainWindow->ui->MailLineEdit1->text(), 2)){
// show_error_label(mainWindow->ui->RegErrorLabel, "Your Veda Account prefix is invalid or too short");
// return;
// }
// if (!isWord(mainWindow->ui->MailLineEdit2->text())){
// show_error_label(mainWindow->ui->RegErrorLabel, "Your Veda Account domain is invalid or too short");
// return;
// }
// if (!isWord(mainWindow->ui->MailLineEdit3->text(), 2)){
// show_error_label(mainWindow->ui->RegErrorLabel, "Your Veda Account suffix is invalid or too short");
// return;
// }
if (!isEmailValidAddress(
std::string(
QString(
mainWindow->ui->MailLineEdit1->text() +
mainWindow->ui->MailDogLineEdit->text() +
mainWindow->ui->MailLineEdit2->text() +
mainWindow->ui->MailDotLineEdit1->text() +
mainWindow->ui->MailLineEdit3->text()
).toLocal8Bit().data()
))){
show_error_label(mainWindow->ui->RegErrorLabel, "Your Veda Account name is not a valid email address");
return;
}
if (PASS_MIN_LEN > mainWindow->ui->password_lineEdit_3->text().size()){
show_error_label(mainWindow->ui->RegErrorLabel, "Your password is too short");
return;
}
if (mainWindow->ui->confirmPasswordLineEdit->text() != mainWindow->ui->password_lineEdit_3->text()){
show_error_label(mainWindow->ui->RegErrorLabel, "Your password confirm does not match your password");
return;
}
if (SECRET_MIN_LEN > mainWindow->ui->secret_lineEdit_3->text().size()){
show_error_label(mainWindow->ui->RegErrorLabel, "Your secret phrase is too short");
return;
}
if (mainWindow->ui->confirmSecretLineEdit->text() != mainWindow->ui->secret_lineEdit_3->text()){
show_error_label(mainWindow->ui->RegErrorLabel, "Your secret phrase confirm does not match your secret phrase");
return;
}
if (!isWord(mainWindow->ui->first_name_lineEdit->text())){
show_error_label(mainWindow->ui->RegErrorLabel, "Your first name is invalid or empty");
return;
}
if (!isWord(mainWindow->ui->last_name_lineEdit->text())){
show_error_label(mainWindow->ui->RegErrorLabel, "Your last name is invalid or empty");
return;
}
char *curnode = QString_to_char_array(current_node);
int pass_len;
char *pass = QString_to_char_array(mainWindow->ui->password_lineEdit_3->text(), &pass_len);
if (NULL == pass){
qDebug()<<"low memory";
return;
}
int secret_len;
char *secret = QString_to_char_array(mainWindow->ui->secret_lineEdit_3->text(), &secret_len);
if (NULL == secret){
free(pass);
qDebug()<<"low memory";
return;
}
int cert_len;
char *mailToCheck = NULL;
char *certificate = make_certificate(mailToCheck, &cert_len);
if (NULL == certificate){
free(pass);
free(secret);
qDebug()<<"low memory";
return;
}
regMail = mailToCheck;
emit server_reg_1(engine,
PATH_TO_WALLETS_DIR,
curnode,
pass,
pass_len,
secret,
secret_len,
certificate,
cert_len,
mailToCheck);
toggle_loading_screen(9, true);
}
void vedaEMailClient::registration_form_back_ButtonClicked()
{
mainWindow->ui->stackedWidget->setCurrentIndex(0);
}
void vedaEMailClient::on_logOut_Button_clicked()
{
veda_wallet_free(wstk);
// saveReadMessageList();
autorenew_timer->stop();
autoLogOutTimer->stop();
getMoreTokensButtonClickCount = 0;
currentIncomingPage = -1;
loggedIn = false;
mainWindow->ui->stackedWidget->setCurrentIndex(0);
// main_menu_form->hide();
// ui->description_label->clear();
// show_begin();
}
void vedaEMailClient::main_menu_form_new_ButtonClicked()
{
if (0 == mainWindow->ui->stackedWidgetPage3->currentIndex()) return;
mainWindow->ui->lineEditPage6->clear();
mainWindow->ui->newLetterPlainTextEdit->clear();
while (!outcomingFileButtons.isEmpty()) {
mainWindow->removeOutcomingFile(outcomingFileButtons.last());
delete outcomingFileButtons.last();
outcomingFileButtons.removeLast();
}
overallAttachmentsSize = 0;
// attachmentsGood = true;
mainWindow->ui->stackedWidgetPage3->setCurrentIndex(0);
}
void vedaEMailClient::main_menu_form_incoming_ButtonClicked()
{
if (1 == mainWindow->ui->stackedWidgetPage3->currentIndex()) return;
mainWindow->ui->stackedWidgetPage3->setCurrentIndex(1);
}
void vedaEMailClient::main_menu_form_outcoming_ButtonClicked()
{
if (2 == mainWindow->ui->stackedWidgetPage3->currentIndex()) return;
mainWindow->ui->stackedWidgetPage3->setCurrentIndex(2);
}
void vedaEMailClient::message_list_itemClicked()
{
message_list_item *temp = (message_list_item*)sender();
//0. Вписать автора
mainWindow->ui->lineEditPage3->setText(temp->get_author());
//1. Найти нужный токен и запросить его инфо
auto it = j_tokens[JSON_BALANCE_MASS].begin();
CurrentOpenedIncomingMessage = incoming_letters_indexes[temp->get_index()];
// read_letter_form->set_index(index_needed);
std::advance(it, CurrentOpenedIncomingMessage);
currentReadMessageVID = it.key();
//Сделать письмо прочитанным
temp->unsetBold();
addMessageToReadMessageList(currentReadMessageVID);
#ifndef VEDA_PROTO_BUF
json j;
#else
TokenPb::Token token;
#endif
#ifndef VEDA_PROTO_BUF
j = get_token_json_by_vid(currentReadMessageVID);
if (j.empty()){
qDebug()<<"parse json failure";
return;
}
#else
token = get_token_pb_by_vid(currentReadMessageVID);
if (!token.has_user() || !token.has_genesis()){
qDebug()<<"parse protobuf failure";
return;
}
#endif
//2. Взять поле с текстом
try {
mainWindow->ui->readLetterPlainTextEdit->clear();
#ifdef VEDA_PROTO_BUF
if (token.genesis().color_text_cnt() == 1){
#endif
mainWindow->ui->readLetterPlainTextEdit->setPlainText(
QString::fromStdString(
#ifndef VEDA_PROTO_BUF
j[JSON_TOKEN_GENESIS][JSON_TOKEN_GENESIS_COLOR_NAME].get<std::string>()
#else
token.genesis().color_text()
#endif
));
#ifdef VEDA_PROTO_BUF
}
#endif
} catch (...) {
qDebug()<<"taking data from token exception";
return;
}
#ifdef VEDA_PROTO_BUF
//3. Проверить вложенные файлы
readMessageFilesAttachedNames.clear();
readMessageFilesAttachedCount = 0;
fileAttachment *tempFA;
while (!incomingFileButtons.isEmpty()) {
tempFA = incomingFileButtons.last();
mainWindow->removeIncomingFile(tempFA);
delete tempFA;
incomingFileButtons.removeLast();
}
if (0 < (readMessageFilesAttachedCount = token.genesis().color_file_size())){
for (int i = 0; i < readMessageFilesAttachedCount; i++) {
readMessageFilesAttachedNames << QString::fromStdString(
token.genesis().color_file(i).name()
);
tempFA = new fileAttachment(true, readMessageFilesAttachedNames.last(), QString(),
token.genesis().color_file(i).len(),
mainWindow->ui->readMessageScrollAreaWidgetContents);
mainWindow->addIncomingFile(tempFA);
incomingFileButtons << tempFA;
connect(tempFA, SIGNAL(clicked(bool, const QString &)),
this, SLOT(fileButtonClicked(bool, const QString &)));
}
//обновить кнопку
// mainWindow->showReadMessageSaveFilesSection(readMessageFilesAttachedNames);
}
else {
// mainWindow->hideReadMessageSaveFilesSection();
}
#endif
if (mainWindow->ui->readLetterPlainTextEdit->toPlainText().isEmpty()){
// mainWindow->ui->decryptButton->setDisabled(true);
mainWindow->ui->decryptButton->hide();
}
else {
mainWindow->ui->decryptButton->setEnabled(true);
mainWindow->ui->decryptButton->show();
}
mainWindow->ui->stackedWidgetPage3->setCurrentIndex(3);
}
void vedaEMailClient::on_settings_Button_clicked()
{
mainWindow->ui->stackedWidget->setCurrentIndex(10);
}
void vedaEMailClient::settings_form_back_ButtonClicked()
{
if (loggedIn){
mainWindow->ui->stackedWidget->setCurrentIndex(3);
mainWindow->ui->stackedWidgetPage3->setCurrentIndex(1);
}
else {
mainWindow->ui->stackedWidget->setCurrentIndex(0);
mainWindow->ui->stackedWidgetPage3->setCurrentIndex(1);
}
}
void vedaEMailClient::on_balance_Button_clicked()
{
mainWindow->ui->stackedWidget->setCurrentIndex(2);
}
void vedaEMailClient::balance_form_back_ButtonClicked()
{
mainWindow->ui->stackedWidget->setCurrentIndex(3);
mainWindow->ui->stackedWidgetPage3->setCurrentIndex(1);
}
void vedaEMailClient::read_letter_form_decrypt_ButtonClicked()
{
auto it = j_tokens[JSON_BALANCE_MASS].begin();
std::advance(it, CurrentOpenedIncomingMessage);
// char *token_j_buf = NULL;
// int token_j_buf_len = 0;
// token_j_buf = get_token_buffer_by_vid(it.key(), token_j_buf_len);
// if (NULL == token_j_buf){
// qDebug()<<"get token failure";
// return;
// }
char *vid_ch = std_string_to_char_array(it.key());
if (NULL == vid_ch){
qDebug()<<"low memory";
return;
}
char *decrypted = NULL;
int decrypted_len = 0;
// if (LIBVEDAWALLET_NOERROR != veda_wallet_decrypt_marked_token(wstk,
if (LIBVEDAWALLET_NOERROR != veda_wallet_decrypt_marked_token_text(wstk,
// token_j_buf,
// token_j_buf_len,
vid_ch,
&decrypted,
decrypted_len)){
qDebug()<<"decrypt failure";
// free(token_j_buf);
free(vid_ch);
}
else {
mainWindow->ui->readLetterPlainTextEdit->setPlainText(decrypted);
// free(token_j_buf);
free(vid_ch);
free(decrypted);
}
mainWindow->ui->decryptButton->setDisabled(true);
}
void vedaEMailClient::new_letter_form_send_ButtonClicked()
{
//если что-то не заполнено - ничего не делать
if (mainWindow->ui->lineEditPage6->text().isEmpty() ||
(mainWindow->ui->newLetterPlainTextEdit->toPlainText().isEmpty() && (0 == overallAttachmentsSize))){
return;
}
// if (!attachmentsGood){
// show_error_label(mainWindow->ui->NewLetterErrLabel, "Attachments size must be less then 50MB");
// return;
// }
//если там мыло
if (isEmailValidAddress(mainWindow->ui->lineEditPage6->text().toLocal8Bit().data())){
// if (!get_wid_by_email_locally(mainWindow->ui->lineEditPage6->text())){
char *email = QString_to_char_array(mainWindow->ui->lineEditPage6->text());
emit server_get_wid_list_by_email(wstk,
email);
startAutoRenewTimer();
startAutoLogOutTimer();
toggle_loading_screen(3, true);
// }
// else {//если нашлось локально
// finish_sending_message();
// }
}
else if (mainWindow->ui->lineEditPage6->text().contains("(")) {//мыло с описанием адреса
recipient_wid = mainWindow->ui->lineEditPage6->text().split("(")[1];//WID + ")"
recipient_wid.chop(1);//WID
finish_sending_message();
}
else {//адрес
recipient_wid = mainWindow->ui->lineEditPage6->text();
finish_sending_message();
}
}
void vedaEMailClient::doubleClicked()
{
if (0 == mainWindow->ui->stackedWidget->currentIndex()){
mainWindow->ShowAllCompletionsOnLoginLineEdit();
}
else if (0 == mainWindow->ui->stackedWidgetPage3->currentIndex()) {
mainWindow->ShowAllCompletionsOnRecipientLineEdit();
}
}
void vedaEMailClient::error_timeout()
{
// _error_label->setText("");
for (int i = 0, limit = errorLabels.size(); i < limit; i++) {
errorLabels[i]->setText("");
}
}
void vedaEMailClient::begin_form_login_lineEdit_textChanged(const QString &text)
{
///\todo сделать подгон текста под размер если не будет сделано наоборот
}
void vedaEMailClient::autoLogOut()
{
// qDebug()<<"autologout";
mainWindow->ui->logOut_Button->click();
}
void vedaEMailClient::autoLogOutSettingsChanged()
{
int newOption;
if (mainWindow->ui->button0Page10->isChecked()){
newOption = 0;
}
else if (mainWindow->ui->button1Page10->isChecked()) {
newOption = 1;
}
else if (mainWindow->ui->button2Page10->isChecked()) {
newOption = 2;
}
else {
newOption = 3;
}
if (newOption != autoLogOutTimerMinuteRange){
// qDebug()<<"autologout option changed to " << newOption << " minutes";
autoLogOutTimerMinuteRange = newOption;
saveAutoLogOutSettings();
if (loggedIn){
startAutoLogOutTimer();
}
}
}
void vedaEMailClient::email_by_wid_getter(const string wid, const int index, GetMailByWIDType type)
{
QString ret;
//1. Найти локально
if (type != IniFileWalletsSection){
std::vector<VedaIniEntry> local;
if (0 != iniWrapper->getAllEntrysByName(INI_FILE_ADDRESS_BOOK_SECTION, local)){
for (int i = 0; i < local.size(); i++){
if (wid == local[i].value){
emit got_email_locally(QString::fromStdString(local[i].name), index, type);
return;
// return QString::fromStdString(iniWrapper->datas[i].name);
}
}
}
}
//2. Если локальный поиск успеха не дал, обратиться к серверу
char *wid_ch = std_string_to_char_array(wid);
if (NULL == wid_ch){
// return ret;
emit got_email_locally(QString(), index, type);
return;
}
toggle_loading_screen(3, true);
emit server_get_email(wstk, wid_ch, index, type);
startAutoRenewTimer();
startAutoLogOutTimer();
// char *email_ch = NULL;
// int email_ch_len = 0;
// if (LIBVEDAWALLET_NOERROR != veda_wallet_get_email(wstk,
// wid_ch,
// &email_ch,
// email_ch_len)){
// free(wid_ch);
//// return ret;
// }
// free(wid_ch);
// ret = email_ch;
//3. добавить в адресную книгу
// std::string section_name_string = INI_FILE_ADDRESS_BOOK_SECTION;
// for (int i = 0; i < iniWrapper->datas.size(); i++){
// if (iniWrapper->datas[i].index != section_name_string) continue;
// }
// return ret;
}
void vedaEMailClient::email_by_wid_placer(QString email, const int index, GetMailByWIDType type, bool from_server)
{
std::string wid;
if (Incoming == type){
if ((index >= incoming_message_list.size()) || email.isEmpty()) return;
wid = incoming_message_list[index]->get_wid();
incoming_message_list[index]->set_author(email);
}
else if (Outcoming == type) {
if ((index >= outcoming_message_list.size()) || email.isEmpty()) return;
wid = outcoming_message_list[index]->get_wid();
outcoming_message_list[index]->set_author(email);
}
else if (IniFileWalletsSection == type){
if ((index >= iniWrapper->datas.size()) || email.isEmpty()) return;
iniWrapper->datas[index].name = email.toLocal8Bit().data();
emit decrementEmailsGotByWIDsCount();
return;
}
if (from_server){
//Если пришло от сервера, добавить в адресную книгу в соответствующее алфавитному порядку место
toggle_loading_screen(3, false);
std::string email_string = email.toLocal8Bit().data();
VedaIniEntry temp;
temp.index = INI_FILE_ADDRESS_BOOK_SECTION;
temp.name = email_string;
temp.value = wid;
int i = 0;
for (; i < iniWrapper->datas.size(); i++){
if (0 == strcmp(iniWrapper->datas[i].index.c_str(), INI_FILE_ADDRESS_BOOK_SECTION)){
break;
}
}
bool pseudo_inserted = false;
if (i == iniWrapper->datas.size()){
//если этой секции в ini раньше не было
iniWrapper->datas.push_back(temp);
}
else{//если секция есть
bool inserted = false;
auto it = iniWrapper->datas.begin();
for (;
(i < iniWrapper->datas.size()) && !inserted;
i++) {
if (iniWrapper->datas[i].name > email_string){
iniWrapper->datas.insert(it + i,temp);
inserted = true;
}
else if (iniWrapper->datas[i].name == email_string) {
int j = i;
//вставить среди записей соответствующих данному email в алфавитном порядке wid'ов
for (;
(j < iniWrapper->datas.size()) &&
(0 == strcmp(INI_FILE_ADDRESS_BOOK_SECTION, iniWrapper->datas[j].index.c_str())) &&
(iniWrapper->datas[j].name == email_string);
j++){
//случай, когда надо вставить в конец, рассмотрен ниже
if (iniWrapper->datas[j].value < wid) continue;
else if (iniWrapper->datas[j].value == wid) {
pseudo_inserted = inserted = true;
break;
}
else {
iniWrapper->datas.insert(it + j,temp);
inserted = true;
break;
}
}
if (!inserted && !pseudo_inserted){//если вышел из секции, найдя такой же email
if (j == iniWrapper->datas.size()){
iniWrapper->datas.push_back(temp);
inserted = true;
}
else {
iniWrapper->datas.insert(it + j, temp);
inserted = true;
}
}
}
else{
continue;
}
}
//наконец, если секция была в конце и надо вставить в самый конец
if (!inserted) iniWrapper->datas.push_back(temp);
}
}
//отправить сигнал надо в конце чтобы все хорошо прочиталось
if (Incoming == type){
if (from_server){
// qDebug()<<"incoming placed from server";
ini_file_address_book_section_replaces_by_incoming_was_from_server = true;
}
if (0 == --ini_file_address_book_section_replaces_count_by_incoming){
// qDebug()<<"incoming to place: " << ini_file_address_book_section_replaces_count_by_incoming;
// qDebug()<<"all incoming placed";
allIncomingQueryiesEnded = true;
emit allIncomingEmailsPlaced();
}
}
else if (Outcoming == type) {
if (from_server){
// qDebug()<<"outcoming placed from server";
ini_file_address_book_section_replaces_by_outcoming_was_from_server = true;
}
if (0 == --ini_file_address_book_section_replaces_count_by_outcoming){
// qDebug()<<"outcoming to place: " << ini_file_address_book_section_replaces_count_by_outcoming;
// qDebug()<<"all outcoming placed";
allOutcomingQueryiesEnded = true;
emit allOutcomingEmailsPlaced();
}
}
// if (!pseudo_inserted) iniWrapper->writeConfigFile();
}
void vedaEMailClient::emailByWIDIniFileDecrementer()
{
if (0 == --ini_file_wallets_section_replaces_count){
updateUnknownWalletsEverywhere();
iniWrapper->writeConfigFile();
}
}
void vedaEMailClient::recipientCompleterRefresher()
{
if (allIncomingQueryiesEnded && allOutcomingQueryiesEnded){
if (ini_file_address_book_section_replaces_by_incoming_was_from_server ||
ini_file_address_book_section_replaces_by_outcoming_was_from_server){
iniWrapper->writeConfigFile();
read_address_book();
}
}
}
void vedaEMailClient::resetAutoLogOutTimer()
{
// qDebug()<<"activity";
startAutoLogOutTimer();
}
void vedaEMailClient::server_from_reg_1(int error, bool res, uint64_t _wstk)
{
// toggle_loading_screen();
toggle_loading_screen(9, false);
if (res){
wstk = _wstk;
// char *code = QString_to_char_array("leha-kartoha");
// if (NULL == code){
// veda_wallet_free(wstk);
// qDebug()<<"low memory";
// return;
// }
// emit server_reg_2(code, strlen(code));
mainWindow->ui->reg2MailLabel->setText(regMail);
mainWindow->ui->reg2CodeLineEdit->clear();
mainWindow->ui->reg2CodeLineEdit->setFocus();
mainWindow->ui->stackedWidget->setCurrentIndex(4);
}
else {
// if ((20011 == error) || (20012 == res) || (32 == error)){
// show_error_label(mainWindow->ui->RegErrorLabel, "error code: " + QString::number(error));
// }
// else {
show_error_label(mainWindow->ui->RegErrorLabel, "error code: " + QString::number(error));
// }
}
}
void vedaEMailClient::server_from_reg_2(int error)
{
toggle_loading_screen(4, false);
if (LIBVEDAWALLET_NOERROR == error){
registration_form_back_ButtonClicked();
save_wallets(mainWindow->ui->MailLineEdit1->text() +
mainWindow->ui->MailDogLineEdit->text() +
mainWindow->ui->MailLineEdit2->text() +
mainWindow->ui->MailDotLineEdit1->text() +
mainWindow->ui->MailLineEdit3->text(),
find_new_wid());
mainWindow->ui->first_name_lineEdit->clear();
mainWindow->ui->last_name_lineEdit->clear();
mainWindow->ui->password_lineEdit_3->clear();
mainWindow->ui->secret_lineEdit_3->clear();
mainWindow->ui->confirmPasswordLineEdit->clear();
mainWindow->ui->confirmSecretLineEdit->clear();
mainWindow->ui->MailLineEdit1->clear();
mainWindow->ui->MailLineEdit2->clear();
mainWindow->ui->MailLineEdit3->clear();
mainWindow->ui->reg2CodeLineEdit->clear();
read_wallets();
mainWindow->ui->back_Button_3->click();
show_error_label(mainWindow->ui->BeginErrLabel, "Account successfully registered", false);
}
else {
//reDo reg1
registration_form_sign_up_ButtonClicked();
show_error_label(mainWindow->ui->reg2ErrorLabel, "Invalid code from email (error code: " + QString::number(error) + ")");
}
}
void vedaEMailClient::server_from_auth(uint64_t _wstk, int error, char *token_mas, uint64_t token_mas_len, char *__balance, uint64_t _token_cnt, uint64_t marked_token_cnt, char *trn_list, int trn_list_size)
{
toggle_loading_screen(0, false);
if (LIBVEDAWALLET_NOERROR == error){
wstk = _wstk;
if (NULL != token_mas){
j_tokens = json::parse(std::string(token_mas, token_mas_len));
free(token_mas);
}
if (__balance) {
balance = (uint64_t)atoll(__balance);
free(__balance);
tokens_count = _token_cnt;
}
letters_count = marked_token_cnt;
if (NULL != trn_list){
j_trns = json::parse(std::string(trn_list, trn_list_size));
free(trn_list);
}
if (mainWindow->ui->login_lineEdit->text().contains("(")){
current_mail_address = mainWindow->ui->login_lineEdit->text().split("(")[0];
current_mail_address.chop(1);
}
else {
current_mail_address = mainWindow->ui->login_lineEdit->text();
}
mainWindow->ui->mainMenuMaillabel->setText(current_mail_address);
mainWindow->ui->login_lineEdit->clear();
mainWindow->ui->password_lineEdit->clear();
mainWindow->ui->secret_lineEdit->clear();
readReadMessageList();
renew_frontend();
mainWindow->ui->stackedWidget->setCurrentIndex(3);
mainWindow->ui->stackedWidgetPage3->setCurrentIndex(1);
// toggle_main_menu_upper_buttons(true);
// main_menu_form->show();
// switch_main_menu_content(incoming_message_list_form);
// main_menu_form->ui->incoming_Button->click();
// begin_form->hide();
get_mails_for_wallets_section();
loggedIn = true;
}
else {
show_error_label(mainWindow->ui->BeginErrLabel, "error code: " + QString::number(error));
autorenew_timer->stop();
autoLogOutTimer->stop();
}
}
void vedaEMailClient::server_from_get_tokens(int res, char *trns)
{
toggle_loading_screen(currentMainWindowIndex, false);
if ((LIBVEDAWALLET_NOERROR == res) || ignore_get_tokens_on_refresh){
ignore_get_tokens_on_refresh = false;
bool need_to_refresh_balance = true;
char *token_mas = NULL;
uint64_t token_mas_len = 0;
if (j_tokens.empty()
||
(j_tokens.count(JSON_BALANCE_MASS) && j_tokens[JSON_BALANCE_MASS].is_null())){
if (LIBVEDAWALLET_NOERROR != veda_wallet_form_token_mas(wstk,
&token_mas,
token_mas_len)){
//баланса не было и нет
need_to_refresh_balance = false;
}
}
else {//баланс был
std::string token_string = j_tokens.dump();
token_mas_len = token_string.size();
token_mas = (char *)malloc(token_mas_len + 1);
if ((NULL == token_mas) && (!token_string.empty())){
return;
}
memset(token_mas, 0x0, token_mas_len + 1);
memcpy(token_mas, token_string.c_str(), token_mas_len);
}
if (need_to_refresh_balance){
char *__balance = NULL;
char *token_mas_out = NULL;
uint64_t token_mas_len_out = 0;
int res = LIBVEDAWALLET_NOERROR;
if (LIBVEDAWALLET_NOERROR != (res = veda_wallet_refresh_balance(wstk,
token_mas,
token_mas_len,
&token_mas_out,
token_mas_len_out,
&__balance,
tokens_count,
letters_count))){
j_tokens.clear();
incoming_letters_indexes.clear();
tokens_indexes.clear();
tokens_count = 0;
letters_count = 0;
balance = 0;
}
else {
if (0 == token_mas_len_out){
token_mas_out = token_mas;
token_mas_len_out = token_mas_len;
}
else if (token_mas) free(token_mas);
}
balance = (uint64_t)atoll(__balance);
free(__balance);
j_tokens = json::parse(std::string(token_mas_out, token_mas_len_out));
free(token_mas_out);
//обновить транзакции
if (NULL != trns){
json j;
try {
j = json::parse(trns);
j_trns = j;
free(trns);
} catch (...) {
}
}
forceUpdateIncomingFirstPage = (LIBVEDAWALLET_NOERROR == res);
renew_frontend();
}
}
else {
if ((20011 == res) || (20012 == res) || (32 == res)){
show_error_label(mainWindow->ui->refreshErrorLabel, "Connection is lost. Log out and log in please");
}
else if (20013 == res) {
//не надо ничего делать, просто ничего нового нет
}
else {
show_error_label(mainWindow->ui->refreshErrorLabel, "error code: " + QString::number(res));
}
}
}
void vedaEMailClient::server_from_send_tokens(int res)
{
toggle_loading_screen(3, false);
///\todo возможно форма результата
if (LIBVEDAWALLET_NOERROR == res){
mainWindow->ui->lineEditPage6->clear();
mainWindow->ui->newLetterPlainTextEdit->clear();
/* ui->message_textEdit->clear();
ui->recipient_lineEdit->clear();*/
// new_letter_form->clear();
ignore_get_tokens_on_refresh = true;
mainWindow->ui->refresh_Button->click();
mainWindow->ui->incoming_Button->click();
}
else {
if ((20011 == res) || (20012 == res) || (32 == res)){
show_error_label(mainWindow->ui->NewLetterErrLabel, "Connection is lost. Log out and log in please");
}
else {
show_error_label(mainWindow->ui->NewLetterErrLabel, "error code: " + QString::number(res));
}
}
}
void vedaEMailClient::server_from_get_wid_list_by_email(json WIDs, int res)
{
toggle_loading_screen(3, false);
if (LIBVEDAWALLET_NOERROR == res){
if (!WIDs.empty()){
try {
// recipient_wid = QString::fromStdString(WIDs.begin().value().get<std::string>()); ///\todo обработать случай нескольких почт на одно мыло
WIDsByMail.clear();
for (auto it = WIDs.begin(); it != WIDs.end(); it++) {
WIDsByMail << it.value().get<std::string>();
}
} catch (...) {
qDebug()<<"error parsing json";
return;
}
}
//обработать различные варианты количества аккаунтов, связанных с email'ом
if (0 == WIDsByMail.size()){
show_error_label(mainWindow->ui->NewLetterErrLabel, "This Veda account does not exist");
}
else if (1 == WIDsByMail.size()){
recipient_wid = QString::fromStdString(WIDsByMail[0]);
if (!recipientLineEditCompletions.contains(mainWindow->ui->lineEditPage6->text())){
addWIDListToAddressBook(false);
read_address_book();
}
finish_sending_message();
}
else { // > 1
addWIDListToAddressBook();
read_address_book();
show_error_label(mainWindow->ui->NewLetterErrLabel, "This Veda account have more than one adresses, choose one");
mainWindow->CompleteOnRecipientLineEdit();
}
}
else {
if ((20011 == res) || (20012 == res) || (32 == res)){
show_error_label(mainWindow->ui->NewLetterErrLabel, "Connection is lost. Log out and log in please");
}
else if ((20025 == res) || (20010 == res)){
show_error_label(mainWindow->ui->NewLetterErrLabel, "Recipient account does not exist");
}
else {
show_error_label(mainWindow->ui->NewLetterErrLabel, "Recieving address information failure. Error code: " + QString::number(res));
}
}
}
void vedaEMailClient::server_from_create_empty_messages(int res)
{
toggle_loading_screen(2, false);
if (LIBVEDAWALLET_NOERROR == res){
show_error_label(mainWindow->ui->BalanceErrLabel, "Your messages were successfully created They will appear on your account soon", false);
mainWindow->ui->GetMoreMessagesButton->setDisabled(true);
getMoreTokensButtonClickCount++;
ignore_get_tokens_on_refresh = true;
mainWindow->ui->refresh_Button->click();
}
else {
if ((20011 == res) || (20012 == res) || (32 == res)){
show_error_label(mainWindow->ui->BalanceErrLabel, "Connection is lost. Log out and log in please");
}
else {
show_error_label(mainWindow->ui->BalanceErrLabel, "error code: " + QString::number(res));
}
}
}
void vedaEMailClient::on_refresh_Button_clicked()
{
currentMainWindowIndex = mainWindow->ui->stackedWidget->currentIndex();
toggle_loading_screen(currentMainWindowIndex, true);
emit server_get_tokens(wstk, ignore_get_tokens_on_refresh);
startAutoRenewTimer();
startAutoLogOutTimer();
}
void vedaEMailClient::settings_account_form_clear_local_address_book_ButtonClicked()
{
if (!iniWrapper->datas.empty()){
for (int i = 0; i < iniWrapper->datas.size();){
if (0 == strcmp(INI_FILE_ADDRESS_BOOK_SECTION, iniWrapper->datas[i].index.c_str())){
iniWrapper->datas.erase(iniWrapper->datas.begin() + i);
}
else {
i++;
}
}
iniWrapper->writeConfigFile();
}
}
void vedaEMailClient::read_letter_form_reply_ButtonClicked()
{
mainWindow->ui->new_Button->click();
mainWindow->ui->lineEditPage6->setText(mainWindow->ui->lineEditPage3->text());
mainWindow->ui->newLetterPlainTextEdit->clear();
}
void vedaEMailClient::incoming_message_list_form_next_ButtonClicked()
{
if (currentIncomingPage == (incoming_pages_num - 1)) return;
if (currentIncomingPage == (incoming_pages_num - 2)){
incoming_message_list_form_last_ButtonClicked();
}
else {
currentIncomingPage++;
lettersToShow = LETTERS_PER_PAGE;
current_first_incoming_letter += LETTERS_PER_PAGE;
}
fill_incoming_message_list();
}
void vedaEMailClient::incoming_message_list_form_prev_ButtonClicked()
{
if (0 == currentIncomingPage) return;
if (1 == currentIncomingPage){
incoming_message_list_form_first_ButtonClicked();
}
else {
currentIncomingPage--;
lettersToShow = LETTERS_PER_PAGE;
current_first_incoming_letter -= LETTERS_PER_PAGE;
}
fill_incoming_message_list();
}
void vedaEMailClient::incoming_message_list_form_first_ButtonClicked()
{
if (!forceUpdateIncomingFirstPage){
if (0 == currentIncomingPage) return;
}
currentIncomingPage = 0;
if (1 == incoming_pages_num){
lettersToShow = incoming_letters_indexes.size();
}
else {
lettersToShow = LETTERS_PER_PAGE;
}
current_first_incoming_letter = 0;
fill_incoming_message_list();
}
void vedaEMailClient::incoming_message_list_form_last_ButtonClicked()
{
if ((incoming_pages_num - 1) == currentIncomingPage) return;
currentIncomingPage = incoming_pages_num - 1;
lettersToShow = LastPageLetterCount;
current_first_incoming_letter = incoming_letters_indexes.size() - lettersToShow;
// mainWindow->ui->button7Page3->hide();
// mainWindow->ui->button6Page3->hide();
fill_incoming_message_list();
}
void vedaEMailClient::balance_form_getMoreMessages_ButtonClicked()
{
char *color_text = std_string_to_char_array(" ");
if (NULL == color_text){
qDebug()<<"Low memory";
return;
}
char *WIDR = QString_to_char_array(current_wid);
if (NULL == WIDR){
free(color_text);
qDebug()<<"Low memory";
return;
}
int com_mas_len = 0;
char *com_mass = form_token_mas_by_index(tokens_indexes[0], &com_mas_len);
emit server_create_empty_messages(wstk,
color_text,
MARKED_TOKENS_PER_COMISSION_TOKEN,
WIDR,
com_mass,
com_mas_len);
startAutoRenewTimer();
startAutoLogOutTimer();
toggle_loading_screen(2, true);
}
void vedaEMailClient::newLetterAttachButtonClicked()
{
QString fileToAttachName = QFileDialog::getOpenFileName(this,
"Choose file to attach. File must be less than 50MB",
QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation)[0],
"");
if (fileToAttachName.isEmpty()) return;
QFile fileToAttach(fileToAttachName);
if (!fileToAttach.open(QIODevice::ReadOnly)){
show_error_label(mainWindow->ui->NewLetterErrLabel, "Opening file error");
return;
}
uint64_t fileSize = 0;
fileSize = MAX(0, fileToAttach.size());
fileToAttach.close();
if (0 == fileSize){
show_error_label(mainWindow->ui->NewLetterErrLabel, "File is empty or corrupted");
return;
}
else if (MAX_FILE_SIZE < (fileSize + overallAttachmentsSize)){
show_error_label(mainWindow->ui->NewLetterErrLabel, "Attachments size must be less then 50MB");
// attachmentsGood = false;
return;
}
overallAttachmentsSize += fileSize;
fileAttachment *tempFA;
tempFA = new fileAttachment(false, cutFileName(fileToAttachName),
fileToAttachName, fileSize,
mainWindow->ui->newLetterScrollAreaWidgetContents);
mainWindow->addOutcomingFile(tempFA);
outcomingFileButtons << tempFA;
connect(tempFA, SIGNAL(clicked(bool, const QString &)),
this, SLOT(fileButtonClicked(bool, const QString &)));
}
void vedaEMailClient::readMessageFormDeleteButtonClicked()
{
char *vid_ch = NULL;
if (NULL == (vid_ch = std_string_to_char_array(currentReadMessageVID))){
qDebug()<<"low memory";
return;
}
int res = LIBVEDAWALLET_NOERROR;
if (LIBVEDAWALLET_NOERROR != (res = veda_wallet_delete_token_by_id(wstk, vid_ch))){
show_error_label(mainWindow->ui->NewLetterErrLabel, "Error deleting message, code: " + QString::number(res));
}
else {
ignore_get_tokens_on_refresh = true;
mainWindow->ui->refresh_Button->click();
mainWindow->ui->incoming_Button->click();
}
}
//void vedaEMailClient::fileToSaveChoosen()
//{
// QString SaveLocation;
// SaveLocation = QFileDialog::getSaveFileName(this,
// "Save file as",
// QStandardPaths::standardLocations(QStandardPaths::DownloadLocation)[0] +
// "/" +
// mainWindow->ui->button0Page8->text(),
// "");
// if (!SaveLocation.isEmpty()){
// QFile file(SaveLocation);
//// if (!file.open(QIODevice::WriteOnly)){
//// qDebug()<<"open file fail";
//// return;
//// }
//// else {
// // file.close();
// char *data = NULL;
// int dataLen = 0;
// char *curVID = std_string_to_char_array(currentReadMessageVID);
// if (NULL == curVID){
// qDebug()<<"low memory";
// return;
// }
// char *fileName = QString_to_char_array(mainWindow->ui->button0Page8->text());
// if (NULL == fileName){
// free(curVID);
// qDebug()<<"low memory";
// return;
// }
// int res = veda_wallet_decrypt_marked_token_file(wstk,
// curVID,
// fileName,
// &data,
// dataLen);
// free(curVID);
// free(fileName);
// if (LIBVEDAWALLET_NOERROR != res){
// qDebug()<<"decrypt file fail";
// return;
// }
// else {
// if (!file.open(QIODevice::WriteOnly)){
// qDebug()<<"open file fail";
// }
// else {
// file.write(data, dataLen);
// file.close();
// }
// free(data);
// }
//// }
// }
//}
void vedaEMailClient::fileButtonClicked(bool incoming, const QString &fileName/*, const QString &fileNameWithPath*/)
{
if (incoming){
//клик по входящему файлу приведет к его сохранению
QString SaveLocation;
SaveLocation = QFileDialog::getSaveFileName(this,
"Save file as",
QStandardPaths::standardLocations(QStandardPaths::DownloadLocation)[0] +
"/" +
fileName,
"");
if (!SaveLocation.isEmpty()){
QFile file(SaveLocation);
char *data = NULL;
int dataLen = 0;
char *curVID = std_string_to_char_array(currentReadMessageVID);
if (NULL == curVID){
qDebug()<<"low memory";
return;
}
char *_fileName = QString_to_char_array(fileName);
if (NULL == _fileName){
free(curVID);
qDebug()<<"low memory";
return;
}
int res = veda_wallet_decrypt_marked_token_file(wstk,
curVID,
_fileName,
&data,
dataLen);
free(curVID);
free(_fileName);
if (LIBVEDAWALLET_NOERROR != res){
qDebug()<<"decrypt file fail";
return;
}
else {
if (!file.open(QIODevice::WriteOnly)){
qDebug()<<"open file fail";
}
else {
file.write(data, dataLen);
file.close();
}
free(data);
}
}
}
else { //outcoming
//клик по исходящему файлу означает его удаление из списка прикрепленных
fileAttachment *_sender = (fileAttachment*)sender();
uint64_t fileSize = _sender->getFileSize();
if (overallAttachmentsSize < fileSize){
overallAttachmentsSize = 0;
}
else {
overallAttachmentsSize -= fileSize;
}
// if (MAX_FILE_SIZE > overallAttachmentsSize){
//// attachmentsGood = true;
// }
mainWindow->removeOutcomingFile(_sender);
outcomingFileButtons.removeOne(_sender);
disconnect(_sender, SIGNAL(clicked(bool, const QString &)),
this, SLOT(fileButtonClicked(bool, const QString &)));
delete _sender;
}
}
void vedaEMailClient::reg2ConfirmButtonClicked()
{
if (mainWindow->ui->reg2CodeLineEdit->text().size() != REG_2_CODE_SIZE){
show_error_label(mainWindow->ui->reg2ErrorLabel, "Code size is wrong");
return;
}
else {
int codeLen = 0;
char *code = QString_to_char_array(mainWindow->ui->reg2CodeLineEdit->text(), &codeLen);
if (NULL == code){
qDebug()<<"Low memory";
return;
}
toggle_loading_screen(4, true);
emit server_reg_2(code, codeLen);
}
}
void vedaEMailClient::reg2BackButtonClicked()
{
deleteUncompletedBox();
mainWindow->ui->stackedWidget->setCurrentIndex(9);
}
void vedaEMailClient::setPreferredNodeButtonClicked()
{
if (preferredNodeEditable){
if (mainWindow->ui->preferredNodeLineEdit1->text().isEmpty() ||
mainWindow->ui->preferredNodeLineEdit2->text().isEmpty() ||
mainWindow->ui->preferredNodeLineEdit3->text().isEmpty() ||
mainWindow->ui->preferredNodeLineEdit4->text().isEmpty()){
show_error_label(mainWindow->ui->settingsErrorLabel, "invalid IP address");
return;
}
mainWindow->ui->preferredNodeLineEdit1->setReadOnly(true);
mainWindow->ui->preferredNodeLineEdit2->setReadOnly(true);
mainWindow->ui->preferredNodeLineEdit3->setReadOnly(true);
mainWindow->ui->preferredNodeLineEdit4->setReadOnly(true);
savePreferredNode(
mainWindow->ui->preferredNodeLineEdit1->text() +
mainWindow->ui->preferredNodeDotLineEdit1->text() +
mainWindow->ui->preferredNodeLineEdit2->text() +
mainWindow->ui->preferredNodeDotLineEdit2->text() +
mainWindow->ui->preferredNodeLineEdit3->text() +
mainWindow->ui->preferredNodeDotLineEdit3->text() +
mainWindow->ui->preferredNodeLineEdit4->text()
);
show_error_label(mainWindow->ui->settingsErrorLabel, "Changes are saved. Restart Veda Email to apply them", false);
preferredNodeEditable = false;
mainWindow->ui->setPreferredNodeButton->setText(SET_PREFERRED_NODE_BUTTON_EDIT_TEXT);
}
else {
mainWindow->ui->preferredNodeLineEdit1->setReadOnly(false);
mainWindow->ui->preferredNodeLineEdit2->setReadOnly(false);
mainWindow->ui->preferredNodeLineEdit3->setReadOnly(false);
mainWindow->ui->preferredNodeLineEdit4->setReadOnly(false);
preferredNodeEditable = true;
mainWindow->ui->setPreferredNodeButton->setText(SET_PREFERRED_NODE_BUTTON_APPLY_TEXT);
mainWindow->ui->preferredNodeLineEdit1->setFocus();
}
}
void vedaEMailClient::beginSettingsButtonClicked()
{
on_settings_Button_clicked();
}
bool doubleClickFilter::eventFilter(QObject *obj, QEvent *ev)
{
if (ev->type() == QEvent::MouseButtonDblClick){
emit doubleClick();
}
return QObject::eventFilter(obj, ev);
}
bool InactivityFilter::eventFilter(QObject *obj, QEvent *ev)
{
if(ev->type() == QEvent::KeyPress ||
ev->type() == QEvent::MouseMove ||
ev->type() == QEvent::MouseButtonPress ||
ev->type() == QEvent::MouseButtonRelease ||
ev->type() == QEvent::MouseButtonDblClick)
emit activity();
return QObject::eventFilter(obj, ev);
}
| 33.213514
| 206
| 0.570122
|
vedatech
|
5f7dee38b98c8a217027242610347707acbfcb85
| 3,993
|
cc
|
C++
|
ChiTech/ChiMesh/VolumeMesher/Extruder/volmesher_extruder_utils.cc
|
zachhardy/chi-tech
|
18fb6cb691962a90820e2ef4fcb05473f4a6bdd6
|
[
"MIT"
] | 1
|
2021-06-15T12:57:35.000Z
|
2021-06-15T12:57:35.000Z
|
ChiTech/ChiMesh/VolumeMesher/Extruder/volmesher_extruder_utils.cc
|
zachhardy/chi-tech
|
18fb6cb691962a90820e2ef4fcb05473f4a6bdd6
|
[
"MIT"
] | 6
|
2020-08-17T16:27:12.000Z
|
2020-08-19T13:59:45.000Z
|
ChiTech/ChiMesh/VolumeMesher/Extruder/volmesher_extruder_utils.cc
|
Naktakala/chi-tech
|
df5f517d5aff1d167db50ccbcf4229ac0cb668c4
|
[
"MIT"
] | null | null | null |
#include "volmesher_extruder.h"
#include "chi_mpi.h"
extern ChiMPI& chi_mpi;
#include "chi_log.h"
extern ChiLog& chi_log;
//###################################################################
/**Computes the partition id of a template cell's projection onto 3D.*/
chi_mesh::Vector3
chi_mesh::VolumeMesherExtruder::ComputeTemplateCell3DCentroid(
const chi_mesh::CellPolygon& n_template_cell,
const chi_mesh::MeshContinuum& template_continuum,
int z_level_begin,int z_level_end)
{
chi_mesh::Vector3 n_centroid_precompd;
size_t tc_num_verts = n_template_cell.vertex_ids.size();
for (auto tc_vid : n_template_cell.vertex_ids)
{
auto temp_vert = template_continuum.vertices[tc_vid];
temp_vert.z = vertex_layers[z_level_begin];
n_centroid_precompd = n_centroid_precompd + temp_vert;
}
for (auto tc_vid : n_template_cell.vertex_ids)
{
auto temp_vert = template_continuum.vertices[tc_vid];
temp_vert.z = vertex_layers[z_level_end];
n_centroid_precompd = n_centroid_precompd + temp_vert;
}
n_centroid_precompd = n_centroid_precompd/(2*(double)tc_num_verts);
return n_centroid_precompd;
}
//###################################################################
/**Computes a cell's partition id based on a centroid.*/
int chi_mesh::VolumeMesherExtruder::
GetCellPartitionIDFromCentroid(chi_mesh::Vector3& centroid)
{
int px = options.partition_x;
int py = options.partition_y;
chi_mesh::Cell n_gcell(chi_mesh::CellType::GHOST);
n_gcell.centroid = centroid;
auto xyz_partition_indices = GetCellXYZPartitionID(&n_gcell);
int nxi = std::get<0>(xyz_partition_indices);
int nyi = std::get<1>(xyz_partition_indices);
int nzi = std::get<2>(xyz_partition_indices);
return nzi*px*py + nyi*px + nxi;
}
//###################################################################
/**Determines if a template cell is neighbor to the current partition.*/
bool chi_mesh::VolumeMesherExtruder::
IsTemplateCellNeighborToThisPartition(
const chi_mesh::CellPolygon& template_cell,
const chi_mesh::MeshContinuum& template_continuum,
int z_level,int tc_index)
{
int iz = z_level;
int tc = tc_index;
//========================= Loop over template cell neighbors
// for side neighbors
bool is_neighbor_to_partition = false;
for (auto& tc_face : template_cell.faces)
{
if (tc_face.has_neighbor)
{
auto n_template_cell = (chi_mesh::CellPolygon&)(
template_continuum.local_cells[tc_face.neighbor_id]);
auto n_centroid_precompd = ComputeTemplateCell3DCentroid(
n_template_cell, template_continuum, iz, iz+1);
int n_gcell_partition_id =
GetCellPartitionIDFromCentroid(n_centroid_precompd);
if (n_gcell_partition_id == chi_mpi.location_id)
{
is_neighbor_to_partition = true;
break;
}
}//if neighbor not border
}//for neighbors
//========================= Now look at bottom neighbor
//Bottom face
if (iz != 0)
{
auto n_template_cell = (chi_mesh::CellPolygon&)
(template_continuum.local_cells[tc]);
auto n_centroid_precompd = ComputeTemplateCell3DCentroid(
n_template_cell, template_continuum, iz-1, iz);
int n_gcell_partition_id =
GetCellPartitionIDFromCentroid(n_centroid_precompd);
if (n_gcell_partition_id == chi_mpi.location_id)
is_neighbor_to_partition = true;
}//if neighbor not border
//========================= Now look at top neighbor
//Top Face
if (iz != (vertex_layers.size()-2))
{
auto n_template_cell = (chi_mesh::CellPolygon&)
(template_continuum.local_cells[tc]);
auto n_centroid_precompd = ComputeTemplateCell3DCentroid(
n_template_cell, template_continuum, iz+1, iz+2);
int n_gcell_partition_id =
GetCellPartitionIDFromCentroid(n_centroid_precompd);
if (n_gcell_partition_id == chi_mpi.location_id)
is_neighbor_to_partition = true;
}//if neighbor not border
return is_neighbor_to_partition;
}
| 31.195313
| 72
| 0.682194
|
zachhardy
|
5f818f9475dd8d88af7f52f3e7b6fd09ace621dc
| 918
|
cpp
|
C++
|
code/walk_to_point/rotate_and_straight_by_boss.cpp
|
RoboticRobo/Mapping-robot
|
31d9443766482ea9793c6258b0b5178245689fd1
|
[
"MIT"
] | null | null | null |
code/walk_to_point/rotate_and_straight_by_boss.cpp
|
RoboticRobo/Mapping-robot
|
31d9443766482ea9793c6258b0b5178245689fd1
|
[
"MIT"
] | null | null | null |
code/walk_to_point/rotate_and_straight_by_boss.cpp
|
RoboticRobo/Mapping-robot
|
31d9443766482ea9793c6258b0b5178245689fd1
|
[
"MIT"
] | null | null | null |
void walk_to(double posx, double posy, double angle, int endx, int endy) {
cvNamedWindow("robot");
double diffx = abs(posx - endx);
double diffy = abs(posy - endy);
angle = angle - 180;
if (angle < 0) {
angle += 360;
}
double target_angle = atan(diffx / diffy);
target_angle = target_angle * 180 / M_PI;
double diff_angle = target_angle - angle;
if (abs(target_angle - angle) > 5) {
double vl, vr;
if (diff_angle > 0) {
vl = 1;
vr = -1;
}
else {
vr = 1;
vl = -1;
}
int velL = (int)(vl*Create_MaxVel);
int velR = (int)(vr*Create_MaxVel);
robot.DriveDirect(velL, velR);
cvWaitKey(20);
return;
}
if (diffx > 1 || diffy > 1)
{
double vx, vz;
vx = vz = 0.0;
vx = 1.0;
double vl = vx - vz;
double vr = vx + vz;
int velL = (int)(vl*Create_MaxVel);
int velR = (int)(vr*Create_MaxVel);
robot.DriveDirect(velL, velR);
cvWaitKey(20);
return;
}
}
| 16.105263
| 74
| 0.593682
|
RoboticRobo
|
5f8849b8ce469f7a3964ae045e2df48b913c9ff3
| 223
|
cpp
|
C++
|
Pbinfo/CMMMC.cpp
|
Al3x76/cpp
|
08a0977d777e63e0d36d87fcdea777de154697b7
|
[
"MIT"
] | 7
|
2019-01-06T19:10:14.000Z
|
2021-10-16T06:41:23.000Z
|
Pbinfo/CMMMC.cpp
|
Al3x76/cpp
|
08a0977d777e63e0d36d87fcdea777de154697b7
|
[
"MIT"
] | null | null | null |
Pbinfo/CMMMC.cpp
|
Al3x76/cpp
|
08a0977d777e63e0d36d87fcdea777de154697b7
|
[
"MIT"
] | 6
|
2019-01-06T19:17:30.000Z
|
2020-02-12T22:29:17.000Z
|
#include <iostream>
using namespace std;
int main(){
int a, b, aa, bb;
cin>>a>>b;
aa=a;
bb=b;
while(b){
int rest=a%b;
a=b;
b=rest;
}
cout<<(aa*bb)/a;
return 0;
}
| 10.619048
| 21
| 0.434978
|
Al3x76
|
5f932c96d1112c807e8069c6b60d434c05881c93
| 585
|
cpp
|
C++
|
test/mp/count.cpp
|
Cleyera/gdv
|
c89dd24898a58c4f905a4d53b6c2b262f2689b09
|
[
"MIT"
] | null | null | null |
test/mp/count.cpp
|
Cleyera/gdv
|
c89dd24898a58c4f905a4d53b6c2b262f2689b09
|
[
"MIT"
] | null | null | null |
test/mp/count.cpp
|
Cleyera/gdv
|
c89dd24898a58c4f905a4d53b6c2b262f2689b09
|
[
"MIT"
] | null | null | null |
#include <gdv/mp/test/test.h>
GDV_MP_TEST_CASE(count) {
using l1 = ::std::tuple<int, char, short>;
using l2 = ::std::tuple<int, int, int>;
using l3 = ::std::tuple<>;
GDV_MP_TEST_EQ((count<l1, int>::value), (size_t)1);
GDV_MP_TEST_EQ((count<l2, int>::value), (size_t)3);
GDV_MP_TEST_EQ((count<l3, int>::value), (size_t)0);
#ifdef GDV_MP_ENABLE_VARIABLE_TEMPLATES
GDV_MP_TEST_EQ((count_v<l1, int>), (size_t)1);
GDV_MP_TEST_EQ((count_v<l2, int>), (size_t)3);
GDV_MP_TEST_EQ((count_v<l3, int>), (size_t)0);
#endif // GDV_MP_ENABLE_VARIABLE_TEMPLATES
}
| 36.5625
| 55
| 0.664957
|
Cleyera
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.