text string | size int64 | token_count int64 |
|---|---|---|
#ifndef __BOARDINPUTCOMPONENT_H
#define __BOARDINPUTCOMPONENT_H
#include "InputComponent.hpp"
#include "SDL.h"
class BoardInputComponent : public InputComponent {
public:
virtual void update( GameState *obj, GameEngine *engine );
BoardInputComponent( GameBoard *board, SDL_Event *event );
~BoardInputComponent();
protected:
SDL_Rect **_squares;
int _rows;
int _columns;
static const int _tile_x_offset = 4;
static const int _tile_y_offset = 4;
static const int _tile_width = 142;
static const int _tile_height =142;
int _mouse_x;
int _mouse_y;
};
#endif /* __BOARDINPUTCOMPONENT_H */
| 618 | 231 |
#include "SPlisHSPlasH/Common.h"
#include "SPlisHSPlasH/TimeManager.h"
#include "Utilities/OBJLoader.h"
#include "SPlisHSPlasH/Utilities/SurfaceSampling.h"
#include "SPlisHSPlasH/Viscosity/ViscosityBase.h"
#include <fstream>
#include "SPlisHSPlasH/Simulation.h"
#include "FluidSimulator.h"
#include "Utilities/Timing.h"
#include "Utilities/Counting.h"
#include "Utilities/FileSystem.h"
#include "GazeboSceneLoader.h"
#include <memory>
// Enable memory leak detection
#ifdef _DEBUG
#ifndef EIGEN_ALIGN
#define new DEBUG_NEW
#endif
#endif
using namespace SPH;
using namespace Eigen;
using namespace std;
using namespace Utilities;
using namespace GenParam;
using namespace gazebo;
const std::string objFilePath("/tmp/");
FluidSimulator::FluidSimulator()
{
REPORT_MEMORY_LEAKS;
std::cout << "Plugin loaded" << std::endl;
}
void FluidSimulator::RunStep()
{
simulationSteps++;
base->timeStepNoGUI();
// publish all the boundary particles positions
this->publishFluidParticles();
this->publishBoundaryParticles();
}
FluidSimulator::~FluidSimulator()
{
this->connections.clear();
base->cleanup();
Utilities::Timing::printAverageTimes();
Utilities::Timing::printTimeSums();
Utilities::Counting::printAverageCounts();
Utilities::Counting::printCounterSums();
delete Simulation::getCurrent();
}
void FluidSimulator::publishBoundaryParticles()
{
msgs::Fluid boundary_particles_msg;
boundary_particles_msg.set_name("boundary_particles");
for (int i = 0; i < SPH::Simulation::getCurrent()->numberOfBoundaryModels(); ++i) //scene.boundaryModels.size(); ++i)
{
BoundaryModel_Akinci2012 *bm = static_cast<BoundaryModel_Akinci2012 *>(SPH::Simulation::getCurrent()->getBoundaryModel(i));
for (int j = 0; j < (int)bm->numberOfParticles(); j++)
{
ignition::math::Vector3d boundary_particles = ignition::math::Vector3d(
bm->getPosition(j)[0],
bm->getPosition(j)[1],
bm->getPosition(j)[2]);
gazebo::msgs::Set(boundary_particles_msg.add_position(), boundary_particles);
}
}
this->rigidObjPub->Publish(boundary_particles_msg);
}
void FluidSimulator::publishFluidParticles()
{
if (simulationSteps % 5 == 0)
{
msgs::Fluid fluid_positions_msg;
fluid_positions_msg.set_name("fluid_positions");
for (unsigned int j = 0; j < Simulation::getCurrent()->numberOfFluidModels(); j++)
{
FluidModel *model = Simulation::getCurrent()->getFluidModel(j);
//std::cout << "Density " << model->getViscosityBase()->VISCOSITY_COEFFICIENT << std::endl;;
for (unsigned int i = 0; i < model->numActiveParticles(); ++i)
{
gazebo::msgs::Set(fluid_positions_msg.add_position(),
ignition::math::Vector3d(
model->getPosition(i)[0],
model->getPosition(i)[1],
model->getPosition(i)[2]));
}
this->fluidObjPub->Publish(fluid_positions_msg);
}
}
}
void FluidSimulator::Init()
{
this->node = transport::NodePtr(new transport::Node());
this->node->Init(this->world->Name());
this->fluidObjPub = this->node->Advertise<msgs::Fluid>("~/fluid_pos", 10);
this->rigidObjPub = this->node->Advertise<msgs::Fluid>("~/rigids_pos", 10);
base = std::make_unique<GazeboSimulatorBase>();
base->init(this->fluidPluginSdf);
this->ParseSDF();
base->initSimulation();
base->initBoundaryData();
this->publishBoundaryParticles();
}
void FluidSimulator::Load(physics::WorldPtr parent, sdf::ElementPtr sdf)
{
this->world = parent;
this->fluidPluginSdf = sdf;
this->connections.push_back(event::Events::ConnectWorldUpdateEnd(
boost::bind(&FluidSimulator::RunStep, this)));
}
void FluidSimulator::RegisterMesh(physics::CollisionPtr collision, std::string extension, std::string path)
{
// Get collision mesh by name
const gazebo::common::Mesh *mesh = common::MeshManager::Instance()->GetMesh(collision->GetName());
// Export the mesh to a temp file in the selected format
std::string objFilePath = path + collision->GetModel()->GetName() + "_" + collision->GetName() + ".obj";
common::MeshManager::Instance()->Export(mesh, FileSystem::normalizePath(objFilePath), extension);
base->processBoundary(collision, objFilePath);
}
void FluidSimulator::ParseSDF()
{
// get all models from the world
physics::Model_V models = world->Models();
// iterate through all models
for (physics::Model_V::iterator currentModel = models.begin(); currentModel != models.end(); ++currentModel)
{
// get all links from the model
physics::Link_V model_links = currentModel->get()->GetLinks();
std::cout << "Model: " << currentModel->get()->GetName() << std::endl;
// iterate through all the links
for (physics::Link_V::iterator link_it = model_links.begin(); link_it != model_links.end(); ++link_it)
{
// get all collisions of the link
physics::Collision_V collisions = link_it->get()->GetCollisions();
std::cout << "\t Link: " << link_it->get()->GetName() << std::endl;
// iterate through all the collisions
for (physics::Collision_V::iterator collision_it = collisions.begin(); collision_it != collisions.end(); ++collision_it)
{
std::cout << "\t\t Collision: " << (*collision_it)->GetName() << std::endl;
physics::CollisionPtr coll_ptr = boost::static_pointer_cast<physics::Collision>(*collision_it);
// check the geometry type of the given collision
sdf::ElementPtr geometry_elem = coll_ptr->GetSDF()->GetElement("geometry");
// get the name of the geometry
std::string geometry_type = geometry_elem->GetFirstElement()->GetName();
// check type of the geometry
if (geometry_type == "box")
{
// Get the size of the box
ignition::math::Vector3d size = geometry_elem->GetElement(geometry_type)->Get<ignition::math::Vector3d>("size");
// Create box shape
common::MeshManager::Instance()->CreateBox((*collision_it)->GetName(), ignition::math::Vector3d(size.X(), size.Y(), size.Z()),
ignition::math::Vector2d(1, 1));
// Generate an obj file in the temporary directory containing the mesh of the box
RegisterMesh(*collision_it, "obj", objFilePath);
}
else if (geometry_type == "cylinder")
{
// Cylinder dimensions
double radius = geometry_elem->GetElement(geometry_type)->GetElement("radius")->Get<double>();
double length = geometry_elem->GetElement(geometry_type)->GetElement("length")->Get<double>();
// Create cylinder mesh
common::MeshManager::Instance()->CreateCylinder((*collision_it)->GetName(), radius, length, 32, 32);
//Generate an obj file in the temporary directory containing the mesh of the cylinder
RegisterMesh(*collision_it, "obj", objFilePath);
}
else if (geometry_type == "sphere")
{
// Sphere radius
double radius = geometry_elem->GetElement(geometry_type)->GetElement("radius")->Get<double>();
// Create a sphere mesh
common::MeshManager::Instance()->CreateSphere((*collision_it)->GetName(), radius, 32, 32);
// Generate an obj file in the temporary directory containing the mesh of the sphere
RegisterMesh(*collision_it, "obj", objFilePath);
}
else if (geometry_type == "plane")
{
ignition::math::Vector3d normal;
ignition::math::Vector2d size;
// Plane dimensions. To prevent a huge plane which causes problems when
// sampling it, for now it is harcoded
if ((*collision_it)->GetName() == "collision_ground_plane")
{
normal = ignition::math::Vector3d(0, 0, 1); // = geom_elem->GetElement(geom_type)->GetElement("normal")->Get<ignition::math::Vector3d>();
size = ignition::math::Vector2d(2.0, 2.0); //= geom_elem->GetElement(geom_type)->GetElement("size")->Get<ignition::math::Vector2d>();
}
else
{
normal = geometry_elem->GetElement(geometry_type)->GetElement("normal")->Get<ignition::math::Vector3d>();
size = geometry_elem->GetElement(geometry_type)->GetElement("size")->Get<ignition::math::Vector2d>();
}
// Generate the plane mesh
common::MeshManager::Instance()->CreatePlane((*collision_it)->GetName(), ignition::math::Vector3d(0.0, 0.0, 1.0), 0.0, size, ignition::math::Vector2d(4.0, 4.0), ignition::math::Vector2d());
//Generate an obj file in the temporary directory containing the mesh of the plane
RegisterMesh(*collision_it, "obj", objFilePath);
}
else if (geometry_type == "mesh")
{
// get the uri element value
const std::string uri = geometry_elem->GetElement(geometry_type)->GetElement("uri")->Get<std::string>();
// get the filepath from the uri
const std::string filepath = common::SystemPaths::Instance()->FindFileURI(uri);
const gazebo::common::Mesh *mesh = common::MeshManager::Instance()->GetMesh(filepath);
std::string fullMeshPath = objFilePath + (*collision_it)->GetModel()->GetName() + "_" + (*collision_it)->GetName() + ".obj";
// Export the mesh to a temp file in the selected format
common::MeshManager::Instance()->Export(mesh, FileSystem::normalizePath(fullMeshPath), "obj");
base->processBoundary(*collision_it, fullMeshPath);
}
else
{
// Error for other possible weird types
gzerr << "Collision type [" << geometry_type << "] unimplemented\n";
}
}
}
}
}
void FluidSimulator::reset()
{ /*
Utilities::Timing::printAverageTimes();
Utilities::Timing::reset();
Utilities::Counting::printAverageCounts();
Utilities::Counting::reset();
Simulation::getCurrent()->reset();
base->reset(); */
}
GZ_REGISTER_WORLD_PLUGIN(FluidSimulator)
| 9,472 | 3,520 |
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int id;
TreeNode* solve(vector<int>& preorder , int limit ){
if(id >= preorder.size() ){
return NULL;
}
int curr_value = preorder[id];
if(curr_value > limit){
return NULL;
}
TreeNode* root = new TreeNode(curr_value);
id++;
root->left = solve(preorder, curr_value );
root->right = solve(preorder, limit );
return root;
}
TreeNode* bstFromPreorder(vector<int>& preorder) {
id = 0;
return solve(preorder , INT_MAX);
}
};
| 792 | 259 |
#include "Commands.h"
#define LOCTEXT_NAMESPACE "FBlueprintToRSTDocModule"
void FBlueprintToRSTDocCommands::RegisterCommands()
{
UI_COMMAND(Action, "BlueprintToRSTDoc", "Execute BlueprintToRSTDoc action", EUserInterfaceActionType::Button, FInputGesture());
}
#undef LOCTEXT_NAMESPACE
| 292 | 105 |
#include "TestCube.h"
#include "Cube.h"
#include "BindableCodex.h"
#include "ImGui\imgui.h"
#include "BindableCommon.h"
#include "Texture.h"
#include "Sampler.h"
#include "TransformCbufDoubleBoi.h"
#include "DepthStencil.h"
using namespace DirectX;
TestCube::TestCube(Graphics& gfx, float size)
{
using namespace Bind;
auto model = Cube::MakeIndependentTextured();
model.Transform(XMMatrixScaling(size, size, size));
model.SetNormalsIndependentFlat();
m_UID = "$cube." + std::to_string(size);
AddBind(VertexBuffer::Resolve(gfx, m_UID, model.vertices));
AddBind(IndexBuffer::Resolve(gfx, m_UID, model.indices));
AddBind(Texture::Resolve(gfx, "Images\\brickwall.jpg"));
AddBind(Texture::Resolve(gfx, "Images\\brickwall_normal.jpg", 1.0f));
AddBind(Sampler::Resolve(gfx));
auto pvs = VertexShader::Resolve(gfx, "PhongVS.cso");
auto pvsbc = pvs->GetBytecode();
AddBind(std::move(pvs));
AddBind(PixelShader::Resolve(gfx, "PhongPSNormalMap.cso"));
AddBind(PixelConstantBuffer<PSMaterialConstant>::Resolve(gfx, pmc, 1.0f));
AddBind(InputLayout::Resolve(gfx, model.vertices.GetLayout(), pvsbc));
AddBind(Topology::Resolve(gfx, D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST));
AddBind(std::make_shared<TransformCbufDoubleBoi>(gfx, *this, 0, 2));
AddBind(std::make_shared<Blender>(gfx, false, 0.5f));
AddBind(Rasterizer::Resolve(gfx, false));
AddBind(Topology::Resolve(gfx, D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST));
AddBind(DepthStencil::Resolve(gfx));
}
void TestCube::SetPos(DirectX::XMFLOAT3 pos) noexcept
{
m_pos = pos;
}
void TestCube::SetRotation(float pitch, float yaw, float roll) noexcept
{
this->pitch = pitch;
this->yaw = yaw;
this->roll = roll;
}
void TestCube::Draw(Graphics& gfx) const noexcept(!IS_DEBUG)
{
Drawable::Draw(gfx);
}
DirectX::XMMATRIX TestCube::GetTransformXM() const noexcept
{
return XMMatrixRotationRollPitchYaw(pitch, yaw, roll) *
XMMatrixTranslation(m_pos.x, m_pos.y, m_pos.z);
}
std::string TestCube::GetUID() const noexcept
{
return m_UID;
}
void TestCube::ItemSelected() noexcept
{
m_bMenu = true;
}
bool TestCube::IsMenuDrawable() const noexcept
{
return m_bMenu;
}
void TestCube::DrawMenu(Graphics& gfx) noexcept
{
if (ImGui::Begin(m_UID.c_str(), &m_bMenu))
{
ImGui::Text("Position");
ImGui::SliderFloat("X", &m_pos.x, -80.0f, 80.0f, "%.1f");
ImGui::SliderFloat("Y", &m_pos.y, -80.0f, 80.0f, "%.1f");
ImGui::SliderFloat("Z", &m_pos.z, -80.0f, 80.0f, "%.1f");
ImGui::Text("Orientation");
ImGui::SliderAngle("Pitch", &pitch, -180.0f, 180.0f);
ImGui::SliderAngle("Yaw", &yaw, -180.0f, 180.0f);
ImGui::SliderAngle("Roll", &roll, -180.0f, 180.0f);
ImGui::Text("Shading");
bool changed0 = ImGui::SliderFloat("Spec. Int.", &pmc.specularIntensity, 0.0f, 1.0f);
bool changed1 = ImGui::SliderFloat("Spec. Power", &pmc.specularPower, 0.0f, 100.0f);
bool checkState = pmc.normalMappingEnabled == TRUE;
bool changed2 = ImGui::Checkbox("Enable Normal Map", &checkState);
pmc.normalMappingEnabled = checkState ? TRUE : FALSE;
if (changed0 || changed1 || changed2)
{
QueryBindable<Bind::PixelConstantBuffer<PSMaterialConstant>>()->Update(gfx, pmc);
}
}
ImGui::End();
}
| 3,170 | 1,381 |
#include "BehaviourModifier.h"
BehaviourModifier::BehaviourModifier()
{
}
BehaviourModifier::~BehaviourModifier()
{
//Do I still Delete ID?
//Or just set it to nullptr
delete ID;
ID = nullptr;
}
void BehaviourModifier::AttachID(std::string &ID_)
{
*ID = ID_;
}
void BehaviourModifier::GenerateGenderTrait(bool autoGenerateGenders, int genderRatio)
{
//Takes the string value of the ID and assigns 1/2 male and 1/2 female population
if (autoGenerateGenders)
{
if (std::stoi(*ID) % genderRatio == 0)
{
genderTrait = true;
}
else
{
genderTrait = false;
}
}
else
{
genderTrait = true;
}
}
void BehaviourModifier::AdjustPersonality(int personalityType, double distributionMean, double distributionOffset)
{
switch (personalityType)
{
case 0:
personality00.adjustDistribution(distributionMean, distributionOffset);
break;
case 1:
personality01.adjustDistribution(distributionMean, distributionOffset);
break;
case 2:
personality02.adjustDistribution(distributionMean, distributionOffset);
break;
case 3:
personality03.adjustDistribution(distributionMean, distributionOffset);
break;
default:
personalityType = 0;
break;
}
}
void BehaviourModifier::ForcefullySetPersonalityValue(int personalityValue, double value)
{
switch (personalityValue)
{
case 0:
personality00.setValueForcefully(value);
break;
case 1:
personality01.setValueForcefully(value);
break;
case 2:
personality02.setValueForcefully(value);
break;
case 3:
personality03.setValueForcefully(value);
break;
default: personalityValue = 0;
break;
}
}
void BehaviourModifier::EstablishPersonality()
{
personality00.EstablishPersonality(genderTrait);
personality01.EstablishPersonality(genderTrait);
personality02.EstablishPersonality(genderTrait);
personality03.EstablishPersonality(genderTrait);
}
void BehaviourModifier::PrintPersonalityInfo(int personalityType)
{
switch (personalityType)
{
case 0:
personality00.Print();
break;
case 1:
personality01.Print();
break;
case 2:
personality02.Print();
break;
case 3:
personality03.Print();
break;
default:
personalityType = 0;
break;
}
}
std::string BehaviourModifier::getPersonalityName(int personalityType)
{
switch (personalityType)
{
case 0:
return personality00.getPersonalityName();
break;
case 1:
return personality01.getPersonalityName();
break;
case 2:
return personality02.getPersonalityName();
break;
case 3:
return personality03.getPersonalityName();
break;
default:
return personality00.getPersonalityName();
break;
}
}
double BehaviourModifier::getPersonalityValue(int personalityType)
{
switch (personalityType)
{
case 0:
return personality00.getValue();
break;
case 1:
return personality01.getValue();
break;
case 2:
return personality02.getValue();
break;
case 3:
return personality03.getValue();
break;
default:
return personality00.getValue();
break;
}
}
| 2,969 | 1,164 |
/*
Copyright (c) 2015-2021 Alternative Games Ltd / Turo Lamminen
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 <cassert>
#include <cerrno>
#include <cstring>
#include <sys/stat.h>
#include <stdexcept>
#include "Utils.h"
#include <SDL.h>
struct FILEDeleter {
void operator()(FILE *f) { fclose(f); }
};
static FILE *logFile;
void logInit() {
assert(!logFile);
char *logFilePath = SDL_GetPrefPath("", "SMAADemo");
std::string logFileName(logFilePath);
SDL_free(logFilePath);
logFileName += "logfile.txt";
logFile = fopen(logFileName.c_str(), "wb");
}
void logWrite(const nonstd::string_view &message) {
// Write to console if opening log file failed
FILE *f = logFile ? logFile : stdout;
fwrite(message.data(), 1, message.size(), f);
fputc('\n', f);
}
void logWriteError(const nonstd::string_view &message) {
// Write to log and stderr
if (logFile) {
fwrite(message.data(), 1, message.size(), logFile);
fputc('\n', logFile);
fflush(logFile);
}
fwrite(message.data(), 1, message.size(), stderr);
fputc('\n', stderr);
fflush(stderr);
}
void logShutdown() {
assert(logFile);
fflush(logFile);
fclose(logFile);
logFile = nullptr;
}
void logFlush() {
assert(logFile);
fflush(logFile);
}
std::vector<char> readTextFile(std::string filename) {
std::unique_ptr<FILE, FILEDeleter> file(fopen(filename.c_str(), "rb"));
if (!file) {
THROW_ERROR("file not found {}", filename);
}
int fd = fileno(file.get());
if (fd < 0) {
THROW_ERROR("no fd");
}
struct stat statbuf;
memset(&statbuf, 0, sizeof(struct stat));
int retval = fstat(fd, &statbuf);
if (retval < 0) {
THROW_ERROR("fstat failed for \"{}\": {}", filename, strerror(errno));
}
unsigned int filesize = static_cast<unsigned int>(statbuf.st_size);
// ensure NUL -termination
std::vector<char> buf(filesize + 1, '\0');
size_t ret = fread(&buf[0], 1, filesize, file.get());
if (ret != filesize)
{
THROW_ERROR("fread failed");
}
return buf;
}
std::vector<char> readFile(std::string filename) {
std::unique_ptr<FILE, FILEDeleter> file(fopen(filename.c_str(), "rb"));
if (!file) {
THROW_ERROR("file not found {}", filename);
}
int fd = fileno(file.get());
if (fd < 0) {
THROW_ERROR("no fd");
}
struct stat statbuf;
memset(&statbuf, 0, sizeof(struct stat));
int retval = fstat(fd, &statbuf);
if (retval < 0) {
THROW_ERROR("fstat failed for \"{}\": {}", filename, strerror(errno));
}
unsigned int filesize = static_cast<unsigned int>(statbuf.st_size);
std::vector<char> buf(filesize, '\0');
size_t ret = fread(&buf[0], 1, filesize, file.get());
if (ret != filesize)
{
THROW_ERROR("fread failed");
}
return buf;
}
void writeFile(const std::string &filename, const void *contents, size_t size) {
std::unique_ptr<FILE, FILEDeleter> file(fopen(filename.c_str(), "wb"));
fwrite(contents, 1, size, file.get());
}
bool fileExists(const std::string &filename) {
std::unique_ptr<FILE, FILEDeleter> file(fopen(filename.c_str(), "rb"));
if (file) {
return true;
} else {
return false;
}
}
int64_t getFileTimestamp(const std::string &filename) {
struct stat statbuf;
memset(&statbuf, 0, sizeof(struct stat));
int retval = stat(filename.c_str(), &statbuf);
if (retval < 0) {
THROW_ERROR("fstat failed for \"{}\": {}", filename, strerror(errno));
}
return statbuf.st_mtime;
}
| 4,332 | 1,670 |
/*
* MIT License
*
* Copyright (c) 2021 CSCS, ETH Zurich
* 2021 University of Basel
*
* 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
* @brief General purpose utilities
*
* @author Sebastian Keller <sebastian.f.keller@gmail.com>
*/
#pragma once
#include <utility>
#include "cstone/cuda/annotation.hpp"
/*! @brief A template to create structs as a type-safe version to using declarations
*
* Used in public API functions where a distinction between different
* arguments of the same underlying type is desired. This provides a type-safe
* version to using declarations. Instead of naming a type alias, the name
* is used to define a struct that inherits from StrongType<T>, where T is
* the underlying type.
*
* Due to the T() conversion and assignment from T,
* an instance of StrongType<T> struct behaves essentially like an actual T, while construction
* from T is disabled. This makes it impossible to pass a T as a function parameter
* of type StrongType<T>.
*/
template<class T, class Phantom>
struct StrongType
{
using ValueType [[maybe_unused]] = T;
//! default ctor
constexpr HOST_DEVICE_FUN StrongType() : value_{} {}
//! construction from the underlying type T, implicit conversions disabled
explicit constexpr HOST_DEVICE_FUN StrongType(T v) : value_(std::move(v)) {}
//! assignment from T
constexpr HOST_DEVICE_FUN StrongType& operator=(T v)
{
value_ = std::move(v);
return *this;
}
//! conversion to T
constexpr HOST_DEVICE_FUN operator T() const { return value_; } // NOLINT
//! access the underlying value
constexpr HOST_DEVICE_FUN T value() const { return value_; }
private:
T value_;
};
/*! @brief StrongType equality comparison
*
* Requires that both T and Phantom template parameters match.
* For the case where a comparison between StrongTypes with matching T, but differing Phantom
* parameters is desired, the underlying value attribute should be compared instead
*/
template<class T, class Phantom>
constexpr HOST_DEVICE_FUN
bool operator==(const StrongType<T, Phantom>& lhs, const StrongType<T, Phantom>& rhs)
{
return lhs.value() == rhs.value();
}
//! @brief comparison function <
template<class T, class Phantom>
constexpr HOST_DEVICE_FUN
bool operator<(const StrongType<T, Phantom>& lhs, const StrongType<T, Phantom>& rhs)
{
return lhs.value() < rhs.value();
}
//! @brief comparison function >
template<class T, class Phantom>
constexpr HOST_DEVICE_FUN
bool operator>(const StrongType<T, Phantom>& lhs, const StrongType<T, Phantom>& rhs)
{
return lhs.value() > rhs.value();
}
//! @brief addition
template<class T, class Phantom>
constexpr HOST_DEVICE_FUN
StrongType<T, Phantom> operator+(const StrongType<T, Phantom>& lhs, const StrongType<T, Phantom>& rhs)
{
return StrongType<T, Phantom>(lhs.value() + rhs.value());
}
//! @brief subtraction
template<class T, class Phantom>
constexpr HOST_DEVICE_FUN
StrongType<T, Phantom> operator-(const StrongType<T, Phantom>& lhs, const StrongType<T, Phantom>& rhs)
{
return StrongType<T, Phantom>(lhs.value() - rhs.value());
}
//! @brief simple pair that's usable in both CPU and GPU code
template<class T>
class pair
{
public:
constexpr pair() = default;
HOST_DEVICE_FUN constexpr
pair(T first, T second) : data{first, second} {}
HOST_DEVICE_FUN constexpr T& operator[](int i) { return data[i]; }
HOST_DEVICE_FUN constexpr const T& operator[](int i) const { return data[i]; }
private:
HOST_DEVICE_FUN friend constexpr bool operator==(const pair& a, const pair& b)
{
return a.data[0] == b.data[0] && a.data[1] == b.data[1];
}
HOST_DEVICE_FUN friend constexpr bool operator<(const pair& a, const pair& b)
{
bool c0 = a.data[0] < b.data[0];
bool e0 = a.data[0] == b.data[0];
bool c1 = a.data[1] < b.data[1];
return c0 || (e0 && c1);
}
T data[2];
};
//! @brief ceil(divident/divisor) for integers
HOST_DEVICE_FUN constexpr unsigned iceil(size_t dividend, unsigned divisor)
{
return (dividend + divisor - 1) / divisor;
}
| 5,188 | 1,707 |
#ifndef DMN_KVM_NO_USE_PRAGMA
#pragma once
#endif /* DMN_KVM_NO_USE_PRAGMA */
#ifndef DMN_KVM_ESC_HPP
#define DMN_KVM_ESC_HPP
#include "KVMTypes.hpp"
#include <cstdint>
namespace DmN::KVM {
/// Объект (нет) который может быть инстансирован
struct Instanceble_t {
virtual Object_t *newInstance(Value_t **args, size_t args_c) { return nullptr; };
};
/// Универсальная основа для Enum-а
struct Enum_t : public LLTNameble, public Modifiable, public Instanceble_t, public FieldStorage_t {
explicit Enum_t(SI_t name,
uint8_t modifier,
Value_t **enums,
SI_t *names,
uint8_t enumsCount) : LLTNameble(name, LLTypes::ENUM), Modifiable(modifier) {
this->enums = enums;
this->names = names;
this->enumsCount = enumsCount;
}
SDL::DmNCollection<Field_t> *getFields() override {
return nullptr; // TODO:
}
struct Object_t *newInstance(Value_t **args, size_t args_c) override {
return nullptr; // TODO:
}
/// Перечисления
Value_t **enums;
/// Имена перечислений
SI_t *names;
/// Кол-во перечислений
uint8_t enumsCount;
};
/// Универсальная основа для структуры
struct Struct_t : public LLTNameble, public Modifiable, public Instanceble_t, public FieldStorage_t {
explicit Struct_t(SI_t name,
uint8_t modifier,
Field_t **fields,
uint8_t fieldsCount,
CI_t *parents,
uint8_t parentsCount) : LLTNameble(name, LLTypes::STRUCT), Modifiable(modifier) {
this->fields = fields;
this->fieldsCount = fieldsCount;
this->parents = parents;
this->parentsCount = parentsCount;
}
SDL::DmNCollection<Field_t> *getFields() override {
return nullptr; // TODO:
}
struct Object_t *newInstance(Value_t **args, size_t args_c) override {
return nullptr; // TODO:
}
/// Поля
Field_t **fields;
/// Кол-во полей
uint8_t fieldsCount;
/// Предки (ID предков)
CI_t *parents;
/// Кол-во предков
uint8_t parentsCount: 5;
};
/// Универсальная основа для Class-а
class Class_t
: public LLTNameble,
public Modifiable,
public Instanceble_t,
public FieldStorage_t,
public MethodStorage_t {
public:
explicit Class_t(SI_t name, uint8_t modifier, Field_t **fields, uint8_t fieldsCount, Method_t **methods,
uint8_t methodsCount, CI_t *parents, uint8_t parentsCount) : LLTNameble(name,
LLTypes::CLASS),
Modifiable(modifier) {
this->fields = fields;
this->fieldsCount = fieldsCount;
this->methods = methods;
this->methodsCount = methodsCount;
this->parents = parents;
this->parentsCount = parentsCount;
}
SDL::DmNCollection<Field_t> *getFields() override {
return nullptr; // TODO:
}
SDL::DmNCollection<Method_t> *getMethods() override {
return nullptr; // TODO:
}
struct Object_t *newInstance(Value_t **args, size_t args_c) override {
return nullptr; // TODO:
}
/// Массив полей
Field_t **fields;
/// Кол-во полей
uint8_t fieldsCount;
/// Массив методов
Method_t **methods;
/// Кол-во методов
uint8_t methodsCount;
/// Предки (ID предков)
CI_t *parents;
/// Кол-во предков
uint8_t parentsCount: 5;
};
/// Основа класса со встроенными классами
class ISClass_t : public Class_t {
public:
explicit ISClass_t(Class_t *base, SI_t name, uint8_t modifier, Field_t **fields,
uint32_t fieldsCount,
Method_t **methods,
uint32_t methodsCount, CI_t *parents, uint8_t parentsCount) : Class_t(name,
modifier,
fields,
fieldsCount,
methods,
methodsCount,
parents,
parentsCount) {
this->base = base;
}
/// Основной класс
Class_t *base;
};
class EnumClass_t : public Class_t, public Enum_t {
SDL::DmNCollection<Field_t> *getFields() override {
return nullptr; // TODO:
}
SDL::DmNCollection<Method_t> *getMethods() override {
return nullptr; // TODO:
}
};
}
#endif /* DMN_KVM_ESC_HPP */ | 5,583 | 1,516 |
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class BSTIterator {
public:
stack<int> st;
void getin(TreeNode* root)
{
if(!root) return ;
getin(root->right);
st.push(root->val);
getin(root->left);
}
BSTIterator(TreeNode* root) {
getin(root);
}
int next() {
int i =st.top();
st.pop();
return i;
}
bool hasNext() {
return !st.empty();
}
};
/**
* Your BSTIterator object will be instantiated and called as such:
* BSTIterator* obj = new BSTIterator(root);
* int param_1 = obj->next();
* bool param_2 = obj->hasNext();
*/ | 955 | 328 |
/************************************************************************
This sketch reads the temperature from a OneWire device and then publishes
to the Particle cloud. From there, IFTTT can be used to log the date,
time, and temperature to a Google Spreadsheet. Read more in our tutorial
here: http://docs.particle.io/tutorials/topics/maker-kit
This sketch is the same as the example from the OneWire library, but
with the addition of three lines at the end to publish the data to the
cloud.
Use this sketch to read the temperature from 1-Wire devices
you have attached to your Particle device (core, p0, p1, photon, electron)
Temperature is read from: DS18S20, DS18B20, DS1822, DS2438
Expanding on the enumeration process in the address scanner, this example
reads the temperature and outputs it from known device types as it scans.
I/O setup:
These made it easy to just 'plug in' my 18B20 (note that a bare TO-92
sensor may read higher than it should if it's right next to the Photon)
D3 - 1-wire ground, or just use regular pin and comment out below.
D4 - 1-wire signal, 2K-10K resistor to D5 (3v3)
D5 - 1-wire power, ditto ground comment.
A pull-up resistor is required on the signal line. The spec calls for a 4.7K.
I have used 1K-10K depending on the bus configuration and what I had out on the
bench. If you are powering the device, they all work. If you are using parisidic
power it gets more picky about the value.
NOTE: This sketch requires the OneWire library, which can be added from the
<-- Libraries tab on the left.
************************************************************************/
OneWire ds = OneWire(D4); // 1-wire signal on pin D4
unsigned long lastUpdate = 0;
float lastTemp;
void setup() {
Serial.begin(9600);
// Set up 'power' pins, comment out if not used!
pinMode(D3, OUTPUT);
pinMode(D5, OUTPUT);
digitalWrite(D3, LOW);
digitalWrite(D5, HIGH);
}
// up to here, it is the same as the address acanner
// we need a few more variables for this example
void loop(void) {
byte i;
byte present = 0;
byte type_s;
byte data[12];
byte addr[8];
float celsius, fahrenheit;
if ( !ds.search(addr)) {
Serial.println("No more addresses.");
Serial.println();
ds.reset_search();
delay(250);
return;
}
// The order is changed a bit in this example
// first the returned address is printed
Serial.print("ROM =");
for( i = 0; i < 8; i++) {
Serial.write(' ');
Serial.print(addr[i], HEX);
}
// second the CRC is checked, on fail,
// print error and just return to try again
if (OneWire::crc8(addr, 7) != addr[7]) {
Serial.println("CRC is not valid!");
return;
}
Serial.println();
// we have a good address at this point
// what kind of chip do we have?
// we will set a type_s value for known types or just return
// the first ROM byte indicates which chip
switch (addr[0]) {
case 0x10:
Serial.println(" Chip = DS1820/DS18S20");
type_s = 1;
break;
case 0x28:
Serial.println(" Chip = DS18B20");
type_s = 0;
break;
case 0x22:
Serial.println(" Chip = DS1822");
type_s = 0;
break;
case 0x26:
Serial.println(" Chip = DS2438");
type_s = 2;
break;
default:
Serial.println("Unknown device type.");
return;
}
// this device has temp so let's read it
ds.reset(); // first clear the 1-wire bus
ds.select(addr); // now select the device we just found
// ds.write(0x44, 1); // tell it to start a conversion, with parasite power on at the end
ds.write(0x44, 0); // or start conversion in powered mode (bus finishes low)
// just wait a second while the conversion takes place
// different chips have different conversion times, check the specs, 1 sec is worse case + 250ms
// you could also communicate with other devices if you like but you would need
// to already know their address to select them.
delay(1000); // maybe 750ms is enough, maybe not, wait 1 sec for conversion
// we might do a ds.depower() (parasite) here, but the reset will take care of it.
// first make sure current values are in the scratch pad
present = ds.reset();
ds.select(addr);
ds.write(0xB8,0); // Recall Memory 0
ds.write(0x00,0); // Recall Memory 0
// now read the scratch pad
present = ds.reset();
ds.select(addr);
ds.write(0xBE,0); // Read Scratchpad
if (type_s == 2) {
ds.write(0x00,0); // The DS2438 needs a page# to read
}
// transfer and print the values
Serial.print(" Data = ");
Serial.print(present, HEX);
Serial.print(" ");
for ( i = 0; i < 9; i++) { // we need 9 bytes
data[i] = ds.read();
Serial.print(data[i], HEX);
Serial.print(" ");
}
Serial.print(" CRC=");
Serial.print(OneWire::crc8(data, 8), HEX);
Serial.println();
// Convert the data to actual temperature
// because the result is a 16 bit signed integer, it should
// be stored to an "int16_t" type, which is always 16 bits
// even when compiled on a 32 bit processor.
int16_t raw = (data[1] << 8) | data[0];
if (type_s == 2) raw = (data[2] << 8) | data[1];
byte cfg = (data[4] & 0x60);
switch (type_s) {
case 1:
raw = raw << 3; // 9 bit resolution default
if (data[7] == 0x10) {
// "count remain" gives full 12 bit resolution
raw = (raw & 0xFFF0) + 12 - data[6];
}
celsius = (float)raw * 0.0625;
break;
case 0:
// at lower res, the low bits are undefined, so let's zero them
if (cfg == 0x00) raw = raw & ~7; // 9 bit resolution, 93.75 ms
if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
// default is 12 bit resolution, 750 ms conversion time
celsius = (float)raw * 0.0625;
break;
case 2:
data[1] = (data[1] >> 3) & 0x1f;
if (data[2] > 127) {
celsius = (float)data[2] - ((float)data[1] * .03125);
}else{
celsius = (float)data[2] + ((float)data[1] * .03125);
}
}
// remove random errors
if((((celsius <= 0 && celsius > -1) && lastTemp > 5)) || celsius > 125) {
celsius = lastTemp;
}
fahrenheit = celsius * 1.8 + 32.0;
lastTemp = celsius;
Serial.print(" Temperature = ");
Serial.print(celsius);
Serial.print(" Celsius, ");
Serial.print(fahrenheit);
Serial.println(" Fahrenheit");
// now that we have the readings, we can publish them to the cloud
String temperature = String(fahrenheit); // store temp in "temperature" string
Particle.publish("temperature", temperature, PRIVATE); // publish to dashboard
delay(5000); // 5-sec delay
}
| 6,747 | 2,386 |
class Solution {
private:
unordered_map<string, int> pathLevel;
unordered_map<string, vector<string>> nextNode;
vector<vector<string>> ans;
public:
vector<vector<string>> findLadders(string beginWord, string endWord, unordered_set<string> &wordList) {
bfs(wordList, beginWord, endWord);
vector<string> myans;
dfs(wordList, beginWord, endWord, myans);
return ans;
}
void bfs(unordered_set<string>& wordList, string beginWord, string endWord) {
queue<string> q;
q.push(beginWord);
pathLevel[beginWord] = 0;
while (!q.empty()) {
string curWord = q.front();
q.pop();
int level = pathLevel[curWord];
if (curWord == endWord) continue;
vector<string> myNextNode;
for (int i = 0; i < curWord.length(); i++) {
string nextWord = curWord;
for (int j = 0; j < 26; j++) {
if (curWord[i] == 'a' + j) continue;
nextWord[i] = 'a' + j;
if (wordList.find(nextWord) == wordList.end()) continue;
if (pathLevel.find(nextWord) == pathLevel.end()) {
pathLevel[nextWord] = level + 1;
q.push(nextWord);
}
if (pathLevel[nextWord] == level + 1) myNextNode.push_back(nextWord);
}
}
nextNode[curWord] = myNextNode;
}
}
void dfs(unordered_set<string>& wordList, string curWord, string endWord, vector<string>& myans) {
myans.push_back(curWord);
if (curWord == endWord) {
ans.push_back(myans);
myans.pop_back();
return;
}
int level = pathLevel[curWord];
vector<string> myNextNode = nextNode[curWord];
for (int i = 0; i < myNextNode.size(); i++) {
dfs(wordList, myNextNode[i], endWord, myans);
}
myans.pop_back();
}
};
| 2,030 | 621 |
/*
* dnk_biphasic_offset_cli.cxx
*
* Created on: 30 сент. 2019 г.
* Author: root
*/
#include "dnk_biphasic_offset_cli.h"
#ifdef _HIREDIS
eErrorTp dnk_biphasic_offset_cli::make_selection_by_interval(u64 ts_start_ms,u64 ts_stop_ms,u32 limit,rapidjson::Document & result_root){
if (fault==ERROR){
GPRINT(NORMAL_LEVEL,"make_selection_by_interval is fault\n");
return ERROR;
}
GPRINT(MEDIUM_LEVEL,"Make_selection_by_interval ts_start_ms %llu ts_stop_ms %llu point_limit %u\n",ts_start_ms,ts_stop_ms,limit);
//GPRINT(NORMAL_LEVEL,"make_selection_by_interval M1\n");
result_root.SetObject();
std::pair<eErrorTp, vector<string>> res,res2;
TIME_T ts_stop=(u64)ts_stop_ms/1000;
TIME_T ts_start=(u64)ts_start_ms/1000;
TIME_T tss;
//Json::Reader read;
string fn_old;
string format_path[total_storage];
//Json::Value header_root;
rapidjson::Document header_root;
bool format_getting=false;
// bool result_root_init=false;
u32 aidx=0;
u32 limf=(limit/dal_lines_in_block)+1;
res=command("ZREVRANGEBYSCORE ts %lu %lu LIMIT 0 1",ts_start,0);
TIME_T ts_start_tmp=ts_start;
if ((res.second.size()==0)||(res.first==ERROR)){
GPRINT(HARD_LEVEL,"ZREVRANGEBYSCORE ts %lu %lu LIMIT 0 1 result is null, try next time %llu\n",ts_start,0,ts_start_ms);
}
else //поиск предыдущего фрагмента, для захвата всего диапазона
ts_start_tmp=stol(res.second[0]);
res=command("HMGET %u te",ts_start_tmp);
if ((res.second.size()==0)||(res.first==ERROR)){
GPRINT(HARD_LEVEL,"HMGET %u te result is null\n",ts_start_tmp);
}
else{
//пропустить фрагмент если его содержимое старее ts_start_tmp
TIME_T et=stol(res.second[0]);
if (et<ts_start)
ts_start_tmp=et;
}
if (ts_start_tmp>ts_stop)
return NO_ERROR;
//printf("sts %lu ts_start %lu ts_stop %lu limf %u\n",TIME(NULL),ts_start,ts_stop,limf);
//Search in files
GPRINT(MEDIUM_LEVEL,"ZRANGEBYSCORE ts %u %u LIMIT 0 %u\n",ts_start_tmp,ts_stop,limf);
res=command("ZRANGEBYSCORE ts %u %u LIMIT 0 %u",ts_start_tmp,ts_stop,limf);
if ((res.first==ERROR)||(res.second.size()==0)){
GetFormatPath(format_path);
if (ReadJsonFormatFile_rpd(header_root,format_path)==ERROR){
return ERROR;
}
return make_selection_step_by_step_DB_All(ts_start_ms,ts_stop_ms,header_root,result_root);
}
u32 ctr=res.second.size();
GPRINT(MEDIUM_LEVEL,"Founded %d arch files\n",ctr);
//printf("ts_start_ms %llu ts_stop_ms %llu ctr %u\n",ts_start_ms,ts_stop_ms,ctr);
for (u32 z=0;z<ctr;z++){
res2=command("HMGET %s te cn ext crc",res.second[z].c_str());
TIME_T t_end=stoll(res2.second[0]);
TIME_T t_st=stoll(res.second[z]);
string fn=res.second[z]+'_'+res2.second[0]+':'+res2.second[1]+'['+res2.second[3]+"]."+res2.second[2];
string data;
if (GetDataFromGzip(data,fn,t_st,format_path)==NO_ERROR){
rapidjson::Document dr_root;
dr_root.SetObject();
rapidjson::Document data_root;
rapidjson::ParseResult rapid_result=data_root.Parse(data.c_str());
if (rapid_result.Code()==0){
if (format_getting==false){
if (ReadJsonFormatFile_rpd(header_root,format_path)==ERROR){
return ERROR;
}
format_getting=true;
}
MakeObjectFromDataAndHeader_rpd(data_root,header_root,dr_root,false);
if ((!dr_root.HasMember("t"))||(!dr_root["t"].IsArray())){
return ERROR;
}
for (u32 e=0;e<dr_root["m"].Size();e++){
TIME_T t=dr_root["t"][e].GetInt();
ts_start_ms=dr_root["m"][e].GetUint64()+1;
if (t<ts_start){
GPRINT(MEDIUM_LEVEL,"Skip ts %lu < start_ts %lu\n",t,ts_start);
continue;
}
if (t>ts_stop){
GPRINT(MEDIUM_LEVEL,"Skip ts %lu > ts_stop %lu\n",t,ts_stop);
continue;
}
// printf(" point %llu, found %llu\n",dia[r].ts[k],dr_root["m"][e].asUInt64());
for (auto & key:dr_root.GetObject() ){
const char* keys=key.name.GetString();
if (result_root.HasMember(keys)==false){
rapidjson::Value val(rapidjson::kArrayType);
rapidjson::Value index(keys, (u32)strlen(keys), result_root.GetAllocator());
result_root.AddMember(index,val,result_root.GetAllocator());
}
//if (dr_root[keys][e].IsString())
// printf("add %s\n",dr_root[keys][e].GetString());
// if (dr_root[keys][e].IsUint())
// printf("add %u\n",dr_root[keys][e].GetUint());
result_root[keys].PushBack(dr_root[keys][e], result_root.GetAllocator());
}
aidx++;
if (aidx>=limit)
break;
//result_root_init=true;
}
}
}
}
if (format_getting==false){
GetFormatPath(format_path);
if (ReadJsonFormatFile_rpd(header_root,format_path)==ERROR){
return ERROR;
}
}
make_selection_step_by_step_DB_All(ts_start_ms,ts_stop_ms,header_root,result_root);
//printf("Search in DB %d\n",result_root["m"].size());
return NO_ERROR;
}
eErrorTp dnk_biphasic_offset_cli::make_selection_step_by_step_rpd(u64 ts_start_ms,u64 ts_stop_ms,u32 interval_ms,TIME_T point_limit,rapidjson::Document & result_root){
if (fault==ERROR){
GPRINT(NORMAL_LEVEL,"make_selection_step_by_step is fault\n");
return ERROR;
}
if (interval_ms==0)
return ERROR;
GPRINT(MEDIUM_LEVEL,"Make_selection_step_by_step ts_start_ms %llu ts_stop_ms %llu interval_ms %llu point_limit %u\n",ts_start_ms,ts_stop_ms,interval_ms,point_limit);
result_root.SetObject();
std::pair<eErrorTp, vector<string>> res_t,res,res2;
vector<diapason> dia;
u64 saved_ts_stop_ms=ts_stop_ms;
TIME_T ts_stop=ts_stop_ms/1000;
TIME_T ts_start=ts_start_ms/1000;
TIME_T ctr=((ts_stop_ms-ts_start_ms)/interval_ms)+1;
if (ctr>point_limit)
ctr=point_limit;
TIME_T t_st;
TIME_T t_end;
string fn;
u64 t_end_ms;
u64 t_st_ms;
TIME_T ctr_cntr=0;
GPRINT(MEDIUM_LEVEL,"\n*****\n**make_selection_step_by_step [start %llu stop %llu cntr %u interval_ms %u]\n",ts_start_ms,ts_stop_ms,ctr,interval_ms);
while ((ts_start_ms<ts_stop_ms)&&(ctr>=ctr_cntr)){
ts_start=ts_start_ms/1000;
ctr_cntr++;
res=command("ZREVRANGEBYSCORE ts %lu %lu LIMIT 0 1",ts_start,0);
if ((res.second.size()==0)||(res.first==ERROR)){
ts_start_ms+=interval_ms;
GPRINT(HARD_LEVEL,"ZREVRANGEBYSCORE ts %lu %lu LIMIT 0 1 result is null, try next time %llu\n",ts_start,0,ts_start_ms);
continue;
}
t_st=stoll(res.second[0]);
GPRINT(HARD_LEVEL,"got %d\n",res.second.size());
res2=command("HMGET %s te cn ext crc",res.second[0].c_str());
if ((res2.second.size()==0)||(res2.first==ERROR)){
ts_start_ms+=interval_ms;
GPRINT(HARD_LEVEL,"HMGET %s te cn ext crc result is null, try next time %llu\n",res.second[0].c_str(),ts_start_ms);
continue;
}
t_end=stoll(res2.second[0]);
t_end_ms=(u64)t_end*1000;
t_st_ms=(u64)t_st*1000;
if ((ts_start>=t_st)&&(ts_start<=t_end)){
fn=res.second[0]+'_'+res2.second[0]+':'+res2.second[1]+'['+res2.second[3]+"]."+res2.second[2];
dia.emplace_back(ts_start_ms,ts_start,fn);
ts_start_ms+=interval_ms;
GPRINT(HARD_LEVEL,"Collect %s, ts_start enter to diapason\n",fn.c_str());
//printf("t_st_ms %llu ts_start_ms %llu t_end_ms %llu\n",t_st_ms,ts_start_ms,t_end_ms);
while((ts_start_ms>=t_st_ms)&&(ts_start_ms<=t_end_ms)){
dia[dia.size()-1].add(ts_start_ms);
//printf("* fn %s point %llu>=%llu<=%llu\n",fn.c_str(),t_st_ms,ts_start_ms,t_end_ms);
ts_start_ms+=interval_ms;
}
}
else{
ts_start_ms+=interval_ms;
GPRINT(HARD_LEVEL,"Skip ts_start out in diapason [%u] %u [%u]\n",t_st,ts_start,t_end);
}
}
u32 tp=0;
bool result_root_init=false;
u32 aidx=0;
bool format_getting=false;
rapidjson::Document header_root;
string format_path[total_storage];
for (u32 r=0;r<dia.size();r++){
string data;
if (GetDataFromGzip(data,dia[r].fname,dia[r].start_ts,format_path)==NO_ERROR){
rapidjson::Document dr_root;
dr_root.SetObject();
rapidjson::Document data_root;
rapidjson::ParseResult rapid_result=data_root.Parse(data.c_str());
if (rapid_result.Code()==0){
if (format_getting==false){
if (ReadJsonFormatFile_rpd(header_root,format_path)==ERROR){
return ERROR;
}
format_getting=true;
}
MakeObjectFromDataAndHeader_rpd(data_root,header_root,dr_root,false);
if ((!dr_root.HasMember("t"))||(!dr_root["t"].IsArray())){
return ERROR;
}
u32 k=0;
u32 diasz=dia[r].ts.size();
for (u32 e=0;e<dr_root["m"].Size();e++){
if (((u64)dr_root["m"][e].GetInt64())>=dia[r].ts[k]){
for (auto& key : dr_root.GetObject())
{
const char* keys=key.name.GetString();
if (result_root.HasMember(keys)==false){
rapidjson::Value val(rapidjson::kArrayType);
rapidjson::Value index(keys, (u32)strlen(keys), result_root.GetAllocator());
result_root.AddMember(index,val,result_root.GetAllocator());
}
result_root[keys].PushBack(dr_root[keys][e], result_root.GetAllocator());
}
k++;
if (k>=diasz)
{
break;
}
}
}
}
}
tp+=dia[r].ts.size();
}
if (format_getting==false){
GetFormatPath(format_path);
if (ReadJsonFormatFile_rpd(header_root,format_path)==ERROR){
return ERROR;
}
}
if (dal_upload_from_DB_method==SBS_UPLOAD_METHOD_IN_DB_ALL)
make_selection_step_by_step_DB_All(ts_start_ms,saved_ts_stop_ms,header_root,result_root);
else
make_selection_step_by_step_DB_step(ts_start_ms,saved_ts_stop_ms,interval_ms,header_root,result_root,aidx);
return NO_ERROR;
}
eErrorTp dnk_biphasic_offset_cli::make_selection_step_by_step_DB_All(u64 ts_start_ms,u64 saved_ts_stop_ms,rapidjson::Document & header_root,rapidjson::Document & result_root){
rapidjson::Document result_db_root;
result_db_root.SetArray();
rapidjson::Document dr_root;
dr_root.SetObject();
//u64 saved_ts_stop_ms=UINT64_MAX;
//bool result_root_init=false;
GPRINT(MEDIUM_LEVEL,"search elements in redis start %llu stop %llu\n",ts_start_ms,saved_ts_stop_ms);
if ((make_selection_from_db(ts_start_ms,saved_ts_stop_ms,result_db_root)==NO_ERROR)){
if ((result_db_root.IsArray())&&(result_db_root.Size()!=0)){
MakeObjectFromDataAndHeader_rpd(result_db_root,header_root,dr_root,false);
if ((!dr_root.HasMember("t"))||(!dr_root["t"].IsArray())){
GPRINT(MEDIUM_LEVEL,"temporary elements in redis is broken dump: %s\n",(char*)StyledWriteJSON(&dr_root).c_str());
return ERROR;
}
GPRINT(MEDIUM_LEVEL,"found [%u] temporary elements in redis\n",dr_root["m"].Size());
for (u32 e=0;e<dr_root["m"].Size();e++){
for (auto& key : dr_root.GetObject()){
const char* keys=key.name.GetString();
//printf("obj %s\n",keys);
if (result_root.HasMember(keys)==false){
rapidjson::Value val(rapidjson::kArrayType);
rapidjson::Value index(keys, (u32)strlen(keys), result_root.GetAllocator());
result_root.AddMember(index,val,result_root.GetAllocator());
}
result_root[keys].PushBack(dr_root[keys][e], result_root.GetAllocator());
}
}
return NO_ERROR;
}
else{
GPRINT(MEDIUM_LEVEL,"not found temporary elements in redis\n");
return ERROR;
}
}
else{
GPRINT(MEDIUM_LEVEL,"redis db is broken\n");
return ERROR;
}
return ERROR;
}
eErrorTp dnk_biphasic_offset_cli::make_selection_step_by_step_DB_step(u64 ts_start_ms,u64 saved_ts_stop_ms,u64 interval_ms,rapidjson::Document & header_root,rapidjson::Document & result_root,u32 & aidx){
rapidjson::Document result_db_root;
result_db_root.SetArray();
rapidjson::Document dr_root;
dr_root.SetObject();
//bool result_root_init=false;
if ((make_selection_from_db(ts_start_ms,saved_ts_stop_ms,result_db_root)==NO_ERROR)){
if ((result_db_root.IsArray())&&(result_db_root.Size()!=0)){
MakeObjectFromDataAndHeader_rpd(result_db_root,header_root,dr_root,false);
if ((!dr_root.HasMember("t"))||(!dr_root["t"].IsArray())){
return ERROR;
}
GPRINT(MEDIUM_LEVEL,"found [%u] temporary elements in redis\n",dr_root["m"].Size());
u64 fval=(u64)dr_root["m"][0].GetInt64();
while(ts_start_ms<fval){
ts_start_ms+=interval_ms;
}
for (u32 e=0;e<dr_root["m"].Size();e++){
//printf(" in db %llu ts_start_ms %llu\n",dr_root["m"][e].asUInt64(),ts_start_ms);
if ((u64)dr_root["m"][e].GetInt64()>=ts_start_ms){
//printf(" found in db %llu ts_start_ms %llu\n",dr_root["m"][e].asUInt64(),ts_start_ms);
for (auto & key:dr_root.GetObject() ){
const char* keys=key.name.GetString();
if (result_root.HasMember(keys)==false){
rapidjson::Value val(rapidjson::kArrayType);
rapidjson::Value index(keys, (u32)strlen(keys), result_root.GetAllocator());
result_root.AddMember(index,val,result_root.GetAllocator());
}
result_root[keys].PushBack(dr_root[keys][e], result_root.GetAllocator());
}
ts_start_ms+=interval_ms;
}
}
}
}
else{
GPRINT(MEDIUM_LEVEL,"not found temporary elements in redis\n");
}
return NO_ERROR;
}
eErrorTp dnk_biphasic_offset_cli::search_min_max(TIME_T & ts_start,TIME_T & ts_stop){
std::pair<eErrorTp, vector<string>> resmin,resmin_for_max,resmax;
resmin=command("ZRANGEBYSCORE ts 0 %u LIMIT 0 1",ts_stop);
if ((resmin.first==ERROR)||(resmin.second.size()==0))
return ERROR;
resmin_for_max=command("ZRANGE ts -1 -1");
if ((resmin_for_max.first==ERROR)||(resmin_for_max.second.size()==0))
return ERROR;
resmax=command("HMGET %s te",resmin_for_max.second[0].c_str());
if ((resmax.first==ERROR)||(resmax.second.size()==0))
return ERROR;
TIME_T minval=stol(resmin.second[0]);
TIME_T maxval=stol(resmax.second[0]);
if (ts_stop<minval){
GPRINT(MEDIUM_LEVEL,"Skip search:ts_stop[%u]<minval[%u]\n",ts_stop,minval);
return ERROR;
}
if (ts_start>maxval){
GPRINT(MEDIUM_LEVEL,"Skip search:ts_start[%u]<maxval[%u]\n",ts_start,maxval);
return ERROR;
}
if (ts_start<minval)
ts_start=minval;
if (ts_stop>maxval)
ts_stop=maxval;
if (ts_start>ts_stop){
GPRINT(MEDIUM_LEVEL,"Skip search:ts_start[%u]>ts_stop[%u]\n",ts_start,ts_stop);
return ERROR;
}
GPRINT(MEDIUM_LEVEL,"Found min %u max %u\n",ts_start,ts_stop);
//if (((minval>=ts_start)||(ts_start<0))&&((maxval<=ts_stop)||(ts_stop<0))){
// ts_start=minval
// ts_stop=maxval;
// return NO_ERROR;
//}
return NO_ERROR;
}
eErrorTp dnk_biphasic_offset_cli::make_selection_from_db(u64 ts_start_ms,u64 ts_stop_ms,rapidjson::Document & result_db_root){
std::pair<eErrorTp, vector<string>> res=command("GET u");
if (res.first==NO_ERROR){
std::pair<eErrorTp, vector<string>> res1=command("ZRANGEBYSCORE u%s %llu %llu",res.second[0].c_str(),ts_start_ms,ts_stop_ms);
if (res1.first==NO_ERROR){
if (res1.second.size()!=0){
string s="[";
for (u32 z=0;z<res1.second.size();z++){
s=s+res1.second[z]+',';
}
s[s.size()-1]=']';
rapidjson::ParseResult rp =result_db_root.Parse(s.c_str());
if (rp.Code()==0){
return NO_ERROR;
}
else
return ERROR;
}
return NO_ERROR;
}
else
return ERROR;
}
else
return NO_ERROR;
}
eErrorTp dnk_biphasic_offset_cli::GetFormatPath(string * format_path){
TIME_T t=TIME((u32*)NULL);
struct tm * ptm=GMTIME(&t);
u32 year=ptm->tm_year+1900;
//printf("e\n");
string dal_path0=string_format("%s/%s/%d/%s",dal_base_path[0].c_str(),DNK_BIPHASIC_PREFIX,year,dal_groupid.c_str());
//printf("e1\n");
string dal_path1=string_format("%s/%s/%d/%s",dal_base_path[1].c_str(),DNK_BIPHASIC_PREFIX,year,dal_groupid.c_str());
//printf("e2\n");
format_path[0]=dal_path0+'/'+FORMAT_TABLE_FILENAME;
format_path[1]=dal_path1+'/'+FORMAT_TABLE_FILENAME;
return NO_ERROR;
}
eErrorTp dnk_biphasic_offset_cli::GetDataFromGzip(string & result,string & fname,TIME_T ts,string * format_path){
struct tm * ptm=GMTIME(&ts);
u32 year=ptm->tm_year+1900;
string dal_path0=string_format("%s/%s/%d/%s",dal_base_path[0].c_str(),DNK_BIPHASIC_PREFIX,year,dal_groupid.c_str());
string dal_path1=string_format("%s/%s/%d/%s",dal_base_path[1].c_str(),DNK_BIPHASIC_PREFIX,year,dal_groupid.c_str());
string p0=dal_path0+'/'+fname;
string p1=dal_path1+'/'+fname;
format_path[0]=dal_path0+'/'+FORMAT_TABLE_FILENAME;
format_path[1]=dal_path1+'/'+FORMAT_TABLE_FILENAME;
//if (GetFileSize(p1.c_str()!=0)){
if (UngzipFile((char*)p0.c_str(),result)==NO_ERROR){
GPRINT(MEDIUM_LEVEL,"Success gunzip file %s\n",p0.c_str());
return NO_ERROR;
}
else{
GPRINT(NORMAL_LEVEL,"Error gunzip file %s, try gunzip reserved %s\n",p0.c_str(),p1.c_str());
if (UngzipFile((char*)p1.c_str(),result)==NO_ERROR)
{
GPRINT(MEDIUM_LEVEL,"Success gunzip file %s\n",p1.c_str());
remove((char*)p0.c_str());
CopyFile((char*)p1.c_str(),(char*)p0.c_str());
return NO_ERROR;
}
else{
GPRINT(NORMAL_LEVEL,"Error gunzip file %s\n",p1.c_str());
return ERROR;
}
}
return ERROR;
}
#endif
| 17,105 | 8,459 |
#include "stdafx.h"
std::vector<BYTE> ReadHex(std::wstring strIn)
{
std::vector<BYTE> dataOut(strIn.size() / 2);
for (uint32_t cursor = 0; cursor < dataOut.size(); cursor++)
{
dataOut[cursor] = (BYTE)std::stoul(strIn.substr(cursor * 2, 2), NULL, 16);
//if (swscanf_s(strIn.substr(cursor * 2, 2).c_str(), L"%x", &scannedDigit) != 1)
//{
// throw;
//}
// dataOut[cursor] = (BYTE)(scannedDigit & 0x000000FF);
}
return dataOut;
}
uint32_t GetTimeStamp(void)
{
FILETIME now = { 0 };
LARGE_INTEGER convert = { 0 };
// Get the current timestamp
GetSystemTimeAsFileTime(&now);
convert.LowPart = now.dwLowDateTime;
convert.HighPart = now.dwHighDateTime;
convert.QuadPart = (convert.QuadPart - (UINT64)(11644473600000 * 10000)) / 10000000;
return convert.LowPart;
}
void WriteToFile(std::wstring fileName, std::vector<BYTE> data, DWORD dwCreationDisposition)
{
// http://stackoverflow.com/questions/14841396/stdunique-ptr-deleters-and-the-win32-api
std::unique_ptr<std::remove_pointer<HANDLE>::type, decltype(&::CloseHandle)> hFile(::CreateFile(fileName.c_str(), GENERIC_WRITE, 0, NULL, dwCreationDisposition, FILE_ATTRIBUTE_NORMAL, NULL), &::CloseHandle);
SetFilePointer(hFile.get(), 0, 0, FILE_END);
DWORD bytesWritten = 0;
if (!WriteFile(hFile.get(), data.data(), data.size(), &bytesWritten, NULL))
{
throw GetLastError();
}
}
void WriteToFile(std::wstring fileName, std::string data)
{
// http://stackoverflow.com/questions/14841396/stdunique-ptr-deleters-and-the-win32-api
std::unique_ptr<std::remove_pointer<HANDLE>::type, decltype(&::CloseHandle)> hFile(::CreateFile(fileName.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL), &::CloseHandle);
DWORD bytesWritten = 0;
if (!WriteFile(hFile.get(), data.c_str(), data.size(), &bytesWritten, NULL))
{
throw GetLastError();
}
}
void WriteToFile(std::wstring fileName, UINT32 data)
{
// http://stackoverflow.com/questions/14841396/stdunique-ptr-deleters-and-the-win32-api
std::unique_ptr<std::remove_pointer<HANDLE>::type, decltype(&::CloseHandle)> hFile(::CreateFile(fileName.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL), &::CloseHandle);
DWORD bytesWritten = 0;
std::vector<byte> dataOut(16, 0);
dataOut.resize(sprintf_s((char*)dataOut.data(), dataOut.size(), "%ul", data) - 1);
if (!WriteFile(hFile.get(), dataOut.data(), dataOut.size(), &bytesWritten, NULL))
{
throw GetLastError();
}
}
std::string ReadStrFromFile(std::wstring fileName)
{
// http://stackoverflow.com/questions/14841396/stdunique-ptr-deleters-and-the-win32-api
std::unique_ptr<std::remove_pointer<HANDLE>::type, decltype(&::CloseHandle)> hFile(::CreateFile(fileName.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL), &::CloseHandle);
DWORD bytesRead = 0;
std::string data(GetFileSize(hFile.get(), NULL), '\0');
if (!ReadFile(hFile.get(), (LPVOID)data.c_str(), data.size(), &bytesRead, NULL))
{
throw GetLastError();
}
return data;
}
std::vector<BYTE> ReadFromFile(std::wstring fileName)
{
// http://stackoverflow.com/questions/14841396/stdunique-ptr-deleters-and-the-win32-api
std::unique_ptr<std::remove_pointer<HANDLE>::type, decltype(&::CloseHandle)> hFile(::CreateFile(fileName.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL), &::CloseHandle);
DWORD bytesRead = 0;
std::vector<BYTE> data(GetFileSize(hFile.get(), NULL));
if (!ReadFile(hFile.get(), data.data(), data.size(), &bytesRead, NULL))
{
throw GetLastError();
}
return data;
}
FILETIME ConvertWinTimeStamp(UINT32 timeStamp)
{
LARGE_INTEGER convert = { 0 };
convert.QuadPart = ((LONGLONG)timeStamp * 10000000) + (LONGLONG)(11644473600000 * 10000);
FILETIME out = { 0 };
out.dwLowDateTime = convert.LowPart;
out.dwHighDateTime = convert.HighPart;
return out;
}
PCCERT_CONTEXT CertFromFile(std::wstring fileName)
{
uint32_t retVal = 0;
std::vector<BYTE> rawCert = ReadFromFile(fileName);
DWORD result;
if (CryptStringToBinaryA((LPSTR)rawCert.data(), rawCert.size(), CRYPT_STRING_BASE64HEADER, NULL, &result, NULL, NULL))
{
std::vector<BYTE> derCert(result, 0);
if (!CryptStringToBinaryA((LPSTR)rawCert.data(), rawCert.size(), CRYPT_STRING_BASE64HEADER, derCert.data(), &result, NULL, NULL))
{
throw GetLastError();
}
rawCert = derCert;
}
PCCERT_CONTEXT hCert = NULL;
if ((hCert = CertCreateCertificateContext(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, rawCert.data(), rawCert.size())) == NULL)
{
throw retVal;
}
return hCert;
}
std::vector<BYTE> CertThumbPrint(PCCERT_CONTEXT hCert)
{
uint32_t retVal = 0;
BCRYPT_ALG_HANDLE hSha1 = NULL;
if ((retVal = BCryptOpenAlgorithmProvider(&hSha1, BCRYPT_SHA1_ALGORITHM, NULL, 0)) != 0)
{
throw retVal;
}
std::vector<BYTE> digest(20, 0);
if ((retVal = BCryptHash(hSha1, NULL, 0, hCert->pbCertEncoded, hCert->cbCertEncoded, digest.data(), digest.size())) != 0)
{
throw retVal;
}
BCryptCloseAlgorithmProvider(hSha1, 0);
return digest;
}
std::wstring ToHexWString(std::vector<BYTE> &byteVector)
{
std::wstring stringOut((byteVector.size() + 2) * 2, '\0');
DWORD result = stringOut.size();
if (!CryptBinaryToStringW(byteVector.data(), byteVector.size(), CRYPT_STRING_HEXRAW, (LPWSTR)stringOut.c_str(), &result))
{
throw GetLastError();
}
stringOut.resize(stringOut.size() - 4);
return stringOut;
}
std::string ToHexString(std::vector<BYTE> &byteVector)
{
std::string stringOut((byteVector.size() + 2) * 2, '\0');
DWORD result = stringOut.size();
if (!CryptBinaryToStringA(byteVector.data(), byteVector.size(), CRYPT_STRING_HEXRAW, (LPSTR)stringOut.c_str(), &result))
{
throw GetLastError();
}
stringOut.resize(stringOut.size() - 4);
return stringOut;
}
std::wstring ToDevIDWString(std::vector<BYTE> &byteVector, bool uri)
{
DWORD retVal;
DWORD result;
std::vector<BYTE> devID(byteVector.size() / 4, 0);
for (UINT32 n = 0; n < byteVector.size(); n++)
{
devID[n] = byteVector[n] ^ byteVector[byteVector.size() / 4 + n] ^ byteVector[byteVector.size() / 2 + n] ^ byteVector[byteVector.size() / 4 * 3 + n];
}
if (!CryptBinaryToStringW(devID.data(), devID.size(), uri ? CRYPT_STRING_BASE64URI : CRYPT_STRING_BASE64, NULL, &result))
{
retVal = GetLastError();
throw retVal;
}
std::wstring devIDStr(result, '\0');
if (!CryptBinaryToStringW(devID.data(), devID.size(), uri ? CRYPT_STRING_BASE64URI : CRYPT_STRING_BASE64, (LPWSTR)devIDStr.c_str(), &result))
{
retVal = GetLastError();
throw retVal;
}
devIDStr.resize(devIDStr.size() - 2);
devIDStr[devIDStr.size() - 1] = L'\0';
return devIDStr;
}
std::string ToDevIDString(std::vector<BYTE> &byteVector, bool uri)
{
DWORD retVal;
DWORD result;
std::vector<BYTE> devID(byteVector.size() / 4, 0);
for (UINT32 n = 0; n < byteVector.size(); n++)
{
devID[n] = byteVector[n] ^ byteVector[byteVector.size() / 4 + n] ^ byteVector[byteVector.size() / 2 + n] ^ byteVector[byteVector.size() / 4 * 3 + n];
}
if (!CryptBinaryToStringA(devID.data(), devID.size(), uri ? CRYPT_STRING_BASE64URI : CRYPT_STRING_BASE64, NULL, &result))
{
retVal = GetLastError();
throw retVal;
}
std::string devIDStr(result, '\0');
if (!CryptBinaryToStringA(devID.data(), devID.size(), uri ? CRYPT_STRING_BASE64URI : CRYPT_STRING_BASE64, (LPSTR)devIDStr.c_str(), &result))
{
retVal = GetLastError();
throw retVal;
}
devIDStr.resize(devIDStr.size() - 2);
devIDStr[devIDStr.size() - 1] = '\0';
return devIDStr;
}
| 8,008 | 3,102 |
#include <gtest/gtest.h>
#include "cpp_cachetools/policies.hpp"
#include "cpp_cachetools/indexes.hpp"
#include "cpp_cachetools/cache.hpp"
#include "../fake_clock/fake_clock.hh"
struct TTLTestCache: Cache<policies::Builder<policies::TTL<testing::fake_clock>::Class>::with_index<indexes::HashedIndex>::Class> {};
using namespace std::chrono_literals;
TEST(TTLCache, EvictsWhenTimeIsOver) {
auto cache_duration = testing::fake_clock::duration(60);
auto advance = testing::fake_clock::duration(31);
auto &&cache = TTLTestCache::build<int, int>(10, cache_duration);
cache->insert(1, 1);
testing::fake_clock::advance(advance);
auto not_expired = cache->get(1);
EXPECT_EQ(not_expired.value(), 1);
testing::fake_clock::advance(advance);
auto retrieved = cache->get(1);
EXPECT_EQ(retrieved, std::optional<int>{});
}
TEST(TTLCache, EvictsOlderFirstWhenFull) {
auto cache_duration = testing::fake_clock::duration(60);
auto advance = testing::fake_clock::duration(31);
auto &&cache = TTLTestCache::build<int, int>(2, cache_duration);
cache->insert(1, 1);
cache->insert(2, 2);
cache->insert(3, 3);
auto evicted_because_old = cache->get(1);
EXPECT_EQ(evicted_because_old, std::optional<int>{});
testing::fake_clock::advance(advance);
EXPECT_EQ(cache->get(2), 2);
EXPECT_EQ(cache->get(3), 3);
}
TEST(TTLCache, EvictsExpiredFirst) {
auto cache_duration = testing::fake_clock::duration(60);
auto advance = testing::fake_clock::duration(31);
auto &&cache = TTLTestCache::build<int, int>(2, cache_duration);
cache->insert(1, 1);
testing::fake_clock::advance(advance);
cache->insert(2, 2);
testing::fake_clock::advance(advance);
cache->insert(3, 3);
auto evicted_because_old = cache->get(1);
EXPECT_EQ(evicted_because_old, std::optional<int>{});
EXPECT_EQ(cache->get(2), 2);
testing::fake_clock::advance(advance);
EXPECT_EQ(cache->get(3), 3);
}
| 1,966 | 744 |
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "common_event_listener.h"
#include "event_log_wrapper.h"
namespace OHOS {
namespace EventFwk {
CommonEventListener::CommonEventListener(const std::shared_ptr<CommonEventSubscriber> &commonEventSubscriber)
: commonEventSubscriber_(commonEventSubscriber)
{
Init();
}
CommonEventListener::~CommonEventListener()
{}
void CommonEventListener::NotifyEvent(const CommonEventData &commonEventData, const bool &ordered, const bool &sticky)
{
EVENT_LOGI("enter");
if (!IsReady()) {
EVENT_LOGE("not ready");
return;
}
std::function<void()> onReceiveEventFunc =
std::bind(&CommonEventListener::OnReceiveEvent, this, commonEventData, ordered, sticky);
handler_->PostTask(onReceiveEventFunc);
}
ErrCode CommonEventListener::Init()
{
EVENT_LOGD("ready to init");
if (runner_ == nullptr) {
if (!commonEventSubscriber_) {
EVENT_LOGE("Failed to init with CommonEventSubscriber nullptr");
return ERR_INVALID_OPERATION;
}
if (CommonEventSubscribeInfo::HANDLER == commonEventSubscriber_->GetSubscribeInfo().GetThreadMode()) {
runner_ = EventRunner::GetMainEventRunner();
} else {
runner_ = EventRunner::Create(true);
}
if (!runner_) {
EVENT_LOGE("Failed to init due to create runner error");
return ERR_INVALID_OPERATION;
}
}
if (handler_ == nullptr) {
handler_ = std::make_shared<EventHandler>(runner_);
if (!handler_) {
EVENT_LOGE("Failed to init due to create handler error");
return ERR_INVALID_OPERATION;
}
}
return ERR_OK;
}
bool CommonEventListener::IsReady()
{
if (runner_ == nullptr) {
EVENT_LOGE("runner is not ready");
return false;
}
if (handler_ == nullptr) {
EVENT_LOGE("handler is not ready");
return false;
}
return true;
}
void CommonEventListener::OnReceiveEvent(
const CommonEventData &commonEventData, const bool &ordered, const bool &sticky)
{
EVENT_LOGI("enter");
int code = commonEventData.GetCode();
std::string data = commonEventData.GetData();
std::shared_ptr<AsyncCommonEventResult> result =
std::make_shared<AsyncCommonEventResult>(code, data, ordered, sticky, this);
if (result == nullptr) {
EVENT_LOGE("Failed to create AsyncCommonEventResult");
return;
}
if (!commonEventSubscriber_) {
EVENT_LOGE("CommonEventSubscriber ptr is nullptr");
return;
}
commonEventSubscriber_->SetAsyncCommonEventResult(result);
commonEventSubscriber_->OnReceiveEvent(commonEventData);
if ((commonEventSubscriber_->GetAsyncCommonEventResult() != nullptr) && ordered) {
commonEventSubscriber_->GetAsyncCommonEventResult()->FinishCommonEvent();
}
}
} // namespace EventFwk
} // namespace OHOS | 3,520 | 1,048 |
#include "OpenCommand.h"
bool OpenCommand::can_execute(const CommandContext& context) const
{
return !context.is_file_open();
}
void OpenCommand::execute(const CommandContext& context) const
{
if (context.args_count() != 2)
{
throw CommandParamsException();
}
const std::string path = context.arg(PATH_INDEX);
context.open_svg(path);
}
void OpenCommand::onSuccess(const CommandContext& context) const
{
context.out() << "Successfully opened file " << context.file_path() << "." << std::endl;
}
| 508 | 167 |
//===-- MCTargetOptionsCommandFlags.cpp --------------------------*- C++
//-*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file contains machine code-specific flags that are shared between
// different command line tools.
//
//===----------------------------------------------------------------------===//
#include "llvm/MC/MCTargetOptionsCommandFlags.h"
using namespace llvm;
#define MCOPT(TY, NAME) \
static cl::opt<TY> *NAME##View; \
TY llvm::mc::get##NAME() { \
assert(NAME##View && "RegisterMCTargetOptionsFlags not created."); \
return *NAME##View; \
}
#define MCOPT_EXP(TY, NAME) \
MCOPT(TY, NAME) \
Optional<TY> llvm::mc::getExplicit##NAME() { \
if (NAME##View->getNumOccurrences()) { \
TY res = *NAME##View; \
return res; \
} \
return None; \
}
MCOPT_EXP(bool, RelaxAll)
MCOPT(bool, IncrementalLinkerCompatible)
MCOPT(int, DwarfVersion)
MCOPT(bool, ShowMCInst)
MCOPT(bool, FatalWarnings)
MCOPT(bool, NoWarn)
MCOPT(bool, NoDeprecatedWarn)
MCOPT(std::string, ABIName)
llvm::mc::RegisterMCTargetOptionsFlags::RegisterMCTargetOptionsFlags() {
#define MCBINDOPT(NAME) \
do { \
NAME##View = std::addressof(NAME); \
} while (0)
static cl::opt<bool> RelaxAll(
"mc-relax-all", cl::desc("When used with filetype=obj, relax all fixups "
"in the emitted object file"));
MCBINDOPT(RelaxAll);
static cl::opt<bool> IncrementalLinkerCompatible(
"incremental-linker-compatible",
cl::desc(
"When used with filetype=obj, "
"emit an object file which can be used with an incremental linker"));
MCBINDOPT(IncrementalLinkerCompatible);
static cl::opt<int> DwarfVersion("dwarf-version", cl::desc("Dwarf version"),
cl::init(0));
MCBINDOPT(DwarfVersion);
static cl::opt<bool> ShowMCInst(
"asm-show-inst",
cl::desc("Emit internal instruction representation to assembly file"));
MCBINDOPT(ShowMCInst);
static cl::opt<bool> FatalWarnings("fatal-warnings",
cl::desc("Treat warnings as errors"));
MCBINDOPT(FatalWarnings);
static cl::opt<bool> NoWarn("no-warn", cl::desc("Suppress all warnings"));
static cl::alias NoWarnW("W", cl::desc("Alias for --no-warn"),
cl::aliasopt(NoWarn));
MCBINDOPT(NoWarn);
static cl::opt<bool> NoDeprecatedWarn(
"no-deprecated-warn", cl::desc("Suppress all deprecated warnings"));
MCBINDOPT(NoDeprecatedWarn);
static cl::opt<std::string> ABIName(
"target-abi", cl::Hidden,
cl::desc("The name of the ABI to be targeted from the backend."),
cl::init(""));
MCBINDOPT(ABIName);
#undef MCBINDOPT
}
MCTargetOptions llvm::mc::InitMCTargetOptionsFromFlags() {
MCTargetOptions Options;
Options.MCRelaxAll = getRelaxAll();
Options.MCIncrementalLinkerCompatible = getIncrementalLinkerCompatible();
Options.DwarfVersion = getDwarfVersion();
Options.ShowMCInst = getShowMCInst();
Options.ABIName = getABIName();
Options.MCFatalWarnings = getFatalWarnings();
Options.MCNoWarn = getNoWarn();
Options.MCNoDeprecatedWarn = getNoDeprecatedWarn();
return Options;
}
| 4,249 | 1,225 |
//===========================================================================
/*
Software License Agreement (BSD License)
Copyright (c) 2003-2012, CHAI3D.
(www.chai3d.org)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of CHAI3D nor the names of its contributors may
be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER 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.
\author <http://www.chai3d.org>
\author Sebastien Grange
\version $MAJOR.$MINOR.$RELEASE $Rev: 387 $
*/
//===========================================================================
//---------------------------------------------------------------------------
#include "system/CString.h"
#include "math/CMaths.h"
//---------------------------------------------------------------------------
#include <iostream>
#include <iomanip>
using namespace std;
//---------------------------------------------------------------------------
//===========================================================================
/*!
Compute the length of a string up to 255 characters. If the end of string
cannot be found, then -1 is returned as a result.
\param a_string Input string. Pointer to a char.
\return Return the length of the string.
*/
//===========================================================================
int cStringLength(const char* a_input)
{
return (int)(strlen(a_input));
}
//===========================================================================
/*!
Convert a string into lower case.
\param a_string Input string
\return Returns the output string.
*/
//===========================================================================
string cStringToLower(const string& a_input)
{
string result = a_input;
transform(result.begin(), result.end(), result.begin(), ::tolower);
return (result);
}
//===========================================================================
/*!
Finds the extension in a filename.
\param a_input Input filename.
\param a_includeDot If \b true, include the dot at the beginning of
the extension. (example: ".jpg")
\return Returns a string containing the extension.
*/
//===========================================================================
string cFindFileExtension(const string& a_input,
const bool a_includeDot)
{
int pos = (int)(a_input.find_last_of("."));
if (pos < 0) return "";
if (a_includeDot)
{
return a_input.substr(pos, a_input.length());
}
else
{
return a_input.substr(pos+1, a_input.length());
}
}
//===========================================================================
/*!
Discards the path component of a filename and returns the filename itself,
optionally including the extension.
\param a_input Input string containing path and filename
\param a_includeExtension Should the output include the extension?
\return Returns the output string.
*/
//===========================================================================
string cFindFilename(const string& a_input,
const bool a_includeFileExtension)
{
string result = a_input;
int pos = (int)(result.find_last_of("\\"));
if (pos > -1) result = result.substr(pos+1, result.length()-pos-1);
pos = (int)(result.find_last_of("/"));
if (pos > -1) result = result.substr(pos+1, result.length()-pos-1);
if (!a_includeFileExtension)
{
pos = (int)(result.find_last_of("."));
result = result.substr(0, pos);
}
return (result);
}
//===========================================================================
/*!
Returns the string a_filename by replacing its extension with a new
string provided by parameter a_extension.
\param a_filename The input filename
\param a_extension The extension to replace a_input's extension with
\return Returns the output string.
*/
//===========================================================================
string cReplaceFileExtension(const string& a_filename,
const string& a_extension)
{
string result = a_filename;
int pos = (int)(result.find_last_of("."));
if (pos < 0) return a_filename;
result.replace(pos+1, result.length(), a_extension);
return (result);
}
//===========================================================================
/*!
Finds only the _path_ portion of source, and copies it with
_no_ trailing '\\'. If there's no /'s or \\'s, writes an
empty string.
\param a_dest String which will contain the directory name.
\param a_source Input string containing path and filename.
\return Return \b true for success, \b false if there's no separator.
*/
//===========================================================================
string cFindDirectory(const string& a_input)
{
return (a_input.substr(0, a_input.length() - cFindFilename(a_input, true).length()));
}
//===========================================================================
/*!
Convert a \e boolean into a \e string.
\param a_value Input value of type \e boolean.
\return Return output string.
*/
//===========================================================================
string cStr(const bool a_value)
{
string result;
if (a_value)
result = "true";
else
result = "false";
return (result);
}
//===========================================================================
/*!
Convert an \e integer into a \e string.
\param a_value Input value of type \e integer.
\return Return output string.
*/
//===========================================================================
string cStr(const int a_value)
{
ostringstream result;
result << a_value;
return (result.str());
}
//===========================================================================
/*!
Convert a \e float into a \e string.
\param a_value Input value of type \e float.
\param a_precision Number of digits displayed after the decimal point.
\return Return output string.
*/
//===========================================================================
string cStr(const float a_value,
const unsigned int a_precision)
{
ostringstream result;
result << fixed << setprecision(a_precision) << a_value;
return (result.str());
}
//===========================================================================
/*!
Convert a \e double into a \e string.
\param a_value Input value of type \e double.
\param a_precision Number of digits displayed after the decimal point.
\return Return output string.
*/
//===========================================================================
string cStr(const double& a_value,
const unsigned int a_precision)
{
ostringstream result;
result << fixed << setprecision(a_precision) << a_value;
return (result.str());
}
| 8,685 | 2,430 |
#pragma once // Source encoding: UTF-8 with BOM (π is a firstcase Greek "pi").
#include <cppx-core-language/assert-cpp/is-c++17-or-later.hpp>
#include <cppx-core-language/mix-in/Adapt_as_forward_iterator_.hpp> // cppx::mix_in::Adapt_as_forward_iterator_
#include <cppx-core-language/types/Truth.hpp> // cppx::Truth
#include <cppx-core-language/tmp/Enable_if_.hpp> // cppx::Enable_if_
#include <cppx-core-language/tmp/type-checkers.hpp> // cppx::is_integral_
#include <cppx-core-language/tmp/type-modifiers.hpp> // cppx::As_unsigned_
#include <cppx-core-language/calc/number-type-properties.hpp> // cppx::(min_, max_)
#include <c/assert.hpp>
namespace cppx::_{
template<
class Integer,
class = Enable_if_< is_integral_<Integer> >
>
class Sequence_
{
using Unsigned = As_unsigned_<Integer>;
Unsigned m_first;
Unsigned m_last;
class Iterator:
public mix_in::Adapt_as_forward_iterator_<Iterator, Integer>
{
Unsigned m_current;
public:
void advance() { ++m_current; }
auto operator*() const noexcept
-> Integer
{ return static_cast<Integer>( m_current ); }
friend auto operator==( const Iterator& a, const Iterator& b ) noexcept
-> Truth
{ return a.m_current == b.m_current; }
explicit Iterator( const Integer value ) noexcept
: m_current( static_cast<Unsigned>( value ) )
{}
};
public:
constexpr auto first() const noexcept
-> Integer
{ return static_cast<Integer>( m_first ); }
constexpr auto last() const noexcept
-> Integer
{ return static_cast<Integer>( m_last ); }
constexpr auto n_values() const noexcept
-> Integer
{ return static_cast<Integer>( 1 + m_last - m_first ); }
constexpr auto is_empty() const noexcept
-> Truth
{ return n_values() == 0; }
template< class Value_integer >
constexpr auto contains( const Value_integer x ) const noexcept
-> Truth
{
if constexpr( max_<Value_integer> > max_<Integer> ) {
if( x > max_<Integer> ) {
return false;
}
}
if constexpr( min_<Value_integer> < min_<Integer> ) {
// Here Value_integer is necessarily a signed type.
if constexpr( is_signed_<Integer> ) {
if( x < min_<Integer> ) {
return false;
}
} else {
if( x < 0 ) { // Comparing to Integer(0) could wrap.
return false;
}
}
}
return m_first <= Unsigned( x ) and Unsigned( x ) <= m_last;
}
auto begin() const noexcept -> Iterator { return Iterator( m_first ); }
auto end() const noexcept -> Iterator { return Iterator( m_last + 1 ); }
constexpr Sequence_( const Integer first, const Integer last ) noexcept
: m_first( first )
, m_last( last )
{
assert(
first <= last or
static_cast<Unsigned>( first ) == static_cast<Unsigned>( last ) + 1
);
}
};
using Sequence = Sequence_<int>;
// Free function notation / convention adapters:
template< class Integer >
inline constexpr auto n_items( const Sequence_<Integer>& seq ) noexcept
-> Size
{ return seq.n_values(); }
template< class Integer >
inline constexpr auto is_empty( const Sequence_<Integer>& seq ) noexcept
-> Size
{ return seq.is_empty(); }
template< class Integer, class Value_integer >
inline constexpr auto is_in( const Sequence_<Integer>& seq, const Value_integer v ) noexcept
-> Truth
{ return seq.contains( v ); }
// Factory functions:
template< class Integer >
inline constexpr auto zero_to( const Integer n ) noexcept
-> Sequence_<Integer>
{ return Sequence_<Integer>( 0, n - 1 ); }
template< class Integer >
inline constexpr auto one_through( const Integer n ) noexcept
-> Sequence_<Integer>
{ return Sequence_<Integer>( 1, n ); }
} // namespace cppx::_
// Exporting namespaces:
namespace cppx {
namespace syntax {
CPPX_USE_FROM_NAMESPACE( _,
Sequence_,
Sequence,
zero_to,
one_through,
is_in
);
} // namespace syntax
using namespace cppx::syntax;
} // namespace cppx
| 4,831 | 1,382 |
//
// EreDownloader.hpp
// Strategy Pattern
//
// Created by Liangchuan Gu on 12/12/2015.
// Copyright © 2015 Lee Inc. All rights reserved.
//
#ifndef EreDownloader_hpp
#define EreDownloader_hpp
#include "FeedDownloader.hpp"
namespace Li{
class EreDownloader : public FeedDownloader
{
public:
EreDownloader(const std::string& externalRetrievalId);
EreDownloader(const EreDownloader& other);
EreDownloader& operator=(const EreDownloader& other);
virtual int retrieveFileList();
};
} // End of namespace Li
#endif /* EreDownloader_hpp */
| 598 | 205 |
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/projector/projector_controller_impl.h"
#include "ash/capture_mode/capture_mode_controller.h"
#include "ash/capture_mode/capture_mode_metrics.h"
#include "ash/projector/projector_metadata_controller.h"
#include "ash/projector/projector_ui_controller.h"
#include "ash/public/cpp/projector/projector_client.h"
#include "ash/public/cpp/projector/projector_session.h"
#include "ash/shell.h"
#include "base/bind.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/current_thread.h"
#include "base/task/thread_pool.h"
#include "media/mojo/mojom/speech_recognition_service.mojom.h"
namespace ash {
namespace {
// String format of the screencast name.
constexpr char kScreencastPathFmtStr[] =
"Screencast %d-%02d-%02d %02d.%02d.%02d";
// Create directory. Returns true if saving succeeded, or false otherwise.
bool CreateDirectory(const base::FilePath& path) {
DCHECK(!base::CurrentUIThread::IsSet());
DCHECK(!path.empty());
// The path is constructed from datetime which should be unique for most
// cases. In case it is already exist, returns false.
if (base::PathExists(path)) {
LOG(ERROR) << "Path has already existed: " << path;
return false;
}
if (!base::CreateDirectory(path)) {
LOG(ERROR) << "Failed to create path: " << path;
return false;
}
return true;
}
std::string GetScreencastName() {
base::Time::Exploded exploded_time;
base::Time::Now().LocalExplode(&exploded_time);
return base::StringPrintf(kScreencastPathFmtStr, exploded_time.year,
exploded_time.month, exploded_time.day_of_month,
exploded_time.hour, exploded_time.minute,
exploded_time.second);
}
} // namespace
ProjectorControllerImpl::ProjectorControllerImpl()
: projector_session_(std::make_unique<ash::ProjectorSessionImpl>()),
ui_controller_(std::make_unique<ash::ProjectorUiController>(this)),
metadata_controller_(
std::make_unique<ash::ProjectorMetadataController>()) {}
ProjectorControllerImpl::~ProjectorControllerImpl() = default;
// static
ProjectorControllerImpl* ProjectorControllerImpl::Get() {
return static_cast<ProjectorControllerImpl*>(ProjectorController::Get());
}
void ProjectorControllerImpl::StartProjectorSession(
const std::string& storage_dir) {
DCHECK(CanStartNewSession());
auto* controller = CaptureModeController::Get();
if (!controller->is_recording_in_progress()) {
// A capture mode session can be blocked by many factors, such as policy,
// DLP, ... etc. We don't start a Projector session until we're sure a
// capture session started.
controller->Start(CaptureModeEntryType::kProjector);
if (controller->IsActive())
projector_session_->Start(storage_dir);
}
}
void ProjectorControllerImpl::CreateScreencastContainerFolder(
CreateScreencastContainerFolderCallback callback) {
base::FilePath mounted_path;
if (!client_->GetDriveFsMountPointPath(&mounted_path)) {
LOG(ERROR) << "Failed to get DriveFs mounted point path.";
// TODO(b/200846160): Notify user when there is an error.
std::move(callback).Run(base::FilePath());
return;
}
auto path = mounted_path.Append("root")
.Append(projector_session_->storage_dir())
.Append(GetScreencastName());
base::ThreadPool::PostTaskAndReplyWithResult(
FROM_HERE, {base::MayBlock()}, base::BindOnce(&CreateDirectory, path),
base::BindOnce(&ProjectorControllerImpl::OnContainerFolderCreated,
weak_factory_.GetWeakPtr(), path, std::move(callback)));
}
void ProjectorControllerImpl::SetClient(ProjectorClient* client) {
client_ = client;
}
void ProjectorControllerImpl::OnSpeechRecognitionAvailable(bool available) {
if (ProjectorController::AreExtendedProjectorFeaturesDisabled())
return;
if (available == is_speech_recognition_available_)
return;
is_speech_recognition_available_ = available;
}
void ProjectorControllerImpl::OnTranscription(
const media::SpeechRecognitionResult& result) {
// Render transcription.
if (is_caption_on_) {
ui_controller_->OnTranscription(result.transcription, result.is_final);
}
if (result.is_final && result.timing_information.has_value()) {
// Records final transcript.
metadata_controller_->RecordTranscription(result);
}
}
void ProjectorControllerImpl::OnTranscriptionError() {
CaptureModeController::Get()->EndVideoRecording(
EndRecordingReason::kProjectorTranscriptionError);
}
bool ProjectorControllerImpl::IsEligible() const {
return is_speech_recognition_available_ ||
ProjectorController::AreExtendedProjectorFeaturesDisabled();
}
bool ProjectorControllerImpl::CanStartNewSession() const {
// TODO(crbug.com/1165435) Add other pre-conditions to starting a new
// projector session.
return IsEligible() && !projector_session_->is_active() &&
client_->IsDriveFsMounted();
}
void ProjectorControllerImpl::OnToolSet(const chromeos::AnnotatorTool& tool) {
// TODO(b/198184362): Reflect the annotator tool changes on the Projector
// toolbar.
}
void ProjectorControllerImpl::OnUndoRedoAvailabilityChanged(
bool undo_available,
bool redo_available) {
// TODO(b/198184362): Reflect undo and redo buttons availability on the
// Projector toolbar.
}
void ProjectorControllerImpl::SetCaptionBubbleState(bool is_on) {
ui_controller_->SetCaptionBubbleState(is_on);
}
void ProjectorControllerImpl::OnCaptionBubbleModelStateChanged(bool is_on) {
is_caption_on_ = is_on;
}
void ProjectorControllerImpl::MarkKeyIdea() {
metadata_controller_->RecordKeyIdea();
ui_controller_->OnKeyIdeaMarked();
}
void ProjectorControllerImpl::OnRecordingStarted() {
ui_controller_->ShowToolbar();
StartSpeechRecognition();
ui_controller_->OnRecordingStateChanged(true /* started */);
metadata_controller_->OnRecordingStarted();
}
void ProjectorControllerImpl::OnRecordingEnded() {
DCHECK(projector_session_->is_active());
StopSpeechRecognition();
ui_controller_->OnRecordingStateChanged(false /* started */);
// TODO(b/197152209): move closing selfie cam to ProjectorUiController.
if (client_->IsSelfieCamVisible())
client_->CloseSelfieCam();
// Close Projector toolbar.
ui_controller_->CloseToolbar();
if (projector_session_->screencast_container_path()) {
// Finish saving the screencast if the container is available. The container
// might be unavailable if fail in creating the directory.
SaveScreencast();
}
projector_session_->Stop();
// At this point, the screencast might not synced to Drive yet. Open
// Projector App which showing the Gallery view by default.
client_->OpenProjectorApp();
}
void ProjectorControllerImpl::OnRecordingStartAborted() {
DCHECK(projector_session_->is_active());
// Delete the DriveFS path that might have been created for this aborted
// session if any.
if (projector_session_->screencast_container_path()) {
base::ThreadPool::PostTask(
FROM_HERE, {base::MayBlock()},
base::BindOnce(base::GetDeletePathRecursivelyCallback(),
*projector_session_->screencast_container_path()));
}
projector_session_->Stop();
}
void ProjectorControllerImpl::OnLaserPointerPressed() {
ui_controller_->OnLaserPointerPressed();
}
void ProjectorControllerImpl::OnMarkerPressed() {
ui_controller_->OnMarkerPressed();
}
void ProjectorControllerImpl::OnClearAllMarkersPressed() {
ui_controller_->OnClearAllMarkersPressed();
}
void ProjectorControllerImpl::OnUndoPressed() {
ui_controller_->OnUndoPressed();
}
void ProjectorControllerImpl::OnSelfieCamPressed(bool enabled) {
ui_controller_->OnSelfieCamPressed(enabled);
DCHECK_NE(client_, nullptr);
if (enabled == client_->IsSelfieCamVisible())
return;
if (enabled) {
client_->ShowSelfieCam();
return;
}
client_->CloseSelfieCam();
}
void ProjectorControllerImpl::OnMagnifierButtonPressed(bool enabled) {
ui_controller_->OnMagnifierButtonPressed(enabled);
}
void ProjectorControllerImpl::OnChangeMarkerColorPressed(SkColor new_color) {
ui_controller_->OnChangeMarkerColorPressed(new_color);
}
void ProjectorControllerImpl::SetProjectorUiControllerForTest(
std::unique_ptr<ProjectorUiController> ui_controller) {
ui_controller_ = std::move(ui_controller);
}
void ProjectorControllerImpl::SetProjectorMetadataControllerForTest(
std::unique_ptr<ProjectorMetadataController> metadata_controller) {
metadata_controller_ = std::move(metadata_controller);
}
void ProjectorControllerImpl::StartSpeechRecognition() {
if (ProjectorController::AreExtendedProjectorFeaturesDisabled())
return;
DCHECK(is_speech_recognition_available_);
DCHECK(!is_speech_recognition_on_);
DCHECK_NE(client_, nullptr);
client_->StartSpeechRecognition();
is_speech_recognition_on_ = true;
}
void ProjectorControllerImpl::StopSpeechRecognition() {
if (ProjectorController::AreExtendedProjectorFeaturesDisabled())
return;
DCHECK(is_speech_recognition_available_);
DCHECK(is_speech_recognition_on_);
DCHECK_NE(client_, nullptr);
client_->StopSpeechRecognition();
is_speech_recognition_on_ = false;
}
void ProjectorControllerImpl::OnContainerFolderCreated(
const base::FilePath& path,
CreateScreencastContainerFolderCallback callback,
bool success) {
if (!success) {
LOG(ERROR) << "Failed to create screencast container path: "
<< path.DirName();
std::move(callback).Run(base::FilePath());
return;
}
projector_session_->set_screencast_container_path(path);
std::move(callback).Run(GetScreencastFilePathNoExtension());
}
void ProjectorControllerImpl::SaveScreencast() {
metadata_controller_->SaveMetadata(GetScreencastFilePathNoExtension());
}
base::FilePath ProjectorControllerImpl::GetScreencastFilePathNoExtension()
const {
auto screencast_container_path =
projector_session_->screencast_container_path();
DCHECK(screencast_container_path.has_value());
return screencast_container_path->Append(GetScreencastName());
}
} // namespace ash
| 10,424 | 3,258 |
/**
* Author: Alessio Placitelli
* Contact: a.placitelli _@_ a2p.it
*
*/
#include "GPUImageLookupFilter.h"
const std::string GPUImageLookupFilter::kGPUImageLookupFragmentShaderString("\
varying highp vec2 textureCoordinate;\
varying highp vec2 textureCoordinate2;\
\
uniform sampler2D inputImageTexture;\
uniform sampler2D inputImageTexture2;\
\
void main()\
{\
lowp vec4 textureColor = texture2D(inputImageTexture, textureCoordinate);\
\
mediump float blueColor = textureColor.b * 63.0;\
\
mediump vec2 quad1;\
quad1.y = floor(floor(blueColor) / 8.0);\
quad1.x = floor(blueColor) - (quad1.y * 8.0);\
\
mediump vec2 quad2;\
quad2.y = floor(ceil(blueColor) / 8.0);\
quad2.x = ceil(blueColor) - (quad2.y * 8.0);\
\
highp vec2 texPos1;\
texPos1.x = (quad1.x * 0.125) + 0.5/512.0 + ((0.125 - 1.0/512.0) * textureColor.r);\
texPos1.y = (quad1.y * 0.125) + 0.5/512.0 + ((0.125 - 1.0/512.0) * textureColor.g);\
\
highp vec2 texPos2;\
texPos2.x = (quad2.x * 0.125) + 0.5/512.0 + ((0.125 - 1.0/512.0) * textureColor.r);\
texPos2.y = (quad2.y * 0.125) + 0.5/512.0 + ((0.125 - 1.0/512.0) * textureColor.g);\
\
lowp vec4 newColor1 = texture2D(inputImageTexture2, texPos1);\
lowp vec4 newColor2 = texture2D(inputImageTexture2, texPos2);\
\
lowp vec4 newColor = mix(newColor1, newColor2, fract(blueColor));\
gl_FragColor = vec4(newColor.rgb, textureColor.w);\
}"
);
GPUImageLookupFilter::GPUImageLookupFilter() :
GPUImageTwoInputFilter()
{
GPUImageTwoInputFilter::initWithFragmentShaderFromString(kGPUImageLookupFragmentShaderString);
}
GPUImageLookupFilter::~GPUImageLookupFilter()
{
} | 1,724 | 729 |
/* Copyright 2016-2018 Dimitrij Mijoski
*
* This file is part of Nuspell.
*
* Nuspell 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.
*
* Nuspell 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 Nuspell. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file aff_data.hxx
* Affixing data structures.
*/
#ifndef NUSPELL_AFF_DATA_HXX
#define NUSPELL_AFF_DATA_HXX
#include <iosfwd>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include "locale_utils.hxx"
#include "structures.hxx"
namespace nuspell {
auto get_locale_name(std::string lang, std::string enc,
const std::string& filename = "") -> std::string;
class Encoding {
std::string name;
public:
enum Enc_Type { SINGLEBYTE = false, UTF8 = true };
Encoding() = default;
Encoding(const std::string& e);
auto operator=(const std::string& e) -> Encoding&;
auto empty() const -> bool { return name.empty(); }
operator const std::string&() const { return name; }
auto value() const -> const std::string& { return name; }
auto is_utf8() const -> bool { return name == "UTF-8"; }
operator Enc_Type() const { return is_utf8() ? UTF8 : SINGLEBYTE; }
};
enum Flag_Type {
FLAG_SINGLE_CHAR /**< single-character flag, e.g. for "a" */,
FLAG_DOUBLE_CHAR /**< double-character flag, e.g for "aa" */,
FLAG_NUMBER /**< numerical flag, e.g. for 61 */,
FLAG_UTF8 /**< UTF-8 flag, e.g. for "á" */
};
template <class CharT>
struct Aff_Structures {
Substr_Replacer<CharT> input_substr_replacer;
Substr_Replacer<CharT> output_substr_replacer;
Break_Table<CharT> break_table;
std::basic_string<CharT> ignored_chars;
Prefix_Table<CharT> prefixes;
Suffix_Table<CharT> suffixes;
std::vector<Compound_Pattern<CharT>> compound_patterns;
};
struct Affix {
using string = std::string;
template <class T>
using vector = std::vector<T>;
char16_t flag;
bool cross_product;
string stripping;
string appending;
Flag_Set new_flags;
string condition;
vector<string> morphological_fields;
};
struct Compound_Check_Pattern {
using string = std::string;
string first_word_end;
string second_word_begin;
string replacement;
char16_t first_word_flag;
char16_t second_word_flag;
};
using Dic_Data_Base =
Hash_Multiset<std::pair<std::string, Flag_Set>, std::string,
member<std::pair<std::string, Flag_Set>, std::string,
&std::pair<std::string, Flag_Set>::first>>;
/**
* @brief Map between words and word_flags.
*
* Flags are stored as part of the container. Maybe for the future flags should
* be stored elsewhere (flag aliases) and this should store pointers.
*
* Does not store morphological data as is low priority feature and is out of
* scope.
*/
class Dic_Data : public Dic_Data_Base {
public:
using Dic_Data_Base::equal_range;
auto equal_range(const std::wstring& word) const
-> std::pair<Dic_Data_Base::local_const_iterator,
Dic_Data_Base::local_const_iterator>
{
return equal_range(boost::locale::conv::utf_to_utf<char>(word));
}
};
struct Aff_Data {
// types
using string = std::string;
using u16string = std::u16string;
using istream = std::istream;
template <class T>
using vector = std::vector<T>;
template <class T, class U>
using pair = std::pair<T, U>;
// data members
// word list
Dic_Data words;
Aff_Structures<char> structures;
Aff_Structures<wchar_t> wide_structures;
// general options
std::locale locale_aff;
Flag_Type flag_type;
bool complex_prefixes;
bool fullstrip;
bool checksharps;
bool forbid_warn;
char16_t circumfix_flag;
char16_t forbiddenword_flag;
char16_t keepcase_flag;
char16_t need_affix_flag;
char16_t substandard_flag;
char16_t warn_flag;
vector<Flag_Set> flag_aliases;
string wordchars; // deprecated?
// suggestion options
string keyboard_layout;
string try_chars;
char16_t nosuggest_flag;
unsigned short max_compound_suggestions;
unsigned short max_ngram_suggestions;
unsigned short max_diff_factor;
bool only_max_diff;
bool no_split_suggestions;
bool suggest_with_dots;
vector<pair<string, string>> replacements;
vector<string> map_related_chars; // vector<vector<string>>?
vector<pair<string, string>> phonetic_replacements;
// compounding options
unsigned short compound_min_length;
unsigned short compound_max_word_count;
char16_t compound_flag;
char16_t compound_begin_flag;
char16_t compound_last_flag;
char16_t compound_middle_flag;
char16_t compound_onlyin_flag;
char16_t compound_permit_flag;
char16_t compound_forbid_flag;
char16_t compound_root_flag;
char16_t compound_force_uppercase;
bool compound_more_suffixes;
bool compound_check_up;
bool compound_check_rep;
bool compound_check_case;
bool compound_check_triple;
bool compound_simplified_triple;
vector<u16string> compound_rules;
unsigned short compound_syllable_max;
string compound_syllable_vowels;
Flag_Set compound_syllable_num;
// methods
auto set_encoding_and_language(const string& enc,
const string& lang = "") -> void;
auto parse_aff(istream& in) -> bool;
auto parse_dic(istream& in) -> bool;
auto parse_aff_dic(std::istream& aff, std::istream& dic)
{
if (parse_aff(aff))
return parse_dic(dic);
return false;
}
template <class CharT>
auto get_structures() const -> const Aff_Structures<CharT>&;
};
template <>
auto inline Aff_Data::get_structures<char>() const
-> const Aff_Structures<char>&
{
return structures;
}
template <>
auto inline Aff_Data::get_structures<wchar_t>() const
-> const Aff_Structures<wchar_t>&
{
return wide_structures;
}
} // namespace nuspell
#endif // NUSPELL_AFF_DATA_HXX
| 6,148 | 2,203 |
// author : Boris Kolpackov <boris@kolpackov.net>
// $Id: Retransmit.cpp 91626 2010-09-07 10:59:20Z johnnyw $
#include "ace/Time_Value.h" // ACE_Time_Value
#include "ace/OS_NS_stdlib.h" // abort
#include "ace/OS_NS_sys_time.h" // gettimeofday
#include "Retransmit.h"
namespace ACE_RMCast
{
Retransmit::
Retransmit (Parameters const& params)
: params_ (params),
cond_ (mutex_),
stop_ (false)
{
}
void Retransmit::
out_start (Out_Element* out)
{
Element::out_start (out);
tracker_mgr_.spawn (track_thunk, this);
}
void Retransmit::
out_stop ()
{
{
Lock l (mutex_);
stop_ = true;
cond_.signal ();
}
tracker_mgr_.wait ();
Element::out_stop ();
}
void Retransmit::send (Message_ptr m)
{
if (m->find (Data::id) != 0)
{
SN const* sn = static_cast<SN const*> (m->find (SN::id));
Lock l (mutex_);
queue_.bind (sn->num (), Descr (m->clone ()));
}
out_->send (m);
}
void Retransmit::recv (Message_ptr m)
{
if (NAK const* nak = static_cast<NAK const*> (m->find (NAK::id)))
{
Address to (static_cast<To const*> (m->find (To::id))->address ());
if (nak->address () == to)
{
Lock l (mutex_);
for (NAK::iterator j (const_cast<NAK*> (nak)->begin ());
!j.done ();
j.advance ())
{
u64* psn;
j.next (psn);
Message_ptr m;
Queue::ENTRY* pair;
if (queue_.find (*psn, pair) == 0)
{
//cerr << 5 << "PRTM " << to << " " << pair->ext_id_ << endl;
m = pair->int_id_.message ();
pair->int_id_.reset ();
}
else
{
//cerr << 4 << "message " << *psn << " not available" << endl;
m = Message_ptr (new Message);
m->add (Profile_ptr (new SN (*psn)));
m->add (Profile_ptr (new NoData));
}
out_->send (m);
}
}
}
in_->recv (m);
}
ACE_THR_FUNC_RETURN Retransmit::
track_thunk (void* obj)
{
reinterpret_cast<Retransmit*> (obj)->track ();
return 0;
}
void Retransmit::
track ()
{
while (true)
{
Lock l (mutex_);
for (Queue::iterator i (queue_); !i.done ();)
{
if ((*i).int_id_.inc () >= params_.retention_timeout ())
{
u64 sn ((*i).ext_id_);
i.advance ();
queue_.unbind (sn);
}
else
{
i.advance ();
}
}
//FUZZ: disable check_for_lack_ACE_OS
// Go to sleep but watch for "manual cancellation" request.
//
ACE_Time_Value time (ACE_OS::gettimeofday ());
//FUZZ: enable check_for_lack_ACE_OS
time += params_.tick ();
while (!stop_)
{
if (cond_.wait (&time) == -1)
{
if (errno != ETIME)
ACE_OS::abort ();
else
break;
}
}
if (stop_)
break;
}
}
}
| 3,046 | 1,156 |
#include <ros/ros.h>
#include <DegreeOfFreedom.hpp>
namespace RobotControl
{
namespace FrankaLowLevelDriver
{
DegreeOfFreedom::DegreeOfFreedom(unsigned short aChannel,
unsigned long aMinPulseWidth,
unsigned long aMaxPulseWidth,
double aMinAngle,
double aMaxAngle,
double aMaxSpeedPerSecond,
unsigned long aCurrentPos,
unsigned long aTargetPos)
: channel(aChannel),
minPulseWidth(aMinPulseWidth),
maxPulseWidth(aMaxPulseWidth),
minAngle(aMinAngle),
maxAngle(aMaxAngle),
maxSpeedPerSecond(aMaxSpeedPerSecond),
currentPos(aCurrentPos),
targetPos(aTargetPos)
{
}
unsigned long DegreeOfFreedom::pulseWidthFromAngle(double angle) const
{
unsigned long result = ((angle - minAngle) * (maxPulseWidth - minPulseWidth) / (maxAngle - minAngle) + minPulseWidth);
if(result > maxPulseWidth)
{
return maxPulseWidth;
}
else if(result < minPulseWidth)
{
return minPulseWidth;
}
return result;
}
double DegreeOfFreedom::angleFromPulseWidth(unsigned long pulseWidth) const
{
if(pulseWidth < minPulseWidth)
{
pulseWidth = minPulseWidth;
}
else if(pulseWidth > maxPulseWidth)
{
pulseWidth = maxPulseWidth;
}
return ((pulseWidth - minPulseWidth) * (maxAngle - minAngle) / (maxPulseWidth - minPulseWidth) + minAngle);
}
unsigned long DegreeOfFreedom::getConvertedSpeedFromDegreesPerSecond(double speed) const
{
unsigned short speedFactor = maxSpeed / minSpeed;
double result = ((speed - (maxSpeedPerSecond / speedFactor)) * (maxSpeed - minSpeed) /
(maxSpeedPerSecond - (maxSpeedPerSecond / speedFactor)) +
minSpeed);
if(result > maxSpeed)
{
return maxSpeed;
}
if(result < minSpeed)
{
ROS_DEBUG("THE MINIMUM DEGREES PER SECOND FOR THE DOF ON CHANNEL %s IS %s.",
std::to_string(channel).c_str(),
std::to_string(maxSpeedPerSecond / speedFactor).c_str());
return minSpeed;
}
return result;
}
unsigned short DegreeOfFreedom::getChannel() const
{
return this->channel;
}
unsigned long DegreeOfFreedom::getCurrentPos() const
{
return this->currentPos;
}
unsigned long DegreeOfFreedom::getTargetPos() const
{
return this->targetPos;
}
void DegreeOfFreedom::setCurrentPos(unsigned long aCurrentPos)
{
this->currentPos = aCurrentPos;
}
void DegreeOfFreedom::setTargetPos(unsigned long aTargetPos)
{
this->targetPos = aTargetPos;
}
}
} | 2,660 | 833 |
#include "QEMU-GUI.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QEMUGUI w;
//QObject::connect(&a, SIGNAL(aboutToQuit()), &w, SLOT(saveSettingsBeforeQuit()));
w.show();
return a.exec();
}
| 255 | 104 |
// Aria Avazkhani
//2018-07-31
//updated: 2018-08-08
#include "Product.h"
namespace AMA {
Product::Product(char type) {
v_type = type;
v_sku[0] = '\0';
v_unit[0] = '\0';
v_name = nullptr;
v_qty = 0;
v_need = 0;
v_price = 0.0;
v_status = false;
}
Product::Product(const char* sku, const char* n, const char* unit, int qty, bool status, double price, int need) {
name(n);
strncpy(v_sku, sku, max_sku_length);
v_sku[max_sku_length] = '\0';
strncpy(v_unit, unit, max_unit_length);
v_unit[max_unit_length] = '\0';
v_qty = qty;
v_need = need;
v_price = price;
v_status = status;
}
Product::~Product() {
delete[] v_name;
}
Product::Product(const Product& src) {
int c = strlen(src.v_name);
v_type = src.v_type;
strncpy(v_sku, src.v_sku, max_sku_length);
v_sku[max_sku_length] = '\0';
strncpy(v_unit, src.v_unit, max_unit_length);
v_unit[max_unit_length] = '\0';
v_qty = src.v_qty;
v_need = src.v_need;
v_price = src.v_price;
v_status = src.v_status;
if (src.v_name != nullptr) {
v_name = nullptr;
v_name = new char[c];
for (int i = 0; i < c; ++i) {
v_name[i] = src.v_name[i];
}
v_name[c] = '\0';
}
else
v_name = nullptr;
}
void Product::name(const char* name) {
if (name != nullptr) {
int c = strlen(name);
v_name = new char[c +1];
for (int i = 0; i < c; ++i){
v_name[i] = name[i];
}
v_name[c] = '\0';
}
}
const char* Product::name() const {
if (v_name[0] == '\0')
return nullptr;
else
return v_name;
}
const char* Product::sku() const {
return v_sku;
}
const char* Product::unit() const {
return v_unit;
}
bool Product::taxed() const {
return v_status;
}
double Product::price() const {
return v_price;
}
double Product::cost() const {
if (v_status == true)
return price() * (tax + 1);
else
return price();
}
void Product::message(const char* err) {
v_err.message(err);
}
bool Product::isClear() const {
return v_err.isClear();
}
Product& Product::operator=(const Product& cpy) {
if (this != &cpy){
v_type = cpy.v_type;
v_qty = cpy.v_qty;
v_need = cpy.v_need;
v_price = cpy.v_price;
v_status = cpy.v_status;
name(cpy.v_name);
strncpy(v_sku, cpy.v_sku, strlen(cpy.v_sku));
v_sku[strlen(cpy.v_sku)] = '\0';
strncpy(v_unit, cpy.v_unit, strlen(cpy.v_unit));
v_unit[strlen(cpy.v_unit)] = '\0';
}
return *this;
}
std::fstream& Product::store(std::fstream& file, bool newLine) const {
file << v_type << ',' << v_sku << ',' << v_name << ',' << v_unit
<< ',' << v_status << ',' << v_price << ',' << v_qty << ','
<< v_need;
if (newLine == true)
file << endl;
return file;
}
std::fstream& Product::load(std::fstream& file) {
char t_sku[max_sku_length];
char t_name[max_name_length];
char t_unit[max_unit_length];
double t_price;
int t_qty, t_need;
char t_tax;
bool t_status;
if (file.is_open()){
file.getline(t_sku, max_sku_length, ',');
t_sku[strlen(t_sku)] = '\0';
file.getline(t_name, max_name_length, ',');
t_name[strlen(t_name)] = '\0';
file.getline(t_unit, max_unit_length, ',');
t_unit[strlen(t_unit)] = '\0';
file >> t_tax;
if (t_tax == '1')
t_status = true;
else if (t_tax == '0')
t_status = false;
file.ignore();
file >> t_price;
file.ignore();
file >> t_qty;
file.ignore();
file >> t_need;
file.ignore();
*this = Product(t_sku, t_name, t_unit, t_qty, t_status, t_price, t_need);
}
return file;
}
std::ostream& Product::write(std::ostream& os, bool linear) const {
if (!(v_err.isClear())){
os << v_err.message();
}
else if (linear){
os << setw(max_sku_length) << left << setfill(' ') << v_sku << '|'
<< setw(20) << left << v_name << '|'
<< setw(7) << right << fixed << setprecision(2) << cost() << '|'
<< setw(4) << right << v_qty << '|'
<< setw(10) << left << v_unit << '|'
<< setw(4) << right << v_need << '|';
}
else{
os << " Sku: " << v_sku << endl
<< " Name (no spaces): " << v_name << endl
<< " Price: " << v_price << endl;
if (v_status == true)
os << " Price after tax: " << cost() << endl;
else{
os << " Price after tax: N/A"<< endl;
}
os << " Quantity on Hand: " << v_qty << " " << v_unit << endl
<< " Quantity needed: " << v_need;
}
return os;
}
std::istream& Product::read(std::istream& is) {
char tax;
char* address = new char[max_name_length + 1];
int qty, need;
double t_price;
if (!is.fail()){
cout << " Sku: ";
is >> v_sku;
cin.ignore();
cout << " Name (no spaces): ";
is >> address;
name(address);
cout << " Unit: ";
is >> v_unit;
cout << " Taxed? (y/n): ";
is >> tax;
if (!is.fail()){
v_err.clear();
if (tax){
bool yes = tax == 'y' || tax == 'Y';
bool no = tax == 'n' || tax == 'N';
if (yes)
v_status = true;
if (no)
v_status = false;
if (!(yes || no)){
is.setstate(std::ios::failbit);
v_err.message("Only (Y)es or (N)o are acceptable");
return is;
}
}
}
else{
is.setstate(std::ios::failbit);
v_err.message("Only (Y)es or (N)o are acceptable");
return is;
}
cout << " Price: ";
is >> t_price;
if (is.fail()) {
v_err.clear();
is.setstate(ios::failbit);
v_err.message("Invalid Price Entry");
return is;
}
else
prices(t_price);
cout << " Quantity on hand: ";
is >> qty;
if (is.fail()){
v_err.clear();
v_err.message("Invalid Quantity Entry");
is.setstate(ios::failbit);
return is;
}
else
quantity(qty);
cout << " Quantity needed: ";
is >> need;
cin.ignore();
if (is.fail()) {
v_err.clear();
v_err.message("Invalid Quantity Needed Entry");
is.setstate(ios::failbit);
return is;
}
else
qtyNeed(need);
if (!is.fail()){
v_err.clear();
}
}
return is;
}
bool Product::operator==(const char* src) const {
if (strcmp(src, this->v_sku) == 0)
return true;
else
return false;
}
double Product::total_cost() const {
return static_cast<double>(v_qty * (v_price + (v_price * tax)));
}
void Product::quantity(int stock) {
v_qty = stock;
}
bool Product::isEmpty() const {
if (v_name == nullptr)
return true;
else
return false;
}
int Product::qtyNeeded() const {
return v_need;
}
int Product::quantity() const {
return v_qty;
}
void Product::qtyNeed(int nd){
v_need = nd;
}
void Product::prices(double pr){
v_price = pr;
}
bool Product::operator>(const char* prd) const {
if (strcmp(v_sku, prd) > 0)
return true;
else
return false;
}
bool Product::operator>(const iProduct& src) const {
if (strcmp(v_name, src.name()) > 0)
return true;
else
return false;
}
int Product::operator+=(int add) {
if (add > 0)
v_qty += add;
return v_qty;
}
std::ostream& operator<<(std::ostream& os, const iProduct& pr) {
return pr.write(os, true);
}
std::istream& operator>>(std::istream& is, iProduct& pr) {
return pr.read(is);
}
double operator+=(double& num, const iProduct& pr) {
return num + pr.total_cost();
}
}
| 7,545 | 3,594 |
#include "40_cpnlTest.h"
double dataAgreementWithFlips(string filename, int D, cpn cpnet){
//Calculates DFA between data and cpnet
//filename tells us the location of the data - Assumed to be written on 1 comma separated line, each entry is an observed outcome
//D tells us the number of data points
//cpnet is the cpn of interest
//first we read in the data and enter it into vector data
vector<int> data(D);
int line=1;
int cols=D;
int d;
ifstream file(filename);
char dummy;
for (int i = 0; i < line; i++){
for (int j = 0; j < cols; j++){
file >> d;
data[j]=d;
if (j < (cols - 1)){
file >> dummy;
}
}
}
file.close();
//nvar is the number of variables in the CP-net
int nvar=cpnet.size;
//convert the data into counts - instead of a list of observed outcomes we have a vector where the ith entry is the number of times outcome i was observed
//outcomes are assumed to be in lexicographic order
vector<int> counts(pow(2,nvar),0);
for(int i=0;i<D;i++){
counts[data[i]]+=1;
}
//LexMult is the lexicographic multipliers of the variables (the mutlipliers we use to convert between outcomes and their enumeration)
vector<int> LexMult(nvar);
for(int i=0;i<nvar;i++){
LexMult[i]=pow(2,nvar-i-1);
}
//AgreementScore will be the DFA score numerator
int AgreementScore=0;
//adjMat is the adjacency matrix of the CP-net structure. entries and breaks are the cpt details
vector<int> adjMat=cpnet.structure;
vector<int> entries=cpnet.cptEntries;
vector<int> breaks=cpnet.cptBreaks;
//for each variable, X, calculate (and add) the the data differences over X flips
for(int i=0;i<nvar;i++){
//parents - 0/1 vector giving the parents of X
//nPa - number of parents
vector<int> parents(nvar);
int nPa=0;
for(int j=0;j<nvar;j++){
parents[j]=adjMat[j*nvar+i];
nPa+=parents[j];
}
//Pa - an nPa vector giving the indices of the parents
vector<int> Pa(nPa);
int counter=0;
for(int j=0;j<nvar;j++){
if(parents[j]==1){
Pa[counter]=j;
counter+=1;
}
}
// nother is the number of variables which are not X or parents of X
int nOther=nvar-1-nPa;
// otherWeights - list of all possible weights these other variables can add to the lexicographic posn of an outcome
//otherAssts - cycles through all possible assignments to these other variables
std::vector<int> otherWeights(pow(2,nOther));
std::vector<int> otherAssts(nOther,0);
std::vector<int> otherMult(nOther);
if(nOther>0){
int counter=0;
for(int k=0;k<nvar;k++){
if(k!=i){
if(parents[k]==0){
otherMult[counter]=LexMult[k];
counter+=1;
}
}
}
for(int k=0;k<pow(2,nOther);k++){
int weight=0;
for(int l=0;l<nOther;l++){
weight+= otherAssts[l]*otherMult[l];
}
otherWeights[k]=weight;
if(k!=(pow(2,nOther)-1)){
int max=0;
for(int l=0;l<nOther;l++){
if(otherAssts[l]==0){
if(l>max){
max=l;
}
}
}
otherAssts[max]=1;
for(int l=max+1;l<nOther;l++){
otherAssts[l]=0;
}
}
}
}
//For each parent assignment to Pa(X) we find the data differences over all X flips under this assignment
//PaAsst cycles through all possible parental assignments
vector<int> PaAsst(nPa,0);
for(int j=0; j<pow(2,nPa);j++){
//fixedweight is the weight contributed by parent assignment PaAsst to the lexicographic position of an outcome
int fixedweight=0;
for(int k=0;k<nPa;k++){
fixedweight+=PaAsst[k]*LexMult[Pa[k]];
}
//group1/2 are the lists of the lexicographic positions of outcomes with Pa(x)=PaAsst and X=1/2
vector<int> group1(pow(2,nOther));
vector<int> group2(pow(2,nOther));
if(nOther==0){
group1[0]=fixedweight;
group2[0]=fixedweight+LexMult[i];
}
else{
for(int k=0;k<pow(2,nOther);k++){
group1[k]=fixedweight+otherWeights[k];
group2[k]=fixedweight+otherWeights[k]+LexMult[i];
}
}
//value1/2 is the number of data observations of outcomes in group 1/2
int value1=0;
int value2=0;
for(int k=0;k<pow(2,nOther);k++){
value1+=counts[group1[k]];
value2+=counts[group2[k]];
}
//if the CPT rule corresponding to PaAsst is 1>2, then the data difference is value1-value2
// Add this to our score
if(entries[breaks[i]+2*j]==1){
AgreementScore+=value1-value2;
}
else{//if the CPT rule is 2>1, then the data difference is value2-value1
AgreementScore+=value2-value1;
}
//move to next parent assignmnent
if(j!=(pow(2,nPa)-1)){
int max=0;
for(int k=0;k<nPa;k++){
if(PaAsst[k]==0){
max=k;
}
}
PaAsst[max]=1;
for(int k=max+1;k<nPa;k++){
PaAsst[k]=0;
}
}
//We have added the data differences for all PaAsst X-flips to the score
}
//After cycling through all parental assignments, we have now added all X-flip data differences
}
//AgreementScore is now the sum of all variable flip data differences
//To obtain DFA, we must divide this by n*#data points
double ScaledFlipAgreement = (double) AgreementScore/ ((double) nvar* (double) D);
return ScaledFlipAgreement;
}
double dataOrderCompatibleWithCPN(string filename, int D, cpn cpnet, long long int nTests){
//Calculates DOC between the cpnet and data located at filename. nTests the level of approximation we will use in our calculation.
//filename - location of data
//D - number of data points in file
//cpn - CP-net of interest
//nTests - number of comparisons we are going to do (max possible number of tests is number of unordered pairs of outcomes)
//first we read in the data and enter it into vector data
vector<int> data(D);
int line=1;
int cols=D;
int d;
ifstream file(filename);
char dummy;
for (int i = 0; i < line; i++){
for (int j = 0; j < cols; j++){
file >> d;
data[j]=d;
if (j < (cols - 1)){
file >> dummy;
}
}
}
file.close();
//nvar is the number of variables in the CP-net
int nvar=cpnet.size;
//convert the data into counts - instead of a list of observed outcomes we have a vector where the ith entry is the number of times outcome i was observed
//outcomes are assumed to be in lexicographic order
vector<int> counts(pow(2,nvar),0);
for(int i=0;i<D;i++){
counts[data[i]]+=1;
}
//next we ensure that the number of comparisons is not more than the maximum possible
long long int maxComp= (pow(2,nvar)*(pow(2,nvar)-1))/2;
if(nTests>maxComp){
nTests=maxComp;
}
//Comparisons will be a 0/1 vector recording which outcome pairs have been done already.
//Every outcome corresponds to a number between 0 and 2^n-1 (they are enumerated lexicographically)
//A distinct outcome pair can thus be written (a,b) a=/=b. If we order outcome pairs in lexicographic order (when considered as coordinate pair) then the ithe pair corresponds to ith entry of comparisons
//That is (1,0), (2,0), (2,1),(3,0),(3,1),(3,2),(4,0),........
vector<int> Comparisons(maxComp,0);
//if nTests=maxposns then we can just move through the outcome pairs systematically as all need to be tested
//Otherwise, we must select a (not yet considered) outcome pair at random each time
//outposn1 - lexicographic position of outcome 1 in our pair
//outposn2 - lexicographic position of outcome 2
long long int outPosn1=1;
long long int outPosn2=0;
//LexMult is a vector of lexicographic multipliers that we use to move between an outcome and its lex position
vector<long long int> LexMult(nvar);
for(int i=0;i<nvar;i++){
LexMult[i]=pow(2,nvar-i-1);
}
//initiate a random generator for uniform selection of an outcome pair
//randomly selects a number between 0 and maxComp-1, this then gives an outcome pair by the enumeration of pairs we use in Comparisons
struct timeval tv;
gettimeofday(&tv,0);
unsigned long mySeed = tv.tv_sec + tv.tv_usec;
typedef std::mt19937 G;
G g(mySeed);
typedef std::uniform_int_distribution<long long int> Dist;
Dist uni(0, maxComp-1);
//later in the function we need to perform dominance testing. We must add 1 to our breaks vector before feeding the CP-net into this function
//This is an issue left over from translating functions from R to C++
vector<int> breaks=cpnet.cptBreaks;
for(int i=0;i<breaks.size();i++){
breaks[i]+=1;
}
//supportedRelns will count the number of outcomes pairs we test where the cpnet does not contradict the data;
long long int supportedRelns=0;
//perform nTests many outcome pair tests:
for(long long int i=0;i<nTests;i++){
//if nTests<maxposns, we need to randomly select a new outcome pair.
if(nTests<maxComp){
bool newOutcome=false;
while(!newOutcome){
//randomly select an outcome pair by generating its lexicographic position
long long int outPair=uni(g);
//Check Comparisons vector to see if it has been considered previously
if(Comparisons[outPair]==0){
//If it hasn't been considered previously, mark in Comparisons that we have now done this pair
Comparisons[outPair]=1;
newOutcome=true;
//convert the lexicographic position of the pair into the coordinate pair that gives the lex positions of outcome 1 and 2 in the pair
outPosn1=2;
bool identified=false;
while(!identified){
if(outPair<(outPosn1*(outPosn1-1))/2){
identified=true;
outPosn1-=1;
}
else{
outPosn1+=1;
}
}
outPosn2=outPair - ((outPosn1*(outPosn1-1))/2);
}
//If it has been considered previously, generate a new pair and try again
}
}
//If we are systematically moving through the pairs, then mark this pair as considered
if(nTests==maxComp){
Comparisons[i]=1;
}
// let us copy outPosn1/2 to new ints to preserve them
long long int posn1=outPosn1;
long long int posn2=outPosn2;
//next we need to turn the pair of outcome positions into two outcomes (vectors out1 and out2)
vector<int> out1(nvar,1);
vector<int> out2(nvar,1);
for(int j=0;j<nvar;j++){
int div1=posn1/LexMult[j];
if(div1==1){
out1[j]=2;
posn1-=LexMult[j];
}
int div2=posn2/LexMult[j];
if(div2==1){
out2[j]=2;
posn2-=LexMult[j];
}
}
//next we want to find the number of observed data points for the selected outcomes:
int data1=counts[outPosn1];
int data2=counts[outPosn2];
if(data1>data2){
//out1 preferred to out2 is only contradicted by the cpnet if it entails out2>out1 so perform dominance test out2>out1
List DTOut=RSDQRankPriority(cpnet.structure,cpnet.domains,cpnet.cptEntries,breaks,out2,out1);
bool outcome=DTOut.result;
if(!outcome){
//If dominance test false then cpnet does not entail out2>out1 so the data is not contradicted
//Thus, we say the CP-net is consistent with this relation in the data and we add a support count
supportedRelns+=1;
}
}
if(data2>data1){
//out2 preferred to out1 is only contradicted by the cpnet if it entails out1>out2 so perform dominance test out1>out2
List DTOut=RSDQRankPriority(cpnet.structure,cpnet.domains,cpnet.cptEntries,breaks,out1,out2);
bool outcome=DTOut.result;
if(!outcome){
//If dominance test false then cpnet does not entail out1>out2 so the data is not contradicted
//Thus, we say the CP-net is consistent with this relation in the data and we add a support count
supportedRelns+=1;
}
}
if(data1==data2){
//out1 equally preferred to out2 is contradicted by the cpnet if it entails either out1>out2 or out2>out1 so dominance test both
//First we dominance test out1>out2
List DTOut=RSDQRankPriority(cpnet.structure,cpnet.domains,cpnet.cptEntries,breaks,out1,out2);
bool outcome=DTOut.result;
if(!outcome){
//If dominance test is false, we then test out2>out1
DTOut=RSDQRankPriority(cpnet.structure,cpnet.domains,cpnet.cptEntries,breaks,out2,out1);
outcome=DTOut.result;
if(!outcome){
//If both dominance tests are false, neither direction is entailed and the CP-net is consistent with the data relation so we add a support count
supportedRelns+=1;
}
}
}
//if we are moving through the pairs systematically, we then move on to next pair:
if(nTests==maxComp){
if(outPosn2==(outPosn1-1)){
outPosn1+=1;
outPosn2=0;
}
else{
outPosn2+=1;
}
}
}
//supportedRelns now counts the number of tests (outcome pairs) for which the CP-net was consistent with the data relation
//DOC is then obtained by dividing by the number of tests performed
return (double)supportedRelns/(double)nTests;
}
| 15,073 | 4,422 |
//
// Created by andrey on 19.09.18.
//
#include <iostream>
#include <omp.h>
#define N1 3
#define N2 1
int main(){
omp_set_num_threads(N1);
#pragma omp parallel if(omp_get_max_threads() > 2)
{
if(omp_in_parallel()){
printf("Количество нитей: %d; Номер нити : %d\n", omp_get_num_threads(), omp_get_thread_num());
}
}
omp_set_num_threads(N2);
#pragma omp parallel if(omp_get_max_threads() > 2)
{
if(omp_in_parallel()){
printf("Количество нитей: %d; Номер нити : %d\n", omp_get_num_threads(), omp_get_thread_num());
}
}
return 0;
}; | 622 | 261 |
#include <cstdio>
// I/O
#define BUF 65536
struct Reader {
char buf[BUF]; char b; int bi, bz;
Reader() { bi=bz=0; read(); }
void read() {
if (bi==bz) { bi=0; bz = fread(buf, 1, BUF, stdin); }
b = bz ? buf[bi++] : 0; }
void process() {
bool open = true;
while (b != 0) {
if (b == '"') {
if (open) {
putchar('`');
putchar('`');
}
else {
putchar('\'');
putchar('\'');
}
open = !open;
}
else
putchar(b);
read();
}
}
};
int main()
{
Reader rr;
rr.process();
return 0;
}
| 767 | 266 |
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include <iostream>
using namespace cv;
static void help( void )
{
printf("\nThis program illustrates Linear-Polar and Log-Polar image transforms\n"
"Usage :\n"
"./polar_transforms [[camera number -- Default 0],[path_to_filename]]\n\n");
}
int main( int argc, char** argv )
{
VideoCapture capture;
Mat log_polar_img, lin_polar_img, recovered_log_polar, recovered_lin_polar_img;
help();
CommandLineParser parser(argc, argv, "{@input|0|}");
std::string arg = parser.get<std::string>("@input");
if( arg.size() == 1 && isdigit(arg[0]) )
capture.open( arg[0] - '0' );
else
capture.open( arg.c_str() );
if( !capture.isOpened() )
{
const char* name = argv[0];
fprintf(stderr,"Could not initialize capturing...\n");
fprintf(stderr,"Usage: %s <CAMERA_NUMBER> , or \n %s <VIDEO_FILE>\n", name, name);
return -1;
}
namedWindow( "Linear-Polar", WINDOW_NORMAL );
namedWindow( "Log-Polar", WINDOW_NORMAL );
namedWindow( "Recovered Linear-Polar", WINDOW_NORMAL );
namedWindow( "Recovered Log-Polar", WINDOW_NORMAL );
moveWindow( "Linear-Polar", 20,20 );
moveWindow( "Log-Polar", 700,20 );
moveWindow( "Recovered Linear-Polar", 20, 350 );
moveWindow( "Recovered Log-Polar", 700, 350 );
for(;;)
{
Mat frame;
capture >> frame;
if( frame.empty() )
break;
Point2f center( (float)frame.cols / 2, (float)frame.rows / 2 );
double M = (double)frame.cols / 8;
logPolar(frame,log_polar_img, center, M, INTER_LINEAR + WARP_FILL_OUTLIERS);
linearPolar(frame,lin_polar_img, center, M, INTER_LINEAR + WARP_FILL_OUTLIERS);
logPolar(log_polar_img, recovered_log_polar, center, M, WARP_INVERSE_MAP + INTER_LINEAR);
linearPolar(lin_polar_img, recovered_lin_polar_img, center, M, WARP_INVERSE_MAP + INTER_LINEAR + WARP_FILL_OUTLIERS);
imshow("Log-Polar", log_polar_img );
imshow("Linear-Polar", lin_polar_img );
imshow("Recovered Linear-Polar", recovered_lin_polar_img );
imshow("Recovered Log-Polar", recovered_log_polar );
if( waitKey(10) >= 0 )
break;
}
waitKey(0);
return 0;
}
| 2,338 | 896 |
#include <string>
#include <stdint.h>
#include <string.h>
#include "mon.hpp"
namespace std {
uint8_t eep [E2END + 1];
void cli() {}
void sei() {}
void popSREG () {}
void pushSREGAndCli () {}
void eeprom_init () {
for (int i = 0; i < sizeof(eep); i++) {
eep[i] = 0xff;
}
}
void eeprom_busy_wait() {
}
void eeprom_update_byte (u1_mon::plogtable_t p, uint8_t v) {
if (p >= 0 && p < sizeof(eep)) {
// printf(" eep %04x <- %02x\n", p, v);
eep[p] = v;
}
}
void eeprom_write_byte (u1_mon::plogtable_t p, uint8_t v) {
if (p >= 0 && p < sizeof(eep)) {
// printf(" eep %04x <- %02x\n", p, v);
eep[p] = v;
}
}
uint8_t eeprom_read_byte (u1_mon::plogtable_t p) {
if (p >= 0 && p < sizeof(eep)) {
return eep[p];
}
return 0xff;
}
uint16_t eeprom_read_word (u1_mon::plogtable_t p) {
return (eeprom_read_byte(p + 1) << 8) | eeprom_read_byte(p);
}
void eeprom_read_block (void *dest, u1_mon::plogtable_t src, int size) {
uint8_t *p = (uint8_t *)dest;
if (p == NULL) {
return;
}
while (size > 0) {
if (src >= 0 && src < sizeof(eep) ) {
*p++ = eep[src++];
}
size--;
}
}
void eeprom_update_block (void *src, u1_mon::plogtable_t dst, int size) {
uint8_t *pFrom = (uint8_t *)src;
while (size-- > 0) {
uint8_t b = *pFrom++;
eeprom_write_byte(dst++, b);
}
}
}
namespace u1_app {
struct Clock {
uint16_t ms;
uint8_t sec;
uint8_t min;
uint8_t hrs;
};
struct Trim {
uint32_t magic;
uint16_t startCnt; // only 15 bits used -> log record
uint8_t vcpK;
uint8_t vcpD;
uint8_t currK;
int8_t tempK;
int8_t tempOffs;
};
struct LogChargingHistory {
uint8_t typ;
uint32_t time;
struct u1_mon::LogDataCharging data;
};
struct App {
struct u1_mon::LogDataCharging logDataCharging;
struct LogChargingHistory logChargingHistory[4];
struct Trim trim;
struct Clock clock;
} app;
void clearLogHistory ();
void addLogCharging (uint8_t typ, uint32_t time, uint8_t logIndex);
}
using namespace std;
namespace u1_mon {
struct Mon mon;
// uint8_t nextLogIndex (int16_t index) {
// if (index < 0) {
// return 0;
// }
// return index >= EEP_LOG_DESCRIPTORS ? 0 : index + 1;
// }
int16_t findLogDescriptorIndex (uint32_t time) {
int16_t rv = -1;
uint32_t rvTimeDiff = 0xffffffff;
uint8_t index = 0;
plogtable_t p = (plogtable_t)EEP_LOG_START + sizeof (struct LogDescriptor) * index;
struct LogDescriptor d;
while (index < EEP_LOG_DESCRIPTORS) {
eeprom_busy_wait();
eeprom_read_block(&d, p, sizeof (d));
uint8_t typ = d.typ & 0x0f;
if (typ != 0x0f) {
uint32_t diff = d.time > time ? d.time - time : time - d.time;
if (diff < rvTimeDiff) {
rvTimeDiff = diff;
rv = index;
}
u1_app::addLogCharging(typ, d.time, index);
}
index++;
p += sizeof(struct LogDescriptor);
}
return rv;
}
int16_t findNewestLogDescriptorIndex () {
return findLogDescriptorIndex(0xffffffff);
}
int16_t findOldestLogDescriptorIndex () {
return findLogDescriptorIndex(0);
}
void readLogData (uint8_t index, uint8_t *pDest, uint8_t destSize) {
if (index >= EEP_LOG_DESCRIPTORS) {
return;
}
eeprom_busy_wait();
plogtable_t pFrom = (plogtable_t)EEP_LOG_SLOTS_START + EEP_LOG_SLOT_SIZE * index;
eeprom_read_block(pDest, pFrom, destSize);
printf(" readLogData %d %p %d -> %02x %02x %02x %02x\n", index, (void *)(pDest), destSize, pDest[0], pDest[1], pDest[2], pDest[3]);
}
uint8_t saveLog (uint8_t typ, void *pData, uint8_t size) {
if (typ >= 0x0f) {
return 0xff; // error
}
struct LogDescriptor d;
d.typ = 0x0f;
pushSREGAndCli(); {
uint16_t tHigh = (u1_app::app.trim.startCnt << 1) | ((u1_app::app.clock.hrs >> 4) & 0x01);
uint16_t tLow = ((u1_app::app.clock.hrs & 0x0f) << 12) | ((u1_app::app.clock.min & 0x3f) << 6) | (u1_app::app.clock.sec & 0x3f);
d.time = (((uint32_t)tHigh) << 16) | tLow;
} popSREG();
uint8_t index = 0;
plogtable_t p = (plogtable_t)EEP_LOG_START;
plogtable_t pTo = (plogtable_t)EEP_LOG_SLOTS_START;
uint8_t lastTyp = typ;
if (mon.log.index < EEP_LOG_DESCRIPTORS) {
index = mon.log.index;
p += index * sizeof (struct LogDescriptor);
pTo += index * EEP_LOG_SLOT_SIZE;
lastTyp = mon.log.lastTyp == 0 ? 0xff : mon.log.lastTyp;
}
uint8_t rv;
int16_t bytes = size;
uint8_t slotCnt = 0;
do {
if (lastTyp != typ || slotCnt > 0) {
index++;
p += sizeof (struct LogDescriptor);
pTo += EEP_LOG_SLOT_SIZE;
if (index >= EEP_LOG_DESCRIPTORS) {
p = (plogtable_t)EEP_LOG_START;
pTo = (plogtable_t)EEP_LOG_SLOTS_START;
index = 0;
}
}
if (slotCnt == 0) {
rv = index;
}
d.typ = (d.typ & 0x0f) | (slotCnt++ << 4);
eeprom_busy_wait();
eeprom_update_block(&d, p, sizeof(d));
uint8_t l = bytes < EEP_LOG_SLOT_SIZE ? bytes : EEP_LOG_SLOT_SIZE;
eeprom_busy_wait();
if (pData != NULL && size > 0) {
eeprom_update_block(pData, pTo, l);
bytes -= EEP_LOG_SLOT_SIZE;
pData = ((uint8_t *)pData) + l;
}
} while (bytes > 0 && slotCnt < 16);
index = rv;
p = (plogtable_t)EEP_LOG_START + index * sizeof (struct LogDescriptor);
d.typ = typ;
uint8_t slot = 0;
while (slotCnt-- > 0) {
d.typ = (d.typ & 0x0f) | (slot << 4);
eeprom_busy_wait();
eeprom_write_byte(p, *((uint8_t *)&d));
p += sizeof (struct LogDescriptor);
mon.log.index = index++;
slot++;
if (index >= EEP_LOG_DESCRIPTORS) {
p = (plogtable_t)EEP_LOG_START;
index = 0;
}
}
mon.log.lastTyp = typ;
u1_app::addLogCharging(typ, d.time, rv);
return rv;
}
void startupLog () {
int16_t startIndex = findNewestLogDescriptorIndex();
mon.log.index = startIndex < 0 ? EEP_LOG_DESCRIPTORS : startIndex + 1;
if (mon.log.index >= EEP_LOG_DESCRIPTORS) {
mon.log.index = 0;
}
mon.log.lastTyp = 0xff;
saveLog(LOG_TYPE_SYSTEMSTART, NULL, 0);
}
void clearEEP (plogtable_t pStartAddr, uint16_t size) {
while (size-- > 0 && (uint16_t)pStartAddr <= E2END) {
eeprom_busy_wait();
eeprom_write_byte(pStartAddr++, 0xff);
}
eeprom_busy_wait();
}
void clearLogTable () {
clearEEP((plogtable_t)EEP_LOG_START, E2END + 1 - EEP_LOG_START);
mon.log.index = 0xff;
mon.log.lastTyp = 0x0f;
}
int8_t cmd_log (uint8_t argc, const char **argv) {
if (argc == 2 && strcmp("clear", argv[1]) == 0) {
clearLogTable();
return 0;
}
if (argc > 1) { return -1; }
struct LogDescriptor d;
int16_t startIndex = findOldestLogDescriptorIndex();
uint8_t cnt = 0;
if (startIndex >= 0) {
uint8_t index = (uint8_t)startIndex;
plogtable_t p = (plogtable_t)EEP_LOG_START + sizeof (struct LogDescriptor) * index;
struct LogDescriptor d;
do {
eeprom_busy_wait();
eeprom_read_block(&d, p, sizeof (d));
if ((d.typ & 0x0f) != 0x0f) {
cnt++;
uint8_t typ = d.typ & 0x0f;
uint8_t subIndex = d.typ >> 4;
uint16_t startupCnt = d.time >> 17;
uint8_t hrs = (d.time >> 12) & 0x1f;
uint8_t min = (d.time >> 6) & 0x3f;
uint8_t sec = d.time & 0x3f;
printf(" %2d(%01x/%01x) %5d-%02d:%02d:%02d -> ", index, typ, subIndex, startupCnt, hrs, min, sec);
uint8_t slot[EEP_LOG_SLOT_SIZE];
eeprom_busy_wait();
eeprom_read_block(&slot, (plogtable_t)EEP_LOG_SLOTS_START + index * EEP_LOG_SLOT_SIZE, sizeof (slot));
switch (d.typ) {
case LOG_TYPE_SYSTEMSTART: {
printf("system start");
break;
}
case LOG_TYPE_STARTCHARGE: {
struct LogDataStartCharge *pData = (struct LogDataStartCharge *)&slot;
printf("start charge maxAmps=%u", pData->maxAmps);
break;
}
case LOG_TYPE_CHARGING: case LOG_TYPE_STOPCHARGING: {
struct LogDataCharging *pData = (struct LogDataCharging *)&slot;
uint8_t e = pData->energyKwhX256 >> 8;
uint8_t nk = ((pData->energyKwhX256 & 0xff) * 100 + 128) / 256;
if (d.typ == LOG_TYPE_STOPCHARGING) {
printf("stop ");
}
printf("charge %u:%02u, E=%u.%02ukWh", pData->chgTimeHours, pData->chgTimeMinutes, e, nk);
break;
}
default: {
printf("? (");
for (uint8_t i = 0; i < sizeof slot; i++) {
printf(" %02x", slot[i]);
}
printf(")");
break;
}
}
printf("\n");
}
index++;
p += sizeof(struct LogDescriptor);
if (index >= EEP_LOG_DESCRIPTORS) {
index = 0;
p = (plogtable_t)EEP_LOG_START;
}
} while (index != startIndex);
}
printf("%d valid log records\n", cnt);
printf("\nLog history:\n");
for (uint8_t i = 0; i < (sizeof (u1_app::app.logChargingHistory) / sizeof (u1_app::app.logChargingHistory[0])); i++) {
struct u1_app::LogChargingHistory *p= &(u1_app::app.logChargingHistory[i]);
printf(" %u: typ=%u time=%04x%04x ", i, p->typ, (uint16_t)(p->time >> 16), (uint16_t)(p->time));
printf("= %u-%u:%02u:%02u -> ", (uint16_t)(p->time >> 17), (uint16_t)((p->time >> 12) & 0x1f), (uint16_t)((p->time >> 6) & 0x3f), (uint16_t)(p->time & 0x3f));
printf(" %u:%02umin", p->data.chgTimeHours, p->data.chgTimeMinutes);
printf(" %u.%02ukWh", p->data.energyKwhX256 >> 8, ((p->data.energyKwhX256 & 0xff) * 100 + 128) / 256);
printf("\n");
}
return 0;
}
}
namespace u1_app {
void clearLogHistory () {
int s = sizeof (u1_app::app.logChargingHistory);
memset(u1_app::app.logChargingHistory, 0, sizeof (u1_app::app.logChargingHistory));
}
void addLogCharging (uint8_t typ, uint32_t time, uint8_t logIndex) {
static uint8_t index = 0;
if (typ != LOG_TYPE_STOPCHARGING) {
return;
}
struct u1_app::LogChargingHistory *px = &u1_app::app.logChargingHistory[index];
px->typ = typ;
px->time = time;
u1_mon::readLogData(logIndex, (uint8_t*)&px->data, sizeof(px->data));
printf("hist[%d]: set %p ... %u %04x%04x\n", index, (void *)px, logIndex, (uint16_t)(time >> 16), (uint16_t)time);
index++;
if (index >= (sizeof(app.logChargingHistory) / sizeof(app.logChargingHistory[0]))) {
index
}
}
}
int main () {
eeprom_init();
u1_app::app.trim.startCnt = 0x01;
u1_app::app.clock.hrs = 0;
u1_app::app.clock.min = 0x00;
u1_app::app.clock.sec = 0x00;
u1_mon::mon.log.index = 0xff;
u1_mon::startupLog();
struct u1_mon::LogDataStartCharge x1 = { 10 };
struct u1_mon::LogDataCharging x2 = { 0, 0, 0 };
u1_mon::saveLog(1, &x1, sizeof x1);
for (int i = 0; i < 100; i++) {
if (i % 100 == 99) {
uint8_t f[16];
for (int i = 0; i < sizeof f; i++) {
f[i] = i + 10;
}
u1_mon::saveLog(14, &f, sizeof f);
} else if (i % 10 == 9) {
u1_mon::saveLog(3, &x2, sizeof x2);
} else {
u1_mon::saveLog(2, &x2, sizeof x2);
}
u1_app::app.clock.sec++;
if (u1_app::app.clock.sec == 60) {
u1_app::app.clock.min++;
u1_app::app.clock.sec = 0;
}
x2.chgTimeMinutes += 2;
if (x2.chgTimeMinutes >= 60) {
x2.chgTimeMinutes -= 60;
x2.chgTimeHours++;
}
x2.energyKwhX256 += 200;
}
u1_app::clearLogHistory();
u1_mon::startupLog();
const char *argv[] = { "cmd_log" };
u1_mon::cmd_log(1, argv);
return 0;
}
| 13,925 | 5,181 |
#include "Clove/Graphics/Validation/ValidationCommandBuffer.hpp"
namespace clove {
namespace detail {
template<typename QueueType, typename BufferType>
void initialiseBuffer(QueueType *queue, BufferType *buffer) {
bool const allowBufferReuse{ (queue->getDescriptor().flags & QueueFlags::ReuseBuffers) != 0 };
dynamic_cast<ValidationCommandBuffer *>(buffer)->setAllowBufferReuse(allowBufferReuse);
}
template<typename SubmissionType>
void validateBuffersUsage(SubmissionType const &submission) {
for(auto &commandBuffer : submission.commandBuffers) {
auto *buffer{ dynamic_cast<ValidationCommandBuffer *>(commandBuffer) };
if(buffer->getCommandBufferUsage() == CommandBufferUsage::OneTimeSubmit && buffer->bufferHasBeenUsed()) {
CLOVE_ASSERT_MSG(false, "GraphicsCommandBuffer recorded with CommandBufferUsage::OneTimeSubmit has already been used. Only buffers recorded with CommandBufferUsage::Default can submitted multiples times after being recorded once.");
break;
}
}
}
template<typename SubmissionType>
void markBuffersAsUsed(SubmissionType const &submission) {
for(auto &commandBuffer : submission.commandBuffers) {
dynamic_cast<ValidationCommandBuffer *>(commandBuffer)->markAsUsed();
}
}
}
//Graphics
template<typename BaseQueueType>
std::unique_ptr<GhaGraphicsCommandBuffer> ValidationGraphicsQueue<BaseQueueType>::allocateCommandBuffer() {
auto commandBuffer{ BaseQueueType::allocateCommandBuffer() };
detail::initialiseBuffer(this, commandBuffer.get());
return commandBuffer;
}
template<typename BaseQueueType>
void ValidationGraphicsQueue<BaseQueueType>::submit(GraphicsSubmitInfo const &submission, GhaFence *signalFence) {
detail::validateBuffersUsage(submission);
BaseQueueType::submit(submission, signalFence);
detail::markBuffersAsUsed(submission);
}
//Compute
template<typename BaseQueueType>
std::unique_ptr<GhaComputeCommandBuffer> ValidationComputeQueue<BaseQueueType>::allocateCommandBuffer() {
auto commandBuffer{ BaseQueueType::allocateCommandBuffer() };
detail::initialiseBuffer(this, commandBuffer.get());
return commandBuffer;
}
template<typename BaseQueueType>
void ValidationComputeQueue<BaseQueueType>::submit(ComputeSubmitInfo const &submission, GhaFence *signalFence) {
detail::validateBuffersUsage(submission);
BaseQueueType::submit(submission, signalFence);
detail::markBuffersAsUsed(submission);
}
//Transfer
template<typename BaseQueueType>
std::unique_ptr<GhaTransferCommandBuffer> ValidationTransferQueue<BaseQueueType>::allocateCommandBuffer() {
auto commandBuffer{ BaseQueueType::allocateCommandBuffer() };
detail::initialiseBuffer(this, commandBuffer.get());
return commandBuffer;
}
template<typename BaseQueueType>
void ValidationTransferQueue<BaseQueueType>::submit(TransferSubmitInfo const &submission, GhaFence *signalFence) {
detail::validateBuffersUsage(submission);
BaseQueueType::submit(submission, signalFence);
detail::markBuffersAsUsed(submission);
}
}
| 3,410 | 893 |
// Copyright 2019-2021 Cambridge Quantum Computing
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
/**
* @file
* @brief Include this file rather than including the Eigen headers directly
*/
#include "Utils/Json.hpp"
#if defined(__clang__)
#pragma GCC diagnostic push
#if __has_warning("-Wdeprecated-copy")
#pragma GCC diagnostic ignored "-Wdeprecated-copy"
#endif
#endif
#include <Eigen/Dense>
#include <Eigen/SparseCore>
#include <unsupported/Eigen/KroneckerProduct>
#include <unsupported/Eigen/MatrixFunctions>
#if defined(__clang__)
#pragma GCC diagnostic pop
#endif
namespace Eigen {
template <typename _Scalar, int _Rows, int _Cols>
void to_json(nlohmann::json& j, const Matrix<_Scalar, _Rows, _Cols>& matrix) {
for (Index i = 0; i < matrix.rows(); ++i) {
nlohmann::json row = nlohmann::json::array();
for (Index j = 0; j < matrix.cols(); ++j) {
row.push_back(matrix(i, j));
}
j.push_back(row);
}
}
template <typename _Scalar, int _Rows, int _Cols>
void from_json(const nlohmann::json& j, Matrix<_Scalar, _Rows, _Cols>& matrix) {
for (size_t i = 0; i < j.size(); ++i) {
const auto& j_row = j.at(i);
for (size_t j = 0; j < j_row.size(); ++j) {
matrix(i, j) =
j_row.at(j).get<typename Matrix<_Scalar, _Rows, _Cols>::Scalar>();
}
}
}
} // namespace Eigen
| 1,854 | 660 |
#include "mouselistener.h"
mouseListener::mouseListener():colorAzul(0),colorRojo(0)
{
}
//type_class is the color RED or BLUE
//The temps are the weight for each coordiante and the Bias
//which are generated randomly
void mouseListener::addObject(int &Xcoordinate, int &Ycoordinate, int type_class)
{
if(!checkIfExist(Xcoordinate,Ycoordinate))
{
if(type_class == 1)
colorRojo++;
else
colorAzul++;
std::vector<int> temp;
temp.push_back(Xcoordinate-250);
temp.push_back((Ycoordinate-250)*-1);
temp.push_back(type_class);
objects.push_back(temp);
}
}
std::vector<std::vector<int>>mouseListener::getObject()
{
return objects;
}
void mouseListener::print()
{
for(int x = 0; x < objects.size();x++)
{
for(int y = 0; y < 2;y++)
{
std::cout << std::setprecision(4);
if(y ==1 )
{
std::cout << "Y:" << (objects[x][y]-250)*-1 << " ";
}
else std::cout << "X:" << objects[x][y]-250 << " ";
}
std::cout << std::endl;
}
}
//Checks if the coordinate has already been taken
//ensuring that only one class can only be on one coordinate (x,y)
bool mouseListener::checkIfExist(int &Xcoordinate,int&Ycoordinate)
{
for(int x = 0; x < objects.size();x++)
{
for(int y = 0; y < 2;y++)
{
if(objects[x][y] == Xcoordinate and objects[x][y]== Ycoordinate)
return true;
}
}
return false;
}
std::vector<int>mouseListener::getClassesSize()
{
std::vector<int>temp;
temp.push_back(colorAzul);
temp.push_back(colorRojo);
return temp;
}
| 1,690 | 581 |
#include <iostream>
#include <chrono>
#include <vector>
#include "securitybot.h"
using namespace std::chrono;
using namespace elma;
using namespace securitybot;
SecurityBot& EvadeState:: securitybot() { return (SecurityBot&) state_machine(); }
void EvadeState::during(){
securitybot().evadeMoveFunction();
}
| 316 | 100 |
/*! @file
* Defines the entry point for the console application.
@author $Author \n
*/
#include "stdafx.h"
#include "gas_exchange.h"
#include <iostream>
#include <fstream>
#include <algorithm>
#include <sstream>
using namespace std;
// uses std::string, a more generic method than CString
/*! \namespace photomod
\details photomod is the namespace and contains the code needed to run the model. In includes an interface
\b _tmain (named by Visual Studio), and \b gasexchange.cpp, the model itself */
using namespace photomod; //Photosynthesis module
/*! \b Program _tmain
* \page Interface
* \par Interface to photosynthesis module
* \details This program demonstrates how to call the photosynthesis module
*
*
* \par Use of this interface
* Two input files are needed (@b parameters.csv and @b ClimateIn.dat) and one output file is created (@b Results.dat). ClimateIn.dat is the
default name, any file can be input when prompted by the program. A detailed description of the input files follows.
* -# A comma delimited parameter file containing the parameters for the photosynthesis module, one line for each species (Parameters.csv)
* -# An comma delimted environmental file @b (ClimateIn.dat) each line should have these variables (separated by commas):
* \li temperature (C)
* \li PAR (umol photons m-2 s-1)
\li CO2 content (umol mol-1)
\li humidity (%)
\li wind (m s-1)
\li a flag (0,1) to tell the program if constant temperature is used (or let temperature of leaf
vary with stomatal conductance).
* -# an output file is produced with results @b (Results.dat) each line is written as:
* \li PAR (umol photons m-2 s-1)
\li Net Photosynthesis (umol CO2 m-2 s-1)
\li Gross Photosynthesis
\li VPD (kPa)
\li LeafTemperature (C)
\li BoundaryLayerConductance (mol m-2 s-1)
\li Internal CO2 (umol mol-1)
\li Respiration (umolCO2 m-2 s-1)
\li Transpiration (umol H2O m-2 s-1) \n
-# In your calling program, execute the function SetParams first to initialize the calculator for a specific plant species
* Then execute the function:
\b SetVal(PFD, Temperature, CO2, RelativeHumidity, Wind, Pressure, ConstantTemperature)
to pass environmental parameters needed
to calculate carbon assimilation and transpiration. This will call the function \b GasEx() which carries out the calculations \n
* -# Use the public get functions described in the CGasExchange Class to retrieve the calculated
* variables.
*/
int _tmain(int argc, _TCHAR* argv[])
{
/*! \brief these are the variables for the interface */
string DataLine; //!< \b DataLine, holds line of data read from file with climate data
string Remark; //!< \b Remark, remark from parameter file
char* context = NULL; //!< \b context, pointer needed to use strtok_s function
bool ConstantTemperature; //!< \b ConstantTemperature, if set to 1, model does not solve for leaf temperature
photomod::CGasExchange::tParms thisParms; //!< \b thisParms, object to hold parameters sent to photosynthesis module
const char *pDelim=","; //!< \b pDelim, -pointer to character (delimiter) that separates entries in the parameter file
char * pnt; //!< \b pnt, -pointer to the next word to be read from parameter file
char CharTest ='A'; //!< \b CharTest -variable to test if there are characters in the line of data (indicates end of data)
bool found=false; //!< \b found -Boolean to indicate the species line was found in the parameter file
string temp ; //!< \b temp -temporary variable for holding string objects
/*! \brief \li these variables hold data sent to model */
double PFD, /*!< \b PFD light umol ppfd m-2 s-1- */
Temperature, /*!< \b Temperature leaf temperature C*/
RelativeHumidity,Wind, CO2, Pressure=100;
ifstream ParamFile, DataFile; //!< \b ParamFile, \b DataFile - files to hold parameters and variables for a single run
ofstream OutputFile; //!< \b OutputFile holds data output from photosynthesis module
//Define a pointer to a new variable as a GasExchange Object
photomod::CGasExchange *MyLeafGasEx; //!< \b MyLeafGasEx - define a gas exchange object type
// Create a new GasExchange Object
MyLeafGasEx= new CGasExchange(); //create a new gas exchange object on the stack
//variables to hold results from gas exchange module.
double Anet, VPD,Agross,LeafTemperature, Respiration, InternalCO2, StomatalConductance,
BoundaryLayerConductance, Transpiration;
//assign defaults in case user does not want to enter other information (DataLine is empty)
string DataFileName="ClimateIn.dat", OutputFileName="Results.dat";
string Species ="Maize"; //!< \b Species of plant for calculatioins
// Get datafile name, and species name if entered by user.
cout << "enter name of file with input data and species name separated by commas:" <<endl
<< "hit Enter with empty string for defaults" <<endl;
getline(cin,DataLine);
if (!DataLine.empty()) //if empty defaults to string names assigned above
{
pnt=strtok_s((char*)DataLine.c_str(), pDelim, &context ); //pnt is a pointer to the last recently found token in the string
DataFileName.assign(pnt); // first token is a file name
pnt=strtok_s(NULL, pDelim, &context ); //get ready for the next token by getting pointer to recently found token in the string
Species.assign(pnt); // next token is species
Species.erase(remove(Species.begin(),Species.end(),' '),Species.end()); //remove blanks from species name in case any are present
pnt=NULL; //finished with these two
}
// open file with parameters and data
ParamFile.open("parameters.csv", std::ifstream::in);
if (!ParamFile)
{
std::cerr << "Parameter file not found \n";
return 0;
}
DataFile.open(DataFileName.c_str());
if (!DataFile)
{
std::cerr << "Data file with input not found \n";
return 0;
}
FILE * pFile;
pFile=fopen((char*)OutputFileName.c_str(),"w");
fprintf(pFile, "PAR ANet AGross VPD Leaf_Temp BoundaryL_Conduc InternalCO2 Respiration StomatalConduct Transpiration\n");
OutputFile.open(OutputFileName.c_str());
std::getline(ParamFile,DataLine); //get header from parameter file
// last line of file may be empty or contain numbers, this indicates file is at the end
while (!ParamFile.eof() && isalpha(CharTest)) //loops through file reads each line and tests if the correct species is found
{
getline(ParamFile,DataLine); // get the first line of data
CharTest=DataLine.at(0); //check that line contains alphabetical text at beginning
pnt=strtok_s((char*)DataLine.c_str(), pDelim, &context ); // pick off the first word before the token (',')
//First read file to find the desired plant species
temp.assign(pnt);
temp.erase(remove(temp.begin(),temp.end(),' '),temp.end()); // removes spaces from string
thisParms.ID=temp;
temp.clear();
//Eliminate case issues - convert everything to lower case
transform(thisParms.ID.begin(), thisParms.ID.end(),thisParms.ID.begin(), ::tolower);
transform(Species.begin(), Species.end(),Species.begin(), ::tolower);
//Search for the correct species in file
if (thisParms.ID.compare(Species)==0 && !found) //continue to parse string
{
pnt = strtok_s( NULL,pDelim, &context ); // iterate to clean string of characters already read
// This section parses string, each iteration it cleans string of characters already read
while(pnt!=NULL )
{
// printf( "Tokenized string using * is:: %s\n", pnt ); // for debugging
temp.assign(pnt);
thisParms.species=temp;
temp.clear();
pnt = strtok_s( NULL,pDelim, &context );
temp.assign(pnt);
thisParms.Type=temp;
temp.clear();
pnt = strtok_s( NULL,pDelim, &context );
thisParms.Vcm25=atof(pnt);
pnt = strtok_s( NULL,pDelim, &context );
thisParms.Jm25=atof(pnt);
pnt = strtok_s( NULL,pDelim, &context );
thisParms.Vpm25=atof(pnt);
pnt = strtok_s( NULL,pDelim, &context );
thisParms.TPU25=atof(pnt);
pnt = strtok_s( NULL,pDelim, &context );
thisParms.Rd25=atof(pnt);
pnt = strtok_s( NULL,pDelim, &context );
thisParms.Theta=atof(pnt);
pnt = strtok_s( NULL,pDelim, &context );
thisParms.EaVc=atof(pnt);
pnt = strtok_s( NULL,pDelim, &context );
thisParms.Eaj=atof(pnt);
pnt = strtok_s( NULL,pDelim, &context );
thisParms.Hj=atof(pnt);
pnt = strtok_s( NULL,pDelim, &context );
thisParms.Sj=atof(pnt);
pnt = strtok_s( NULL,pDelim, &context );
thisParms.Hv=atof(pnt);
pnt = strtok_s( NULL,pDelim, &context );
thisParms.EaVp=atof(pnt);
pnt = strtok_s( NULL,pDelim, &context );
thisParms.Sv=atof(pnt);
pnt = strtok_s( NULL,pDelim, &context );
thisParms.Eap=atof(pnt);
pnt = strtok_s( NULL,pDelim, &context );
thisParms.Ear=atof(pnt);
pnt = strtok_s( NULL,pDelim, &context );
thisParms.g0=atof(pnt);
pnt = strtok_s( NULL,pDelim, &context );
thisParms.g1=atof(pnt);
pnt = strtok_s( NULL,pDelim, &context );
thisParms.stomaRatio=atof(pnt);
pnt = strtok_s( NULL,pDelim, &context );
thisParms.LfWidth=atof(pnt);
pnt = strtok_s( NULL,pDelim, &context );
thisParms.LfAngFact=atof(pnt);
pnt = strtok_s( NULL,pDelim, &context );
temp.assign(pnt);
thisParms.Remark=temp;
temp.clear();
pnt=strtok_s(NULL,pDelim, &context);
found=true;
}
}
}
// Implementation to interact with photosynthesis model is here
CharTest='1'; //initialize CharTest
int start=1;
bool LineEmpty=false; //Checks if file with environmental data is finished.
//output variables
//Initialize Gas exchange object by passing species and relavent parameters read earlier
MyLeafGasEx->SetParams(&thisParms);
// loop to read environmental input data and call object to calculate results
while (!LineEmpty)
{
getline(DataFile, DataLine);
if (DataLine.length()==0) LineEmpty=true;
else
{
//CharTest=DataLine.at(0); // check for valid data
pnt=strtok_s((char*)DataLine.c_str(), pDelim, &context ); //token is the delimiter
PFD=atof(pnt);
pnt=strtok_s(NULL,pDelim,&context);
Temperature=atof(pnt);
pnt=strtok_s(NULL,pDelim,&context);
CO2=atof(pnt);
pnt=strtok_s(NULL,pDelim,&context);
RelativeHumidity=atof(pnt);
pnt=strtok_s(NULL,pDelim,&context);
Wind=atof(pnt);
pnt=strtok_s(NULL,pDelim,&context);
ConstantTemperature=atoi(pnt);
// pass relavent environmental variables to gas exchange object and execute module
MyLeafGasEx->SetVal(PFD, Temperature, CO2, RelativeHumidity,
Wind, Pressure, ConstantTemperature);
// Return calculated variables from gas exchange object
Anet=MyLeafGasEx->get_ANet();
Agross=MyLeafGasEx->get_AGross();
VPD=MyLeafGasEx->get_VPD();
LeafTemperature=MyLeafGasEx->get_LeafTemperature();
BoundaryLayerConductance=MyLeafGasEx->get_BoundaryLayerConductance();
InternalCO2=MyLeafGasEx->get_Ci();
Respiration=MyLeafGasEx->get_Respiration();
StomatalConductance=MyLeafGasEx->get_StomatalConductance();
Transpiration=MyLeafGasEx->get_Transpiration();
fprintf(pFile,"%8.2f %6.2f %6.2f %8.3f %4.1f %8.3f %4.1f %6.2f %8.3f %8.3f\n", PFD, Anet, Agross, VPD,
LeafTemperature, BoundaryLayerConductance,InternalCO2,Respiration,
StomatalConductance, Transpiration);
}
}
DataFile.close();
DataFile.close();
fclose(pFile);
return 0;
}
| 11,673 | 4,271 |
/**
* @file MDFlexParser.cpp
* @author F. Gratl
* @date 10/18/19
*/
#include "MDFlexParser.h"
bool MDFlexParser::parseInput(int argc, char **argv, MDFlexConfig &config) {
// we need to copy argv because the call to getOpt in _cliParser.inputFilesPresent reorders it...
auto argvCopy = new char *[argc + 1];
for (int i = 0; i < argc; i++) {
auto len = std::string(argv[i]).length() + 1;
argvCopy[i] = new char[len];
strcpy(argvCopy[i], argv[i]);
}
argvCopy[argc] = nullptr;
CLIParser::inputFilesPresent(argc, argv, config);
if (not config.yamlFilename.empty()) {
if (not YamlParser::parseYamlFile(config)) {
return false;
}
}
auto parseSuccess = CLIParser::parseInput(argc, argvCopy, config);
for (int i = 0; i < argc; i++) {
delete[] argvCopy[i];
}
delete[] argvCopy;
return parseSuccess;
}
| 858 | 336 |
#include "content.h"
#include <unistd.h>
#include <cstdlib>
#include <fstream>
#include <functional>
#include <limits>
#include <memory>
#include <thread>
#include <unordered_set>
#ifdef USE_CHROMA
#include "chroma.h"
#endif
#include "fast_cpp_syntax_highlighter.h"
#include "fast_py_syntax_highlighter.h"
#include "tex_util.h"
#include "util.h"
static const std::unordered_set<string> kSpecialCommands = {
"sidenote", "sc", "newline", "serif", "htmlonly",
"latexonly", "footnote", "esc", "tooltip"};
namespace md_parser {
namespace {
// Remove empty p tags. (e.g <p> </p>).
void RemoveEmptyPTag(string* s) {
for (size_t i = 0; i < s->size(); i++) {
if (s->at(i) == '<') {
if (i + 2 < s->size() && s->substr(i, 3) == "<p>") {
size_t p_tag_start = i;
i += 3;
// Ignore whitespaces (tab and space).
while (s->at(i) == ' ' || s->at(i) == '\t') {
i++;
}
if (i + 3 < s->size() && s->substr(i, 4) == "</p>") {
s->erase(p_tag_start, (i + 4) - p_tag_start);
i = p_tag_start - 1;
}
}
}
}
}
void EscapeHtmlString(string* s) {
for (size_t i = 0; i < s->length(); i++) {
if (s->at(i) == '<') {
s->replace(i, 1, "<");
} else if (s->at(i) == '>') {
s->replace(i, 1, ">");
}
}
}
[[maybe_unused]] std::unique_ptr<char[]> cstring_from_string(const string& s) {
std::unique_ptr<char[]> c_str{new char[s.size() + 1]};
for (size_t i = 0; i < s.size(); i++) {
c_str[i] = s.at(i);
}
c_str[s.size()] = '\0';
return c_str;
}
size_t FindNonEscapedChar(const string& content, char c, size_t start) {
size_t pos = start;
while (pos < content.size()) {
pos = content.find(c, pos);
if (pos == string::npos) {
break;
}
if (pos == 0 || content[pos - 1] != '\\') {
return pos;
}
pos++;
}
return std::string::npos;
}
string UnescapeEscapedString(const string& content) {
std::string s;
s.reserve(content.size());
for (size_t i = 0; i < content.size(); i++) {
if (content[i] == '\\' && i + 1 < content.size()) {
s.push_back(content[i + 1]);
i++;
} else {
s.push_back(content[i]);
}
}
return s;
}
string GetHtmlFragmentText(const string& content, const Fragments& fragment,
bool is_str = true) {
if (is_str) {
return content.substr(fragment.str_start,
fragment.str_end - fragment.str_start + 1);
}
return content.substr(fragment.link_start,
fragment.link_end - fragment.link_start + 1);
}
string GetLatexFragmentText(const string& content, const Fragments& fragment,
bool is_str = true, bool no_escape = false) {
if (is_str) {
if (!no_escape) {
return EscapeLatexString(content.substr(
fragment.str_start, fragment.str_end - fragment.str_start + 1));
} else {
return content.substr(fragment.str_start,
fragment.str_end - fragment.str_start + 1);
}
}
return content.substr(fragment.link_start,
fragment.link_end - fragment.link_start + 1);
}
#ifdef USE_CHROMA
[[maybe_unused]] string FormatCodeUsingChroma(const string& code,
const string& lang,
const string& schema) {
auto code_ = cstring_from_string(code);
auto lang_ = cstring_from_string(lang);
auto schema_ = cstring_from_string(schema);
char* formatted =
FormatCodeWithoutInlineCss(code_.get(), lang_.get(), schema_.get());
string formatted_code = formatted;
free(formatted);
return formatted_code;
}
#endif
void StripItguruFromLink(string* link) {
const string itguru = "http://itguru.tistory.com";
size_t itguru_pos = link->find(itguru);
if (itguru_pos == string::npos) {
return;
}
link->replace(itguru_pos, itguru.length(), "");
}
bool IsFileExist(const string& filename) {
std::ifstream f(filename);
return f.good();
}
bool CompareToken(const string& content_, int pos, const string& token) {
if (pos + token.size() > content_.size()) {
return false;
}
return content_.substr(pos, token.size()) == token;
}
} // namespace
Content::Content(const string& content)
: content_(content), already_preprocessed_(false) {
return;
}
void Content::AddContent(const string& s) { content_ += s; }
void Content::Preprocess(ParserEnvironment* parser_env) {
if (already_preprocessed_) {
return;
}
GenerateFragments();
already_preprocessed_ = true;
}
void Content::GenerateFragments() {
// Priorities in processing content.
// Inline Code ( ` )
// Inline Math ( $$ )
// ----------------------------------
// StrikeThrough (~)
// Bold (**, __)
// Italic (*, _)
// Note that when closing, whichever came first must close first.
std::unordered_map<string, int> token_start_pos = {
{"**", -1}, {"*", -1}, {"__", -1}, {"_", -1},
{"`", -1}, {"$$", -1}, {"~~", -1}};
std::unordered_map<string, Fragments::Types> token_and_type = {
{"`", Fragments::Types::INLINE_CODE},
{"$$", Fragments::Types::INLINE_MATH},
{"~~", Fragments::Types::STRIKE_THROUGH},
{"**", Fragments::Types::BOLD},
{"__", Fragments::Types::BOLD},
{"*", Fragments::Types::ITALIC},
{"_", Fragments::Types::ITALIC}};
// When one of following tokens are activated, it ignores anything that
// comes after.
std::vector<string> high_priorities = {"`", "$$"};
// Following tokens can come play between each other.
std::vector<string> low_priorities = {"~~", "**", "__", "*", "_"};
int text_start = -1;
// Now iterate through each character in the content and parse it.
for (size_t i = 0; i < content_.size(); i++) {
string activated_high_priority_token;
for (const string& token : high_priorities) {
if (token_start_pos.at(token) != -1) {
activated_high_priority_token = token;
break;
}
}
// When high priority token is already activated, then we do not
// proceed to process other token.
if (!activated_high_priority_token.empty()) {
if (CompareToken(content_, i, activated_high_priority_token)) {
fragments_.emplace_back(token_and_type[activated_high_priority_token],
token_start_pos[activated_high_priority_token] +
activated_high_priority_token.size(),
i - 1);
token_start_pos[activated_high_priority_token] = -1;
i += (activated_high_priority_token.size() - 1);
}
continue;
}
bool token_handled = false;
for (const string& token : high_priorities) {
if (CompareToken(content_, i, token)) {
if (text_start != -1) {
fragments_.emplace_back(Fragments::Types::TEXT, text_start, i - 1);
text_start = -1;
}
token_start_pos[token] = i;
token_handled = true;
i += (token.size() - 1);
break;
}
}
if (token_handled) {
continue;
}
// Handle links and images.
std::vector<std::function<size_t(Content*, const size_t, int*)>> handlers =
{&Content::HandleLinks, &Content::HandleImages,
&Content::HandleSpecialCommands};
bool handled = false;
for (const auto& handler : handlers) {
size_t result = handler(this, i, &text_start);
if (result != i) {
i = result;
handled = true;
break;
}
}
if (handled) {
continue;
}
// Now try to process low priority tokens.
for (const string& token : low_priorities) {
if (CompareToken(content_, i, token)) {
token_handled = true;
int token_start = token_start_pos[token];
if (token_start == -1) {
if (text_start != -1) {
fragments_.emplace_back(Fragments::Types::TEXT, text_start, i - 1);
text_start = -1;
}
fragments_.emplace_back(token_and_type[token]);
token_start_pos[token] = i;
i += (token.size() - 1);
} else {
// There is one edge case we have to care about.
// When '**' is found, it is possible that it is actually two
// separate '*' and '*'. The only case this is true is
// '**' token came before '*' is entered.
// E.g **abc*c***
// ==> **abc*c* ** (1)
// *abc**c***
// ==> *abc**c** * (2)
if (text_start != -1) {
fragments_.emplace_back(Fragments::Types::TEXT, text_start, i - 1);
text_start = -1;
}
if (token.size() == 2) {
string half_token = token.substr(0, 1);
if (token_start < token_start_pos[half_token]) {
// In this case we have to recognize token as a half token.
// Note that this is the case (1).
fragments_.emplace_back(token_and_type[half_token]);
token_start_pos[half_token] = -1;
i += (half_token.size() - 1);
} else {
fragments_.emplace_back(token_and_type[token]);
token_start_pos[token] = -1;
i += (token.size() - 1);
}
} else {
fragments_.emplace_back(token_and_type[token]);
token_start_pos[token] = -1;
i += (token.size() - 1);
}
text_start = -1;
}
break;
}
}
if (token_handled) {
continue;
}
// Otherwise, it is a simple text token.
if (text_start == -1) {
text_start = i;
}
}
// Handle last chunk of text_start (if exists).
if (text_start != -1) {
fragments_.emplace_back(Fragments::Types::TEXT, text_start,
content_.size() - 1);
}
}
string Content::OutputHtml(ParserEnvironment* parser_env) {
bool bold = false;
bool italic = false;
bool strike_through = false;
string html = "<p>";
for (size_t i = 0; i < fragments_.size(); i++) {
if (fragments_[i].type == Fragments::Types::BOLD) {
if (!bold) {
html += "<span class='font-weight-bold'>";
} else {
html += "</span>";
}
bold = !bold;
} else if (fragments_[i].type == Fragments::Types::ITALIC) {
if (!italic) {
html += "<span class='font-italic'>";
} else {
html += "</span>";
}
italic = !italic;
} else if (fragments_[i].type == Fragments::Types::STRIKE_THROUGH) {
if (!strike_through) {
html += "<span class='font-strike'>";
} else {
html += "</span>";
}
strike_through = !strike_through;
} else if (fragments_[i].type == Fragments::Types::SIDENOTE) {
html +=
StrCat("</p><aside class='sidenote'>",
GetHtmlFragmentText(content_, fragments_[i]), "</aside><p>");
} else if (fragments_[i].type == Fragments::Types::SMALL_CAPS) {
html += StrCat("<span class='font-smallcaps'>",
GetHtmlFragmentText(content_, fragments_[i]), "</span>");
} else if (fragments_[i].type == Fragments::Types::SERIF) {
html += StrCat("<span class='font-serif-italic'>",
GetHtmlFragmentText(content_, fragments_[i]), "</span>");
} else if (fragments_[i].type == Fragments::Types::HTML_ONLY) {
html += GetHtmlFragmentText(content_, fragments_[i]);
} else if (fragments_[i].type == Fragments::Types::ESCAPE) {
html += GetHtmlFragmentText(content_, fragments_[i]);
} else if (fragments_[i].type == Fragments::Types::FOOTNOTE) {
html += StrCat("<sup>", GetHtmlFragmentText(content_, fragments_[i]),
"</sup>");
} else if (fragments_[i].type == Fragments::Types::TOOLTIP) {
html += StrCat(
"<span class='page-tooltip' data-tooltip='",
UnescapeEscapedString(
GetHtmlFragmentText(content_, fragments_[i], false)),
"' data-tooltip-position='bottom'>",
UnescapeEscapedString(GetHtmlFragmentText(content_, fragments_[i])),
"</span>");
} else if (fragments_[i].type == Fragments::Types::FORCE_NEWLINE) {
html += "<br>";
} else if (fragments_[i].type == Fragments::Types::LINK) {
string url = GetHtmlFragmentText(content_, fragments_[i], false);
StripItguruFromLink(&url);
// If the link does not contain "http://", then this is a link that goes
// back to our website.
string link_text = GetHtmlFragmentText(content_, fragments_[i]);
if (url.find("http") == string::npos) {
string url = parser_env->GetUrlOfReference(&link_text);
EscapeHtmlString(&link_text);
if (!url.empty()) {
html += StrCat("<a href='", url, "' class='link-code'>", link_text,
"</a>");
continue;
}
}
html += StrCat("<a href='", url, "'>", link_text, "</a>");
} else if (fragments_[i].type == Fragments::Types::IMAGE) {
string img_src = GetHtmlFragmentText(content_, fragments_[i], false);
// (alt) caption= (caption)
string alt_and_caption = GetHtmlFragmentText(content_, fragments_[i]);
string caption, alt;
auto caption_pos = alt_and_caption.find("caption=");
if (caption_pos != string::npos) {
caption = alt_and_caption.substr(caption_pos + 8);
alt = alt_and_caption.substr(caption_pos);
} else {
alt = alt_and_caption;
}
// If this image is from old tistory dump, then we have to switch to the
// local iamge.
if (img_src.find("http://img1.daumcdn.net") != string::npos) {
auto id_start = img_src.find("image%2F");
if (id_start == string::npos) {
LOG << "Daum Image URL is weird";
} else {
id_start += 8;
const string image_name = img_src.substr(id_start);
std::vector<string> file_ext_candidate = {".png", ".jpg", ".jpeg",
".gif"};
for (const auto& ext : file_ext_candidate) {
if (IsFileExist(StrCat("../static/img/", image_name, ext))) {
img_src = StrCat("/img/", image_name, ext);
break;
}
}
}
}
// Check webp version exist. If exists, then we use picture tag instead.
auto image_name_end = img_src.find_last_of(".");
if (image_name_end != string::npos) {
const string webp_image_name =
img_src.substr(0, image_name_end) + ".webp";
if (IsFileExist("../static" + webp_image_name)) {
html += StrCat(
R"(</p><figure><picture><source type="image/webp" srcset=")",
webp_image_name, R"("><img class="content-img" src=")", img_src,
R"(" alt=")", alt, R"("></picture><figcaption>)", caption,
R"(</figcaption></figure><p>)");
continue;
}
}
html += StrCat("</p><figure><img class='content-img' src='", img_src,
"' alt='", alt, "'><figcaption>", caption,
"</figcaption></figure><p>");
} else if (fragments_[i].type == Fragments::Types::CODE) {
html += StrCat("</p>", fragments_[i].formatted_code, "<p>");
} else if (fragments_[i].type == Fragments::Types::INLINE_CODE) {
string inline_code = GetHtmlFragmentText(content_, fragments_[i]);
string ref_url = parser_env->GetUrlOfReference(&inline_code);
EscapeHtmlString(&inline_code);
if (!ref_url.empty()) {
html += StrCat("<a href='", ref_url, "' class='link-code'>",
inline_code, "</a>");
} else {
html += StrCat("<code class='inline-code'>", inline_code, "</code>");
}
} else if (fragments_[i].type == Fragments::Types::INLINE_MATH) {
html += StrCat("<span class='math-latex'>$",
GetHtmlFragmentText(content_, fragments_[i]), "$</span>");
} else if (fragments_[i].type != Fragments::Types::LATEX_ONLY) {
string text = GetHtmlFragmentText(content_, fragments_[i]);
EscapeHtmlString(&text);
html += text;
}
}
html += "</p>";
RemoveEmptyPTag(&html);
return html;
}
string Content::OutputLatex(ParserEnvironment* parser_env) {
bool bold = false;
bool italic = false;
bool strike_through = false;
string latex;
for (const auto& fragment : fragments_) {
if (fragment.type == Fragments::Types::BOLD) {
if (!bold) {
latex += "\\textbf{";
} else {
latex += "}";
}
bold = !bold;
} else if (fragment.type == Fragments::Types::ITALIC) {
if (!italic) {
latex += "\\emph{";
} else {
latex += "}";
}
italic = !italic;
} else if (fragment.type == Fragments::Types::STRIKE_THROUGH) {
if (!strike_through) {
// \usepackage[normalem]{ulem}
latex += "\\sout{";
} else {
latex += "}";
}
strike_through = !strike_through;
} else if (fragment.type == Fragments::Types::SIDENOTE) {
latex += StrCat(R"(\footnote{)", GetLatexFragmentText(content_, fragment),
"} ");
/*
latex += StrCat("\n\\begin{sidenotebox}\n",
GetLatexFragmentText(content_, fragment),
"\n\\end{sidenotebox}\n");
latex += StrCat(" \\marginpar{\\footnotesize ",
GetLatexFragmentText(content_, fragment), "}\n");
*/
} else if (fragment.type == Fragments::Types::SMALL_CAPS) {
latex +=
StrCat("\\textsc{", GetLatexFragmentText(content_, fragment), "}");
} else if (fragment.type == Fragments::Types::SERIF) {
latex += StrCat("\\emph{", GetLatexFragmentText(content_, fragment), "}");
} else if (fragment.type == Fragments::Types::LATEX_ONLY) {
latex += GetLatexFragmentText(content_, fragment);
} else if (fragment.type == Fragments::Types::ESCAPE) {
latex += GetLatexFragmentText(content_, fragment);
} else if (fragment.type == Fragments::Types::FORCE_NEWLINE) {
latex += "\\newline";
} else if (fragment.type == Fragments::Types::LINK) {
// \usepackage{hyperref}
string url = GetLatexFragmentText(content_, fragment, false);
StripItguruFromLink(&url);
// If the link does not contain "http://", then this is a link that goes
// back to our website.
string link_text = GetLatexFragmentText(content_, fragment);
if (url.find("http") == string::npos) {
string url = parser_env->GetUrlOfReference(&link_text);
if (!url.empty()) {
latex += StrCat("\\href{", url, "}{", link_text, "}");
continue;
}
}
latex += StrCat("\\href{", url, "}{", link_text, "}");
} else if (fragment.type == Fragments::Types::IMAGE) {
string img_src = GetLatexFragmentText(content_, fragment, false);
// (alt) caption= (caption)
string alt_and_caption = GetLatexFragmentText(content_, fragment);
string caption, alt;
auto caption_pos = alt_and_caption.find("caption=");
if (caption_pos != string::npos) {
caption = alt_and_caption.substr(caption_pos + 8);
alt = alt_and_caption.substr(caption_pos);
} else {
alt = alt_and_caption;
}
// If this image is from old tistory dump, then we have to switch to the
// local iamge.
if (img_src.find("http://img1.daumcdn.net") != string::npos) {
auto id_start = img_src.find("image%2F");
if (id_start == string::npos) {
LOG << "Daum Image URL is weird";
} else {
id_start += 8;
const string image_name = img_src.substr(id_start);
std::vector<string> file_ext_candidate = {".png", ".jpg", ".jpeg",
".gif"};
for (const auto& ext : file_ext_candidate) {
if (IsFileExist(StrCat("../static/img/", image_name, ext))) {
img_src = StrCat("/img/", image_name, ext);
break;
}
}
}
}
string ext = img_src.substr(img_src.size() - 3);
if (ext == "gif" || ext == "svg") {
img_src.erase(img_src.size() - 3);
img_src.append("png");
}
if (caption.empty()) {
latex += StrCat(
"\n\\begin{figure}[H]\n\\centering\n\\includegraphics[max width="
"0.7\\linewidth]{",
img_src, "}\n\\end{figure}\n");
} else {
latex += StrCat(
"\n\\begin{figure}[H]\n\\centering\n\\includegraphics[max width="
"0.7\\linewidth]{",
img_src, "}\n\\caption*{", caption, "}\n\\end{figure}\n");
}
} else if (fragment.type == Fragments::Types::INLINE_CODE) {
string inline_code = GetLatexFragmentText(content_, fragment);
latex += StrCat("\\texttt{", inline_code, "}");
} else if (fragment.type == Fragments::Types::INLINE_MATH) {
// Should use unescaped fragment text.
latex += StrCat("$", GetHtmlFragmentText(content_, fragment), "$");
} else if (fragment.type != Fragments::Types::HTML_ONLY) {
latex += GetLatexFragmentText(content_, fragment);
}
}
return latex;
}
size_t Content::HandleLinks(const size_t start_pos, int* text_start) {
if (content_[start_pos] != '[') {
return start_pos;
}
// Search for the ending ']'.
size_t end_bracket = content_.find(']', start_pos);
if (end_bracket == string::npos) return start_pos;
if (end_bracket + 1 >= content_.size() || content_[end_bracket + 1] != '(') {
return start_pos;
}
size_t link_start = end_bracket + 1;
size_t link_end = content_.find(')', link_start);
if (link_end == string::npos) return start_pos;
if (*text_start != -1) {
fragments_.emplace_back(Fragments::Types::TEXT, *text_start, start_pos - 1);
*text_start = -1;
}
fragments_.emplace_back(Fragments::Types::LINK, start_pos + 1,
end_bracket - 1, link_start + 1, link_end - 1);
return link_end;
}
size_t Content::HandleSpecialCommands(const size_t start_pos, int* text_start) {
if (content_[start_pos] != '\\') {
return start_pos;
}
const auto delimiter_pos = FindNonEscapedChar(content_, '{', start_pos + 1);
if (delimiter_pos == string::npos) {
return start_pos;
}
const auto body_end = FindNonEscapedChar(content_, '}', delimiter_pos + 1);
if (body_end == string::npos) {
return start_pos;
}
const auto delimiter =
content_.substr(start_pos + 1, delimiter_pos - (start_pos + 1));
if (!SetContains(kSpecialCommands, delimiter)) {
return start_pos;
}
if (*text_start != -1) {
fragments_.emplace_back(Fragments::Types::TEXT, *text_start, start_pos - 1);
*text_start = -1;
}
if (delimiter == "sidenote") {
fragments_.emplace_back(Fragments::Types::SIDENOTE, delimiter_pos + 1,
body_end - 1);
return body_end;
} else if (delimiter == "sc") {
fragments_.emplace_back(Fragments::Types::SMALL_CAPS, delimiter_pos + 1,
body_end - 1);
return body_end;
} else if (delimiter == "newline") {
fragments_.emplace_back(Fragments::Types::FORCE_NEWLINE, delimiter_pos + 1,
body_end - 1);
return body_end;
} else if (delimiter == "serif") {
fragments_.emplace_back(Fragments::Types::SERIF, delimiter_pos + 1,
body_end - 1);
return body_end;
} else if (delimiter == "latexonly") {
fragments_.emplace_back(Fragments::Types::LATEX_ONLY, delimiter_pos + 1,
body_end - 1);
return body_end;
} else if (delimiter == "htmlonly") {
fragments_.emplace_back(Fragments::Types::HTML_ONLY, delimiter_pos + 1,
body_end - 1);
return body_end;
} else if (delimiter == "footnote") {
fragments_.emplace_back(Fragments::Types::FOOTNOTE, delimiter_pos + 1,
body_end - 1);
return body_end;
} else if (delimiter == "esc") {
fragments_.emplace_back(Fragments::Types::ESCAPE, delimiter_pos + 1,
body_end - 1);
return body_end;
} else if (delimiter == "tooltip") {
const auto tooltip_desc_start =
FindNonEscapedChar(content_, '{', body_end + 1);
if (tooltip_desc_start == string::npos) {
return start_pos;
}
const auto tooltip_desc_end =
FindNonEscapedChar(content_, '}', tooltip_desc_start + 1);
if (tooltip_desc_end == string::npos) {
return start_pos;
}
fragments_.emplace_back(Fragments::Types::TOOLTIP, delimiter_pos + 1,
body_end - 1, tooltip_desc_start + 1,
tooltip_desc_end - 1);
return tooltip_desc_end;
}
return start_pos;
}
size_t Content::HandleImages(const size_t start_pos, int* text_start) {
if (content_[start_pos] != '!' || start_pos == content_.size() - 1) {
return start_pos;
}
// Images are in exact same format as the links except for the starting !
// symbol.
size_t res = HandleLinks(start_pos + 1, text_start);
if (res == start_pos + 1) return start_pos;
// Need to change LINK to IMAGE.
fragments_.back().type = Fragments::Types::IMAGE;
return res;
}
} // namespace md_parser
| 25,466 | 8,504 |
// Copyright 2019 The Marl Authors.
//
// 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 "marl/conditionvariable.h"
#include "marl_test.h"
TEST_F(WithoutBoundScheduler, ConditionVariable) {
bool trigger[3] = {false, false, false};
bool signal[3] = {false, false, false};
std::mutex mutex;
marl::ConditionVariable cv;
std::thread thread([&] {
for (int i = 0; i < 3; i++) {
std::unique_lock<std::mutex> lock(mutex);
cv.wait(lock, [&] { return trigger[i]; });
signal[i] = true;
cv.notify_one();
}
});
ASSERT_FALSE(signal[0]);
ASSERT_FALSE(signal[1]);
ASSERT_FALSE(signal[2]);
for (int i = 0; i < 3; i++) {
{
std::unique_lock<std::mutex> lock(mutex);
trigger[i] = true;
cv.notify_one();
cv.wait(lock, [&] { return signal[i]; });
}
ASSERT_EQ(signal[0], 0 <= i);
ASSERT_EQ(signal[1], 1 <= i);
ASSERT_EQ(signal[2], 2 <= i);
}
thread.join();
}
TEST_P(WithBoundScheduler, ConditionVariable) {
bool trigger[3] = {false, false, false};
bool signal[3] = {false, false, false};
std::mutex mutex;
marl::ConditionVariable cv;
std::thread thread([&] {
for (int i = 0; i < 3; i++) {
std::unique_lock<std::mutex> lock(mutex);
cv.wait(lock, [&] { return trigger[i]; });
signal[i] = true;
cv.notify_one();
}
});
ASSERT_FALSE(signal[0]);
ASSERT_FALSE(signal[1]);
ASSERT_FALSE(signal[2]);
for (int i = 0; i < 3; i++) {
{
std::unique_lock<std::mutex> lock(mutex);
trigger[i] = true;
cv.notify_one();
cv.wait(lock, [&] { return signal[i]; });
}
ASSERT_EQ(signal[0], 0 <= i);
ASSERT_EQ(signal[1], 1 <= i);
ASSERT_EQ(signal[2], 2 <= i);
}
thread.join();
}
| 2,259 | 859 |
///////////////////////////////////////////////////////////////////////////////
// helper_detail.cpp
//
// unicomm - Unified Communication protocol C++ library.
//
// Unified Communication protocol different helper entities.
//
// 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)
//
// 2009, (c) Dmitry Timoshenko.
#include <unicomm/detail/helper_detail.hpp>
#include <smart/utils.hpp>
#include <boost/filesystem.hpp>
#include <boost/bind.hpp>
#include <stdexcept>
#include <functional>
#include <locale>
#include <sstream>
#include <iomanip>
#include <limits>
#ifdef max
# undef max
#endif
#ifdef min
# undef min
#endif
using std::runtime_error;
using std::out_of_range;
using std::string;
using std::isxdigit;
using std::equal_to;
using std::greater;
using std::stringstream;
using std::numeric_limits;
using boost::filesystem::exists;
using boost::filesystem::path;
//-----------------------------------------------------------------------------
void unicomm::detail::check_path(const string &s)
{
if (!exists(path(s)))
{
throw runtime_error("File or directory doesn't exist [" + s + "]");
}
}
//-----------------------------------------------------------------------------
string& unicomm::detail::normalize_path(string &s)
{
if (!s.empty())
{
const string::value_type c = *(s.end() - 1);
if (c != '\\' && c != '/')
{
s += '/';
}
}
return s;
}
//-----------------------------------------------------------------------------
string unicomm::detail::normalize_path(const string &s)
{
string ss = s;
return normalize_path(ss);
}
//-----------------------------------------------------------------------------
// declaration for compiler
namespace unicomm
{
namespace detail
{
string& process_hex_str(string& s);
} // namespace unicomm
} // namespace detail
// fixme: use boost regex to implement this routine
string& unicomm::detail::process_hex_str(string& s)
{
static const char* token = "\\x";
for (size_t pos = s.find(token); pos != string::npos;
pos = s.find(token))
{
size_t end = pos += 2;
while (end < s.size() && isxdigit(s[end]))
{
++end;
}
smart::throw_if<runtime_error>(boost::bind(equal_to<size_t>(), end, pos),
"Hexadecimal number should have at least one digit");
BOOST_ASSERT(end > pos && " - End index should be greater start");
stringstream ss(s.substr(pos, end - pos));
size_t char_code = 0;
ss >> std::hex >> char_code;
smart::throw_if<out_of_range>(boost::bind(greater<size_t>(), char_code,
numeric_limits<unsigned char>::max()), "Number too big for char code");
pos -= 2;
s.replace(pos, end - pos, 1, static_cast<char>(char_code));
}
return s;
}
//-----------------------------------------------------------------------------
string unicomm::detail::process_hex_str(const std::string& s)
{
string ss = s;
return process_hex_str(ss);
}
| 3,025 | 986 |
#include <iostream>
#include <cstring>
using namespace std;
int state[5][1000010];
int solve(int i, int j) {
if (i == 1 && j == 1) return 0;
if (state[i][j] != -1) return state[i][j];
state[i][j] = 0;
for (int k = 1; k <= 2; k++)
if (j - k > 0)
state[i][j] |= (1 - solve(i, j - k));
for (int k = 1; k <= 3; k++)
if (i - k > 0)
state[i][j] |= (1 - solve(i - k, j));
return state[i][j];
}
int main() {
// #ifndef ONLINE_JUDGE
// freopen("/home/shiva/Learning/1.txt", "r", stdin);
// freopen("/home/shiva/Learning/2.txt", "w", stdout);
// #endif
memset(state, -1, sizeof state);
for (int i = 1; i <= 4; i++)
for (int j = 1; j < 1000010; j++)
state[i][j] = solve(i, j);
int t, n, m;
cin >> t;
while (t--) {
cin >> n >> m;
if (state[(n - 1) % 4 + 1][m])
cout << "Tuzik\n";
else
cout << "Vanya\n";
}
}
| 839 | 442 |
#include "counters-bones.hpp"
#ifndef BARRY_COUNTERS_MEAT_HPP
#define BARRY_COUNTERS_MEAT_HPP 1
#define COUNTER_TYPE() Counter<Array_Type,Data_Type>
#define COUNTER_TEMPLATE_ARGS() <typename Array_Type, typename Data_Type>
#define COUNTER_TEMPLATE(a,b) \
template COUNTER_TEMPLATE_ARGS() inline a COUNTER_TYPE()::b
COUNTER_TEMPLATE(,Counter)(
const Counter<Array_Type,Data_Type> & counter_
) : count_fun(counter_.count_fun), init_fun(counter_.init_fun) {
if (counter_.delete_data)
{
this->data = new Data_Type(*counter_.data);
this->delete_data = true;
} else {
this->data = counter_.data;
this->delete_data = false;
}
this->name = counter_.name;
this->desc = counter_.desc;
return;
}
COUNTER_TEMPLATE(,Counter)(
Counter<Array_Type,Data_Type> && counter_
) noexcept :
count_fun(std::move(counter_.count_fun)),
init_fun(std::move(counter_.init_fun)),
data(std::move(counter_.data)),
delete_data(std::move(counter_.delete_data)),
name(std::move(counter_.name)),
desc(std::move(counter_.desc))
{
counter_.data = nullptr;
counter_.delete_data = false;
} ///< Move constructor
COUNTER_TEMPLATE(COUNTER_TYPE(),operator=)(
const Counter<Array_Type,Data_Type> & counter_
)
{
if (this != &counter_) {
this->count_fun = counter_.count_fun;
this->init_fun = counter_.init_fun;
if (counter_.delete_data)
{
this->data = new Data_Type(*counter_.data);
this->delete_data = true;
} else {
this->data = counter_.data;
this->delete_data = false;
}
this->name = counter_.name;
this->desc = counter_.desc;
}
return *this;
}
COUNTER_TEMPLATE(COUNTER_TYPE() &,operator=)(
Counter<Array_Type,Data_Type> && counter_
) noexcept {
if (this != &counter_)
{
// Data
if (delete_data)
delete data;
this->data = std::move(counter_.data);
this->delete_data = std::move(counter_.delete_data);
counter_.data = nullptr;
counter_.delete_data = false;
// Functions
this->count_fun = std::move(counter_.count_fun);
this->init_fun = std::move(counter_.init_fun);
// Descriptions
this->name = std::move(counter_.name);
this->desc = std::move(counter_.desc);
}
return *this;
} ///< Move assignment
COUNTER_TEMPLATE(double, count)(Array_Type & Array, uint i, uint j)
{
if (count_fun == nullptr)
return 0.0;
return count_fun(Array, i, j, data);
}
COUNTER_TEMPLATE(double, init)(Array_Type & Array, uint i, uint j)
{
if (init_fun == nullptr)
return 0.0;
return init_fun(Array, i, j, data);
}
COUNTER_TEMPLATE(std::string, get_name)() const {
return this->name;
}
COUNTER_TEMPLATE(std::string, get_description)() const {
return this->name;
}
////////////////////////////////////////////////////////////////////////////////
// Counters
////////////////////////////////////////////////////////////////////////////////
#define COUNTERS_TYPE() Counters<Array_Type,Data_Type>
#define COUNTERS_TEMPLATE_ARGS() <typename Array_Type, typename Data_Type>
#define COUNTERS_TEMPLATE(a,b) \
template COUNTERS_TEMPLATE_ARGS() inline a COUNTERS_TYPE()::b
COUNTERS_TEMPLATE(, Counters)() {
this->data = new std::vector<Counter<Array_Type,Data_Type>*>(0u);
this->to_be_deleted = new std::vector< uint >(0u);
this->delete_data = true;
this->delete_to_be_deleted = true;
}
COUNTERS_TEMPLATE(COUNTER_TYPE() &, operator[])(uint idx) {
return *(data->operator[](idx));
}
COUNTERS_TEMPLATE(, Counters)(const Counters<Array_Type,Data_Type> & counter_) :
data(new std::vector< Counter<Array_Type,Data_Type>* >(0u)),
to_be_deleted(new std::vector< uint >(0u)),
delete_data(true),
delete_to_be_deleted(true)
{
// Checking which need to be deleted
std::vector< bool > tbd(counter_.size(), false);
for (auto& i : *(counter_.to_be_deleted))
tbd[i] = true;
// Copy all counters, if a counter is tagged as
// to be deleted, then copy the value
for (auto i = 0u; i != counter_.size(); ++i)
{
if (tbd[i])
this->add_counter(*counter_.data->operator[](i));
else
this->add_counter(counter_.data->operator[](i));
}
return;
}
COUNTERS_TEMPLATE(, Counters)(Counters<Array_Type,Data_Type> && counters_) noexcept :
data(std::move(counters_.data)),
to_be_deleted(std::move(counters_.to_be_deleted)),
delete_data(std::move(counters_.delete_data)),
delete_to_be_deleted(std::move(counters_.delete_to_be_deleted))
{
// Taking care of memory
counters_.data = nullptr;
counters_.to_be_deleted = nullptr;
counters_.delete_data = false;
counters_.delete_to_be_deleted = false;
}
COUNTERS_TEMPLATE(COUNTERS_TYPE(), operator=)(const Counters<Array_Type,Data_Type> & counter_) {
if (this != &counter_) {
// Checking which need to be deleted
std::vector< bool > tbd(counter_.size(), false);
for (auto i : *(counter_.to_be_deleted))
tbd[i] = true;
// Removing the data currently stored in the
this->clear();
data = new std::vector< Counter<Array_Type,Data_Type>* >(0u);
to_be_deleted = new std::vector< uint >(0u);
delete_data = true;
delete_to_be_deleted = true;
// Copy all counters, if a counter is tagged as
// to be deleted, then copy the value
for (uint i = 0u; i != counter_.size(); ++i)
{
if (tbd[i])
this->add_counter(*counter_.data->operator[](i));
else
this->add_counter(counter_.data->operator[](i));
}
}
return *this;
}
COUNTERS_TEMPLATE(COUNTERS_TYPE() &, operator=)(Counters<Array_Type,Data_Type> && counters_) noexcept
{
if (this != &counters_)
{
// Removing the data currently stored in the
this->clear();
data = std::move(counters_.data);
to_be_deleted = std::move(counters_.to_be_deleted);
delete_data = std::move(counters_.delete_data);
delete_to_be_deleted = std::move(counters_.delete_to_be_deleted);
counters_.data = nullptr;
counters_.to_be_deleted = nullptr;
counters_.delete_data = false;
counters_.delete_to_be_deleted = false;
}
return *this;
}
COUNTERS_TEMPLATE(void, add_counter)(Counter<Array_Type, Data_Type> & counter)
{
to_be_deleted->push_back(data->size());
data->push_back(new Counter<Array_Type, Data_Type>(counter));
return;
}
COUNTERS_TEMPLATE(void, add_counter)(Counter<Array_Type, Data_Type> * counter)
{
data->push_back(counter);
return;
}
COUNTERS_TEMPLATE(void, add_counter)(
Counter_fun_type<Array_Type,Data_Type> count_fun_,
Counter_fun_type<Array_Type,Data_Type> init_fun_,
Data_Type * data_,
bool delete_data_,
std::string name_,
std::string desc_
)
{
/* We still need to delete the counter since we are using the 'new' operator.
* Yet, the actual data may not need to be deleted.
*/
to_be_deleted->push_back(data->size());
data->push_back(new Counter<Array_Type,Data_Type>(
count_fun_,
init_fun_,
data_,
delete_data_,
name_,
desc_
));
return;
}
COUNTERS_TEMPLATE(void, clear)()
{
for (auto& i : (*to_be_deleted))
delete data->operator[](i);
if (delete_data)
delete data;
if (delete_to_be_deleted)
delete to_be_deleted;
data = nullptr;
to_be_deleted = nullptr;
return;
}
COUNTERS_TEMPLATE(std::vector<std::string>, get_names)() const
{
std::vector< std::string > out(this->size());
for (unsigned int i = 0u; i < out.size(); ++i)
out[i] = this->data->at(i)->get_name();
return out;
}
COUNTERS_TEMPLATE(std::vector<std::string>, get_descriptions)() const
{
std::vector< std::string > out(this->size());
for (unsigned int i = 0u; i < out.size(); ++i)
out[i] = this->data->at(i)->get_description();
return this->name;
}
#undef COUNTER_TYPE
#undef COUNTER_TEMPLATE_ARGS
#undef COUNTER_TEMPLATE
#undef COUNTERS_TYPE
#undef COUNTERS_TEMPLATE_ARGS
#undef COUNTERS_TEMPLATE
#endif | 8,663 | 3,062 |
//clang 3.8.0
#include <iostream>
#include <functional>
using ft = std::function<void(int)>;
void p(const char* m, int i){
std::cout << m << ":" << i << std::endl;
}
int i;
class test{
int j;
public:
test(){j = ++i; p("ctor", j);}
~test(){p("dtor", j);}
test(const test& t){j = t.j*10; p("copy ctor", j);}
test(test&& t){j = t.j*100; p("move ctor", j);}
void operator()(int i){
std::cout << i << std::endl;
}
};
int main()
{
test o;
ft f;
//f = [&o](int i){o(i);};
f = o;
f(1);
std::cout << "Hello, world!\n";
return 0;
}
/*
ctor:1
copy ctor:10
move ctor:1000
dtor:10
1
Hello, world!
dtor:1000
dtor:1
*/
| 749 | 348 |
/*
*Name: Jared Wallace
*Date: 09-05-2014
*Section: 18
*
* Answers to questions:
* 1) const int NUM = 200;
* int x = 0;
* cout << "Please enter the value of x";
* cin >> x;
* if (x < NUM)
* {
* cout << "Hooray";
* }
* 2) T && F = F
* T || F = T
* F && F = F
* !(T && T) = F
* !T && T = F
* 3) 3
* awww...
* 4
*
*This program will function as a simple calculator, only performing one
*operation at a time.
*/
#include <iostream>
#include <cstdlib>
#include <cmath> // For the pow operation (Not required for this lab)
using namespace std;
int main()
{
const int OP_ADD = 0;
const int OP_SUB = 1;
const int OP_MUL = 2;
const int OP_DIV = 3;
const int OP_MOD = 4;
const int OP_EXP = 5;
const int OP_RED = 6;
const int OP_WRT = 7;
int inst = 0;
int data0 = 0;
int data1 = 0;
int data2 = 0;
cout << "Please enter the value for the instruction ";
cin >> inst;
cout << endl << "\nPlease enter the first operand ";
cin >> data1;
cout << endl << "\nPlease enter the second operand ";
cin >> data2;
if (inst == OP_ADD)
data0 = data1 + data2;
else if (inst == OP_SUB)
data0 = data1 - data2;
else if (inst == OP_MUL)
data0 = data1 * data2;
else if (inst == OP_DIV)
data0 = data1 / data2;
else if (inst == OP_MOD)
data0 = data1 % data2;
else if (inst == OP_EXP) // Not required for this lab
data0 = pow(data1, data2);
else
{
cout << "\nUnable to perform operation.";
data0 = -1;
}
cout << "\nYour calculation is complete.";
if (data0 != -1)
cout << "\nThe result is " << data0 << endl;
else
cout << "\nNo result obtained.\n";
return EXIT_SUCCESS;
}
| 1,913 | 684 |
#define COMPONENT slingload
#define COMPONENT_BEAUTIFIED SlingLoad
#include "\z\slr\addons\main\script_mod.hpp"
// #define DEBUG_MODE_FULL
// #define DISABLE_COMPILE_CACHE
// #define CBA_DEBUG_SYNCHRONOUS
// #define ENABLE_PERFORMANCE_COUNTERS
#ifdef DEBUG_ENABLED_SLINGLOAD
#define DEBUG_MODE_FULL
#endif
#ifdef DEBUG_SETTINGS_SLINGLOAD
#define DEBUG_SETTINGS DEBUG_SETTINGS_SLINGLOAD
#endif
#include "\z\slr\addons\main\script_macros.hpp"
| 453 | 191 |
#include "SimpleContinueHook.h"
#include <GameDownloader/GameDownloadService.h>
#include <Core/Service.h>
#include <QtCore/QDebug>
SimpleContinueHook::SimpleContinueHook(int hookId, QList<int> *preList, QList<int> *postList)
: HookBase(QString("hookId_%1").arg(hookId))
, _hookId(hookId)
, _preList(preList)
, _postList(postList)
, _beforeCallCount(0)
, _afterCallCount(0)
{
}
SimpleContinueHook::~SimpleContinueHook()
{
}
HookBase::HookResult SimpleContinueHook::beforeDownload(GameDownloadService *, ServiceState *state)
{
const P1::Core::Service *service = state->service();
this->_beforeCallCount++;
this->_preList->append(this->_hookId);
qDebug() << "beforeDownload " << (service == 0 ? "service is null" : service->id());
return HookBase::Continue;
}
HookBase::HookResult SimpleContinueHook::afterDownload(GameDownloadService *, ServiceState *state)
{
const P1::Core::Service *service = state->service();
this->_afterCallCount++;
this->_postList->append(this->_hookId);
qDebug() << "afterDownload " << (service == 0 ? "service is null" : service->id());
return HookBase::Continue;
}
| 1,167 | 403 |
#include <windows.h>
BOOL WINAPI DllMain(
HINSTANCE hinstDLL, // handle to DLL module
DWORD fdwReason, // reason for calling function
LPVOID lpReserved ) // reserved
{
switch (fdwReason)
{
case DLL_PROCESS_ATTACH:
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
} | 372 | 150 |
#include "EDCommon.h"
#include "EDDefault.h"
// (THIS SHOULD BE THE FIRST FUNCTION YOU COMPLETE. YOUR OTHER FUNCTIONS WILL NOT APPEAR TO WORK PROPERLY WITHOUT IT.)
void OrthoNormalInverse( matrix4f &MatrixO, const matrix4f &MatrixA )
{
// Replace this call with your own implementation of the Orthnormal Inverse algorithm
EDOrthoNormalInverse( MatrixO, MatrixA );
}
void MouseLook( matrix4f &mat, float fTime )
{
POINT mousePos;
GetCursorPos( &mousePos );
SetCursorPos( 400, 300 );
float mouseDiff[2] = { float(400 - mousePos.x), float(mousePos.y - 300) };
// Replace this call with your own implementation of the Mouse-Look algorithm
float fCameraRotateRate = 0.002f;
EDMouseLook( mat, mouseDiff, fCameraRotateRate );
}
void LookAt( matrix4f &mat, const vec3f &target )
{
// Replace this call with your own implementation of the Look-At algorithm
EDLookAt( mat, target );
}
void TurnTo( matrix4f &mat, const vec3f &target, float fTime )
{
// Replace this call with your own implementation of the Turn-To algorithm
EDTurnTo( mat, target, fTime );
}
void HardAttach( matrix4f &AttachMat, const matrix4f &AttachToMat, const vec3f &offset )
{
// Replace this call with your own implementation of the Hard-Attach algorithm
EDHardAttach( AttachMat, AttachToMat, offset );
}
void SoftAttach( matrix4f &AttachMat, const matrix4f &AttachToMat, queue< matrix4f > &Buffer, const vec3f &offset )
{
// Replace this call with your own implementation of the Soft-Attach algorithm
EDSoftAttach( AttachMat, AttachToMat, offset );
} | 1,541 | 529 |
/*
using namespace GFW;
Device::Device() {
}
Device::~Device() {
}
void Device::Begin(String str) {
assert(this->device.find(str) == this->device.end());
this->stack.push_back(&this->device[str]);
}
void Device::End() {
assert(this->stack_count,TEXT("Error:DeviceStackCount"));
this->stack.pop_back();
if(this->stack.size()){}
}
*/ | 340 | 128 |
// Given an number N count How many digit present in that number
/*
Example :-
Input :- N = 2000
Output :- 4
Input :- N = 12345678
Output :- 8
*/
#include <iostream>
using namespace std;
int countDigit(int n)
{
if(n==0)
return 0 ;
int count = 1;
n = n/10;
return count+countDigit(n);
}
int main() {
int n;
cin>>n;
int count = countDigit(n);
cout<<"The digit present in that number are : "<<count<<endl;
}
/*
Input :-
2000
Output :-
The digit present in that number are : 4
*/ | 528 | 205 |
/*
Typical usage for an OpenGL program:
int main()
{
lak::core_init();
lak::window window(...);
window.init_opengl(...);
uint32_t framerate = 60;
auto last_counter = lak::performance_counter();
// main loop
while(...)
{
// event handlers
// update code
// draw code
window.swap();
last_counter = lak::yield_frame(last_counter, framerate);
}
window.close();
lak::core_quit();
}
*/
#ifndef LAK_WINDOW_HPP
#define LAK_WINDOW_HPP
#include "lak/platform.hpp"
#include "lak/events.hpp"
#include "lak/bank_ptr.hpp"
#include "lak/image.hpp"
#include "lak/memmanip.hpp"
#include "lak/string.hpp"
#include "lak/surface.hpp"
#include "lak/vec.hpp"
#include "lak/profile.hpp"
namespace lak
{
enum struct graphics_mode
{
None = 0,
Software = 1,
OpenGL = 2,
Vulkan = 3
};
struct software_settings
{
};
struct opengl_settings
{
bool double_buffered = false;
uint8_t depth_size = 24;
uint8_t colour_size = 8;
uint8_t stencil_size = 8;
int major = 3;
int minor = 2;
};
struct vulkan_settings
{
};
struct software_context;
struct opengl_context;
struct vulkan_context;
struct window_handle;
extern template struct lak::array<lak::window_handle, lak::dynamic_extent>;
extern template struct lak::railcar<lak::window_handle>;
extern template struct lak::bank<lak::window_handle>;
extern template size_t lak::bank<lak::window_handle>::internal_create<
lak::window_handle>(lak::window_handle &&);
using const_window_handle_ref = const lak::window_handle &;
extern template size_t lak::bank<lak::window_handle>::internal_create<
lak::const_window_handle_ref>(lak::const_window_handle_ref &&);
extern template struct lak::unique_bank_ptr<lak::window_handle>;
extern template struct lak::shared_bank_ptr<lak::window_handle>;
using window_handle_bank = lak::bank<lak::window_handle>;
/* --- create/destroy window --- */
lak::window_handle *create_window(const lak::software_settings &s);
lak::window_handle *create_window(const lak::opengl_settings &s);
lak::window_handle *create_window(const lak::vulkan_settings &s);
bool destroy_window(lak::window_handle *w);
/* --- window state --- */
lak::wstring window_title(const lak::window_handle *w);
bool set_window_title(lak::window_handle *w, const lak::wstring &s);
lak::vec2l_t window_size(const lak::window_handle *w);
lak::vec2l_t window_drawable_size(const lak::window_handle *w);
bool set_window_size(lak::window_handle *w, lak::vec2l_t s);
bool set_window_cursor_pos(const lak::window_handle *w, lak::vec2l_t p);
// :TODO:
// bool set_window_drawable_size(lak::window_handle *w, lak::vec2l_t s);
/* --- graphics control --- */
lak::graphics_mode window_graphics_mode(const lak::window_handle *w);
// :TODO: This probably belongs in the platform header.
bool set_opengl_swap_interval(const lak::opengl_context &c, int interval);
bool swap_window(lak::window_handle *w);
// Yield this thread until the target framerate is achieved.
uint64_t yield_frame(const uint64_t last_counter,
const uint32_t target_framerate);
/* --- window wrapper class --- */
struct window
{
private:
lak::unique_bank_ptr<lak::window_handle> _handle;
window(lak::unique_bank_ptr<lak::window_handle> &&handle);
public:
inline window(window &&w) : _handle(lak::move(w._handle)) {}
static lak::result<window> make(const lak::software_settings &s);
static lak::result<window> make(const lak::opengl_settings &s);
static lak::result<window> make(const lak::vulkan_settings &s);
~window();
inline lak::window_handle *handle() { return _handle.get(); }
inline const lak::window_handle *handle() const { return _handle.get(); }
inline lak::graphics_mode graphics() const
{
return lak::window_graphics_mode(handle());
}
inline lak::wstring title() const { return lak::window_title(handle()); }
inline window &set_title(const lak::wstring &title)
{
ASSERT(lak::set_window_title(handle(), title));
return *this;
}
inline lak::vec2l_t size() const { return lak::window_size(handle()); }
inline lak::vec2l_t drawable_size() const
{
return lak::window_drawable_size(handle());
}
inline window &set_size(lak::vec2l_t size)
{
ASSERT(lak::set_window_size(handle(), size));
return *this;
}
inline const window &set_cursor_pos(lak::vec2l_t pos) const
{
ASSERT(lak::set_window_cursor_pos(handle(), pos));
return *this;
}
inline bool swap() { return lak::swap_window(handle()); }
};
}
#include <ostream>
[[maybe_unused]] inline std::ostream &operator<<(std::ostream &strm,
lak::graphics_mode mode)
{
switch (mode)
{
case lak::graphics_mode::OpenGL: strm << "OpenGL"; break;
case lak::graphics_mode::Software: strm << "Software"; break;
case lak::graphics_mode::Vulkan: strm << "Vulkan"; break;
default: strm << "None"; break;
}
return strm;
}
#endif
| 5,011 | 1,833 |
#include <iostream>
#include "ArbolGeneral.hpp"
#include "tablero.hpp"
#include <string>
using namespace std;
int main(int argc, char *argv[]){
//Tablero vacío 6x7
Tablero tablero(6, 7);
//Manualmente se insertan algunos movimientos:
tablero.colocarFicha(3); //Jugador 1 inserta ficha en columna 3
tablero.cambiarTurno();
tablero.colocarFicha(1); //Jugador 2 inserta ficha en columna 1
tablero.cambiarTurno();
tablero.colocarFicha(3); //Jugador 1 inserta ficha en columna 3.
tablero.cambiarTurno();
//Se muestra el tablero
cout << "Tablero obtenido tras tres movimientos: \n"<<tablero;
//A partir de la situación actual del tablero, montamos un árbol para estudiar algunas posibilidades.
// Éste es el árbol que queremos montar:
// tablero
// |
// |---------------|
// tablero1 tablero2
// |
// tablero3
//Árbol 'partida', con 'tablero' como nodo raíz
ArbolGeneral<Tablero> partida(tablero);
//Estudio opciones a partir de tablero: Jugador 2 coloca ficha en columna 1. (tablero1)
Tablero tablero1(tablero); //tablero queda sin modificar
tablero1.colocarFicha(1);
ArbolGeneral<Tablero> arbol1 (tablero1); //creo árbol con un nodo (tablero1)
//Otra opción: Jugador 2 coloca ficha en columna 2. (tablero2)
Tablero tablero2(tablero); //tablero queda sin modificar
tablero2.colocarFicha(2);
ArbolGeneral<Tablero> arbol2(tablero2); //creo árbol con un nodo
// Sobre la última opción, ahora contemplo la posibilidad de que
// Jugador 1 coloque ficha también en columna 2.
tablero2.cambiarTurno(); //modifico tablero2 (esta modificación sería tablero3)
tablero2.colocarFicha(2);
ArbolGeneral<Tablero> arbol3 (tablero2); //creo árbol con un nodo
arbol2.insertar_hijomasizquierda(arbol2.raiz(), arbol3); //añado este árbol como hijo de arbol2
// Inserto arbol1 y arbol2 como hijos de partida.
// arbol1 es el hijo más a la izquierda y arbol2 es hermano a la derecha de arbol1
// Forma de hacerlo A: inserto varios hijomasizquierda en el orden inverso al deseado
// partida.insertar_hijomasizquierda(partida.raiz(), arbol2);
// partida.insertar_hijomasizquierda(partida.raiz(), arbol1); //hijomasizquierda desplaza al anterior a la derecha
// Forma de hacerlo B: inserto un hijomasizquierda y hermanoderecha
partida.insertar_hijomasizquierda(partida.raiz(), arbol1); //inserto un hijomasizquierda
partida.insertar_hermanoderecha(partida.hijomasizquierda(partida.raiz()), arbol2); //le inserto un hermanoderecha
// Recorremos en preorden para comprobar el arbol 'partida' resultante
cout << "\nÁrbol en preorden: \n"<<endl;
partida.recorrer_preorden();
// Podamos el hijomasizquierda y recorremos en preorden:
ArbolGeneral<Tablero> rama_podada;
partida.podar_hermanoderecha(partida.hijomasizquierda(partida.raiz()), rama_podada);
cout << "\nRecorrido preorden después de podar arbol2: \n"<<endl;
partida.recorrer_preorden();
cout << "\nRecorrido preorden de la rama podada: \n"<<endl;
rama_podada.recorrer_preorden();
// Probamos ArbolGeneral::asignar_subarbol. Asignamos a partida la rama_podada:
partida.asignar_subarbol(rama_podada, rama_podada.raiz());
cout << "\nRecorrido preorden después de asignar a la raiz la rama_podada: \n"<<endl;
partida.recorrer_preorden();
cout << "\nRecorrido postorden después de asignar a la raiz la rama_podada: \n"<<endl;
partida.recorrer_postorden();
return 0;
}
| 3,596 | 1,445 |
#version 420
in vec2 Position;
out vec2 texCoords;
void main()
{
gl_Position = vec4(Position.xy, 0.0f ,1.0f);
gl_Position.x /=(.5f* 1280.0f);
//gl_Position.x = gl_Position.x;
gl_Position.y /= (.5f*720.0f);
gl_Position.x -= 1f;
gl_Position.y -= 1f;
gl_Position.y *= -1.0f;
texCoords = vec2(1.0f-Position.x/1280.0f,Position.y/720.0f); //(gl_Position.xy + 1.0f) * 0.5f;
} | 386 | 217 |
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "LaunchFromProfileCommand.h"
#include "DesktopPlatformModule.h"
#include "ILauncherProfile.h"
#include "ILauncherProfileManager.h"
#include "ILauncherTask.h"
#include "ILauncherWorker.h"
#include "ILauncher.h"
#include "ILauncherServicesModule.h"
#include "ITargetDeviceServicesModule.h"
#include "UserInterfaceCommand.h"
#include "Misc/CommandLine.h"
#include "Misc/OutputDeviceRedirector.h"
DEFINE_LOG_CATEGORY_STATIC(LogUFECommands, All, All);
void FLaunchFromProfileCommand::Run(const FString& Params)
{
// Get the name of the profile from the command line.
FString ProfileName;
FParse::Value(FCommandLine::Get(), TEXT("-PROFILENAME="), ProfileName);
if (ProfileName.IsEmpty())
{
UE_LOG(LogUFECommands, Warning, TEXT("Profile name was found. Please use '-PROFILENAME=' in your command line."));
return;
}
// Loading the launcher services module to get the needed profile.
ILauncherServicesModule& LauncherServicesModule = FModuleManager::LoadModuleChecked<ILauncherServicesModule>(TEXT("LauncherServices"));
ILauncherProfileManagerRef ProfileManager = LauncherServicesModule.GetProfileManager();
ILauncherProfilePtr Profile = ProfileManager->FindProfile(ProfileName);
// Loading the Device Proxy Manager to get the needed Device Manager.
ITargetDeviceServicesModule& DeviceServiceModule = FModuleManager::LoadModuleChecked<ITargetDeviceServicesModule>(TEXT("TargetDeviceServices"));
TSharedRef<ITargetDeviceProxyManager> DeviceProxyManager = DeviceServiceModule.GetDeviceProxyManager();
UE_LOG(LogUFECommands, Display, TEXT("Begin the process of launching a project using the provided profile."));
ILauncherRef LauncherRef = LauncherServicesModule.CreateLauncher();
ILauncherWorkerPtr LauncherWorkerPtr = LauncherRef->Launch(DeviceProxyManager, Profile.ToSharedRef());
// This will allow us to pipe the launcher messages into the command window.
LauncherWorkerPtr.Get()->OnOutputReceived().AddStatic(&FLaunchFromProfileCommand::MessageReceived);
// Allows us to exit this command once the launcher worker has completed or is canceled
LauncherWorkerPtr.Get()->OnCompleted().AddRaw(this, &FLaunchFromProfileCommand::LaunchCompleted);
LauncherWorkerPtr.Get()->OnCanceled().AddRaw(this, &FLaunchFromProfileCommand::LaunchCanceled);
TArray<ILauncherTaskPtr> TaskList;
int32 NumOfTasks = LauncherWorkerPtr->GetTasks(TaskList);
UE_LOG(LogUFECommands, Display, TEXT("There are '%i' tasks to be completed."), NumOfTasks);
// Holds the current element in the TaskList array.
int32 TaskIndex = 0;
// Holds the name of the current tasked.
FString TriggeredTask;
bTestRunning = true;
while (bTestRunning)
{
if (TaskIndex >= NumOfTasks) continue;
ILauncherTaskPtr CurrentTask = TaskList[TaskIndex];
// Log the current task, but only once per run.
if (CurrentTask->GetStatus() == ELauncherTaskStatus::Busy)
{
if (CurrentTask->GetDesc() == TriggeredTask) continue;
TriggeredTask = *CurrentTask->GetDesc();
UE_LOG(LogUFECommands, Display, TEXT("Current Task is %s"), *TriggeredTask);
TaskIndex++;
}
}
}
void FLaunchFromProfileCommand::MessageReceived(const FString& InMessage)
{
GLog->Logf(ELogVerbosity::Log, TEXT("%s"), *InMessage);
}
void FLaunchFromProfileCommand::LaunchCompleted(bool Outcome, double ExecutionTime, int32 ReturnCode)
{
UE_LOG(LogUFECommands, Log, TEXT("Profile launch command %s."), Outcome ? TEXT("is SUCCESSFUL") : TEXT("has FAILED"));
bTestRunning = false;
}
void FLaunchFromProfileCommand::LaunchCanceled(double ExecutionTime)
{
UE_LOG(LogUFECommands, Log, TEXT("Profile launch command was canceled."));
bTestRunning = false;
} | 3,694 | 1,165 |
Given two arrays a[] and b[] respectively of size n and m, the task is to print the count of elements in the intersection (or common elements) of the two arrays.
For this question, the intersection of two arrays can be defined as the set containing distinct common elements between the two arrays.
Example 1:
Input:
n = 5, m = 3
a[] = {89, 24, 75, 11, 23}
b[] = {89, 2, 4}
Output: 1
Explanation:
89 is the only element
in the intersection of two arrays.
class Solution{
public:
//Function to return the count of the number of elements in
//the intersection of two arrays.
int NumberofElementsInIntersection (int a[], int b[], int n, int m )
{
// Your code goes here
unordered_map<int,int> mp;
for(int i=0;i<n;i++)
{
mp[a[i]]++;
if(mp[a[i]]>1)
mp[a[i]]--;
}
for(int i=0;i<m;i++)
{
// Insert only if there is element present from last array.
//Else this could lead to error because one array can also contain one ele more than one time
if(mp[b[i]]==1)
mp[b[i]]++;
}
int count=0;
for(auto ele: mp)
{
if(ele.second>1)
count++;
}
return count;
}
};
Correct Answer.Correct Answer
Execution Time:0.81 | 1,358 | 429 |
/*
Register an image pair based on SIFT features
Author: Abhishek Dutta <adutta@robots.ox.ac.uk>
Date: 3 Jan. 2018
some code borrowed from: vlfeat-0.9.20/src/sift.c
*/
#include "imreg_sift/imreg_sift.h"
// normalize input points such that their centroid is the coordinate origin (0, 0)
// and their average distance from the origin is sqrt(2).
// pts is 3 x n matrix
void imreg_sift::get_norm_matrix(const MatrixXd& pts, Matrix<double,3,3>& T) {
Vector3d mu = pts.rowwise().mean();
MatrixXd norm_pts = (pts).colwise() - mu;
VectorXd x2 = norm_pts.row(0).array().pow(2);
VectorXd y2 = norm_pts.row(1).array().pow(2);
VectorXd dist = (x2 + y2).array().sqrt();
double scale = sqrt(2) / dist.array().mean();
T(0,0) = scale; T(0,1) = 0; T(0,2) = -scale * mu(0);
T(1,0) = 0; T(1,1) = scale; T(1,2) = -scale * mu(1);
T(2,0) = 0; T(2,1) = 0; T(2,2) = 1;
}
// Implementation of Direct Linear Transform (DLT) algorithm as described in pg. 91
// Multiple View Geometry in Computer Vision, Richard Hartley and Andrew Zisserman, 2nd Edition
// assumption: X and Y are point correspondences. Four 2D points. (4 X 3 in homogenous coordinates)
// X and Y : n x 3 matrix
// H : 3x3 matrix
void imreg_sift::dlt(const MatrixXd& X, const MatrixXd& Y, Matrix<double,3,3>& H) {
size_t n = X.rows();
MatrixXd A(2*n, 9);
A.setZero();
for(size_t i=0; i<n; ++i) {
A.row(2*i).block(0,3,1,3) = -Y(i,2) * X.row(i);
A.row(2*i).block(0,6,1,3) = Y(i,1) * X.row(i);
A.row(2*i + 1).block(0,0,1,3) = Y(i,2) * X.row(i);
A.row(2*i + 1).block(0,6,1,3) = -Y(i,0) * X.row(i);
}
JacobiSVD<MatrixXd> svd(A, ComputeFullV);
// Caution: the last column of V are reshaped into 3x3 matrix as shown in Pg. 89
// of Hartley and Zisserman (2nd Edition)
// svd.matrixV().col(8).array().resize(3,3) is not correct!
H << svd.matrixV()(0,8), svd.matrixV()(1,8), svd.matrixV()(2,8),
svd.matrixV()(3,8), svd.matrixV()(4,8), svd.matrixV()(5,8),
0, 0, svd.matrixV()(8,8); // affine transform
// svd.matrixV()(6,8), svd.matrixV()(7,8), svd.matrixV()(8,8); // projective transform
}
void imreg_sift::estimate_transform(const MatrixXd& X, const MatrixXd& Y, string& transform, Matrix<double,3,3>& T) {
if (transform == "identity") {
T << 1.0, 0.0, 0.0,
0.0, 1.0, 0.0,
0.0, 0.0, 1.0;
}
if (transform == "translation" || transform == "rigid" || transform == "similarity") {
// ignore homogenous representation
Matrix<double,4,2> X_, Y_;
X_ = X.block<4,2>(0,0);
Y_ = Y.block<4,2>(0,0);
// example values to test with spot the difference demo image.
// should give identity rotation
// X_ << -1.1684, -1.34154,
// -1.3568, -1.28858,
// -1.08083,-1.0768,
// -1.47721,-1.02969;
// Y_ << -1.15706, -1.33154,
// -1.35822,-1.28466,
// -1.08694, -1.07509,
// -1.48525, -1.02964;
size_t m = X_.cols();
size_t n = X_.rows();
Matrix<double,2,4> Xt_, Yt_;
Xt_ = X_.transpose();
Yt_ = Y_.transpose();
// subtract mean from points
VectorXd X_mu = Xt_.rowwise().mean();
VectorXd Y_mu = Yt_.rowwise().mean();
Xt_.colwise() -= X_mu;
Yt_.colwise() -= Y_mu;
MatrixXd X_norm = Xt_.transpose();
MatrixXd Y_norm = Yt_.transpose();
// compute matrix A first (3 X 3 rotation matrix)
MatrixXd A = (1.0 / n) * (Y_norm.transpose() * X_norm);
// rotation matrix to compute
Matrix<double,2,2> R;
Matrix<double,2,2> d = Matrix<double,2,2>::Identity();
// do SVD of A
JacobiSVD<MatrixXd> svd_u(A, ComputeFullU);
Matrix<double,2,2> U = svd_u.matrixU();
U(0,0) = -1.0 * U(0,0);
U(1,0) = -1.0 * U(1,0);
JacobiSVD<MatrixXd> svd_v(A, ComputeFullV);
Matrix<double,2,2> V = svd_v.matrixV();
V(0,0) = -1.0 * V(0,0);
V(1,0) = -1.0 * V(1,0);
if (svd_u.rank() == 0) {
cout << "SVD leads to 0 rank!" << endl;
return;
}
if (svd_u.rank() == (m - 1)) {
if ( (U.determinant() * V.determinant() ) > 0) {
R = U * V;
} else {
double s = d(1,1);
d(1,1) = -1;
R = U * d * V;
d(1,1) = s;
}
} else {
R = U * d * V;
}
double scale = 1.0;
// compute scale if its similarity transform
if (transform == "similarity") {
double s_dot_d = svd_u.singularValues().dot(d.diagonal());
double x_norm_var = X_norm.transpose().cwiseAbs2().rowwise().mean().sum();
scale = (1.0 / x_norm_var) * (svd_u.singularValues().dot(d.diagonal()));
}
// apply scale to rotation and translation
Vector2d t = Y_mu - (scale * (R * X_mu));
R = R * scale;
if (transform == "translation") {
// apply identity rotation
T << 1, 0, t(0),
0, 1, t(1),
0, 0, 1;
} else {
T << R(0,0), R(0,1), t(0),
R(1,0), R(1,1), t(1),
0, 0, 1.0;
}
}
if (transform == "affine") {
// estimate affine transform using DLT algorithm
dlt(X, Y, T);
}
// cout << "Final T value is: " << endl;
// cout << T << endl;
}
void imreg_sift::compute_photo_transform(Magick::Image img_one, Magick::Image img_two, Magick::Image& transformed_img) {
int w = img_two.rows();
int h = img_two.columns();
int ransac_iters = 10;
float error_threshold = 0.05;
int num_pts = min(400, min(w,h));
int score = 0;
int max_score = 0;
std::vector<int> x_pts, y_pts;
std::vector<int> inlier_x_pts, inlier_y_pts;
std::vector<int> best_inlier_x_pts, best_inlier_y_pts;
// initialize random number generator to randomly sample pixels from images
random_device rand_device;
mt19937 generator(rand_device());
uniform_int_distribution<int> x_dist(0, w);
uniform_int_distribution<int> y_dist(0, h);
Magick::Color pix = img_one.pixelColor(10,10);
for (int r = 0; r < ransac_iters; r++) {
x_pts.clear(); y_pts.clear();
inlier_x_pts.clear(); inlier_y_pts.clear();
// pick random x and y points
for (int i = 0; i < num_pts; i++) {
x_pts.push_back(x_dist(generator));
y_pts.push_back(y_dist(generator));
}
// select intensities at the random points
Eigen::VectorXd img_one_red(num_pts), img_two_red(num_pts);
Eigen::VectorXd img_one_green(num_pts), img_two_green(num_pts);
Eigen::VectorXd img_one_blue(num_pts), img_two_blue(num_pts);
for (int i = 0; i < num_pts; i++) {
Magick::ColorRGB img_one_px(img_one.pixelColor(x_pts[i], y_pts[i]));
img_one_blue[i] = img_one_px.blue();
img_one_red[i] = img_one_px.red();
img_one_green[i] = img_one_px.green();
// cout << img_one_red[i] << " " << img_one_green[i] << " " << img_one_blue[i] << endl;
Magick::ColorRGB img_two_px(img_two.pixelColor(x_pts[i], y_pts[i]));
img_two_blue[i] = img_two_px.blue();
img_two_red[i] = img_two_px.red();
img_two_green[i] = img_two_px.green();
}
// estimate photometric transform
Matrix3d A = Matrix3d::Identity();
Vector3d b;
VectorXd a_b;
solve_lse(img_one_red, img_two_red, a_b);
A(0,0) = a_b(0);
b(0) = a_b(1);
solve_lse(img_one_green, img_two_green, a_b);
A(1,1) = a_b(0);
b(1) = a_b(1);
solve_lse(img_one_blue, img_two_blue, a_b);
A(2,2) = a_b(0);
b(2) = a_b(1);
MatrixXd B = b.transpose().replicate(num_pts, 1);
// cout << "Computed A amd B are: " << endl;
// cout << A << endl;
// cout << B << endl;
MatrixXd iter_img_one = MatrixXd::Ones(num_pts, 3);
MatrixXd iter_img_two = MatrixXd::Ones(num_pts, 3);
iter_img_one.col(0) << img_one_red;
iter_img_one.col(1) << img_one_green;
iter_img_one.col(2) << img_one_blue;
iter_img_two.col(0) << img_two_red;
iter_img_two.col(1) << img_two_green;
iter_img_two.col(2) << img_two_blue;
// compute image one from estimate
MatrixXd computed_img_one = (iter_img_two * A) + B;
VectorXd errors = (iter_img_one - computed_img_one).cwiseAbs2().rowwise().sum().cwiseSqrt();
for(int k = 0; k < errors.size(); k++) {
// cout << errors(k) << endl;
if (errors(k) < error_threshold) {
inlier_x_pts.push_back(x_pts[k]);
inlier_y_pts.push_back(y_pts[k]);
}
}
score = inlier_x_pts.size();
if (score > max_score) {
best_inlier_x_pts.clear();
best_inlier_y_pts.clear();
for (int j=0; j < inlier_x_pts.size(); j++) {
best_inlier_x_pts.push_back(inlier_x_pts[j]);
best_inlier_y_pts.push_back(inlier_y_pts[j]);
}
}
max_score = best_inlier_x_pts.size();
} // end of ransac loop
// cout << "best inliers are: " << endl;
// cout << best_inlier_x_pts.size() << endl;
if (max_score < 2) {
cout << "Less than 2 points in best inliers. Returning!" << endl;
return;
}
// select intensities at the best inlier points
int best_num_pts = best_inlier_x_pts.size();
Eigen::VectorXd img_one_red(best_num_pts), img_two_red(best_num_pts);
Eigen::VectorXd img_one_green(best_num_pts), img_two_green(best_num_pts);
Eigen::VectorXd img_one_blue(best_num_pts), img_two_blue(best_num_pts);
img_one.modifyImage(); img_two.modifyImage(); transformed_img.modifyImage();
for (int i = 0; i < best_num_pts; i++) {
Magick::ColorRGB img_one_px(img_one.pixelColor(best_inlier_x_pts[i], best_inlier_y_pts[i]));
img_one_blue[i] = img_one_px.blue();
img_one_green[i] = img_one_px.green();
img_one_red[i] = img_one_px.red();
Magick::ColorRGB img_two_px(img_two.pixelColor(best_inlier_x_pts[i], best_inlier_y_pts[i]));
img_two_blue[i] = img_two_px.blue();
img_two_green[i] = img_two_px.green();
img_two_red[i] = img_two_px.red();
}
// estimate photometric transform
Matrix3d A = Matrix3d::Identity();
Vector3d b;
VectorXd a_b;
solve_lse(img_one_red, img_two_red, a_b);
A(0,0) = a_b(0);
b(0) = a_b(1);
solve_lse(img_one_green, img_two_green, a_b);
A(1,1) = a_b(0);
b(1) = a_b(1);
solve_lse(img_one_blue, img_two_blue, a_b);
A(2,2) = a_b(0);
b(2) = a_b(1);
MatrixXd B = b.transpose().replicate(num_pts, 1);
// cout << "Final A and B values are: " << endl;
// cout << A << endl;
// cout << B << endl;
for(unsigned int ii = 0; ii < transformed_img.rows(); ii++) {
for(unsigned int jj = 0; jj < transformed_img.columns(); jj++) {
Magick::ColorRGB img_two_pixel(img_two.pixelColor(jj, ii));
// apply the computed transform
double r = (img_two_pixel.red() * A(0,0)) + B(0,0);
double g = (img_two_pixel.green() * A(1,1)) + B(0,1);
double b = (img_two_pixel.blue() * A(2,2)) + B(0,2);
img_two_pixel.red(r);
img_two_pixel.green(g);
img_two_pixel.blue(b);
transformed_img.pixelColor(jj,ii,img_two_pixel);
}
}
// cout << "done with photometric transform!" << endl;
// transformed_img.write("/home/shrinivasan/Desktop/res_test.jpg");
return;
}
void imreg_sift::solve_lse(Eigen::VectorXd x, Eigen::VectorXd y, VectorXd& a_and_b) {
MatrixXd S = MatrixXd::Ones(y.size(), 2);
double tolerance = 1e-4;
S.col(0) << y;
JacobiSVD<MatrixXd> svd(S, ComputeThinU | ComputeThinV);
MatrixXd singular_values = svd.singularValues();
MatrixXd singular_values_inv(S.rows(), S.cols());
singular_values_inv.setZero();
for (unsigned int i = 0; i < singular_values.rows(); ++i) {
if (singular_values(i) > tolerance) {
singular_values_inv(i, i) = 1. / singular_values(i);
} else {
singular_values_inv(i, i) = 0.;
}
}
a_and_b = (svd.matrixU() * singular_values_inv * svd.matrixV().transpose()).transpose() * x;
}
double imreg_sift::clamp(double v, double min, double max) {
if( v > min ) {
if( v < max ) {
return v;
} else {
return max;
}
} else {
return min;
}
}
void imreg_sift::compute_sift_features(const Magick::Image& img,
vector<VlSiftKeypoint>& keypoint_list,
vector< vector<vl_uint8> >& descriptor_list,
bool verbose) {
vl_bool err = VL_ERR_OK ;
// algorithm parameters based on vlfeat-0.9.20/toolbox/sift/vl_sift.c
int O = - 1 ;
int S = 3 ;
int o_min = 0 ;
double edge_thresh = -1 ;
double peak_thresh = -1 ;
double norm_thresh = -1 ;
double magnif = -1 ;
double window_size = -1 ;
int ndescriptors = 0;
vl_sift_pix *fdata = 0 ;
vl_size q ;
int i ;
vl_bool first ;
double *ikeys = 0 ;
int nikeys = 0, ikeys_size = 0 ;
// move image data to fdata for processing by vl_sift
// @todo: optimize and avoid this overhead
fdata = (vl_sift_pix *) malloc( img.rows() * img.columns() * sizeof(vl_sift_pix) ) ;
if( fdata == NULL ) {
cout << "\nfailed to allocated memory for vl_sift_pix array" << flush;
return;
}
size_t flat_index = 0;
for( unsigned int i=0; i<img.rows(); ++i ) {
for( unsigned int j=0; j<img.columns(); ++j ) {
Magick::ColorGray c = img.pixelColor( j, i );
fdata[flat_index] = c.shade();
++flat_index;
}
}
// create filter
VlSiftFilt *filt = 0 ;
filt = vl_sift_new (img.columns(), img.rows(), O, S, o_min) ;
if (peak_thresh >= 0) vl_sift_set_peak_thresh (filt, peak_thresh) ;
if (edge_thresh >= 0) vl_sift_set_edge_thresh (filt, edge_thresh) ;
if (norm_thresh >= 0) vl_sift_set_norm_thresh (filt, norm_thresh) ;
if (magnif >= 0) vl_sift_set_magnif (filt, magnif) ;
if (window_size >= 0) vl_sift_set_window_size (filt, window_size) ;
if (!filt) {
cout << "\nCould not create SIFT filter." << flush;
goto done ;
}
/* ...............................................................
* Process each octave
* ............................................................ */
i = 0 ;
first = 1 ;
descriptor_list.clear();
keypoint_list.clear();
while (1) {
VlSiftKeypoint const *keys = 0 ;
int nkeys ;
/* calculate the GSS for the next octave .................... */
if (first) {
first = 0 ;
err = vl_sift_process_first_octave (filt, fdata) ;
} else {
err = vl_sift_process_next_octave (filt) ;
}
if (err) {
err = VL_ERR_OK ;
break ;
}
/* run detector ............................................. */
vl_sift_detect(filt) ;
keys = vl_sift_get_keypoints(filt) ;
nkeys = vl_sift_get_nkeypoints(filt) ;
i = 0 ;
/* for each keypoint ........................................ */
for (; i < nkeys ; ++i) {
double angles [4] ;
int nangles ;
VlSiftKeypoint const *k ;
/* obtain keypoint orientations ........................... */
k = keys + i ;
VlSiftKeypoint key_data = *k;
nangles = vl_sift_calc_keypoint_orientations(filt, angles, k) ;
vl_uint8 d[128]; // added by @adutta
/* for each orientation ................................... */
for (q = 0 ; q < (unsigned) nangles ; ++q) {
vl_sift_pix descr[128];
/* compute descriptor (if necessary) */
vl_sift_calc_keypoint_descriptor(filt, descr, k, angles[q]) ;
vector<vl_uint8> descriptor(128);
int j;
for( j=0; j<128; ++j ) {
float value = 512.0 * descr[j];
value = ( value < 255.0F ) ? value : 255.0F;
descriptor[j] = (vl_uint8) value;
d[j] = (vl_uint8) value;
}
descriptor_list.push_back(descriptor);
++ndescriptors;
keypoint_list.push_back(key_data); // add corresponding keypoint
}
}
}
done :
/* release filter */
if (filt) {
vl_sift_delete (filt) ;
filt = 0 ;
}
/* release image data */
if (fdata) {
free (fdata) ;
fdata = 0 ;
}
}
void imreg_sift::get_putative_matches(vector< vector<vl_uint8> >& descriptor_list1,
vector< vector<vl_uint8> >& descriptor_list2,
std::vector< std::pair<uint32_t,uint32_t> >& putative_matches,
float threshold) {
size_t n1 = descriptor_list1.size();
size_t n2 = descriptor_list2.size();
putative_matches.clear();
for( uint32_t i=0; i<n1; i++ ) {
unsigned int dist_best1 = numeric_limits<unsigned int>::max();
unsigned int dist_best2 = numeric_limits<unsigned int>::max();
uint32_t dist_best1_index = -1;
for( uint32_t j=0; j<n2; j++ ) {
unsigned int dist = 0;
for( int d=0; d<128; d++ ) {
int del = descriptor_list1[i][d] - descriptor_list2[j][d];
dist += del*del;
if (dist >= dist_best2) {
break;
}
}
// find the nearest and second nearest point in descriptor_list2
if( dist < dist_best1 ) {
dist_best2 = dist_best1;
dist_best1 = dist;
dist_best1_index = j;
} else {
if( dist < dist_best2 ) {
dist_best2 = dist;
}
}
}
// use Lowe's 2nd nearest neighbour test
float d1 = threshold * (float) dist_best1;
if( (d1 < (float) dist_best2) && dist_best1_index != -1 ) {
putative_matches.push_back( std::make_pair(i, dist_best1_index) );
}
}
}
void imreg_sift::get_diff_image(Magick::Image& im1, Magick::Image& im2, Magick::Image& cdiff) {
Magick::Image im1_gray = im1;
Magick::Image im2_gray = im2;
im1_gray.type(Magick::GrayscaleType);
im2_gray.type(Magick::GrayscaleType);
// difference between im1 and im2 is red Channel
// difference between im2 and im1 is blue channel
// green channel is then just the gray scale image
Magick::Image diff_gray(im1_gray);
diff_gray.composite(im1_gray, 0, 0, Magick::AtopCompositeOp);
diff_gray.composite(im2_gray, 0, 0, Magick::AtopCompositeOp);
cdiff.composite(diff_gray, 0, 0, Magick::CopyGreenCompositeOp);
cdiff.composite(im1_gray, 0, 0, Magick::CopyRedCompositeOp);
cdiff.composite(im2_gray, 0, 0, Magick::CopyBlueCompositeOp);
}
bool imreg_sift::cache_img_with_fid(boost::filesystem::path upload_dir, string fid, imcomp_cache* cache) {
// compute sift features for the selected file
boost::filesystem::path fn = upload_dir / ( fid + ".jpg");
Magick::Image im; im.read( fn.string() );
im.type(Magick::TrueColorType);
// cache the image features
vector<VlSiftKeypoint> keypoints;
vector< vector<vl_uint8> > descriptors;
bool is_cached = cache->get(fid, keypoints, descriptors);
if ( !is_cached ) {
compute_sift_features(im, keypoints, descriptors, false);
cache->put(fid, keypoints, descriptors);
cout << "\n Successfully cached fid: " << fid << "features! " << flush;
cout << "\n first keypoint is: " << keypoints.at(1).x << " " << keypoints.at(1).y << flush;
}
return true;
}
void imreg_sift::ransac_dlt(const char im1_fn[], const char im2_fn[],
double xl, double xu, double yl, double yu,
MatrixXd& Hopt, size_t& fp_match_count,
const char im1_crop_fn[], const char im2_crop_fn[], const char im2_tx_fn[],
const char diff_image_fn[],
const char overlap_image_fn[],
bool& success,
std::string& message,
imcomp_cache * cache,
std::string& transform,
bool is_photometric) {
try {
high_resolution_clock::time_point start = std::chrono::high_resolution_clock::now();
success = false;
message = "";
string im1_file_name(im1_fn);
string im2_file_name(im2_fn);
string base_filename1 = im1_file_name.substr(im1_file_name.find_last_of("/\\") + 1);
std::string::size_type const p1(base_filename1.find_last_of('.'));
base_filename1 = base_filename1.substr(0, p1);
string base_filename2 = im2_file_name.substr(im2_file_name.find_last_of("/\\") + 1);
std::string::size_type const p2(base_filename2.find_last_of('.'));
base_filename2 = base_filename2.substr(0, p2);
Magick::Image im1; im1.read( im1_fn );
Magick::Image im2; im2.read( im2_fn );
// to ensure that image pixel values are 8bit RGB
im1.type(Magick::TrueColorType);
im2.type(Magick::TrueColorType);
// the photometric transformed image
Magick::Image im2_pt(im2.size(), "black");
im2_pt.type(Magick::TrueColorType);
if (is_photometric) {
compute_photo_transform(im1, im2, im2_pt);
}
Magick::Image im1_g = im1;
im1_g.crop( Magick::Geometry(xu-xl, yu-yl, xl, yl) );
Magick::Image im2_g = im2;
// use the photometric transformed image for geometric transform estimation
// Magick::Image im2_g = im2_pt;
vector<VlSiftKeypoint> keypoint_list1, keypoint_list2;
vector< vector<vl_uint8> > descriptor_list1, descriptor_list2;
high_resolution_clock::time_point before_sift = std::chrono::high_resolution_clock::now();
//cout << "time before sift computation: " << (duration_cast<duration<double>>(before_sift - start)).count() << endl;
// check cache before computing features
// TODO: Enable when we have a proper implementation of caching mechanism.
// Disabled for now.
// bool is_im1_cached = cache->get(base_filename1, keypoint_list1, descriptor_list1);
// if (is_im1_cached) {
// cout << "using cached data for fid: " << base_filename1 << endl;
// }
// if (!is_im1_cached) {
// // images are converted to gray scale before processing
// compute_sift_features(im1_g, keypoint_list1, descriptor_list1, false);
// // cache for future use
// cache->put(base_filename1, keypoint_list1, descriptor_list1);
// cout << "successfully cached fid: " << base_filename1 << endl;
// }
// cout << "cached first keypoint is: " << keypoint_list1.at(1).x << " " << keypoint_list1.at(1).y << endl;
//
// bool is_im2_cached = cache->get(base_filename2, keypoint_list2, descriptor_list2);
// if (is_im2_cached) {
// cout << "using cached data for fid: " << base_filename2 << endl;
// }
// if (!is_im2_cached) {
// // images are converted to gray scale before processing
// compute_sift_features(im2_g, keypoint_list2, descriptor_list2, false);
// // cache for future use
// cache->put(base_filename2, keypoint_list2, descriptor_list2);
// cout << "successfully cached fid: " << base_filename2 << endl;
// }
// cout << "second keypoint is: " << keypoint_list2.at(1).x << " " << keypoint_list2.at(1).y << endl;
// compute SIFT features without caching
compute_sift_features(im1_g, keypoint_list1, descriptor_list1, false);
compute_sift_features(im2_g, keypoint_list2, descriptor_list2, false);
// use Lowe's 2nd nn test to find putative matches
float threshold = 1.5f;
std::vector< std::pair<uint32_t, uint32_t> > putative_matches;
get_putative_matches(descriptor_list1, descriptor_list2, putative_matches, threshold);
size_t n_match = putative_matches.size();
fp_match_count = n_match;
// cout << "Putative matches (using Lowe's 2nd NN test) = " << n_match << endl;
// high_resolution_clock::time_point after_putative_match = std::chrono::high_resolution_clock::now();
// cout << "time after putative match computation: " << (duration_cast<duration<double>>(after_putative_match - after_second_sift)).count() << endl;
if( n_match < 9 ) {
message = "Number of feature points that match are very low";
return;
}
// Normalize points so that centroid lies at origin and mean distance to
// original points in sqrt(2)
MatrixXd im1_match_kp(3, n_match);
MatrixXd im2_match_kp(3, n_match);
for( size_t i=0; i<n_match; ++i) {
VlSiftKeypoint kp1 = keypoint_list1.at( putative_matches[i].first );
VlSiftKeypoint kp2 = keypoint_list2.at( putative_matches[i].second );
im1_match_kp(0, i) = kp1.x;
im1_match_kp(1, i) = kp1.y;
im1_match_kp(2, i) = 1.0;
im2_match_kp(0, i) = kp2.x;
im2_match_kp(1, i) = kp2.y;
im2_match_kp(2, i) = 1.0;
}
Matrix<double,3,3> im1_match_kp_tform, im2_match_kp_tform;
get_norm_matrix(im1_match_kp, im1_match_kp_tform);
get_norm_matrix(im2_match_kp, im2_match_kp_tform);
MatrixXd im2_match_kp_tform_inv = im2_match_kp_tform.inverse();
MatrixXd im1_match_norm = im1_match_kp_tform * im1_match_kp;
MatrixXd im2_match_norm = im2_match_kp_tform * im2_match_kp;
//cout << "im1_match_kp_tform=" << im1_match_kp_tform << endl;
//cout << "im2_match_kp_tform=" << im2_match_kp_tform << endl;
// memory cleanup as these are not required anymore
im1_match_kp.resize(0,0);
im2_match_kp.resize(0,0);
// initialize random number generator to randomly sample putative_matches
random_device rand_device;
mt19937 generator(rand_device());
uniform_int_distribution<> dist(0, n_match-1);
// estimate homography using RANSAC
size_t max_score = 0;
Matrix<double,3,3> Hi;
vector<unsigned int> best_inliers_index;
// see Hartley and Zisserman p.119
// in the original image 2 domain, error = sqrt(5.99) * 1 ~ 3 (for SD of 1 pixel error)
// in the normalized image 2 domain, we have to transform this 3 pixel to normalized coordinates
double geom_err_threshold_norm = im2_match_kp_tform(0,0) * 3;
size_t RANSAC_ITER_COUNT = (size_t) ((double) n_match * 0.6);
for( unsigned int iter=0; iter<RANSAC_ITER_COUNT; iter++ ) {
// cout << "==========================[ iter=" << iter << " ]==============================" << endl;
// randomly select 4 matches from putative_matches
int kp_id1 = dist(generator);
int kp_id2 = dist(generator);
int kp_id3 = dist(generator);
int kp_id4 = dist(generator);
//cout << "Random entries from putative_matches: " << kp_id1 << "," << kp_id2 << "," << kp_id3 << "," << kp_id4 << endl;
MatrixXd X(4,3);
X.row(0) = im1_match_norm.col(kp_id1).transpose();
X.row(1) = im1_match_norm.col(kp_id2).transpose();
X.row(2) = im1_match_norm.col(kp_id3).transpose();
X.row(3) = im1_match_norm.col(kp_id4).transpose();
MatrixXd Y(4,3);
Y.row(0) = im2_match_norm.col(kp_id1).transpose();
Y.row(1) = im2_match_norm.col(kp_id2).transpose();
Y.row(2) = im2_match_norm.col(kp_id3).transpose();
Y.row(3) = im2_match_norm.col(kp_id4).transpose();
// dlt(X, Y, Hi);
estimate_transform(X, Y, transform, Hi);
size_t score = 0;
vector<unsigned int> inliers_index;
inliers_index.reserve(n_match);
MatrixXd im1tx_norm = Hi * im1_match_norm; // 3 x n
im1tx_norm.row(0) = im1tx_norm.row(0).array() / im1tx_norm.row(2).array();
im1tx_norm.row(1) = im1tx_norm.row(1).array() / im1tx_norm.row(2).array();
MatrixXd del(2,n_match);
del.row(0) = im1tx_norm.row(0) - im2_match_norm.row(0);
del.row(1) = im1tx_norm.row(1) - im2_match_norm.row(1);
del = del.array().pow(2);
VectorXd error = del.row(0) + del.row(1);
error = error.array().sqrt();
for( size_t k = 0; k < n_match; k++ ) {
if(error(k) < geom_err_threshold_norm) {
score++;
inliers_index.push_back(k);
}
}
// cout << "iter " << iter << " of " << RANSAC_ITER_COUNT << " : score=" << score << ", max_score=" << max_score << ", total_matches=" << putative_matches.size() << endl;
if( score > max_score ) {
max_score = score;
best_inliers_index.swap(inliers_index);
}
} // end RANSAC_ITER_COUNT loop
// high_resolution_clock::time_point after_ransac = std::chrono::high_resolution_clock::now();
// cout << "after ransac is: " << (duration_cast<duration<double>>(after_ransac - after_putative_match)).count() << endl;
if(transform != "identity" && max_score < 3 ) {
message = "Failed to find a suitable transformation";
return;
}
// Recompute homography using all the inliers
// This does not improve the registration
// cout << "re-computing homography using inliers" << endl;
size_t n_inliers = best_inliers_index.size();
MatrixXd X(n_inliers,3);
MatrixXd Y(n_inliers,3);
for( size_t i=0; i<n_inliers; ++i ) {
X.row(i) = im1_match_norm.col( best_inliers_index.at(i) ).transpose();
Y.row(i) = im2_match_norm.col( best_inliers_index.at(i) ).transpose();
}
Matrix<double, 3, 3> Hopt_norm, H;
// dlt(X, Y, Hopt_norm);
//cout << "estimateing transform: " << transform << endl;
estimate_transform(X, Y, transform, Hopt_norm);
// see Hartley and Zisserman p.109
H = im2_match_kp_tform_inv * Hopt_norm * im1_match_kp_tform;
H = H / H(2,2);
// Hopt is the reference variable passed to this method
Hopt = H;
// im1 crop
Magick::Image im1_crop(im1);
Magick::Geometry cropRect1(xu-xl, yu-yl, xl, yl);
im1_crop.crop( cropRect1 );
im1_crop.write( im1_crop_fn );
Magick::Image im2_crop(im2);
im2_crop.crop( cropRect1 );
im2_crop.write( im2_crop_fn );
// ----------------------------------------------------------------
// apply Homography to im2 in order to visualize it along with im1.
// ----------------------------------------------------------------
Matrix<double, 3, 3> Hinv = H.inverse();
// if we are doing photometric, use photometric transformed image
// else just the image 2.
Magick::Image im2t_crop;
if (is_photometric) {
im2t_crop = im2_pt;
} else {
im2t_crop = im2;
}
// some simple affine tralsformations for testing:
// Magick::DrawableAffine affine(1.0, 1.0, 0, 0, 0.0, 0.0);
// Magick::DrawableAffine hinv_affine(1,1,.3,0,0,0); // simple shearing
// Magick::DrawableAffine hinv_affine(1,-1,0,0,0,0); // flip
// Magick::DrawableAffine hinv_affine(1,0.5,0,0,0,0); // scale
// set rotation as per Hinv
Magick::DrawableAffine hinv_affine(Hinv(0,0), Hinv(1,1), Hinv(1,0), Hinv(0,1), 0, 0);
// set translation and resizing using viewport function.
// See: http://www.imagemagick.org/discourse-server/viewtopic.php?f=27&t=33029#p157520.
// As we need to render the image on a webpage canvas, we need to resize the
// width and height of im2. Then offset in x and y direction based on the translation
// computed by Homography (H and Hinv matrices).
string op_w_h_and_offsets = std::to_string(xu-xl) +
"x" +
std::to_string(yu-yl) +
"-" + to_string((int) Hinv(0,2)) +
"-" + to_string((int) Hinv(1,2));
im2t_crop.artifact("distort:viewport", op_w_h_and_offsets);
im2t_crop.affineTransform(hinv_affine);
//cout << "done applying Affine Transform" << endl;
// save result
im2t_crop.write(im2_tx_fn);
// TODO: fix the javascript so that we don't use overlap image as im2t!!
im2t_crop.write(overlap_image_fn);
// high_resolution_clock::time_point before_diff = std::chrono::high_resolution_clock::now();
// cout << "before diff image comp is: " << (duration_cast<duration<double>>(before_diff - after_ransac)).count() << flush;
// difference image
Magick::Image cdiff(im1_crop);
get_diff_image(im1_crop, im2t_crop, cdiff);
cdiff.write(diff_image_fn);
// high_resolution_clock::time_point after_diff = std::chrono::high_resolution_clock::now();
// cout << "after diff image comp is: " << (duration_cast<duration<double>>(after_diff - before_diff)).count() << flush;
success = true;
message = "";
} catch( std::exception &e ) {
success = false;
std::ostringstream ss;
ss << "Exception occured: [" << e.what() << "]";
std::cout << ss.str() << std::endl;
message = ss.str();
}
}
///
/// Robust matching and Thin Plate Spline based image registration
///
/// Robust matching based on:
/// Tran, Q.H., Chin, T.J., Carneiro, G., Brown, M.S. and Suter, D., 2012, October. In defence of RANSAC for outlier rejection in deformable registration. ECCV.
///
/// Thin plate spline registration based on:
/// Bookstein, F.L., 1989. Principal warps: Thin-plate splines and the decomposition of deformations. IEEE TPAMI.
///
void imreg_sift::robust_ransac_tps(const char im1_fn[], const char im2_fn[],
double xl, double xu, double yl, double yu,
MatrixXd& Hopt, size_t& fp_match_count,
const char im1_crop_fn[], const char im2_crop_fn[], const char im2_tx_fn[],
const char diff_image_fn[],
const char overlap_image_fn[],
bool& success,
std::string& message,
imcomp_cache * cache,
bool is_photometric) {
try {
auto start = std::chrono::high_resolution_clock::now();
success = false;
message = "";
Magick::Image im1; im1.read( im1_fn );
Magick::Image im2; im2.read( im2_fn );
string im1_file_name(im1_fn);
string im2_file_name(im2_fn);
string base_filename1 = im1_file_name.substr(im1_file_name.find_last_of("/\\") + 1);
std::string::size_type const p1(base_filename1.find_last_of('.'));
base_filename1 = base_filename1.substr(0, p1);
string base_filename2 = im2_file_name.substr(im2_file_name.find_last_of("/\\") + 1);
std::string::size_type const p2(base_filename2.find_last_of('.'));
base_filename2 = base_filename2.substr(0, p2);
// to ensure that image pixel values are 8bit RGB
im1.type(Magick::TrueColorType);
im2.type(Magick::TrueColorType);
// the photometric transformed image
Magick::Image im2_pt(im2.size(), "black");
im2_pt.type(Magick::TrueColorType);
if (is_photometric) {
compute_photo_transform(im1, im2, im2_pt);
}
Magick::Image im1_g = im1;
im1_g.crop(Magick::Geometry(xu-xl, yu-yl, xl, yl));
Magick::Image im2_g = im2;
vector<VlSiftKeypoint> keypoint_list1, keypoint_list2;
vector< vector<vl_uint8> > descriptor_list1, descriptor_list2;
// check cache before computing features
// TODO: Enable when we have a proper implementation of caching.
// Disabled for now.
// bool is_im1_cached = cache->get(base_filename1, keypoint_list1, descriptor_list1);
// if (is_im1_cached) {
// cout << "using cached data for fid: " << base_filename1 << endl;
// }
// if (!is_im1_cached) {
// // images are converted to gray scale before processing
// compute_sift_features(im1_g, keypoint_list1, descriptor_list1, false);
// // cache for future use
// cache->put(base_filename1, keypoint_list1, descriptor_list1);
// cout << "successfully cached fid: " << base_filename1 << endl;
// }
// cout << "cached first keypoint is: " << keypoint_list1.at(1).x << " " << keypoint_list1.at(1).y << endl;
// bool is_im2_cached = cache->get(base_filename2, keypoint_list2, descriptor_list2);
// if (is_im2_cached) {
// cout << "using cached data for fid: " << base_filename2 << endl;
// }
// if (!is_im2_cached) {
// // images are converted to gray scale before processing
// compute_sift_features(im2_g, keypoint_list2, descriptor_list2, false);
// // cache for future use
// cache->put(base_filename2, keypoint_list2, descriptor_list2);
// cout << "successfully cached fid: " << base_filename2 << endl;
// }
// cout << "second keypoint is: " << keypoint_list2.at(1).x << " " << keypoint_list2.at(1).y << endl;
// Compute SIFT features without caching.
compute_sift_features(im1_g, keypoint_list1, descriptor_list1);
compute_sift_features(im2_g, keypoint_list2, descriptor_list2);
// use Lowe's 2nd nn test to find putative matches
float threshold = 1.5f;
std::vector< std::pair<uint32_t, uint32_t> > putative_matches;
get_putative_matches(descriptor_list1, descriptor_list2, putative_matches, threshold);
size_t n_lowe_match = putative_matches.size();
//cout << "Putative matches (using Lowe's 2nd NN test) = " << putative_matches.size() << endl;
if( n_lowe_match < 9 ) {
fp_match_count = n_lowe_match;
message = "Number of feature points that match are very low";
return;
}
// Normalize points so that centroid lies at origin and mean distance to
// original points in sqrt(2)
//cout << "Creating matrix of size 3x" << n_lowe_match << " ..." << endl;
MatrixXd pts1(3, n_lowe_match);
MatrixXd pts2(3, n_lowe_match);
//cout << "Creating point set matched using lowe ..." << endl;
for( size_t i=0; i<n_lowe_match; ++i) {
VlSiftKeypoint kp1 = keypoint_list1.at( putative_matches[i].first );
VlSiftKeypoint kp2 = keypoint_list2.at( putative_matches[i].second );
pts1(0, i) = kp1.x;
pts1(1, i) = kp1.y;
pts1(2, i) = 1.0;
pts2(0, i) = kp2.x;
pts2(1, i) = kp2.y;
pts2(2, i) = 1.0;
}
//cout << "Normalizing points ..." << endl;
Matrix3d pts1_tform;
get_norm_matrix(pts1, pts1_tform);
//cout << "Normalizing matrix (T) = " << pts1_tform << endl;
MatrixXd pts1_norm = pts1_tform * pts1;
MatrixXd pts2_norm = pts1_tform * pts2;
// form a matrix containing match pair (x,y) <-> (x',y') as follows
// [x y x' y'; ...]
MatrixXd S_all(4, n_lowe_match);
S_all.row(0) = pts1_norm.row(0);
S_all.row(1) = pts1_norm.row(1);
S_all.row(2) = pts2_norm.row(0);
S_all.row(3) = pts2_norm.row(1);
// initialize random number generator to randomly sample putative_matches
mt19937 generator(9973);
uniform_int_distribution<> dist(0, n_lowe_match-1);
MatrixXd S(4,3), hatS(4,3);
double residual;
vector<size_t> best_robust_match_idx;
// @todo: tune this threshold for better generalization
double robust_ransac_threshold = 0.09;
size_t RANSAC_ITER_COUNT = (size_t) ((double) n_lowe_match * 0.6);
//cout << "RANSAC_ITER_COUNT = " << RANSAC_ITER_COUNT << endl;
for( int i=0; i<RANSAC_ITER_COUNT; ++i ) {
S.col(0) = S_all.col( dist(generator) ); // randomly select a match from S_all
S.col(1) = S_all.col( dist(generator) );
S.col(2) = S_all.col( dist(generator) );
Vector4d muS = S.rowwise().mean();
hatS = S.colwise() - muS;
JacobiSVD<MatrixXd> svd(hatS, ComputeFullU);
MatrixXd As = svd.matrixU().block(0, 0, svd.matrixU().rows(), 2);
MatrixXd dx = S_all.colwise() - muS;
MatrixXd del = dx - (As * As.transpose() * dx);
vector<size_t> robust_match_idx;
robust_match_idx.clear();
for( int j=0; j<del.cols(); ++j ) {
residual = sqrt( del(0,j)*del(0,j) + del(1,j)*del(1,j) + del(2,j)*del(2,j) + del(3,j)*del(3,j) );
if ( residual < robust_ransac_threshold ) {
robust_match_idx.push_back(j);
}
}
//cout << i << ": robust_match_idx=" << robust_match_idx.size() << endl;
if ( robust_match_idx.size() > best_robust_match_idx.size() ) {
best_robust_match_idx.clear();
best_robust_match_idx.swap(robust_match_idx);
//cout << "[MIN]" << endl;
}
} // end RANSAC_ITER_COUNT loop
fp_match_count = best_robust_match_idx.size();
if ( fp_match_count < 3 ) {
message = "Very low number of robust matching feature points";
return;
}
//cout << "robust match pairs = " << fp_match_count << endl;
// bin each correspondence pair into cells dividing the original image into KxK cells
// a single point in each cell ensures that no two control points are very close
unsigned int POINTS_PER_CELL = 1;
unsigned int n_cell_w, n_cell_h;
if( im1.rows() > 500 ) {
n_cell_h = 9;
} else {
n_cell_h = 5;
}
unsigned int ch = (unsigned int) (im1.rows() / n_cell_h);
if( im1.columns() > 500 ) {
n_cell_w = 9;
} else {
n_cell_w = 5;
}
unsigned int cw = (unsigned int) (im1.columns() / n_cell_w);
//printf("n_cell_w=%d, n_cell_h=%d, cw=%d, ch=%d", n_cell_w, n_cell_h, cw, ch);
//printf("image size = %ld x %ld", im1.columns(), im1.rows());
vector<size_t> sel_best_robust_match_idx;
for( unsigned int i=0; i<n_cell_w; ++i ) {
for( unsigned int j=0; j<n_cell_h; ++j ) {
unsigned int xl = i * cw;
unsigned int xh = (i+1)*cw - 1;
if( xh > im1.columns() ) {
xh = im1.columns() - 1;
}
unsigned int yl = j * ch;
unsigned int yh = (j+1)*ch - 1;
if( yh > im1.rows() ) {
yh = im1.rows() - 1;
}
//printf("\ncell(%d,%d) = (%d,%d) to (%d,%d)", i, j, xl, yl, xh, yh);
//cout << flush;
vector< size_t > cell_pts;
for( unsigned int k=0; k<best_robust_match_idx.size(); ++k ) {
size_t match_idx = best_robust_match_idx.at(k);
double x = pts1(0, match_idx);
double y = pts1(1, match_idx);
if( x >= xl && x < xh && y >= yl && y < yh ) {
cell_pts.push_back( match_idx );
}
}
if( cell_pts.size() >= POINTS_PER_CELL ) {
uniform_int_distribution<> dist2(0, cell_pts.size()-1);
for( unsigned int k=0; k<POINTS_PER_CELL; ++k ) {
unsigned long cell_pts_idx = dist2(generator);
sel_best_robust_match_idx.push_back( cell_pts.at(cell_pts_idx) );
}
}
}
}
size_t n_cp = sel_best_robust_match_idx.size();
MatrixXd cp1(2,n_cp);
MatrixXd cp2(2,n_cp);
for( size_t i=0; i<n_cp; ++i ) {
unsigned long match_idx = sel_best_robust_match_idx.at(i);
cp1(0,i) = pts1(0, match_idx ); cp1(1,i) = pts1(1, match_idx );
cp2(0,i) = pts2(0, match_idx ); cp2(1,i) = pts2(1, match_idx );
}
// im1 crop
Magick::Image im1_crop(im1);
Magick::Geometry cropRect1(xu-xl, yu-yl, xl, yl);
im1_crop.crop( cropRect1 );
im1_crop.magick("JPEG");
//cout << "\nWriting to " << im1_crop_fn << flush;
im1_crop.write( im1_crop_fn );
Magick::Image im2_crop(im2);
im2_crop.crop( cropRect1 );
//im2_crop.write( im2_crop_fn );
double lambda = 0.001;
double lambda_norm = lambda * (im1_crop.rows() * im1_crop.columns());
// create matrix K
MatrixXd K(n_cp, n_cp);
K.setZero();
double rx, ry, r, r2;
for(unsigned int i=0; i<n_cp; ++i ) {
for(unsigned int j=i; j<n_cp; ++j ) {
// image grid coordinate = (i,j)
// control point coordinate = cp(:,k)
rx = cp1(0,i) - cp1(0,j);
ry = cp1(1,i) - cp1(1,j);
r = sqrt(rx*rx + ry*ry);
r2 = r * r;
K(i, j) = r2*log(r2);
K(j, i) = K(i,j);
}
}
//cout << "K=" << K.rows() << "," << K.cols() << endl;
//cout << "lambda = " << lambda << endl;
// create matrix P
MatrixXd P(n_cp, 3);
for(unsigned int i=0; i<n_cp; ++i ) {
//K(i,i) = 0; // ensure that the diagonal elements of K are 0 (as log(0) = nan)
// approximating thin-plate splines based on:
// Rohr, K., Stiehl, H.S., Sprengel, R., Buzug, T.M., Weese, J. and Kuhn, M.H., 2001. Landmark-based elastic registration using approximating thin-plate splines.
K(i,i) = ((double) n_cp) * lambda * 1;
P(i,0) = 1;
P(i,1) = cp1(0,i);
P(i,2) = cp1(1,i);
}
// cout << "P=" << P.rows() << "," << P.cols() << endl;
//cout << "K=" << endl << K.block(0,0,6,6) << endl;
// cout << "K=" << endl << K << endl;
// create matrix L
MatrixXd L(n_cp+3, n_cp+3);
L.block(0, 0, n_cp, n_cp) = K;
L.block(0, n_cp, n_cp, 3) = P;
L.block(n_cp, 0, 3, n_cp) = P.transpose();
L.block(n_cp, n_cp, 3, 3).setZero();
// cout << "L rows and cols are: " << L.rows() << "," << L.cols() << endl;
// create matrix V
MatrixXd V(n_cp+3, 2);
V.setZero();
for(unsigned int i=0; i<n_cp; ++i ) {
V(i,0) = cp2(0,i);
V(i,1) = cp2(1,i);
}
MatrixXd Linv = L.inverse();
MatrixXd W = Linv * V;
// apply compyute transformations to second image
// cout << "L matrix is: " << endl;
// cout << L << endl;
// Magick::Image im2t_crop( im1_crop.size(), "white");
// string op_w_h_and_offsets;
// Magick::DrawableAffine hinv_affine(W(0,0), W(1,1), W(1,0), W(0,1), 0, 0);
// op_w_h_and_offsets = std::to_string(xu-xl) +
// "x" +
// std::to_string(yu-yl) +
// "-" + to_string((int) W(0,2)) +
// "-" + to_string((int) W(1,2));
// im2t_crop.affineTransform(hinv_affine);
// im2t_crop.artifact("distort:viewport", op_w_h_and_offsets);
Magick::Image im2t_crop( im1_crop.size(), "white");
double x0,x1,y0,y1;
double x, y;
double dx0, dx1, dy0, dy1;
double fxy0, fxy1;
double fxy_red, fxy_green, fxy_blue;
double xi, yi;
double x_non_linear_terms, y_non_linear_terms;
double x_affine_terms, y_affine_terms;
for(unsigned int j=0; j<im1_crop.rows(); j++) {
for(unsigned int i=0; i<im1_crop.columns(); i++) {
//cout << "(" << i << "," << j << ") :" << endl;
xi = ((double) i) + 0.5; // center of pixel
yi = ((double) j) + 0.5; // center of pixel
x_non_linear_terms = 0.0;
y_non_linear_terms = 0.0;
for(unsigned int k=0; k<n_cp; ++k) {
//cout << " k=" << k << endl;
rx = cp1(0,k) - xi;
ry = cp1(1,k) - yi;
r = sqrt(rx*rx + ry*ry);
r2 = r*r;
x_non_linear_terms += W(k, 0) * r2 * log(r2);
y_non_linear_terms += W(k, 1) * r2 * log(r2);
//cout << "(" << x_non_linear_terms << "," << y_non_linear_terms << ")" << flush;
}
x_affine_terms = W(n_cp,0) + W(n_cp+1,0)*xi + W(n_cp+2,0)*yi;
y_affine_terms = W(n_cp,1) + W(n_cp+1,1)*xi + W(n_cp+2,1)*yi;
x = x_affine_terms + x_non_linear_terms;
y = y_affine_terms + y_non_linear_terms;
//printf("(%d,%d) : (xi,yi)=(%.2f,%.2f) (x,y)=(%.2f,%.2f) : (x,y)-affine = (%.2f,%.2f) (x,y)-nonlin = (%.2f,%.2f)", i, j, xi, yi, x, y, x_affine_terms, y_affine_terms, x_non_linear_terms, y_non_linear_terms);
// neighbourhood of xh
x0 = ((int) x);
x1 = x0 + 1;
dx0 = x - x0;
dx1 = x1 - x;
y0 = ((int) y);
y1 = y0 + 1;
dy0 = y - y0;
dy1 = y1 - y;
Magick::ColorRGB fx0y0, fx1y0, fx0y1, fx1y1;
if (is_photometric) {
fx0y0 = im2_pt.pixelColor(x0, y0);
fx1y0 = im2_pt.pixelColor(x1, y0);
fx0y1 = im2_pt.pixelColor(x0, y1);
fx1y1 = im2_pt.pixelColor(x1, y1);
} else {
fx0y0 = im2.pixelColor(x0, y0);
fx1y0 = im2.pixelColor(x1, y0);
fx0y1 = im2.pixelColor(x0, y1);
fx1y1 = im2.pixelColor(x1, y1);
}
// Bilinear interpolation: https://en.wikipedia.org/wiki/Bilinear_interpolation
fxy0 = dx1 * fx0y0.red() + dx0 * fx1y0.red(); // note: x1 - x0 = 1
fxy1 = dx1 * fx0y1.red() + dx0 * fx1y1.red(); // note: x1 - x0 = 1
fxy_red = dy1 * fxy0 + dy0 * fxy1;
fxy0 = dx1 * fx0y0.green() + dx0 * fx1y0.green(); // note: x1 - x0 = 1
fxy1 = dx1 * fx0y1.green() + dx0 * fx1y1.green(); // note: x1 - x0 = 1
fxy_green = dy1 * fxy0 + dy0 * fxy1;
fxy0 = dx1 * fx0y0.blue() + dx0 * fx1y0.blue(); // note: x1 - x0 = 1
fxy1 = dx1 * fx0y1.blue() + dx0 * fx1y1.blue(); // note: x1 - x0 = 1
fxy_blue = dy1 * fxy0 + dy0 * fxy1;
// cout << "red is: " << fx0y0.red() << " green is: " << fx0y0.green() << " blue is: " << fx0y0.blue() << endl;
Magick::ColorRGB fxy(fxy_red, fxy_green, fxy_blue);
im2t_crop.pixelColor(i, j, fxy);
}
}
im2t_crop.write( im2_tx_fn );
im2t_crop.write( overlap_image_fn );
//auto finish = std::chrono::high_resolution_clock::now();
//std::chrono::duration<double> elapsed = finish - start;
//std::cout << "tps registration completed in " << elapsed.count() << " s" << endl;
// difference image
Magick::Image cdiff(im1_crop.size(), "black");
get_diff_image(im1_crop, im2t_crop, cdiff);
cdiff.write(diff_image_fn);
success = true;
message = "";
} catch( std::exception &e ) {
success = false;
std::ostringstream ss;
ss << "Exception occured: [" << e.what() << "]";
message = ss.str();
}
}
| 48,897 | 19,327 |
//
// Created by rotem levy on 27/05/2020.
//
#include "FootSoldier.hpp"
FootSoldier::FootSoldier(uint player_number)
{
player_num = player_number;
hp = MAX_HP;
damage = -10;
type = Type::FootSoldierType;
}
uint FootSoldier::getMaxHP()
{
return MAX_HP;
}
void FootSoldier::attack(std::vector<std::vector<Soldier*>> &b, std::pair<int,int> location)
{
int row = location.first;
int col = location.second;
Soldier* near_enemy = nullptr;
std::pair<int,int> near_enemy_location;
double min = b.size()*b.size();
for(int i = 0 ; i < b.size() ; i ++)
{
for(int j = 0 ; j < b[i].size(); j++)
{
Soldier * temp = b[i][j];
if(temp != nullptr)
{
if(temp->getPlayer_number() != player_num)
{
double dist = Utils::distance(row,col,i,j);
if(dist < min)
{
min = dist;
near_enemy = temp;
near_enemy_location = {i,j};
}
}
}
}
}
if(near_enemy != nullptr)
{
int new_hp = near_enemy->getHp() + damage;
near_enemy->setHp(new_hp);
if(new_hp <= 0)
{
b[near_enemy_location.first][near_enemy_location.second] = nullptr;
}
}
} | 1,451 | 504 |
#include <libopencm3/stm32/rcc.h>
#include <libopencm3/stm32/gpio.h>
#include <logger.h>
#include "CmPinMap.h"
#define error(x) { debug_println(x); debug_flush(); }
static CmPeripheral pinmap_find_peripheral(codal::PinNumber pin, const PinMap *map);
static CmPinMode pinmap_find_mode(codal::PinNumber pin, const PinMap *map);
static CmPinCnf pinmap_find_cnf(codal::PinNumber pin, const PinMap *map);
CmPeripheral pinmap_peripheral(codal::PinNumber pin, const PinMap* map) {
// Return the peripheral for the pin e.g. SPI1.
CmPeripheral peripheral = CM_PERIPHERAL_NC;
if (pin == CM_PIN_NC) { return CM_PERIPHERAL_NC; }
peripheral = pinmap_find_peripheral(pin, map);
if (peripheral == CM_PERIPHERAL_NC) // no mapping available
{ error("pinmap not found for peripheral"); }
return peripheral;
}
CmPinMode pinmap_mode(codal::PinNumber pin, const PinMap* map) {
// Return the pin mode for the peripheral e.g. GPIO_MODE_OUTPUT_2_MHZ.
CmPinMode mode = CM_PINMODE_NC;
if (pin == CM_PIN_NC) { return CM_PINMODE_NC; }
mode = pinmap_find_mode(pin, map);
if (mode == CM_PINMODE_NC) // no mapping available
{ error("pinmap not found for mode"); }
return mode;
}
CmPinCnf pinmap_cnf(codal::PinNumber pin, const PinMap* map) {
// Return the pin config for the peripheral e.g. GPIO_CNF_OUTPUT_PUSHPULL.
CmPinCnf cnf = CM_PINCNF_NC;
if (pin == CM_PIN_NC) { return CM_PINCNF_NC; }
cnf = pinmap_find_cnf(pin, map);
if (cnf == CM_PINCNF_NC) // no mapping available
{ error("pinmap not found for cnf"); }
return cnf;
}
static CmPeripheral pinmap_find_peripheral(codal::PinNumber pin, const PinMap* map) {
// Return the peripheral for the pin e.g. SPI1.
while (map->pin != CM_PIN_NC) {
if (map->pin == pin) { return map->peripheral; }
map++;
}
return CM_PERIPHERAL_NC;
}
static CmPinMode pinmap_find_mode(codal::PinNumber pin, const PinMap* map) {
// Return the pin mode for the peripheral e.g. GPIO_MODE_OUTPUT_2_MHZ.
while (map->pin != CM_PIN_NC) {
if (map->pin == pin) { return map->mode; }
map++;
}
return CM_PINMODE_NC;
}
static CmPinCnf pinmap_find_cnf(codal::PinNumber pin, const PinMap* map) {
// Return the pin config for the peripheral e.g. GPIO_CNF_OUTPUT_PUSHPULL.
while (map->pin != CM_PIN_NC) {
if (map->pin == pin) { return map->cnf; }
map++;
}
return CM_PINCNF_NC;
}
#ifdef TODO
uint32_t pinmap_merge(uint32_t a, uint32_t b) {
// both are the same (inc both NC)
if (a == b)
return a;
// one (or both) is not connected
if (a == (uint32_t)NC)
return b;
if (b == (uint32_t)NC)
return a;
// mis-match error case
error("pinmap mis-match");
return (uint32_t)NC;
}
void pinmap_pinout(codal::PinNumber pin, const PinMap *map) {
if (pin == NC)
return;
while (map->pin != NC) {
if (map->pin == pin) {
pin_function(pin, map->function);
pin_mode(pin, PullNone);
return;
}
map++;
}
error("could not pinout");
}
#endif // TODO
#ifdef NOTUSED
#define error MBED_ERROR
extern GPIO_TypeDef *Set_GPIO_Clock(uint32_t port_idx);
const uint32_t ll_pin_defines[16] = {
#ifdef TODO
LL_GPIO_PIN_0,
LL_GPIO_PIN_1,
LL_GPIO_PIN_2,
LL_GPIO_PIN_3,
LL_GPIO_PIN_4,
LL_GPIO_PIN_5,
LL_GPIO_PIN_6,
LL_GPIO_PIN_7,
LL_GPIO_PIN_8,
LL_GPIO_PIN_9,
LL_GPIO_PIN_10,
LL_GPIO_PIN_11,
LL_GPIO_PIN_12,
LL_GPIO_PIN_13,
LL_GPIO_PIN_14,
LL_GPIO_PIN_15
#endif // TODO
};
typedef enum {
PortA = 0,
PortB = 1,
PortC = 2,
PortD = 3,
PortE = 4,
PortF = 5,
PortG = 6,
PortH = 7,
PortI = 8,
PortJ = 9,
PortK = 10
} PortName;
// Enable GPIO clock and return GPIO base address
GPIO_TypeDef *Set_GPIO_Clock(uint32_t port_idx) {
return NULL; ////TODO
#ifdef TODO
uint32_t gpio_add = 0;
switch (port_idx) {
case PortA:
gpio_add = GPIOA_BASE;
__HAL_RCC_GPIOA_CLK_ENABLE();
break;
case PortB:
gpio_add = GPIOB_BASE;
__HAL_RCC_GPIOB_CLK_ENABLE();
break;
#if defined(GPIOC_BASE)
case PortC:
gpio_add = GPIOC_BASE;
__HAL_RCC_GPIOC_CLK_ENABLE();
break;
#endif
#if defined GPIOD_BASE
case PortD:
gpio_add = GPIOD_BASE;
__HAL_RCC_GPIOD_CLK_ENABLE();
break;
#endif
#if defined GPIOE_BASE
case PortE:
gpio_add = GPIOE_BASE;
__HAL_RCC_GPIOE_CLK_ENABLE();
break;
#endif
#if defined GPIOF_BASE
case PortF:
gpio_add = GPIOF_BASE;
__HAL_RCC_GPIOF_CLK_ENABLE();
break;
#endif
#if defined GPIOG_BASE
case PortG:
#if defined TARGET_STM32L4
__HAL_RCC_PWR_CLK_ENABLE();
HAL_PWREx_EnableVddIO2();
#endif
gpio_add = GPIOG_BASE;
__HAL_RCC_GPIOG_CLK_ENABLE();
break;
#endif
#if defined GPIOH_BASE
case PortH:
gpio_add = GPIOH_BASE;
__HAL_RCC_GPIOH_CLK_ENABLE();
break;
#endif
#if defined GPIOI_BASE
case PortI:
gpio_add = GPIOI_BASE;
__HAL_RCC_GPIOI_CLK_ENABLE();
break;
#endif
#if defined GPIOJ_BASE
case PortJ:
gpio_add = GPIOJ_BASE;
__HAL_RCC_GPIOJ_CLK_ENABLE();
break;
#endif
#if defined GPIOK_BASE
case PortK:
gpio_add = GPIOK_BASE;
__HAL_RCC_GPIOK_CLK_ENABLE();
break;
#endif
default:
error("Pinmap error: wrong port number.");
break;
}
return (GPIO_TypeDef *) gpio_add;
#endif // TODO
}
/**
* Configure pin (mode, speed, output type and pull-up/pull-down)
*/
void pin_function(codal::PinNumber pin, int data)
{
#ifdef TODO
MBED_ASSERT(pin != CM_PIN_NC);
// Get the pin informations
uint32_t mode = STM_PIN_FUNCTION(data);
uint32_t afnum = STM_PIN_AFNUM(data);
uint32_t port = STM_PORT(pin);
uint32_t ll_pin = ll_pin_defines[STM_PIN(pin)];
uint32_t ll_mode = 0;
// Enable GPIO clock
GPIO_TypeDef *gpio = Set_GPIO_Clock(port);
/* Set default speed to high.
* For most families there are dedicated registers so it is
* not so important, register can be set at any time.
* But for families like F1, speed only applies to output.
*/
#if defined (TARGET_STM32F1)
if (mode == STM_PIN_OUTPUT) {
#endif
LL_GPIO_SetPinSpeed(gpio, ll_pin, LL_GPIO_SPEED_FREQ_HIGH);
#if defined (TARGET_STM32F1)
}
#endif
switch (mode) {
case STM_PIN_INPUT:
ll_mode = LL_GPIO_MODE_INPUT;
break;
case STM_PIN_OUTPUT:
ll_mode = LL_GPIO_MODE_OUTPUT;
break;
case STM_PIN_ALTERNATE:
ll_mode = LL_GPIO_MODE_ALTERNATE;
// In case of ALT function, also set he afnum
stm_pin_SetAFPin(gpio, pin, afnum);
break;
case STM_PIN_ANALOG:
ll_mode = LL_GPIO_MODE_ANALOG;
break;
default:
MBED_ASSERT(0);
break;
}
LL_GPIO_SetPinMode(gpio, ll_pin, ll_mode);
#if defined(GPIO_ASCR_ASC0)
/* For families where Analog Control ASC0 register is present */
if (STM_PIN_ANALOG_CONTROL(data)) {
LL_GPIO_EnablePinAnalogControl(gpio, ll_pin);
} else {
LL_GPIO_DisablePinAnalogControl(gpio, ll_pin);
}
#endif
/* For now by default use Speed HIGH for output or alt modes */
if ((mode == STM_PIN_OUTPUT) ||(mode == STM_PIN_ALTERNATE)) {
if (STM_PIN_OD(data)) {
LL_GPIO_SetPinOutputType(gpio, ll_pin, LL_GPIO_OUTPUT_OPENDRAIN);
} else {
LL_GPIO_SetPinOutputType(gpio, ll_pin, LL_GPIO_OUTPUT_PUSHPULL);
}
}
stm_pin_PullConfig(gpio, ll_pin, STM_PIN_PUPD(data));
stm_pin_DisconnectDebug(pin);
#endif // TODO
}
/**
* Configure pin pull-up/pull-down
*/
void pin_mode(codal::PinNumber pin, PinMode mode)
{
#ifdef TODO
MBED_ASSERT(pin != CM_PIN_NC);
uint32_t port_index = STM_PORT(pin);
uint32_t ll_pin = ll_pin_defines[STM_PIN(pin)];
// Enable GPIO clock
GPIO_TypeDef *gpio = Set_GPIO_Clock(port_index);
uint32_t function = LL_GPIO_GetPinMode(gpio, ll_pin);
if ((function == LL_GPIO_MODE_OUTPUT) || (function == LL_GPIO_MODE_ALTERNATE))
{
if ((mode == OpenDrainNoPull) || (mode == OpenDrainPullUp) || (mode == OpenDrainPullDown)) {
LL_GPIO_SetPinOutputType(gpio, ll_pin, LL_GPIO_OUTPUT_OPENDRAIN);
} else {
LL_GPIO_SetPinOutputType(gpio, ll_pin, LL_GPIO_OUTPUT_PUSHPULL);
}
}
if ((mode == OpenDrainPullUp) || (mode == PullUp)) {
stm_pin_PullConfig(gpio, ll_pin, GPIO_PULLUP);
} else if ((mode == OpenDrainPullDown) || (mode == PullDown)) {
stm_pin_PullConfig(gpio, ll_pin, GPIO_PULLDOWN);
} else {
stm_pin_PullConfig(gpio, ll_pin, GPIO_NOPULL);
}
#endif // TODO
}
#endif // NOTUSED
| 10,104 | 3,877 |
//
// (c) 2019 Highwater Games Co. All Rights Reserved.
//
#include "PADO_Object.h"
PADO_Object::PADO_Object()
: position(0, 0) {
}
PADO_Object::~PADO_Object() {
}
void PADO_Object::Initialize() {
}
void PADO_Object::BeginPlay() {
}
void PADO_Object::Update() {
}
void PADO_Object::EndPlay() {
}
void PADO_Object::Render() {
}
void PADO_Object::Destroy() {
if(!spawned) PADO_CatchError(210, "Cannot destroy object! The object isn't spawned : %s", "PADO_Object");
objectContainer->Destroy();
}
void PADO_Object::Spawn(PADO_ObjectContainer *objectContainer, std::string name) {
if(spawned) PADO_CatchError(200, "Object spawned already! : %s", objectName.c_str());
spawned = true;
objectName = name;
this->objectContainer = objectContainer;
}
void PADO_Object::Spawn(PADO_ObjectContainer *objectContainer, std::string name, PADO_Object *parent) {
if(spawned) PADO_CatchError(200, "Object spawned already! : %s", objectName.c_str());
spawned = true;
objectName = name;
this->parent = parent;
this->objectContainer = objectContainer;
}
void PADO_Object::Spawn(PADO_ObjectContainer* objectContainer, std::string name, unsigned int layer) {
if(spawned) PADO_CatchError(200, "Object spawned already! : %s", objectName.c_str());
spawned = true;
objectName = name;
if (0 > setLayer(layer)) setLayer(0);
this->objectContainer = objectContainer;
}
void PADO_Object::Spawn(PADO_ObjectContainer *objectContainer, std::string name, PADO_Object *parent,
unsigned int layer) {
if(spawned) PADO_CatchError(200, "Object spawned already! : %s", objectName.c_str());
spawned = true;
objectName = name;
if (0 > setLayer(layer)) setLayer(0);
this->parent = parent;
this->objectContainer = objectContainer;
}
void PADO_Object::Spawn(PADO_ObjectContainer* objectContainer, std::string name,
unsigned int layer, unsigned int sortInLayer) {
if(spawned) PADO_CatchError(200, "Object spawned already! : %s", objectName.c_str());
spawned = true;
objectName = name;
if (0 > setLayer(layer)) setLayer(0);
if (0 > setSortInLayer(sortInLayer)) setSortInLayer(0);
this->objectContainer = objectContainer;
}
void PADO_Object::Spawn(PADO_ObjectContainer *objectContainer, std::string name, PADO_Object *parent,
unsigned int layer, unsigned int sortInLayer) {
if(spawned) PADO_CatchError(200, "Object spawned already! : %s", objectName.c_str());
spawned = true;
objectName = name;
if (0 > setLayer(layer)) setLayer(0);
if (0 > setSortInLayer(sortInLayer)) setSortInLayer(0);
this->parent = parent;
this->objectContainer = objectContainer;
}
std::string PADO_Object::GetName() {
if(!spawned) PADO_CatchError(221, "Cannot get the name! The object isn't spawned : %s", "PADO_Object");
return objectName;
}
void PADO_Object::setActive(bool active) {
this->active = active;
}
bool PADO_Object::isActive() {
return active;
}
void PADO_Object::setVisibility(bool visibility) {
this->visible = visibility;
}
bool PADO_Object::isVisible() {
return visible;
}
bool PADO_Object::isSpawned() {
return spawned;
}
void PADO_Object::setUpdate(bool update) {
this->update = update;
}
bool PADO_Object::getUpdate() {
return update;
}
void PADO_Object::setPosition(PADO_Vector2 position) {
this->position = position;
}
const PADO_Vector2 *PADO_Object::getPosition() {
return &position;
}
int PADO_Object::setLayer(unsigned int layer) {
if(layer >= MAX_LAYER) {
return -1;
}
this->layer = layer;
return layer;
}
int PADO_Object::getLayer() {
return sortInLayer;
}
int PADO_Object::setSortInLayer(unsigned int sortInLayer) {
if(layer >= MAX_SORT_IN_LAYER) {
return -1;
}
this->sortInLayer = sortInLayer;
return sortInLayer;
}
int PADO_Object::getSortInLayer() {
return sortInLayer;
}
| 3,984 | 1,435 |
// Geometric Tools, LLC
// Copyright (c) 1998-2010
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
//
// File Version: 4.10.0 (2009/11/18)
#include "Wm4FoundationPCH.h"
#include "Wm4Vector2.h"
using namespace Wm4;
template<> const Vector2<float> Vector2<float>::ZERO(0.0f,0.0f);
template<> const Vector2<float> Vector2<float>::UNIT_X(1.0f,0.0f);
template<> const Vector2<float> Vector2<float>::UNIT_Y(0.0f,1.0f);
template<> const Vector2<float> Vector2<float>::ONE(1.0f,1.0f);
template<> const Vector2<double> Vector2<double>::ZERO(0.0,0.0);
template<> const Vector2<double> Vector2<double>::UNIT_X(1.0,0.0);
template<> const Vector2<double> Vector2<double>::UNIT_Y(0.0,1.0);
template<> const Vector2<double> Vector2<double>::ONE(1.0,1.0);
| 881 | 375 |
/* this file has been autogenerated by vtkNodeJsWrap */
/* editing this might proof futile */
#define VTK_WRAPPING_CXX
#define VTK_STREAMS_FWD_ONLY
#include <nan.h>
#include "vtkObjectWrap.h"
#include "vtkBrushWrap.h"
#include "vtkObjectBaseWrap.h"
#include "vtkImageDataWrap.h"
#include "../../plus/plus.h"
using namespace v8;
extern Nan::Persistent<v8::Object> vtkNodeJsNoWrap;
Nan::Persistent<v8::FunctionTemplate> VtkBrushWrap::ptpl;
VtkBrushWrap::VtkBrushWrap()
{ }
VtkBrushWrap::VtkBrushWrap(vtkSmartPointer<vtkBrush> _native)
{ native = _native; }
VtkBrushWrap::~VtkBrushWrap()
{ }
void VtkBrushWrap::Init(v8::Local<v8::Object> exports)
{
Nan::SetAccessor(exports, Nan::New("vtkBrush").ToLocalChecked(), ConstructorGetter);
Nan::SetAccessor(exports, Nan::New("Brush").ToLocalChecked(), ConstructorGetter);
}
void VtkBrushWrap::ConstructorGetter(
v8::Local<v8::String> property,
const Nan::PropertyCallbackInfo<v8::Value>& info)
{
InitPtpl();
info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction());
}
void VtkBrushWrap::InitPtpl()
{
if (!ptpl.IsEmpty()) return;
v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
VtkObjectWrap::InitPtpl( );
tpl->Inherit(Nan::New<FunctionTemplate>(VtkObjectWrap::ptpl));
tpl->SetClassName(Nan::New("VtkBrushWrap").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
Nan::SetPrototypeMethod(tpl, "DeepCopy", DeepCopy);
Nan::SetPrototypeMethod(tpl, "deepCopy", DeepCopy);
Nan::SetPrototypeMethod(tpl, "GetColor", GetColor);
Nan::SetPrototypeMethod(tpl, "getColor", GetColor);
Nan::SetPrototypeMethod(tpl, "GetColorF", GetColorF);
Nan::SetPrototypeMethod(tpl, "getColorF", GetColorF);
Nan::SetPrototypeMethod(tpl, "GetOpacity", GetOpacity);
Nan::SetPrototypeMethod(tpl, "getOpacity", GetOpacity);
Nan::SetPrototypeMethod(tpl, "GetOpacityF", GetOpacityF);
Nan::SetPrototypeMethod(tpl, "getOpacityF", GetOpacityF);
Nan::SetPrototypeMethod(tpl, "GetTexture", GetTexture);
Nan::SetPrototypeMethod(tpl, "getTexture", GetTexture);
Nan::SetPrototypeMethod(tpl, "GetTextureProperties", GetTextureProperties);
Nan::SetPrototypeMethod(tpl, "getTextureProperties", GetTextureProperties);
Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance);
Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance);
Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast);
Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast);
Nan::SetPrototypeMethod(tpl, "SetColor", SetColor);
Nan::SetPrototypeMethod(tpl, "setColor", SetColor);
Nan::SetPrototypeMethod(tpl, "SetColorF", SetColorF);
Nan::SetPrototypeMethod(tpl, "setColorF", SetColorF);
Nan::SetPrototypeMethod(tpl, "SetOpacity", SetOpacity);
Nan::SetPrototypeMethod(tpl, "setOpacity", SetOpacity);
Nan::SetPrototypeMethod(tpl, "SetOpacityF", SetOpacityF);
Nan::SetPrototypeMethod(tpl, "setOpacityF", SetOpacityF);
Nan::SetPrototypeMethod(tpl, "SetTexture", SetTexture);
Nan::SetPrototypeMethod(tpl, "setTexture", SetTexture);
Nan::SetPrototypeMethod(tpl, "SetTextureProperties", SetTextureProperties);
Nan::SetPrototypeMethod(tpl, "setTextureProperties", SetTextureProperties);
#ifdef VTK_NODE_PLUS_VTKBRUSHWRAP_INITPTPL
VTK_NODE_PLUS_VTKBRUSHWRAP_INITPTPL
#endif
ptpl.Reset( tpl );
}
void VtkBrushWrap::New(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
if(!info.IsConstructCall())
{
Nan::ThrowError("Constructor not called in a construct call.");
return;
}
if(info.Length() == 0)
{
vtkSmartPointer<vtkBrush> native = vtkSmartPointer<vtkBrush>::New();
VtkBrushWrap* obj = new VtkBrushWrap(native);
obj->Wrap(info.This());
}
else
{
if(info[0]->ToObject() != vtkNodeJsNoWrap )
{
Nan::ThrowError("Parameter Error");
return;
}
}
info.GetReturnValue().Set(info.This());
}
void VtkBrushWrap::DeepCopy(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkBrushWrap *wrapper = ObjectWrap::Unwrap<VtkBrushWrap>(info.Holder());
vtkBrush *native = (vtkBrush *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkBrushWrap::ptpl))->HasInstance(info[0]))
{
VtkBrushWrap *a0 = ObjectWrap::Unwrap<VtkBrushWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->DeepCopy(
(vtkBrush *) a0->native.GetPointer()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkBrushWrap::GetColor(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkBrushWrap *wrapper = ObjectWrap::Unwrap<VtkBrushWrap>(info.Holder());
vtkBrush *native = (vtkBrush *)wrapper->native.GetPointer();
size_t i;
if(info.Length() > 0 && info[0]->IsUint8Array())
{
v8::Local<v8::Uint8Array>a0(v8::Local<v8::Uint8Array>::Cast(info[0]->ToObject()));
if( a0->Length() < 4 )
{
Nan::ThrowError("Array too short.");
return;
}
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->GetColor(
(unsigned char *)(a0->Buffer()->GetContents().Data())
);
return;
}
else if(info.Length() > 0 && info[0]->IsArray())
{
v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject()));
unsigned char b0[4];
if( a0->Length() < 4 )
{
Nan::ThrowError("Array too short.");
return;
}
for( i = 0; i < 4; i++ )
{
if( !a0->Get(i)->IsUint32() )
{
Nan::ThrowError("Array contents invalid.");
return;
}
b0[i] = a0->Get(i)->Uint32Value();
}
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->GetColor(
b0
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkBrushWrap::GetColorF(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkBrushWrap *wrapper = ObjectWrap::Unwrap<VtkBrushWrap>(info.Holder());
vtkBrush *native = (vtkBrush *)wrapper->native.GetPointer();
size_t i;
if(info.Length() > 0 && info[0]->IsFloat64Array())
{
v8::Local<v8::Float64Array>a0(v8::Local<v8::Float64Array>::Cast(info[0]->ToObject()));
if( a0->Length() < 4 )
{
Nan::ThrowError("Array too short.");
return;
}
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->GetColorF(
(double *)(a0->Buffer()->GetContents().Data())
);
return;
}
else if(info.Length() > 0 && info[0]->IsArray())
{
v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject()));
double b0[4];
if( a0->Length() < 4 )
{
Nan::ThrowError("Array too short.");
return;
}
for( i = 0; i < 4; i++ )
{
if( !a0->Get(i)->IsNumber() )
{
Nan::ThrowError("Array contents invalid.");
return;
}
b0[i] = a0->Get(i)->NumberValue();
}
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->GetColorF(
b0
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkBrushWrap::GetOpacity(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkBrushWrap *wrapper = ObjectWrap::Unwrap<VtkBrushWrap>(info.Holder());
vtkBrush *native = (vtkBrush *)wrapper->native.GetPointer();
unsigned char r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetOpacity();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkBrushWrap::GetOpacityF(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkBrushWrap *wrapper = ObjectWrap::Unwrap<VtkBrushWrap>(info.Holder());
vtkBrush *native = (vtkBrush *)wrapper->native.GetPointer();
double r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetOpacityF();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkBrushWrap::GetTexture(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkBrushWrap *wrapper = ObjectWrap::Unwrap<VtkBrushWrap>(info.Holder());
vtkBrush *native = (vtkBrush *)wrapper->native.GetPointer();
vtkImageData * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetTexture();
VtkImageDataWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkImageDataWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkImageDataWrap *w = new VtkImageDataWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void VtkBrushWrap::GetTextureProperties(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkBrushWrap *wrapper = ObjectWrap::Unwrap<VtkBrushWrap>(info.Holder());
vtkBrush *native = (vtkBrush *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetTextureProperties();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkBrushWrap::NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkBrushWrap *wrapper = ObjectWrap::Unwrap<VtkBrushWrap>(info.Holder());
vtkBrush *native = (vtkBrush *)wrapper->native.GetPointer();
vtkBrush * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->NewInstance();
VtkBrushWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkBrushWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkBrushWrap *w = new VtkBrushWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void VtkBrushWrap::SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkBrushWrap *wrapper = ObjectWrap::Unwrap<VtkBrushWrap>(info.Holder());
vtkBrush *native = (vtkBrush *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectBaseWrap::ptpl))->HasInstance(info[0]))
{
VtkObjectBaseWrap *a0 = ObjectWrap::Unwrap<VtkObjectBaseWrap>(info[0]->ToObject());
vtkBrush * r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->SafeDownCast(
(vtkObjectBase *) a0->native.GetPointer()
);
VtkBrushWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkBrushWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkBrushWrap *w = new VtkBrushWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkBrushWrap::SetColor(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkBrushWrap *wrapper = ObjectWrap::Unwrap<VtkBrushWrap>(info.Holder());
vtkBrush *native = (vtkBrush *)wrapper->native.GetPointer();
size_t i;
if(info.Length() > 0 && info[0]->IsUint8Array())
{
v8::Local<v8::Uint8Array>a0(v8::Local<v8::Uint8Array>::Cast(info[0]->ToObject()));
if( a0->Length() < 3 )
{
Nan::ThrowError("Array too short.");
return;
}
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetColor(
(unsigned char *)(a0->Buffer()->GetContents().Data())
);
return;
}
else if(info.Length() > 0 && info[0]->IsArray())
{
v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject()));
unsigned char b0[3];
if( a0->Length() < 3 )
{
Nan::ThrowError("Array too short.");
return;
}
for( i = 0; i < 3; i++ )
{
if( !a0->Get(i)->IsUint32() )
{
Nan::ThrowError("Array contents invalid.");
return;
}
b0[i] = a0->Get(i)->Uint32Value();
}
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetColor(
b0
);
return;
}
else if(info.Length() > 0 && info[0]->IsUint32())
{
if(info.Length() > 1 && info[1]->IsUint32())
{
if(info.Length() > 2 && info[2]->IsUint32())
{
if(info.Length() > 3 && info[3]->IsUint32())
{
if(info.Length() != 4)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetColor(
info[0]->Uint32Value(),
info[1]->Uint32Value(),
info[2]->Uint32Value(),
info[3]->Uint32Value()
);
return;
}
if(info.Length() != 3)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetColor(
info[0]->Uint32Value(),
info[1]->Uint32Value(),
info[2]->Uint32Value()
);
return;
}
}
}
Nan::ThrowError("Parameter mismatch");
}
void VtkBrushWrap::SetColorF(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkBrushWrap *wrapper = ObjectWrap::Unwrap<VtkBrushWrap>(info.Holder());
vtkBrush *native = (vtkBrush *)wrapper->native.GetPointer();
size_t i;
if(info.Length() > 0 && info[0]->IsFloat64Array())
{
v8::Local<v8::Float64Array>a0(v8::Local<v8::Float64Array>::Cast(info[0]->ToObject()));
if( a0->Length() < 3 )
{
Nan::ThrowError("Array too short.");
return;
}
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetColorF(
(double *)(a0->Buffer()->GetContents().Data())
);
return;
}
else if(info.Length() > 0 && info[0]->IsArray())
{
v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject()));
double b0[3];
if( a0->Length() < 3 )
{
Nan::ThrowError("Array too short.");
return;
}
for( i = 0; i < 3; i++ )
{
if( !a0->Get(i)->IsNumber() )
{
Nan::ThrowError("Array contents invalid.");
return;
}
b0[i] = a0->Get(i)->NumberValue();
}
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetColorF(
b0
);
return;
}
else if(info.Length() > 0 && info[0]->IsNumber())
{
if(info.Length() > 1 && info[1]->IsNumber())
{
if(info.Length() > 2 && info[2]->IsNumber())
{
if(info.Length() > 3 && info[3]->IsNumber())
{
if(info.Length() != 4)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetColorF(
info[0]->NumberValue(),
info[1]->NumberValue(),
info[2]->NumberValue(),
info[3]->NumberValue()
);
return;
}
if(info.Length() != 3)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetColorF(
info[0]->NumberValue(),
info[1]->NumberValue(),
info[2]->NumberValue()
);
return;
}
}
}
Nan::ThrowError("Parameter mismatch");
}
void VtkBrushWrap::SetOpacity(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkBrushWrap *wrapper = ObjectWrap::Unwrap<VtkBrushWrap>(info.Holder());
vtkBrush *native = (vtkBrush *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsUint32())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetOpacity(
info[0]->Uint32Value()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkBrushWrap::SetOpacityF(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkBrushWrap *wrapper = ObjectWrap::Unwrap<VtkBrushWrap>(info.Holder());
vtkBrush *native = (vtkBrush *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsNumber())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetOpacityF(
info[0]->NumberValue()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkBrushWrap::SetTexture(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkBrushWrap *wrapper = ObjectWrap::Unwrap<VtkBrushWrap>(info.Holder());
vtkBrush *native = (vtkBrush *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkImageDataWrap::ptpl))->HasInstance(info[0]))
{
VtkImageDataWrap *a0 = ObjectWrap::Unwrap<VtkImageDataWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetTexture(
(vtkImageData *) a0->native.GetPointer()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkBrushWrap::SetTextureProperties(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkBrushWrap *wrapper = ObjectWrap::Unwrap<VtkBrushWrap>(info.Holder());
vtkBrush *native = (vtkBrush *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetTextureProperties(
info[0]->Int32Value()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
| 16,405 | 7,086 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the Apache 2.0 License.
#include "symmetric_key.h"
#include "../mbedtls/symmetric_key.h"
#include "crypto/openssl/openssl_wrappers.h"
#include "crypto/symmetric_key.h"
#include "ds/logger.h"
#include "ds/thread_messaging.h"
#include <openssl/aes.h>
#include <openssl/evp.h>
namespace crypto
{
using namespace OpenSSL;
KeyAesGcm_OpenSSL::KeyAesGcm_OpenSSL(CBuffer rawKey) :
key(std::vector<uint8_t>(rawKey.p, rawKey.p + rawKey.n)),
evp_cipher(nullptr)
{
const auto n = static_cast<unsigned int>(rawKey.rawSize() * 8);
if (n >= 256)
{
evp_cipher = EVP_aes_256_gcm();
evp_cipher_wrap_pad = EVP_aes_256_wrap_pad();
}
else if (n >= 192)
{
evp_cipher = EVP_aes_192_gcm();
evp_cipher_wrap_pad = EVP_aes_192_wrap_pad();
}
else if (n >= 128)
{
evp_cipher = EVP_aes_128_gcm();
evp_cipher_wrap_pad = EVP_aes_128_wrap_pad();
}
else
{
throw std::logic_error(
fmt::format("Need at least {} bits, only have {}", 128, n));
}
}
size_t KeyAesGcm_OpenSSL::key_size() const
{
return key.size() * 8;
}
void KeyAesGcm_OpenSSL::encrypt(
CBuffer iv,
CBuffer plain,
CBuffer aad,
uint8_t* cipher,
uint8_t tag[GCM_SIZE_TAG]) const
{
std::vector<uint8_t> cb(plain.n + GCM_SIZE_TAG);
int len = 0;
Unique_EVP_CIPHER_CTX ctx;
CHECK1(EVP_EncryptInit_ex(ctx, evp_cipher, NULL, key.data(), NULL));
CHECK1(EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, iv.n, NULL));
CHECK1(EVP_EncryptInit_ex(ctx, NULL, NULL, key.data(), iv.p));
if (aad.n > 0)
CHECK1(EVP_EncryptUpdate(ctx, NULL, &len, aad.p, aad.n));
CHECK1(EVP_EncryptUpdate(ctx, cb.data(), &len, plain.p, plain.n));
CHECK1(EVP_EncryptFinal_ex(ctx, cb.data() + len, &len));
CHECK1(
EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, GCM_SIZE_TAG, &tag[0]));
if (plain.n > 0)
memcpy(cipher, cb.data(), plain.n);
}
bool KeyAesGcm_OpenSSL::decrypt(
CBuffer iv,
const uint8_t tag[GCM_SIZE_TAG],
CBuffer cipher,
CBuffer aad,
uint8_t* plain) const
{
std::vector<uint8_t> pb(cipher.n + GCM_SIZE_TAG);
int len = 0;
Unique_EVP_CIPHER_CTX ctx;
CHECK1(EVP_DecryptInit_ex(ctx, evp_cipher, NULL, NULL, NULL));
CHECK1(EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, iv.n, NULL));
CHECK1(EVP_DecryptInit_ex(ctx, NULL, NULL, key.data(), iv.p));
if (aad.n > 0)
CHECK1(EVP_DecryptUpdate(ctx, NULL, &len, aad.p, aad.n));
CHECK1(EVP_DecryptUpdate(ctx, pb.data(), &len, cipher.p, cipher.n));
CHECK1(EVP_CIPHER_CTX_ctrl(
ctx, EVP_CTRL_GCM_SET_TAG, GCM_SIZE_TAG, (uint8_t*)tag));
int r = EVP_DecryptFinal_ex(ctx, pb.data() + len, &len) > 0;
if (r == 1 && cipher.n > 0)
memcpy(plain, pb.data(), cipher.n);
return r == 1;
}
std::vector<uint8_t> KeyAesGcm_OpenSSL::ckm_aes_key_wrap_pad(
CBuffer plain) const
{
int len = 0;
Unique_EVP_CIPHER_CTX ctx;
EVP_CIPHER_CTX_set_flags(ctx, EVP_CIPHER_CTX_FLAG_WRAP_ALLOW);
CHECK1(EVP_EncryptInit_ex(ctx, evp_cipher_wrap_pad, NULL, NULL, NULL));
CHECK1(EVP_EncryptInit_ex(ctx, NULL, NULL, key.data(), NULL));
CHECK1(EVP_EncryptUpdate(ctx, NULL, &len, plain.p, plain.n));
std::vector<uint8_t> cipher(len);
CHECK1(EVP_EncryptUpdate(ctx, cipher.data(), &len, plain.p, plain.n));
CHECK1(EVP_EncryptFinal_ex(ctx, NULL, &len));
return cipher;
}
std::vector<uint8_t> KeyAesGcm_OpenSSL::ckm_aes_key_unwrap_pad(
CBuffer cipher) const
{
int len = 0;
Unique_EVP_CIPHER_CTX ctx;
EVP_CIPHER_CTX_set_flags(ctx, EVP_CIPHER_CTX_FLAG_WRAP_ALLOW);
CHECK1(EVP_DecryptInit_ex(ctx, evp_cipher_wrap_pad, NULL, NULL, NULL));
CHECK1(EVP_DecryptInit_ex(ctx, NULL, NULL, key.data(), NULL));
CHECK1(EVP_DecryptUpdate(ctx, NULL, &len, cipher.p, cipher.n));
std::vector<uint8_t> plain(len);
CHECK1(EVP_DecryptUpdate(ctx, plain.data(), &len, cipher.p, cipher.n));
plain.resize(len);
if (EVP_DecryptFinal_ex(ctx, NULL, &len) != 1)
{
plain.clear();
}
return plain;
}
}
| 4,186 | 1,863 |
#include "be_belarusian.h"
узор<кляса t>
кляса прыклад
{
};
цэлы_лік зачатак()
{
статычны булеев элемент прыраўнай праўда;
калі(элемент ілжывы)
{
вярні 1;
}
указка_на_поле_сыбалаў_які_закончаны_нулявым_сымбалем p = новы сымбаль[10];
p індэкс(0) прыраўнай 'c';
p індэкс(1) прыраўнай 0;
выпіш(p);
вярні 0;
}
// bad and evil source code:
template<class T>
class exemple {
};
int main()
{
static bool element = true;
if (element == false)
{
return 1;
}
char* p = new char[10];
p[0] = 'c';
p[1] = 0;
printf(p);
return 0;
}
| 550 | 311 |
#include "./framework.hh"
TEST_CASE("stress test #1")
{
SETUP("");
for (auto t = 0u; t < 30; ++t)
APPEND("Foo\n");
ASSERT_EQ(LINE_COUNT(), 31);
ASSERT_EQ(TEXT(), "Foo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\n");
}
TEST_CASE("stress test #2")
{
SETUP("");
for (auto t = 0u; t < 30; ++t) {
APPEND("a");
APPEND(" ");
}
ASSERT_EQ(LINE_COUNT(), 1);
ASSERT_EQ(TEXT(), "a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a");
}
TEST_CASE("stress test #3")
{
SETUP("");
layout.setColumns(10);
layout.setSoftWrap(true);
layout.setCollapseWhitespaces(true);
layout.setJustifyText(true);
RESET();
for (auto t = 0u; t < 30; ++t) {
APPEND("a");
APPEND(" ");
}
ASSERT_EQ(LINE_COUNT(), 6);
ASSERT_EQ(TEXT(), "a a a a a\na a a a a\na a a a a\na a a a a\na a a a a\na a a a a");
}
TEST_CASE("stress test #4")
{
SETUP("");
layout.setColumns(10);
layout.setSoftWrap(true);
layout.setCollapseWhitespaces(true);
layout.setPreserveTrailingSpaces(true);
layout.setJustifyText(true);
RESET();
auto currentPosition = Position(0, 0);
FOR(c, "a b c d e f g h i j k l m n o p q r s t u v w x y z\nA B C D E F G H I J K L M N O P Q R S T U V W X Y Z") {
auto characterIndex = layout.getCharacterIndexForPosition(currentPosition);
SPLICE(characterIndex, 0, c);
currentPosition = layout.getPositionForCharacterIndex(characterIndex + 1);
}
ASSERT_EQ(LINE_COUNT(), 12);
ASSERT_EQ(TEXT(), "a b c d e\nf g h i j\nk l m n o\np q r s t\nu v w x y\nz\nA B C D E\nF G H I J\nK L M N O\nP Q R S T\nU V W X Y\nZ");
}
| 1,806 | 814 |
#include <vector>
#include <limits>
#include "render_world.h"
#include "flat_shader.h"
#include "object.h"
#include "light.h"
#include "ray.h"
Render_World::Render_World()
:background_shader(0),ambient_intensity(0),enable_shadows(true),
recursion_depth_limit(3),disable_fresnel_reflection(false),disable_fresnel_refraction(false)
{}
Render_World::~Render_World()
{
delete background_shader;
for(size_t i=0;i<objects.size();i++) delete objects[i];
for(size_t i=0;i<lights.size();i++) delete lights[i];
}
// Find the closest object of intersection and return the object that was
// intersected. Record the Hit structure in hit. If no intersection occurred,
// return NULL. Note that in the case of a Boolean, the object returned will be
// the Boolean, but the object stored in hit will be the underlying primitive.
// Any intersection with t<=small_t should be ignored.
Object* Render_World::Closest_Intersection(const Ray& ray,Hit& hit)
{
Object* closestObj = nullptr;
double minT = std::numeric_limits<double>::max();
for(Object* var : objects)
{
std::vector<Hit> hits;
var->Intersection(ray, hits);
for(Hit h : hits) {
if (h.t < minT && h.t > small_t) {
minT = h.t;
hit = h;
closestObj = var;
}
}
}
return closestObj;
}
// set up the initial view ray and call
void Render_World::Render_Pixel(const ivec2& pixel_index)
{
Ray ray;
ray.endpoint = camera.position;
ray.direction = (camera.World_Position(pixel_index) - camera.position).normalized();
vec3 color=Cast_Ray(ray, 0);
camera.Set_Pixel(pixel_index,Pixel_Color(color));
}
void Render_World::Render()
{
for(int j=0;j<camera.number_pixels[1];j++)
for(int i=0;i<camera.number_pixels[0];i++)
Render_Pixel(ivec2(i,j));
}
// cast ray and return the color of the closest intersected surface point,
// or the background color if there is no object intersection
vec3 Render_World::Cast_Ray(const Ray& ray,int recursion_depth)
{
Hit objHit;
objHit.object = nullptr;
objHit.t = 0;
objHit.ray_exiting = false;
Object* obj = Closest_Intersection(ray, objHit);
vec3 color;
//If there is an Obj for the ray
if (obj != nullptr && recursion_depth < recursion_depth_limit) {
vec3 point = ray.Point(objHit.t);
vec3 normal = obj->Normal(point);
if (objHit.ray_exiting) {
normal *= -1;
}
color = obj->material_shader->Shade_Surface(
ray,
point,
normal,
recursion_depth,
objHit.ray_exiting);
}
//If there is no Obj, use the background
else {
vec3 dummy;
color = background_shader->Shade_Surface(
ray,
ray.endpoint,
ray.direction,
recursion_depth,
false);
}
return color;
}
| 2,688 | 1,017 |
// Copyright Carl Philipp Reh 2009 - 2021.
// 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)
#ifndef FCPPT_VARIANT_OBJECT_IMPL_HPP_INCLUDED
#define FCPPT_VARIANT_OBJECT_IMPL_HPP_INCLUDED
#include <fcppt/variant/object_decl.hpp>
#include <fcppt/variant/size_type.hpp>
#include <fcppt/variant/detail/get_unsafe_impl.hpp>
#include <fcppt/config/external_begin.hpp>
#include <utility>
#include <variant>
#include <fcppt/config/external_end.hpp>
template <typename... Types>
template <typename U, typename>
fcppt::variant::object<Types...>::object(U &&_other) : impl_{std::forward<U>(_other)}
{
}
template <typename... Types>
template <typename U>
U &fcppt::variant::object<Types...>::get_unsafe()
{
return fcppt::variant::detail::get_unsafe_impl<this_type, U>(this->impl_);
}
template <typename... Types>
template <typename U>
U const &fcppt::variant::object<Types...>::get_unsafe() const
{
return fcppt::variant::detail::get_unsafe_impl<this_type, U>(this->impl_);
}
template <typename... Types>
fcppt::variant::size_type fcppt::variant::object<Types...>::type_index() const
{
return this->impl_.index();
}
template <typename... Types>
bool fcppt::variant::object<Types...>::is_invalid() const
{
return this->type_index() == std::variant_npos;
}
template <typename... Types>
typename fcppt::variant::object<Types...>::std_type &fcppt::variant::object<Types...>::impl()
{
return this->impl_;
}
template <typename... Types>
typename fcppt::variant::object<Types...>::std_type const &
fcppt::variant::object<Types...>::impl() const
{
return this->impl_;
}
#endif
| 1,706 | 621 |
#include <iostream>
#include <iomanip>
#include <cfloat>
#include <cmath>
#include <arprec/mp_real.h>
#include <arprec/mp_int.h>
#include "pslq3.h"
#include "pslq_main.h"
using std::cout;
using std::endl;
int main(int argc, char **argv) {
int mode = 0;
int n;
int r = 7, s = 8;
int nr_digits = 780;
int n_eps;
/* Parse command line arguments. */
parse_command(argc, argv, mode, n, r, s, nr_digits, n_eps);
n = r * s + 1;
n_eps = (nr_digits < 700 ? 10 : 20) - nr_digits;
cout << "nr_digits = " << nr_digits << endl;
cout << "debug_level = " << debug_level << endl;
cout << "n = " << n << endl;
if (debug_level > 0) {
cout << "r = " << r << " s = " << s << endl;
cout << "n_eps = " << n_eps << endl;;
}
/* Initialize data */
mp::mp_init(nr_digits);
matrix<mp_real> x(n);
matrix<mp_real> rel(n);
mp_real eps = pow(mp_real(10.0), n_eps);
init_data(mode, n, r, s, x, rel);
if (debug_level >= 1) {
x.print("Initial x:");
}
/* Perform Level-1 PSLQ. */
int result = pslq3(x, rel, eps);
/* Output recovered relation. */
if (result == RESULT_RELATION_FOUND) {
cout << "Relation found:" << endl;
cout << std::fixed << std::setprecision(0);
for (int i = 0; i < n; i++) {
cout << std::setw(3) << i;
cout << std::setw(24) << rel(i) << endl;
}
} else {
cout << "Precision exhausted." << endl;
}
mp::mp_finalize();
return 0;
}
| 1,433 | 630 |
// Copyright 2016 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "firebase/app.h"
#include "firebase/messaging.h"
#include "firebase/util.h"
// Thin OS abstraction layer.
#include "main.h" // NOLINT
// Execute all methods of the C++ Firebase Cloud Messaging API.
extern "C" int common_main(int argc, const char* argv[]) {
::firebase::App* app;
::firebase::messaging::PollableListener listener;
#if defined(__ANDROID__)
app = ::firebase::App::Create(GetJniEnv(), GetActivity());
#else
app = ::firebase::App::Create();
#endif // defined(__ANDROID__)
LogMessage("Initialized Firebase App.");
LogMessage("Initialize the Messaging library");
::firebase::ModuleInitializer initializer;
initializer.Initialize(
app, &listener, [](::firebase::App* app, void* userdata) {
LogMessage("Try to initialize Firebase Messaging");
::firebase::messaging::PollableListener* listener =
static_cast<::firebase::messaging::PollableListener*>(userdata);
return ::firebase::messaging::Initialize(*app, listener);
});
while (initializer.InitializeLastResult().status() !=
firebase::kFutureStatusComplete) {
if (ProcessEvents(100)) return 1; // exit if requested
}
if (initializer.InitializeLastResult().error() != 0) {
LogMessage("Failed to initialize Firebase Messaging: %s",
initializer.InitializeLastResult().error_message());
ProcessEvents(2000);
return 1;
}
LogMessage("Initialized Firebase Cloud Messaging.");
::firebase::messaging::Subscribe("TestTopic");
LogMessage("Subscribed to TestTopic");
bool done = false;
while (!done) {
std::string token;
if (listener.PollRegistrationToken(&token)) {
LogMessage("Recieved Registration Token: %s", token.c_str());
}
::firebase::messaging::Message message;
while (listener.PollMessage(&message)) {
LogMessage("Recieved a new message");
LogMessage("This message was %s by the user",
message.notification_opened ? "opened" : "not opened");
if (!message.from.empty()) LogMessage("from: %s", message.from.c_str());
if (!message.error.empty())
LogMessage("error: %s", message.error.c_str());
if (!message.message_id.empty()) {
LogMessage("message_id: %s", message.message_id.c_str());
}
if (!message.link.empty()) {
LogMessage(" link: %s", message.link.c_str());
}
if (!message.data.empty()) {
LogMessage("data:");
for (const auto& field : message.data) {
LogMessage(" %s: %s", field.first.c_str(), field.second.c_str());
}
}
if (message.notification) {
LogMessage("notification:");
if (!message.notification->title.empty()) {
LogMessage(" title: %s", message.notification->title.c_str());
}
if (!message.notification->body.empty()) {
LogMessage(" body: %s", message.notification->body.c_str());
}
if (!message.notification->icon.empty()) {
LogMessage(" icon: %s", message.notification->icon.c_str());
}
if (!message.notification->tag.empty()) {
LogMessage(" tag: %s", message.notification->tag.c_str());
}
if (!message.notification->color.empty()) {
LogMessage(" color: %s", message.notification->color.c_str());
}
if (!message.notification->sound.empty()) {
LogMessage(" sound: %s", message.notification->sound.c_str());
}
if (!message.notification->click_action.empty()) {
LogMessage(" click_action: %s",
message.notification->click_action.c_str());
}
}
}
// Process events so that the client doesn't hang.
done = ProcessEvents(1000);
}
::firebase::messaging::Terminate();
delete app;
return 0;
}
| 4,425 | 1,302 |
/*
* Copyright (c) The Shogun Machine Learning Toolbox
* Written (W) 2015 Wu Lin
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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.
*
* The views and conclusions contained in the software and documentation are those
* of the authors and should not be interpreted as representing official policies,
* either expressed or implied, of the Shogun Development Team.
*
* This code specifically adapted from function in varsgpLikelihood.m and varsgpPredict.m
*
* The reference paper is
* Titsias, Michalis K.
* "Variational learning of inducing variables in sparse Gaussian processes."
* International Conference on Artificial Intelligence and Statistics. 2009.
*
*/
#include <shogun/machine/gp/VarDTCInferenceMethod.h>
#include <shogun/machine/gp/GaussianLikelihood.h>
#include <shogun/machine/visitors/ShapeVisitor.h>
#include <shogun/mathematics/Math.h>
#include <shogun/labels/RegressionLabels.h>
#include <shogun/mathematics/eigen3.h>
#include <utility>
using namespace shogun;
using namespace Eigen;
VarDTCInferenceMethod::VarDTCInferenceMethod() : SingleSparseInference()
{
init();
}
VarDTCInferenceMethod::VarDTCInferenceMethod(std::shared_ptr<Kernel> kern, std::shared_ptr<Features> feat,
std::shared_ptr<MeanFunction> m, std::shared_ptr<Labels> lab, std::shared_ptr<LikelihoodModel> mod, std::shared_ptr<Features> lat)
: SingleSparseInference(std::move(kern), std::move(feat), std::move(m), std::move(lab), std::move(mod), std::move(lat))
{
init();
}
void VarDTCInferenceMethod::init()
{
m_yy=0.0;
m_f3=0.0;
m_sigma2=0.0;
m_trk=0.0;
m_Tmm=SGMatrix<float64_t>();
m_Tnm=SGMatrix<float64_t>();
m_inv_Lm=SGMatrix<float64_t>();
m_inv_La=SGMatrix<float64_t>();
m_Knm_inv_Lm=SGMatrix<float64_t>();
SG_ADD(&m_yy, "yy", "yy");
SG_ADD(&m_f3, "f3", "f3");
SG_ADD(&m_sigma2, "sigma2", "sigma2");
SG_ADD(&m_trk, "trk", "trk");
SG_ADD(&m_Tmm, "Tmm", "Tmm");
SG_ADD(&m_Tnm, "Tnm", "Tnm");
SG_ADD(&m_inv_Lm, "inv_Lm", "inv_Lm");
SG_ADD(&m_inv_La, "inv_La", "inv_La");
SG_ADD(&m_Knm_inv_Lm, "Knm_Inv_Lm", "Knm_Inv_Lm");
}
VarDTCInferenceMethod::~VarDTCInferenceMethod()
{
}
void VarDTCInferenceMethod::compute_gradient()
{
Inference::compute_gradient();
if (!m_gradient_update)
{
update_deriv();
m_gradient_update=true;
update_parameter_hash();
}
}
void VarDTCInferenceMethod::update()
{
SG_TRACE("entering");
Inference::update();
update_chol();
update_alpha();
m_gradient_update=false;
update_parameter_hash();
SG_TRACE("leaving");
}
std::shared_ptr<VarDTCInferenceMethod> VarDTCInferenceMethod::obtain_from_generic(
const std::shared_ptr<Inference>& inference)
{
if (inference==NULL)
return NULL;
if (inference->get_inference_type()!=INF_KL_SPARSE_REGRESSION)
error("Provided inference is not of type CVarDTCInferenceMethod!");
return inference->as<VarDTCInferenceMethod>();
}
void VarDTCInferenceMethod::check_members() const
{
SingleSparseInference::check_members();
require(m_model->get_model_type()==LT_GAUSSIAN,
"VarDTC inference method can only use Gaussian likelihood function");
require(m_labels->get_label_type()==LT_REGRESSION, "Labels must be type "
"of RegressionLabels");
}
SGVector<float64_t> VarDTCInferenceMethod::get_diagonal_vector()
{
not_implemented(SOURCE_LOCATION);
return SGVector<float64_t>();
}
float64_t VarDTCInferenceMethod::get_negative_log_marginal_likelihood()
{
if (parameter_hash_changed())
update();
Map<MatrixXd> eigen_inv_La(m_inv_La.matrix, m_inv_La.num_rows, m_inv_La.num_cols);
Map<VectorXd> eigen_ktrtr_diag(m_ktrtr_diag.vector, m_ktrtr_diag.vlen);
//F012 =-(model.n-model.m)*model.Likelihood.logtheta-0.5*model.n*log(2*pi)-(0.5/sigma2)*(model.yy)-sum(log(diag(La)));
float64_t neg_f012 =
(m_ktru.num_cols - m_ktru.num_rows) * std::log(m_sigma2) / 2.0 +
0.5 * m_ktru.num_cols * std::log(2 * Math::PI) +
0.5 * m_yy / (m_sigma2)-eigen_inv_La.diagonal().array().log().sum();
//F3 = (0.5/sigma2)*(yKnmInvLmInvLa*yKnmInvLmInvLa');
float64_t neg_f3=-m_f3;
//model.TrKnn = sum(model.diagKnn);
//TrK = - (0.5/sigma2)*(model.TrKnn - sum(diag(C)) );
float64_t neg_trk=-m_trk;
//F = F012 + F3 + TrK;
//F = - F;
return neg_f012+neg_f3+neg_trk;
}
void VarDTCInferenceMethod::update_chol()
{
// get the sigma variable from the Gaussian likelihood model
auto lik = m_model->as<GaussianLikelihood>();
float64_t sigma=lik->get_sigma();
m_sigma2=sigma*sigma;
//m-by-m matrix
Map<MatrixXd> eigen_kuu(m_kuu.matrix, m_kuu.num_rows, m_kuu.num_cols);
//m-by-n matrix
Map<MatrixXd> eigen_ktru(m_ktru.matrix, m_ktru.num_rows, m_ktru.num_cols);
Map<VectorXd> eigen_ktrtr_diag(m_ktrtr_diag.vector, m_ktrtr_diag.vlen);
//Lm = chol(model.Kmm + model.jitter*eye(model.m))
LLT<MatrixXd> Luu(
eigen_kuu * std::exp(m_log_scale * 2.0) +
std::exp(m_log_ind_noise) *
MatrixXd::Identity(m_kuu.num_rows, m_kuu.num_cols));
m_inv_Lm=SGMatrix<float64_t>(Luu.rows(), Luu.cols());
Map<MatrixXd> eigen_inv_Lm(m_inv_Lm.matrix, m_inv_Lm.num_rows, m_inv_Lm.num_cols);
//invLm = Lm\eye(model.m);
eigen_inv_Lm=Luu.matrixU().solve(MatrixXd::Identity(m_kuu.num_rows, m_kuu.num_cols));
m_Knm_inv_Lm=SGMatrix<float64_t>(m_ktru.num_cols, m_ktru.num_rows);
Map<MatrixXd> eigen_Knm_inv_Lm(m_Knm_inv_Lm.matrix, m_Knm_inv_Lm.num_rows, m_Knm_inv_Lm.num_cols);
// KnmInvLm = model.Knm*invLm;
eigen_Knm_inv_Lm =
(eigen_ktru.transpose() * std::exp(m_log_scale * 2.0)) * eigen_inv_Lm;
m_Tmm=SGMatrix<float64_t>(m_kuu.num_rows, m_kuu.num_cols);
Map<MatrixXd> eigen_C(m_Tmm.matrix, m_Tmm.num_rows, m_Tmm.num_cols);
//C = KnmInvLm'*KnmInvLm;
eigen_C=eigen_Knm_inv_Lm.transpose()*eigen_Knm_inv_Lm;
m_inv_La=SGMatrix<float64_t>(m_kuu.num_rows, m_kuu.num_cols);
Map<MatrixXd> eigen_inv_La(m_inv_La.matrix, m_inv_La.num_rows, m_inv_La.num_cols);
//A = sigma2*eye(model.m) + C;
LLT<MatrixXd> chol_A(m_sigma2*MatrixXd::Identity(m_kuu.num_rows, m_kuu.num_cols)+eigen_C);
//La = chol(A);
//invLa = La\eye(model.m);
eigen_inv_La=chol_A.matrixU().solve(MatrixXd::Identity(m_kuu.num_rows, m_kuu.num_cols));
//L=-invLm*invLm' + sigma2*(invLm*invLa*invLa'*invLm');
m_L=SGMatrix<float64_t>(m_kuu.num_rows, m_kuu.num_cols);
Map<MatrixXd> eigen_L(m_L.matrix, m_L.num_rows, m_L.num_cols);
eigen_L=eigen_inv_Lm*(
m_sigma2*eigen_inv_La*eigen_inv_La.transpose()-MatrixXd::Identity(m_kuu.num_rows, m_kuu.num_cols)
)*eigen_inv_Lm.transpose();
//TrK = - (0.5/sigma2)*(model.TrKnn - sum(diag(C)) );
m_trk = -0.5 / (m_sigma2) *
(eigen_ktrtr_diag.array().sum() * std::exp(m_log_scale * 2.0) -
eigen_C.diagonal().array().sum());
}
void VarDTCInferenceMethod::update_alpha()
{
Map<MatrixXd> eigen_Knm_inv_Lm(m_Knm_inv_Lm.matrix, m_Knm_inv_Lm.num_rows, m_Knm_inv_Lm.num_cols);
Map<MatrixXd> eigen_inv_La(m_inv_La.matrix, m_inv_La.num_rows, m_inv_La.num_cols);
Map<MatrixXd> eigen_inv_Lm(m_inv_Lm.matrix, m_inv_Lm.num_rows, m_inv_Lm.num_cols);
SGVector<float64_t> y=m_labels->as<RegressionLabels>()->get_labels();
Map<VectorXd> eigen_y(y.vector, y.vlen);
SGVector<float64_t> m=m_mean->get_mean_vector(m_features);
Map<VectorXd> eigen_m(m.vector, m.vlen);
//yKnmInvLm = (model.y'*KnmInvLm);
//yKnmInvLmInvLa = yKnmInvLm*invLa;
VectorXd y_cor=eigen_y-eigen_m;
VectorXd eigen_y_Knm_inv_Lm_inv_La_transpose=eigen_inv_La.transpose()*(
eigen_Knm_inv_Lm.transpose()*y_cor);
//alpha = invLm*invLa*yKnmInvLmInvLa';
m_alpha=SGVector<float64_t>(m_kuu.num_rows);
Map<VectorXd> eigen_alpha(m_alpha.vector, m_alpha.vlen);
eigen_alpha=eigen_inv_Lm*eigen_inv_La*eigen_y_Knm_inv_Lm_inv_La_transpose;
m_yy=y_cor.dot(y_cor);
//F3 = (0.5/sigma2)*(yKnmInvLmInvLa*yKnmInvLmInvLa');
m_f3=0.5*eigen_y_Knm_inv_Lm_inv_La_transpose.dot(eigen_y_Knm_inv_Lm_inv_La_transpose)/m_sigma2;
}
void VarDTCInferenceMethod::update_deriv()
{
Map<MatrixXd> eigen_inv_La(m_inv_La.matrix, m_inv_La.num_rows, m_inv_La.num_cols);
Map<MatrixXd> eigen_inv_Lm(m_inv_Lm.matrix, m_inv_Lm.num_rows, m_inv_Lm.num_cols);
Map<VectorXd> eigen_alpha(m_alpha.vector, m_alpha.vlen);
Map<MatrixXd> eigen_L(m_L.matrix, m_L.num_rows, m_L.num_cols);
//m-by-n matrix
Map<MatrixXd> eigen_ktru(m_ktru.matrix, m_ktru.num_rows, m_ktru.num_cols);
Map<MatrixXd> eigen_C(m_Tmm.matrix, m_Tmm.num_rows, m_Tmm.num_cols);
//m_Tmm=SGMatrix<float64_t>(m_kuu.num_rows, m_kuu.num_cols);
m_Tnm=SGMatrix<float64_t>(m_ktru.num_cols, m_ktru.num_rows);
Map<MatrixXd> eigen_Tmm(m_Tmm.matrix, m_Tmm.num_rows, m_Tmm.num_cols);
Map<MatrixXd> eigen_Tnm(m_Tnm.matrix, m_Tnm.num_rows, m_Tnm.num_cols);
auto lik = m_model->as<GaussianLikelihood>();
float64_t sigma=lik->get_sigma();
m_sigma2=sigma*sigma;
//invLmInvLa = invLm*invLa;
//invA = invLmInvLa*invLmInvLa';
//yKnmInvA = yKnmInvLmInvLa*invLmInvLa';
//invKmm = invLm*invLm';
//Tmm = sigma2*invA + yKnmInvA'*yKnmInvA;
//Tmm = invKmm - Tmm;
MatrixXd Tmm=-eigen_L-eigen_alpha*eigen_alpha.transpose();
// Tnm = model.Knm*Tmm;
eigen_Tnm = (eigen_ktru.transpose() * std::exp(m_log_scale * 2.0)) * Tmm;
//Tmm = Tmm - (invLm*(C*invLm'))/sigma2;
eigen_Tmm = Tmm - (eigen_inv_Lm*eigen_C*eigen_inv_Lm.transpose()/m_sigma2);
SGVector<float64_t> y=m_labels->as<RegressionLabels>()->get_labels();
Map<VectorXd> eigen_y(y.vector, y.vlen);
SGVector<float64_t> m=m_mean->get_mean_vector(m_features);
Map<VectorXd> eigen_m(m.vector, m.vlen);
//Tnm = Tnm + (model.y*yKnmInvA);
eigen_Tnm += (eigen_y-eigen_m)*eigen_alpha.transpose();
}
SGVector<float64_t> VarDTCInferenceMethod::get_posterior_mean()
{
not_implemented(SOURCE_LOCATION);
//TODO: implement this method once I get time
return SGVector<float64_t>();
}
SGMatrix<float64_t> VarDTCInferenceMethod::get_posterior_covariance()
{
not_implemented(SOURCE_LOCATION);
//TODO: implement this method once I get time
return SGMatrix<float64_t>();
}
SGVector<float64_t> VarDTCInferenceMethod::get_derivative_wrt_likelihood_model(
Parameters::const_reference param)
{
require(param.first == "log_sigma", "Can't compute derivative of "
"the nagative log marginal likelihood wrt {}.{} parameter",
m_model->get_name(), param.first);
SGVector<float64_t> dlik(1);
Map<VectorXd> eigen_alpha(m_alpha.vector, m_alpha.vlen);
Map<MatrixXd> eigen_inv_La(m_inv_La.matrix, m_inv_La.num_rows, m_inv_La.num_cols);
Map<MatrixXd> eigen_ktru(m_ktru.matrix, m_ktru.num_rows, m_ktru.num_cols);
Map<MatrixXd> eigen_kuu(m_kuu.matrix, m_kuu.num_rows, m_kuu.num_cols);
//yKnmInvLmInvLainvLa = yKnmInvLmInvLa*invLa';
//sigma2aux = sigma2*sum(sum(invLa.*invLa)) + yKnmInvLmInvLainvLa*yKnmInvLmInvLainvLa';
float64_t sigma2aux =
m_sigma2 * eigen_inv_La.cwiseProduct(eigen_inv_La).array().sum() +
eigen_alpha.transpose() *
(eigen_kuu * std::exp(m_log_scale * 2.0) +
std::exp(m_log_ind_noise) *
MatrixXd::Identity(m_kuu.num_rows, m_kuu.num_cols)) *
eigen_alpha;
//Dlik_neg = - (model.n-model.m) + model.yy/sigma2 - 2*F3 - sigma2aux - 2*TrK;
dlik[0]=(m_ktru.num_cols-m_ktru.num_rows)-m_yy/m_sigma2+2.0*m_f3+sigma2aux+2.0*m_trk;
return dlik;
}
SGVector<float64_t> VarDTCInferenceMethod::get_derivative_wrt_inducing_features(
Parameters::const_reference param)
{
//[DXu DXunm] = kernelSparseGradInd(model, Tmm, Tnm);
//DXu_neg = DXu + DXunm/model.sigma2;
Map<MatrixXd> eigen_Tmm(m_Tmm.matrix, m_Tmm.num_rows, m_Tmm.num_cols);
Map<MatrixXd> eigen_Tnm(m_Tnm.matrix, m_Tnm.num_rows, m_Tnm.num_cols);
int32_t dim=m_inducing_features.num_rows;
int32_t num_samples=m_inducing_features.num_cols;
SGVector<float64_t>deriv_lat(dim*num_samples);
deriv_lat.zero();
m_lock.lock();
auto inducing_features=get_inducing_features();
//asymtric part (related to xu and x)
m_kernel->init(inducing_features, m_features);
for(int32_t lat_idx=0; lat_idx<eigen_Tnm.cols(); lat_idx++)
{
Map<VectorXd> deriv_lat_col_vec(deriv_lat.vector+lat_idx*dim,dim);
//p by n
SGMatrix<float64_t> deriv_mat=m_kernel->get_parameter_gradient(param, lat_idx);
Map<MatrixXd> eigen_deriv_mat(deriv_mat.matrix, deriv_mat.num_rows, deriv_mat.num_cols);
//DXunm/model.sigma2;
deriv_lat_col_vec +=
eigen_deriv_mat *
(-std::exp(m_log_scale * 2.0) / m_sigma2 * eigen_Tnm.col(lat_idx));
}
//symtric part (related to xu and xu)
m_kernel->init(inducing_features, inducing_features);
for(int32_t lat_lidx=0; lat_lidx<eigen_Tmm.cols(); lat_lidx++)
{
Map<VectorXd> deriv_lat_col_vec(deriv_lat.vector+lat_lidx*dim,dim);
//p by n
SGMatrix<float64_t> deriv_mat=m_kernel->get_parameter_gradient(param, lat_lidx);
Map<MatrixXd> eigen_deriv_mat(deriv_mat.matrix, deriv_mat.num_rows, deriv_mat.num_cols);
//DXu
deriv_lat_col_vec += eigen_deriv_mat * (-std::exp(m_log_scale * 2.0) *
eigen_Tmm.col(lat_lidx));
}
m_lock.unlock();
return deriv_lat;
}
SGVector<float64_t> VarDTCInferenceMethod::get_derivative_wrt_inducing_noise(
Parameters::const_reference param)
{
require(param.first == "log_inducing_noise", "Can't compute derivative of "
"the nagative log marginal likelihood wrt {}.{} parameter",
get_name(), param.first);
Map<MatrixXd> eigen_Tmm(m_Tmm.matrix, m_Tmm.num_rows, m_Tmm.num_cols);
SGVector<float64_t> result(1);
result[0] =
-0.5 * std::exp(m_log_ind_noise) * eigen_Tmm.diagonal().array().sum();
return result;
}
float64_t VarDTCInferenceMethod::get_derivative_related_cov(SGVector<float64_t> ddiagKi,
SGMatrix<float64_t> dKuui, SGMatrix<float64_t> dKui)
{
Map<VectorXd> eigen_ddiagKi(ddiagKi.vector, ddiagKi.vlen);
Map<MatrixXd> eigen_dKuui(dKuui.matrix, dKuui.num_rows, dKuui.num_cols);
Map<MatrixXd> eigen_dKui(dKui.matrix, dKui.num_rows, dKui.num_cols);
Map<MatrixXd> eigen_Tmm(m_Tmm.matrix, m_Tmm.num_rows, m_Tmm.num_cols);
Map<MatrixXd> eigen_Tnm(m_Tnm.matrix, m_Tnm.num_rows, m_Tnm.num_cols);
//[Dkern Dkernnm DTrKnn] = kernelSparseGradHyp(model, Tmm, Tnm);
//Dkern_neg = 0.5*Dkern + Dkernnm/model.sigma2 - (0.5/model.sigma2)*DTrKnn;
float64_t dkern= -0.5*eigen_dKuui.cwiseProduct(eigen_Tmm).sum()
-eigen_dKui.cwiseProduct(eigen_Tnm.transpose()).sum()/m_sigma2
+0.5*eigen_ddiagKi.array().sum()/m_sigma2;
return dkern;
}
SGVector<float64_t> VarDTCInferenceMethod::get_derivative_wrt_mean(
Parameters::const_reference param)
{
SGVector<float64_t> result;
auto visitor = std::make_unique<ShapeVisitor>();
param.second->get_value().visit(visitor.get());
int64_t len= visitor->get_size();
result=SGVector<float64_t>(len);
SGVector<float64_t> y=m_labels->as<RegressionLabels>()->get_labels();
Map<VectorXd> eigen_y(y.vector, y.vlen);
SGVector<float64_t> m=m_mean->get_mean_vector(m_features);
Map<VectorXd> eigen_m(m.vector, m.vlen);
Map<VectorXd> eigen_alpha(m_alpha.vector, m_alpha.vlen);
//m-by-n matrix
Map<MatrixXd> eigen_ktru(m_ktru.matrix, m_ktru.num_rows, m_ktru.num_cols);
for (index_t i=0; i<result.vlen; i++)
{
SGVector<float64_t> dmu=m_mean->get_parameter_derivative(m_features, param, i);
Map<VectorXd> eigen_dmu(dmu.vector, dmu.vlen);
result[i] = eigen_dmu.dot(
eigen_ktru.transpose() * std::exp(m_log_scale * 2.0) *
eigen_alpha +
(eigen_m - eigen_y)) /
m_sigma2;
}
return result;
}
void VarDTCInferenceMethod::register_minimizer(std::shared_ptr<Minimizer> minimizer)
{
io::warn("The method does not require a minimizer. The provided minimizer will not be used.");
}
| 16,630 | 7,571 |
//Language: MS C++
#include <set>
#include <cmath>
#include <vector>
#include <string>
#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
int k, n;
char m[110][110];
int main(){
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
cin >> k;
memset(m, 0, sizeof(m));
int l = 1, r = 100;
while (r - l > 1){
int m1 = (l + r) / 2;
if (m1 * (m1 - 1) * (m1 - 2) / 6 <= k)
l = m1;
else
r = m1;
}
for (int i = n; i < n + l; i++)
for (int j = n; j < n + l; j++)
if (i != j)
m[i][j] = 1;
n = l;
k -= l * (l - 1) * (l - 2) / 6;
while (k){
l = 1, r = 100;
while (r - l > 1){
int m1 = (l + r) / 2;
if (m1 * (m1 - 1) / 2 <= k)
l = m1;
else
r = m1;
}
k -= l * (l - 1) / 2;
for (int i = 0; i < l; i++)
m[i][n] = 1, m[n][i] = 1;
n++;
}
cout << n << '\n';
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++)
cout << (char)(m[i][j] + 48);
cout << '\n';
}
return 0;
} | 1,287 | 562 |
#include <iostream>
#include <fstream>
#include <string>
#include <string>
using namespace std;
struct TreeNode
{
struct TreeNode* left;
struct TreeNode* right;
char elem;
};
TreeNode* BinaryTreeFromOrderings(string inorder, string aftorder, int length)
{
if(length == 0)
{
return NULL;
}
TreeNode* node = new TreeNode;//Noice that [new] should be written out.
node->elem = *(aftorder.begin()+length-1);
cout<<node->elem<<endl;
int rootIndex = 0;
for(rootIndex = 0;rootIndex < length; rootIndex++)//a variation of the loop
{
if(inorder[rootIndex] == *(aftorder.begin()+length-1))
break;
}
node->left = BinaryTreeFromOrderings(inorder aftorder , rootIndex);
node->right = BinaryTreeFromOrderings(inorder + rootIndex + 1, aftorder + rootIndex , length - (rootIndex + 1));
return node;
}
int main(const int argc,const char** argv)
{
string af;
string in;
cin>>af>>in;
BinaryTreeFromOrderings(in, af, af.length());
return 0;
}
| 1,043 | 350 |
#ifndef FLAPJACKOS_COMMON_INCLUDE_COMMON_EXPECTED_HPP
#define FLAPJACKOS_COMMON_INCLUDE_COMMON_EXPECTED_HPP
#include <cassert>
#include "either.hpp"
#include "error.hpp"
template<typename T>
class Expected {
public:
using Value = T;
template<typename U> using Next = Expected<U>;
Expected(const Value& value) : either_(value) {}
Expected(Value&& value) : either_(std::move(value)) {}
Expected(const Error& error) : either_(error) {}
Expected(Error&& error) : either_(std::move(error)) {}
bool has_value() const { return !either_.is_left(); }
Error& get_error() & { return either_.get_left(); }
Error&& get_error() && { return std::move(either_.get_left()); }
const Error& get_error() const& { return either_.get_left(); }
Value& get_value() & { return either_.get_right(); }
Value&& get_value() && { return std::move(either_.get_right()); }
const Value& get_value() const& { return either_.get_right(); }
auto& get_either() & { return either_; }
auto&& get_either() && { return std::move(either_); }
const auto& get_either() const& { return either_; }
template<typename Function>
auto map_error(Function&& fn) const
{
static_assert(!std::is_void<decltype(fn(get_error()))>::value, "");
if (has_value()) {
return *this;
} else {
return Expected{fn(get_error())};
}
}
template<typename Function>
Expected&& map_error(Function&& fn) &&
{
static_assert(!std::is_void<decltype(fn(get_error()))>::value, "");
if (has_value()) {
return std::move(*this);
} else {
return std::move(Expected{fn(get_error())});
}
}
// Map functor.
// If the expected has value then unwrap it, pass it to the given function,
// wrap the function's return value in another expected, and return that.
// If the expected has no value then return an empty optional with a type
// matching the function.
// A return value of void is handled by mapping to Monostate. Likewise,
// no parameters are passed to `fn' in the case where Value=Monostate.
// This method can be chained with other calls to map(), &c.
template<typename Function>
auto map(Function&& fn) &
{
return map_impl(*this, std::forward<Function>(fn));
}
template<typename Function>
auto map(Function&& fn) &&
{
return map_impl(*this, std::forward<Function>(fn));
}
template<typename Function>
auto map(Function&& fn) const&
{
return map_impl(*this, std::forward<Function>(fn));
}
// If the expected has value then unwrap it, pass it to the given function,
// and then return whatever value that function returned.
// If the expected has no value then return an empty optional with a type
// matching the function.
// A return value of void is handled by mapping to Monostate. Likewise,
// no parameters are passed to `fn' in the case where Value=Monostate.
// This method can be chained with other calls to map(), &c.
template<typename Function>
auto and_then(Function&& fn) &
{
return and_then_impl(*this, std::forward<Function>(fn));
}
template<typename Function>
auto and_then(Function&& fn) &&
{
return and_then_impl(std::move(*this), std::forward<Function>(fn));
}
template<typename Function>
auto and_then(Function&& fn) const&
{
return and_then_impl(*this, std::forward<Function>(fn));
}
// If the expected has no value then execute the function.
// The function accepts no parameters and returns no value.
// Since or_else() returns *this, it can be chained with map(), &c.
template<typename Function>
auto or_else(Function&& fn) &
{
return or_else_impl(*this, std::forward<Function>(fn));
}
template<typename Function>
auto or_else(Function&& fn) &&
{
return or_else_impl(std::move(*this), std::forward<Function>(fn));
}
template<typename Function>
auto or_else(Function&& fn) const&
{
return or_else_impl(*this, std::forward<Function>(fn));
}
private:
Either<Error, Value> either_;
};
#endif // FLAPJACKOS_COMMON_INCLUDE_COMMON_EXPECTED_HPP
| 4,306 | 1,327 |
#include "Noise.h"
#include <CherrySoda/CherrySoda.h>
using noise::Noise;
using namespace cherrysoda;
static STL::Action<> s_updateAction;
Noise::Noise()
: base()
{
SetTitle("Noise");
SetClearColor(Color::Black);
}
void Noise::Update()
{
base::Update();
if (s_updateAction) {
s_updateAction();
}
}
void Noise::Initialize()
{
base::Initialize();
unsigned char* data = new unsigned char[200 * 200 * 4];
std::memset(data, 0xFF, 200 * 200 * 4);
for (int i = 0; i < 200 * 200; ++i) {
data[i * 4 ] = Calc::GetRandom()->Next(256);
data[i * 4 + 1] = Calc::GetRandom()->Next(256);
data[i * 4 + 2] = Calc::GetRandom()->Next(256);
}
auto texture = Texture2D::FromRGBA(data, 200, 200);
delete [] data;
auto image = new Image(texture);
auto entity = new Entity();
auto scene = new Scene();
auto renderer = new EverythingRenderer();
s_updateAction = [image](){ image->RotateOnZ(Engine::Instance()->DeltaTime()); };
renderer->GetCamera()->Position(Math::Vec3(0.f, 0.f, 200.f));
renderer->SetEffect(Graphics::GetEmbeddedEffect("sprite"));
image->CenterOrigin();
entity->Add(image);
scene->Add(entity);
scene->Add(renderer);
SetScene(scene);
}
void Noise::LoadContent()
{
base::LoadContent();
}
| 1,231 | 521 |
#include "ReadArchive.h"
#include "dynamicWrite.h"
#include "serialize.std_vector.h"
#include <gtest/gtest.h>
using namespace serialize19;
TEST(serialize, std_vector) {
using T = std::vector<int>;
auto input = T{7, 13, 23};
auto buffer = dynamicWrite(input);
auto reader = ReadArchive{buffer.slice()};
auto output = T{};
serialize(reader, output);
EXPECT_EQ(output, input);
}
TEST(serialize, std_vector_empty) {
using T = std::vector<int>;
auto input = T{};
auto buffer = dynamicWrite(input);
auto reader = ReadArchive{buffer.slice()};
auto output = T{};
serialize(reader, output);
EXPECT_EQ(output, input);
}
| 709 | 254 |
#pragma once
#include "perceive/foundation.hpp"
#include "perceive/geometry.hpp"
namespace perceive::calibration
{
///
/// Class for efficiently evaluating a 'find-homography' cost function
///
// What not use a closure, like good c++11?? Because this object
// is meant to work with python bindings!
class FindHomographyCostFunctor
{
public:
// Lp norm is appled to the homography errors as a vector
Lp_norm_t method{Lp_norm_t::L1};
// The set of world points, and corner (i.e., image) points
std::vector<Vector2r> W, C;
// Evaluate the cost function for the passed set of parameters
// X is a 3x3 homography (H) in row major order
// the result is the mean-sq-err for (C[i] - H W[i]) in R2
real evaluate(const real X[9]) const;
static real homography_err(const Matrix3r& H, const std::vector<Vector2r>& W,
const std::vector<Vector2r>& C, Lp_norm_t method);
// Unpacks X[9] (ie, the paramaters) as a normalized homography
Matrix3r unpack(const real X[9]) const;
// Human readable print-out shows W and C
std::string to_string() const;
};
// Such that C[i] = H * W[i]
real estimate_homography_LLS(const std::vector<Vector3r>& W,
const std::vector<Vector3r>& C, Matrix3r& H);
real estimate_homography_LLS(const std::vector<Vector2r>& W,
const std::vector<Vector2r>& C, Matrix3r& H);
inline void translate_homographies(vector<Matrix3r>& Hs, const Vector2 C)
{
Matrix3r HC = Matrix3r::Identity();
Matrix3r t;
HC(0, 2) = C(0);
HC(1, 2) = C(1);
for(auto& H : Hs) {
t = HC * H;
H = t;
}
}
void H_to_r1r2t(const Matrix3r& H, Vector3& ssa, Vector3r& t,
bool feedback = false);
void r1r2t_to_H(const Vector3& ssa, const Vector3r& t, Matrix3r& H);
void H_to_r1r2t(const Matrix3r& H, Vector6r& X);
void r1r2t_to_H(const Vector6r& X, Matrix3r& H);
// Given 8 values, calculates the last value of the homography
// (h33), such that the homography has determinant 1.0.
// The value of H(2, 2) is ignored and over-written.
void complete_homography(Matrix3r& H);
} // namespace perceive::calibration
| 2,173 | 776 |
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2014-2019, Lawrence Livermore National Security, LLC.
// Produced at the Lawrence Livermore National Laboratory.
// Written by the LBANN Research Team (B. Van Essen, et al.) listed in
// the CONTRIBUTORS file. <lbann-dev@llnl.gov>
//
// LLNL-CODE-697807.
// All rights reserved.
//
// This file is part of LBANN: Livermore Big Artificial Neural Network
// Toolkit. For details, see http://software.llnl.gov/LBANN or
// https://github.com/LLNL/LBANN.
//
// Licensed under the Apache License, Version 2.0 (the "Licensee"); 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 LBANN_OBJECTIVE_FUNCTIONS_WEIGHT_REGULARIZATION_L2_WEIGHT_REGULARIZATION_HPP_INCLUDED
#define LBANN_OBJECTIVE_FUNCTIONS_WEIGHT_REGULARIZATION_L2_WEIGHT_REGULARIZATION_HPP_INCLUDED
#include "lbann/objective_functions/objective_function_term.hpp"
namespace lbann {
template <typename> class data_type_optimizer;
template <typename> class data_type_weights;
/** @class l2_weight_regularization
* @brief Apply L2 regularization to a set of weights.
*
* Given a weights tensor @f$ w @f$,
* @f[ L2(w) = \frac{1}{2} \sum\limits_{i} w(i)^2 @f]
* Note the @f$ 1/2 @f$ scaling factor.
*/
class l2_weight_regularization : public objective_function_term {
public:
using AccumulateDataType = DataType;
using OptimizerType = data_type_optimizer<DataType>;
using WeightsType = data_type_weights<DataType>;
template <El::Device D>
using DMatType = El::Matrix<AccumulateDataType, D>;
using CPUMatType = DMatType<El::Device::CPU>;
public:
/** @param scale_factor The objective function term is
* @f$ \text{scale\_factor} \times \sum L2(w_i) @f$
*/
l2_weight_regularization(EvalType scale_factor = 1);
l2_weight_regularization* copy() const override { return new l2_weight_regularization(*this); }
/** Archive for checkpoint and restart */
template <class Archive> void serialize( Archive & ar ) {
ar(cereal::base_class<objective_function_term>(this));
}
std::string name() const override { return "L2 weight regularization"; }
void setup(model& m) override;
void start_evaluation() override;
EvalType finish_evaluation() override;
/** Compute the gradient w.r.t. the activations.
*
* L2 regularization is independent of forward prop output, so
* nothing needs to be done here.
*
* @todo Come up with a better function name in the base class.
*/
void differentiate() override {};
/** Compute the gradient w.r.t. the weights.
*
* @f[ \nabla_w L2(w) = w @f]
*/
void compute_weight_regularization() override;
private:
/** Contributions to evaluated value. */
std::map<El::Device, CPUMatType> m_contributions;
/** For non-blocking allreduces. */
Al::request m_allreduce_req;
#ifdef LBANN_HAS_GPU
/** For non-blocking GPU-CPU memory copies. */
gpu_lib::event_wrapper m_copy_event;
#endif // LBANN_HAS_GPU
/** Add the sum of squares of @c vals to @c contribution.
*
* @param vals The values to accumulate
* @param contribution @f$ 1 \times 1 @f$ matrix. Used as an
* accumulation variable.
*/
template <El::Device Device>
static void accumulate_contribution(const DMatType<Device>& vals,
DMatType<Device>& contribution);
};
} // namespace lbann
#endif // LBANN_OBJECTIVE_FUNCTIONS_WEIGHT_REGULARIZATION_L2_WEIGHT_REGULARIZATION_HPP_INCLUDED
| 4,055 | 1,342 |
// Copyright 2021 The CPP Proto Builder Authors
//
// 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 "proto_builder/oss/unified_diff.h"
#include <string>
#include "gmock/gmock.h"
#include "proto_builder/oss/testing/cpp_pb_gunit.h"
namespace proto_builder::oss {
namespace {
using ::testing::HasSubstr;
using ::testing::IsEmpty;
TEST(UnifiedDiffTest, Empty) {
EXPECT_THAT(UnifiedDiff(/*left=*/"", /*right=*/"", "left", "right", 0),
IsEmpty());
}
TEST(UnifiedDiffTest, DiffLineNum) {
EXPECT_THAT(UnifiedDiff(/*left=*/"extra_left_content\n", /*right=*/"", "left",
"right", 0),
HasSubstr("Line Number: 2-2"));
}
TEST(UnifiedDiffTest, SingleDiff) {
EXPECT_THAT(UnifiedDiff("left_content", "right_content", "left", "right", 0),
HasSubstr("Line Number: 1\n"
"--- left_content\n"
"+++ right_content"));
}
TEST(UnifiedDiffTest, DiffOnDiffLines) {
std::string diff = UnifiedDiff(
"same_content\n"
"left_content",
"same_content\n"
"right_content\n"
"extra_right_content",
"left", "right", 0);
EXPECT_THAT(diff, HasSubstr("Line Number: 2\n"
"--- left_content\n"
"+++ right_content\n"));
EXPECT_THAT(diff, HasSubstr("Line Number: 3-3\n"
"+++ extra_right_content"));
}
} // namespace
} // namespace proto_builder::oss
| 1,985 | 655 |
#include<iostream>
#include<algorithm>
using namespace std;
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >> t;
while(t--){
int n;
cin >> n;
unsigned a[n];
unsigned b[n];
for(int i=0 ; i<n ; i++)
cin >> a[i];
for(int i=0 ; i<n ; i++)
cin >> b[i];
sort(a,a+n);
sort(b,b+n);
unsigned long long int out = 0;
for(int i=0 ; i<n ; i++)
out += min(a[i],b[i]);
cout << out << "\n";
}
}
| 443 | 227 |
/*
* CalmOcean.cpp
*
* Created on: Jun 10, 2014
* Author: kristof
*/
#include "peanoclaw/native/scenarios/CalmOcean.h"
#include "peanoclaw/Patch.h"
peanoclaw::native::scenarios::CalmOcean::CalmOcean(
std::vector<std::string> arguments
) : _domainSize(1.0) {
if(arguments.size() != 4) {
std::cerr << "Expected arguments for Scenario 'CalmOcean': subgridTopology subdivisionFactor endTime globalTimestepSize" << std::endl
<< "\tGot " << arguments.size() << " arguments." << std::endl;
throw "";
}
double subgridTopologyPerDimension = atof(arguments[0].c_str());
_demandedMeshWidth = _domainSize/ subgridTopologyPerDimension;
_subdivisionFactor = tarch::la::Vector<DIMENSIONS,int>(atoi(arguments[1].c_str()));
_endTime = atof(arguments[2].c_str());
_globalTimestepSize = atof(arguments[3].c_str());
}
void peanoclaw::native::scenarios::CalmOcean::initializePatch(peanoclaw::Patch& patch) {
const tarch::la::Vector<DIMENSIONS, double> patchPosition = patch.getPosition();
const tarch::la::Vector<DIMENSIONS, double> meshWidth = patch.getSubcellSize();
peanoclaw::grid::SubgridAccessor& accessor = patch.getAccessor();
tarch::la::Vector<DIMENSIONS, int> subcellIndex;
for (int yi = 0; yi < patch.getSubdivisionFactor()(1); yi++) {
for (int xi = 0; xi < patch.getSubdivisionFactor()(0); xi++) {
subcellIndex(0) = xi;
subcellIndex(1) = yi;
double X = patchPosition(0) + xi*meshWidth(0);
double Y = patchPosition(1) + yi*meshWidth(1);
double q0 = getWaterHeight(X, Y);
double q1 = 0.0;
double q2 = 0.0;
accessor.setValueUNew(subcellIndex, 0, q0);
accessor.setValueUNew(subcellIndex, 1, q1);
accessor.setValueUNew(subcellIndex, 2, q2);
accessor.setParameterWithGhostlayer(subcellIndex, 0, 0.0);
assertion2(tarch::la::equals(accessor.getValueUNew(subcellIndex, 0), q0, 1e-5), accessor.getValueUNew(subcellIndex, 0), q0);
assertion2(tarch::la::equals(accessor.getValueUNew(subcellIndex, 1), q1, 1e-5), accessor.getValueUNew(subcellIndex, 1), q1);
assertion2(tarch::la::equals(accessor.getValueUNew(subcellIndex, 2), q2, 1e-5), accessor.getValueUNew(subcellIndex, 2), q2);
}
}
}
tarch::la::Vector<DIMENSIONS,double> peanoclaw::native::scenarios::CalmOcean::computeDemandedMeshWidth(peanoclaw::Patch& patch, bool isInitializing) {
return _demandedMeshWidth;
}
//PeanoClaw-Scenario
tarch::la::Vector<DIMENSIONS,double> peanoclaw::native::scenarios::CalmOcean::getDomainOffset() const {
return 0;
}
tarch::la::Vector<DIMENSIONS,double> peanoclaw::native::scenarios::CalmOcean::getDomainSize() const {
return _domainSize;
}
tarch::la::Vector<DIMENSIONS,double> peanoclaw::native::scenarios::CalmOcean::getInitialMinimalMeshWidth() const {
return _demandedMeshWidth;
}
tarch::la::Vector<DIMENSIONS,int> peanoclaw::native::scenarios::CalmOcean::getSubdivisionFactor() const {
return _subdivisionFactor;
}
double peanoclaw::native::scenarios::CalmOcean::getGlobalTimestepSize() const {
return _globalTimestepSize;
}
double peanoclaw::native::scenarios::CalmOcean::getEndTime() const {
return _endTime;
}
//pure SWE-Scenario
float peanoclaw::native::scenarios::CalmOcean::getWaterHeight(float x, float y) {
return 1.0f;
}
float peanoclaw::native::scenarios::CalmOcean::waterHeightAtRest() {
return getWaterHeight(0, 0);
}
float peanoclaw::native::scenarios::CalmOcean::endSimulation() {
return (float)getEndTime();
}
| 3,483 | 1,355 |
// Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
//
#include "contrib/endpoints/src/grpc/transcoding/request_weaver.h"
#include <string>
#include <vector>
#include "google/protobuf/stubs/stringpiece.h"
#include "google/protobuf/type.pb.h"
#include "google/protobuf/util/internal/datapiece.h"
#include "google/protobuf/util/internal/object_writer.h"
namespace google {
namespace api_manager {
namespace transcoding {
namespace pb = google::protobuf;
namespace pbconv = google::protobuf::util::converter;
RequestWeaver::RequestWeaver(std::vector<BindingInfo> bindings,
pbconv::ObjectWriter* ow)
: root_(), current_(), ow_(ow), non_actionable_depth_(0) {
for (const auto& b : bindings) {
Bind(std::move(b.field_path), std::move(b.value));
}
}
RequestWeaver* RequestWeaver::StartObject(pb::StringPiece name) {
ow_->StartObject(name);
if (current_.empty()) {
// The outermost StartObject("");
current_.push(&root_);
return this;
}
if (non_actionable_depth_ == 0) {
WeaveInfo* info = current_.top()->FindWeaveMsg(name);
if (info != nullptr) {
current_.push(info);
return this;
}
}
// At this point, we don't match any messages we need to weave into, so
// we won't need to do any matching until we leave this object.
++non_actionable_depth_;
return this;
}
RequestWeaver* RequestWeaver::EndObject() {
if (non_actionable_depth_ > 0) {
--non_actionable_depth_;
} else {
WeaveTree(current_.top());
current_.pop();
}
ow_->EndObject();
return this;
}
RequestWeaver* RequestWeaver::StartList(google::protobuf::StringPiece name) {
ow_->StartList(name);
// We don't support weaving inside lists, so we won't need to do any matching
// until we leave this list.
++non_actionable_depth_;
return this;
}
RequestWeaver* RequestWeaver::EndList() {
ow_->EndList();
--non_actionable_depth_;
return this;
}
RequestWeaver* RequestWeaver::RenderBool(google::protobuf::StringPiece name,
bool value) {
if (non_actionable_depth_ == 0) {
CollisionCheck(name);
}
ow_->RenderBool(name, value);
return this;
}
RequestWeaver* RequestWeaver::RenderInt32(google::protobuf::StringPiece name,
google::protobuf::int32 value) {
if (non_actionable_depth_ == 0) {
CollisionCheck(name);
}
ow_->RenderInt32(name, value);
return this;
}
RequestWeaver* RequestWeaver::RenderUint32(google::protobuf::StringPiece name,
google::protobuf::uint32 value) {
if (non_actionable_depth_ == 0) {
CollisionCheck(name);
}
ow_->RenderUint32(name, value);
return this;
}
RequestWeaver* RequestWeaver::RenderInt64(google::protobuf::StringPiece name,
google::protobuf::int64 value) {
if (non_actionable_depth_ == 0) {
CollisionCheck(name);
}
ow_->RenderInt64(name, value);
return this;
}
RequestWeaver* RequestWeaver::RenderUint64(google::protobuf::StringPiece name,
google::protobuf::uint64 value) {
if (non_actionable_depth_ == 0) {
CollisionCheck(name);
}
ow_->RenderUint64(name, value);
return this;
}
RequestWeaver* RequestWeaver::RenderDouble(google::protobuf::StringPiece name,
double value) {
if (non_actionable_depth_ == 0) {
CollisionCheck(name);
}
ow_->RenderDouble(name, value);
return this;
}
RequestWeaver* RequestWeaver::RenderFloat(google::protobuf::StringPiece name,
float value) {
if (non_actionable_depth_ == 0) {
CollisionCheck(name);
}
ow_->RenderFloat(name, value);
return this;
}
RequestWeaver* RequestWeaver::RenderString(
google::protobuf::StringPiece name, google::protobuf::StringPiece value) {
if (non_actionable_depth_ == 0) {
CollisionCheck(name);
}
ow_->RenderString(name, value);
return this;
}
RequestWeaver* RequestWeaver::RenderNull(google::protobuf::StringPiece name) {
if (non_actionable_depth_ == 0) {
CollisionCheck(name);
}
ow_->RenderNull(name);
return this;
}
RequestWeaver* RequestWeaver::RenderBytes(google::protobuf::StringPiece name,
google::protobuf::StringPiece value) {
if (non_actionable_depth_ == 0) {
CollisionCheck(name);
}
ow_->RenderBytes(name, value);
return this;
}
void RequestWeaver::Bind(std::vector<const pb::Field*> field_path,
std::string value) {
WeaveInfo* current = &root_;
// Find or create the path from the root to the leaf message, where the value
// should be injected.
for (size_t i = 0; i < field_path.size() - 1; ++i) {
current = current->FindOrCreateWeaveMsg(field_path[i]);
}
if (!field_path.empty()) {
current->bindings.emplace_back(field_path.back(), std::move(value));
}
}
void RequestWeaver::WeaveTree(RequestWeaver::WeaveInfo* info) {
for (const auto& data : info->bindings) {
pbconv::ObjectWriter::RenderDataPieceTo(
pbconv::DataPiece(pb::StringPiece(data.second), true),
pb::StringPiece(data.first->name()), ow_);
}
info->bindings.clear();
for (auto& msg : info->messages) {
// Enter into the message only if there are bindings or submessages left
if (!msg.second.bindings.empty() || !msg.second.messages.empty()) {
ow_->StartObject(msg.first->name());
WeaveTree(&msg.second);
ow_->EndObject();
}
}
info->messages.clear();
}
void RequestWeaver::CollisionCheck(pb::StringPiece name) {
if (current_.empty()) return;
for (auto it = current_.top()->bindings.begin();
it != current_.top()->bindings.end();) {
if (name == it->first->name()) {
if (it->first->cardinality() == pb::Field::CARDINALITY_REPEATED) {
pbconv::ObjectWriter::RenderDataPieceTo(
pbconv::DataPiece(pb::StringPiece(it->second), true), name, ow_);
} else {
// TODO: Report collision error. For now we just ignore
// the conflicting binding.
}
it = current_.top()->bindings.erase(it);
continue;
}
++it;
}
}
RequestWeaver::WeaveInfo* RequestWeaver::WeaveInfo::FindWeaveMsg(
const pb::StringPiece field_name) {
for (auto& msg : messages) {
if (field_name == msg.first->name()) {
return &msg.second;
}
}
return nullptr;
}
RequestWeaver::WeaveInfo* RequestWeaver::WeaveInfo::CreateWeaveMsg(
const pb::Field* field) {
messages.emplace_back(field, WeaveInfo());
return &messages.back().second;
}
RequestWeaver::WeaveInfo* RequestWeaver::WeaveInfo::FindOrCreateWeaveMsg(
const pb::Field* field) {
WeaveInfo* found = FindWeaveMsg(field->name());
return found == nullptr ? CreateWeaveMsg(field) : found;
}
} // namespace transcoding
} // namespace api_manager
} // namespace google
| 7,569 | 2,489 |
#include "Floor.h"
CFloor::CFloor(glm::vec3 _Pos)
{
Scale = glm::vec3(8.0f, 8.0f, 0.2f);
Rotation = glm::vec3(0.0f, 0.0f, 0.0f);
Pos = _Pos;
VAO = CObjectManager::GetMesh(FLOOR_ENTITY)->VAO;
IndicesCount = CObjectManager::GetMesh(FLOOR_ENTITY)->IndicesCount;
Texture = CObjectManager::GetMesh(FLOOR_ENTITY)->Texture;
Shader = CObjectManager::GetMesh(FLOOR_ENTITY)->Shader;
Type = FLOOR_ENTITY;
}
void CFloor::Update(float _DeltaTime)
{
VPMatrix = CCamera::GetMatrix();
Render();
}
| 493 | 227 |
#include "PanelResources.h"
#include "../../Vendor/imgui-docking/imgui.h"
#include "AssetsObserver.h"
#include "ModuleResources.h"
#include "Resource.h"
#include "../ModuleEditor.h"
#include "PanelResourcePreview.h"
#include <string>
#include <vector>
#include <stack>
void bluefir::editor::PanelResources::Init()
{
}
void bluefir::editor::PanelResources::Draw()
{
if (!enabled_) return;
ImGui::Begin(name_.c_str(), &enabled_);
std::vector<std::string> asset_list = bluefir_resources.observer->GetAssetList();
if (ImGui::TreeNode("Assets"))
{
std::stack<std::string> asset_container;
std::stack<bool> node_open;
asset_container.push(BF_FILESYSTEM_ASSETSDIR);
node_open.push(true);
for (std::string it : asset_list)
{
while (!asset_container.empty() && it.find(asset_container.top()) == it.npos)
{
if (asset_container.empty()) break;
asset_container.pop();
if (node_open.top()) ImGui::TreePop();
node_open.pop();
}
size_t length = asset_container.top().length();
std::string name = it.substr(length+1, it.npos);
if (base::FileSystem::IsDir(it.c_str()))
{
asset_container.push(it);
node_open.push(ImGui::TreeNode(name.c_str()));
}
else
{
if (node_open.top())
{
bool selected = (it == selected_asset);
if (ImGui::Selectable(name.c_str(), &selected))
{
if (selected_uid != 0) ((PanelResourcePreview*)bluefir_editor.resource_preview_)->Release();
selected_asset = it;
selected_uid = bluefir_resources.Find(selected_asset.c_str());
((PanelResourcePreview*)bluefir_editor.resource_preview_)->Set(selected_uid);
}
}
//if (ImGui::TreeNode(name.c_str())) ImGui::TreePop();
}
}
while (!node_open.empty())
{
if (node_open.top()) ImGui::TreePop();
node_open.pop();
}
}
ImGui::Separator();
ImGui::Text("Selected Resource:");
UID uid = bluefir_resources.Find(selected_asset.c_str());
if (uid != 0)
{
const resources::Resource* resource = bluefir_resources.Get(uid);
ImGui::Text("UID: %s\nFile: %s\nType: %d\nInstances: %d", std::to_string(resource->GetUID()).c_str(), resource->GetFile(), (unsigned)resource->GetType(), resource->Count());
}
ImGui::End();
}
| 2,223 | 913 |
#pragma once
#include "base.hpp"
namespace mys {
class NotImplementedError : public Error {
public:
String m_message;
NotImplementedError()
{
}
NotImplementedError(const String& message) : m_message(message)
{
}
virtual ~NotImplementedError()
{
}
[[ noreturn ]] void __throw();
String __str__();
};
class __NotImplementedError final : public __Error {
public:
__NotImplementedError(const mys::shared_ptr<NotImplementedError>& error)
: __Error(static_cast<mys::shared_ptr<Error>>(error))
{
}
};
}
| 569 | 193 |
/* aggregate data */
#include "dataAQ.h"
#include "demogData.h"
#include <iostream>
#include <algorithm>
dataAQ::dataAQ() {}
/* necessary function to aggregate the data - this CAN and SHOULD vary per
student - depends on how they map, etc. */
void dataAQ::createStateData(std::vector<shared_ptr<demogData>> theData) {
//FILL in
std::string currentState = theData[0]->getState();
std::vector<shared_ptr<demogData>> stateCounties;
for (auto entry : theData) {
if (entry->getState() != currentState) {
theStates.insert(std::make_pair(currentState, std::make_shared<demogState>(currentState, stateCounties)));
// std::cout << "New map entry for state: " << currentState << "\n"; //deboog
stateCounties.clear();
currentState = entry->getState();
}
stateCounties.push_back(entry);
}
if (stateCounties.size()) {
theStates.insert(std::make_pair(currentState, std::make_shared<demogState>(currentState, stateCounties)));
//std::cout << "New map entry for (final) state: " << currentState << "\n"; //deboog
stateCounties.clear();
}
//std::cout << theStates.size() << "\n"; //deboog
}
//return the name of the state with the largest population under age 5
string dataAQ::youngestPop() {
//FILL in
double record = 0;
string usurper = "";
for (auto state : theStates) {
if (state.second->getpopUnder5() > record) {
usurper = state.first;
record = state.second->getpopUnder5();
}
}
return usurper;
}
//return the name of the state with the largest population under age 18
string dataAQ::teenPop() {
double record = 0;
string usurper = "";
for (auto state : theStates) {
//std::cout << state.first << ": " << state.second->getpopUnder18() << " vs " << record << "\n";
if (state.second->getpopUnder18() > record) {
usurper = state.first;
record = state.second->getpopUnder18();
}
}
return usurper;
}
//return the name of the state with the largest population over age 65
string dataAQ::wisePop() {
double record = 0;
string usurper = "";
for (auto state : theStates) {
if (state.second->getpopOver65() > record) {
usurper = state.first;
record = state.second->getpopOver65();
}
}
return usurper;
}
//return the name of the state with the largest population who did not receive high school diploma
string dataAQ::underServeHS() {
//FILL in
double record = 0;
string usurper = "";
for (auto state : theStates) {
if ((100.0 - state.second->getHSup()) > record) {
usurper = state.first;
record = 100.0 - state.second->getHSup();
}
}
return usurper;
}
//return the name of the state with the largest population who did receive bachelors degree and up
string dataAQ::collegeGrads() {
double record = 0;
string usurper = "";
for (auto state : theStates) {
if ((state.second->getBAup()) > record) {
usurper = state.first;
record = state.second->getBAup();
}
}
return usurper;
}
//return the name of the state with the largest population below the poverty line
string dataAQ::belowPoverty() {
double record = 0;
string usurper = "";
for (auto state : theStates) {
if (state.second->getPoverty() > record) {
usurper = state.first;
record = state.second->getPoverty();
}
}
return usurper;
}
| 3,340 | 1,136 |
/*
* Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <dali-test-suite-utils.h>
#include <dali/devel-api/threading/semaphore.h>
#include <dali/public-api/dali-core.h>
#include <algorithm>
#include <chrono>
#include <future>
#include <stdexcept>
#include <thread>
int UtcDaliSemaphoreTryAcquire(void)
{
using namespace std::chrono_literals;
constexpr auto waitTime{100ms};
tet_infoline("Testing Dali::Semaphore try acquire methods");
Dali::Semaphore<3> sem(0);
DALI_TEST_EQUALS(false, sem.TryAcquire(), TEST_LOCATION);
DALI_TEST_EQUALS(false, sem.TryAcquireFor(waitTime), TEST_LOCATION);
DALI_TEST_EQUALS(false, sem.TryAcquireUntil(std::chrono::system_clock::now() + waitTime), TEST_LOCATION);
sem.Release(3);
DALI_TEST_EQUALS(true, sem.TryAcquire(), TEST_LOCATION);
DALI_TEST_EQUALS(true, sem.TryAcquireFor(waitTime), TEST_LOCATION);
DALI_TEST_EQUALS(true, sem.TryAcquireUntil(std::chrono::system_clock::now() + waitTime), TEST_LOCATION);
DALI_TEST_EQUALS(false, sem.TryAcquire(), TEST_LOCATION);
DALI_TEST_EQUALS(false, sem.TryAcquireFor(waitTime), TEST_LOCATION);
DALI_TEST_EQUALS(false, sem.TryAcquireUntil(std::chrono::system_clock::now() + waitTime), TEST_LOCATION);
END_TEST;
}
int UtcDaliSemaphoreInvalidArguments(void)
{
tet_infoline("Testing Dali::Semaphore invalid arguments");
Dali::Semaphore<2> sem(0);
DALI_TEST_THROWS(sem.Release(3), std::invalid_argument);
DALI_TEST_THROWS(sem.Release(-1), std::invalid_argument);
sem.Release(1);
DALI_TEST_THROWS(sem.Release(2), std::invalid_argument);
sem.Release(1);
DALI_TEST_THROWS(sem.Release(1), std::invalid_argument);
DALI_TEST_THROWS(Dali::Semaphore<1>(2), std::invalid_argument);
DALI_TEST_THROWS(Dali::Semaphore<>(-1), std::invalid_argument);
END_TEST;
}
int UtcDaliSemaphoreAcquire(void)
{
tet_infoline("Testing Dali::Semaphore multithread acquire");
using namespace std::chrono_literals;
constexpr std::ptrdiff_t numTasks{2};
auto f = [](Dali::Semaphore<numTasks>& sem, bool& flag) {
sem.Acquire();
flag = true;
};
auto flag1{false}, flag2{false};
Dali::Semaphore<numTasks> sem(0);
auto fut1 = std::async(std::launch::async, f, std::ref(sem), std::ref(flag1));
auto fut2 = std::async(std::launch::async, f, std::ref(sem), std::ref(flag2));
DALI_TEST_EQUALS(std::future_status::timeout, fut1.wait_for(100ms), TEST_LOCATION);
DALI_TEST_EQUALS(std::future_status::timeout, fut2.wait_for(100ms), TEST_LOCATION);
DALI_TEST_EQUALS(false, flag1, TEST_LOCATION);
DALI_TEST_EQUALS(false, flag2, TEST_LOCATION);
sem.Release(numTasks);
fut1.wait();
DALI_TEST_EQUALS(true, flag1, TEST_LOCATION);
fut2.wait();
DALI_TEST_EQUALS(true, flag2, TEST_LOCATION);
END_TEST;
}
| 3,329 | 1,327 |
#include "../../osal/InternalErrorCodes.h"
ReturnValue_t InternalErrorCodes::translate(uint8_t code) {
//TODO This class can be removed
return HasReturnvaluesIF::RETURN_FAILED;
}
InternalErrorCodes::InternalErrorCodes() {
}
InternalErrorCodes::~InternalErrorCodes() {
}
| 278 | 99 |
//
// Created by killian on 13/11/18.
// Epitech 3 years remaining
// See http://github.com/KillianG
//
#include <SFML/Window/Event.hpp>
#include "Events.hpp"
#include <iostream>
/**
* simple constructor
* @param mgr eventmanager
*/
gfx::Event::Event(EventManager &mgr) : _mgr(mgr){
}
/**
* get all events using sfml poll event
* @param window the window where the events come from
*/
void gfx::Event::getEvents(std::shared_ptr<sf::RenderWindow> window) {
sf::Event event;
while (window->pollEvent(event)) {
if (event.type == sf::Event::KeyReleased) {
if (event.key.code == sf::Keyboard::Space)
this->_mgr.emit<gfx::KeyReleasedEvent>(std::forward<std::string>("Space"));
}
if (event.type == sf::Event::MouseButtonPressed)
this->_mgr.emit<gfx::ClickEvent>(std::forward<gfx::Vector2I>({event.mouseButton.x, event.mouseButton.y}));
if (event.type == sf::Event::MouseButtonReleased)
this->_mgr.emit<gfx::MouseReleaseEvent>(
std::forward<gfx::Vector2I>({event.mouseButton.x, event.mouseButton.y}));
if (event.type == sf::Event::MouseMoved)
this->_mgr.emit<gfx::MouseMoveEvent>(std::forward<gfx::Vector2I>({event.mouseMove.x, event.mouseMove.y}));
if (event.type == sf::Event::KeyPressed) {
if (event.key.code == sf::Keyboard::Space)
this->_mgr.emit<gfx::KeyPressedEvent>(std::forward<std::string>("Space"));
if (event.key.code == sf::Keyboard::Escape)
this->_mgr.emit<gfx::KeyPressedEvent>(std::forward<std::string>("Escape"));
}
if (event.type == sf::Event::TextEntered) {
std::string str = "";
if (event.text.unicode == 8)
this->_mgr.emit<gfx::InputEvent>();
else {
sf::Utf32::encodeAnsi(event.text.unicode, std::back_inserter(str), 'e');
for (auto a : str) {
if (!std::isalnum(a) && a != '.')
return;
}
this->_mgr.emit<gfx::InputEvent>(std::forward<std::string>(str));
}
}
}
}
/**
* simple constructor for clickevent
* @param pos the position
*/
gfx::ClickEvent::ClickEvent(gfx::Vector2I pos) : pos(pos) {}
/**
* getter for position of clickevent
* @return
*/
const gfx::Vector2I gfx::ClickEvent::getPosition() const {
return this->pos;
}
const gfx::Vector2I gfx::MouseMoveEvent::getPosition() const {
return this->pos;
}
gfx::MouseMoveEvent::MouseMoveEvent(gfx::Vector2I pos) : pos(pos) {}
gfx::MouseReleaseEvent::MouseReleaseEvent(gfx::Vector2I pos) : pos(pos) {
}
const gfx::Vector2I gfx::MouseReleaseEvent::getPosition() const {
return this->pos;
}
gfx::KeyPressedEvent::KeyPressedEvent(std::string key) {
this->key = key;
}
const std::string &gfx::KeyPressedEvent::getKey() const {
return this->key;
}
gfx::KeyReleasedEvent::KeyReleasedEvent(std::string key) {
this->key = key;
}
const std::string &gfx::KeyReleasedEvent::getKey() const {
return this->key;
}
std::string gfx::InputEvent::input = "";
gfx::InputEvent::InputEvent() {
if (gfx::InputEvent::input.size() > 0)
gfx::InputEvent::input.pop_back();
}
gfx::InputEvent::InputEvent(std::string input) {
gfx::InputEvent::input += input;
}
std::string gfx::InputEvent::clear() {
std::string copy = gfx::InputEvent::input;
gfx::InputEvent::input.clear();
return copy;
}
| 3,508 | 1,170 |
#include "RE/NiSystem.h"
#include <cassert>
#include <cstdarg>
namespace RE
{
int NiMemcpy(void* a_dest, std::size_t a_destSize, const void* a_src, std::size_t a_count)
{
auto result = memcpy_s(a_dest, a_destSize, a_src, a_count);
assert(result == 0);
return result;
}
int NiSprintf(char* a_dest, std::size_t a_destSize, const char* a_format, ...)
{
assert(a_format);
std::va_list kArgs;
va_start(kArgs, a_format);
auto ret = NiVsprintf(a_dest, a_destSize, a_format, kArgs);
va_end(kArgs);
return ret;
}
char* NiStrcat(char* a_dest, std::size_t a_destSize, const char* a_src)
{
strcat_s(a_dest, a_destSize, a_src);
return a_dest;
}
char* NiStrncpy(char* a_dest, std::size_t a_destSize, const char* a_src, std::size_t a_count)
{
strncpy_s(a_dest, a_destSize, a_src, a_count);
return a_dest;
}
int NiVsnprintf(char* a_dest, std::size_t a_destSize, std::size_t a_count, const char* a_format, std::va_list a_args)
{
if (a_destSize == 0) {
return 0;
}
assert(a_dest);
assert(a_count < a_destSize || a_count == NI_TRUNCATE);
assert(a_format);
a_dest[0] = '\0';
bool truncate = (a_count == NI_TRUNCATE);
auto result = vsnprintf_s(a_dest, a_destSize, a_count, a_format, a_args);
if (result < -1 && !truncate) {
result = static_cast<int>(a_count);
}
return result;
}
int NiVsprintf(char* a_dest, std::size_t a_destSize, const char* a_format, std::va_list a_args)
{
return NiVsnprintf(a_dest, a_destSize, NI_TRUNCATE, a_format, a_args);
}
}
| 1,526 | 719 |
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define SZ(x) (int(x.size()))
const int N = 1e3 + 10, mod = 1e9 + 7;
int n, m, v[N], fac[N], inv[N], bit[N], fbit[N];
ll f[N][N];
char s[N];
ll qpow(ll base, ll n) {
ll res = 1;
while (n) {
if (n & 1)
res = res * base % mod;
base = base * base % mod;
n >>= 1;
}
return res;
}
ll C(int n, int m) {
return 1ll * fac[n] * inv[m] % mod * inv[n - m] % mod;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
fac[0] = 1;
for (int i = 1; i < N; ++i) fac[i] = 1ll * fac[i - 1] * i % mod;
inv[N - 1] = qpow(fac[N - 1], mod - 2);
for (int i = N - 1; i >= 1; --i) inv[i - 1] = 1ll * inv[i] * i % mod;
bit[0] = 1;
for (int i = 1; i < N; ++i) bit[i] = 1ll * bit[i - 1] * 26 % mod;
fbit[0] = 1;
fbit[1] = qpow(26, mod - 2);
for (int i = 2; i < N; ++i) fbit[i] = 1ll * fbit[i - 1] * fbit[1] % mod;
f[0][0] = 1;
for (int i = 1; i < N; ++i) {
for (int j = 0; j <= i; ++j) {
if (!j) {
f[i][j] += f[i - 1][0] + f[i - 1][1];
f[i][j] %= mod;
} else if (j < i) {
f[i][j] += f[i - 1][j - 1] * 26 + f[i - 1][j + 1];
f[i][j] %= mod;
} else if (j == i) {
f[i][j] += f[i - 1][j - 1] * 26 % mod;
f[i][j] %= mod;
}
}
}
cin >> n >> m;
vector<string> vec(n + 1);
for (int i = 1; i <= n; ++i) cin >> vec[i] >> v[i];
ll res = 0;
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
int len = SZ(vec[j]);
if (i >= len) {
res += f[m][i] * (i - len + 1) % mod * v[j] % mod * fbit[len] % mod;
res %= mod;
}
}
}
printf("%lld\n", res);
return 0;
}
| 1,899 | 898 |
#include "benchmark.hh"
#include <iostream>
// Returns number of seconds between b and a
double calculate(const struct rusage *b, const struct rusage *a)
{
if (b == NULL || a == NULL)
return 0.0;
return ((((a->ru_utime.tv_sec * 1000000 + a->ru_utime.tv_usec)
- (b->ru_utime.tv_sec * 1000000 + b->ru_utime.tv_usec))
+ ((a->ru_stime.tv_sec * 1000000 + a->ru_stime.tv_usec)
- (b->ru_stime.tv_sec * 1000000 + b->ru_stime.tv_usec)))
/ 1000000.0);
}
| 525 | 231 |
#pragma once
#include <variant>
#include <cassert>
#include "error.hpp"
namespace ec {
template<typename T = uint8_t>
class option {
protected:
const std::variant<T, ec::error> var;
public:
/**
* Constructor for storing an actual value
* inside the option.
*/
constexpr option(T real) : var(real) {}
/**
* Constructor for storing an error
* inside the option.
*/
constexpr option(ec::error err) : var(err) {}
/**
* Cast operator for converting the option
* to an error. If there was no error
* stored in the option, OK is returned.
*/
operator ec::error() const {
const auto ptr = std::get_if<ec::error>(&this->var);
if (ptr == nullptr) [[likely]]
return error::ok();
return *ptr;
}
/**
* Class method alias for casting the
* option to an error.
* See overloaded error cast operator
* for more info.
*/
constexpr ec::error error() const {
return static_cast<ec::error>(*this);
}
/**
* Class method alias for casting the
* option to the desireable value. If
* there was no actual value inside the
* option, the assert fails and the program
* should exit.
*
* Do not use this if not sure about
* what is in the option. Before using this
* method, one has to always check if there
* is an error in the option istead with
* (ec::error) cast operator.
*/
constexpr T value() const {
const auto ptr = std::get_if<T>(&this->var);
assert(ptr);
return *ptr;
}
/**
* Cast operator for converting the option
* into a boolean. This returns true when there is
* an error inside, otherwise returns false.
*/
operator bool() const {
const auto ptr = std::get_if<ec::error>(&this->var);
return ptr != nullptr;
}
};
} // namespace ec
| 1,802 | 566 |
/* This software and supporting documentation are distributed by
* Institut Federatif de Recherche 49
* CEA/NeuroSpin, Batiment 145,
* 91191 Gif-sur-Yvette cedex
* France
*
* This software is governed by the CeCILL-B license under
* French law and abiding by the rules of distribution of free software.
* You can use, modify and/or redistribute the software under the
* terms of the CeCILL-B license as circulated by CEA, CNRS
* and INRIA at the following URL "http://www.cecill.info".
*
* As a counterpart to the access to the source code and rights to copy,
* modify and redistribute granted by the license, users are provided only
* with a limited warranty and the software's author, the holder of the
* economic rights, and the successive licensors have only limited
* liability.
*
* In this respect, the user's attention is drawn to the risks associated
* with loading, using, modifying and/or developing or reproducing the
* software by the user in light of its specific status of free software,
* that may mean that it is complicated to manipulate, and that also
* therefore means that it is reserved for developers and experienced
* professionals having in-depth computer knowledge. Users are therefore
* encouraged to load and test the software's suitability as regards their
* requirements in conditions enabling the security of their systems and/or
* data to be ensured and, more generally, to use and operate it in the
* same conditions as regards security.
*
* The fact that you are presently reading this means that you have had
* knowledge of the CeCILL-B license and that you accept its terms.
*/
// activate deprecation warning
#ifdef AIMSDATA_CLASS_NO_DEPREC_WARNING
#undef AIMSDATA_CLASS_NO_DEPREC_WARNING
#endif
#include <cstdlib>
#include <cartodata/volume/volume.h>
#include <aims/optimization/levmrq.h>
#include <aims/io/writer.h>
using namespace std;
using namespace carto;
template < class T >
LMFunction< T > *LevenbergMarquardt< T >::doit( rc_ptr<Volume< T > >& x,
rc_ptr<Volume< T > >& y,
rc_ptr<Volume< T > > *sig,
rc_ptr<Volume< int > > *ia,
rc_ptr<Volume< T > > *covar )
{
ASSERT( x->getSizeY() == 1 && x->getSizeZ() == 1 && x->getSizeT() == 1 );
ASSERT( y->getSizeY() == 1 && y->getSizeZ() == 1 && y->getSizeT() == 1 );
ASSERT( x->getSizeX() == y->getSizeX() );
int i, itst;
T alambda, chisq, ochisq;
bool ok = true, status = true;
int n = x->getSizeX();
int ma = lmFonc->param().size();
VolumeRef< T > tsig( n );
VolumeRef< int > tia( ma );
VolumeRef< T > tcov( ma, ma );
VolumeRef< T > alpha( ma, ma );
if ( sig )
{
ASSERT( (*sig)->getSizeY() == 1 && (*sig)->getSizeZ() == 1
&& (*sig)->getSizeT() == 1);
ASSERT( (*sig)->getSizeX() == x->getSizeX() );
tsig = *sig;
}
else
for ( i=0; i<n; i++ ) tsig( i ) = (T)1;
if ( ia )
{
ASSERT( (*ia)->getSizeY() == 1 && (*ia)->getSizeZ() == 1
&& (*ia)->getSizeT() == 1 );
ASSERT( (*ia)->getSizeX() == ma );
tia = *ia;
}
else
for ( i=0; i<ma; i++ ) tia( i ) = 1;
itst = 0;
alambda = (T)(-1);
chisq = ochisq = (T)0;
status = mrqmin( x, y, tsig, tia, &chisq, &alambda, tcov, alpha );
if ( !status ) return (LMFunction< T > *)0;
while ( ok )
{
ochisq = chisq;
status = mrqmin( x, y, tsig, tia, &chisq, &alambda, tcov, alpha );
if ( !status ) return (LMFunction< T > *)0;
std::cout << "chisq = " << chisq << " vs " << ochisq << std::endl ;
if ( chisq > ochisq ) itst = 0;
else if ( (T)fabs( ochisq - chisq ) < (T)0.1 ) itst++;
if ( itst >= 4 )
{
alambda = (T)0;
status = mrqmin( x, y, tsig, tia, &chisq, &alambda, tcov, alpha );
if ( !status ) return (LMFunction< T > *)0;
ok = false;
}
}
if ( covar ) *covar = tcov;
return lmFonc;
}
template LMFunction< float > *
LevenbergMarquardt< float >::doit( rc_ptr<Volume< float > >& x,
rc_ptr<Volume< float > >& y,
rc_ptr<Volume< float > > *sig,
rc_ptr<Volume< int > > *ia,
rc_ptr<Volume< float > > *covar );
template LMFunction< double > *
LevenbergMarquardt< double >::doit( rc_ptr<Volume< double > >& x,
rc_ptr<Volume< double > >& y,
rc_ptr<Volume< double > > *sig,
rc_ptr<Volume< int > > *ia,
rc_ptr<Volume< double > > *covar );
template< class T >
bool LevenbergMarquardt< T >::mrqmin( rc_ptr<Volume< T > >& x,
rc_ptr<Volume< T > >& y,
rc_ptr<Volume< T > >& sig,
rc_ptr<Volume< int > >& ia,
T *chisq, T *alambda,
rc_ptr<Volume< T > >& covar,
rc_ptr<Volume< T > >& alpha )
{
int j, k, l, m;
int mfit;
int ma = ia->getSizeX();
/*static*/ T ochisq;
/*static*/ vector< T > atry;
/*static*/ VolumeRef< T > beta;
/*static*/ VolumeRef< T > da;
/*static*/ VolumeRef< T > oneda;
atry = vector< T >( ma );
beta = VolumeRef< T >( ma );
da = VolumeRef< T >( ma );
for ( mfit=0, j=0; j<ma; j++ )
if ( ia->at( j ) ) mfit++;
oneda = VolumeRef< T >( mfit );
atry = lmFonc->param();
mrqcof( x, y, sig, ia, chisq, alpha, beta );
ochisq = (*chisq);
if ( *alambda < (T)0 )
{
std::cerr << "init " << std::endl ;
*alambda = (T)0.001;
// std::cerr << "init " << std::endl ;
// atry = vector< T >( ma );
// beta = VolumeRef< T >( ma );
// da = VolumeRef< T >( ma );
//
// for ( mfit=0, j=0; j<ma; j++ )
// if ( ia->at( j ) ) mfit++;
//
// oneda = VolumeRef< T >( mfit );
//
// *alambda = (T)0.001;
//
// mrqcof( x, y, sig, ia, chisq, alpha, beta );
//
// ochisq = (*chisq);
//
// atry = lmFonc->param();
}
for ( j=-1, l=0; l<ma; l++ )
{
if ( ia->at( l ) )
{
for ( j++, k=-1, m=0; m<ma; m++ )
{
if ( ia->at( m ) )
{
k++;
covar->at( j, k ) = alpha->at( j, k );
}
}
covar->at( j, j ) = alpha->at( j, j ) * ( (T)1 + (*alambda) );
oneda( j ) = beta( j );
}
}
// aims::Writer< VolumeRef<T> > wriCov( "covar.ima") ;
// wriCov.write( covar ) ;
//
// aims::Writer< VolumeRef<T> > wriOD( "oneda.ima") ;
// wriOD.write( oneda ) ;
bool status = gaussj.doit( covar, oneda, mfit );
if ( !status ) return false;
for ( j=0; j<mfit; j++ ) da( j ) = oneda( j );
if ( *alambda == (T)0 )
{
covsrt.doit( covar, &ia, mfit );
}
else
{
for ( j=-1, l=0; l<ma; l++ )
if ( ia->at( l ) ) lmFonc->param()[ l ] += da( ++j );
mrqcof( x, y, sig, ia, chisq, covar, da );
if ( *chisq < ochisq )
{
*alambda *= (T)0.1;
std::cout << "alamda decreased from " << *alambda << " to " << *alambda / 10 << endl ;
ochisq = (*chisq);
for ( j=-1, l=0; l<ma; l++ )
{
if ( ia->at( l ) )
{
for ( j++, k=-1, m=0; m<ma; m++ )
{
if ( ia->at( m ) )
{
k++;
alpha->at( j, k ) = covar->at( j, k );
}
}
beta( j ) = da( j );
atry = lmFonc->param();
}
}
}
else
{
//std::cout << "alamda increased from " << *alamda << " to " << *alamda * 10 << endl ;
*alambda *= (T)10.0;
*chisq = ochisq;
lmFonc->param() = atry;
}
}
cout << "mrqmin end" << endl ;
return true;
}
template bool
LevenbergMarquardt< float >::mrqmin( rc_ptr<Volume< float > >& x,
rc_ptr<Volume< float > >& sig,
rc_ptr<Volume< float > >& y,
rc_ptr<Volume< int > >& ia,
float *chisq, float *alambda,
rc_ptr<Volume< float > >& covar,
rc_ptr<Volume< float > >& alpha );
template bool
LevenbergMarquardt< double >::mrqmin( rc_ptr<Volume< double > >& x,
rc_ptr<Volume< double > >& y,
rc_ptr<Volume< double > >& sig,
rc_ptr<Volume< int > >& ia,
double *chisq, double *alambda,
rc_ptr<Volume< double > >& covar,
rc_ptr<Volume< double > >& beta );
template< class T >
void LevenbergMarquardt< T >::mrqcof( rc_ptr<Volume< T > >& x,
rc_ptr<Volume< T > >& y,
rc_ptr<Volume< T > >& sig,
rc_ptr<Volume< int > >& ia,
T *chisq, rc_ptr<Volume< T > >& alpha,
rc_ptr<Volume< T > >& beta )
{
int i, j, k, l, m, mfit=0;
T ymod, wt, sig2i, dy;
int n = x->getSizeX();
int ma = ia->getSizeX();
for ( j=0; j<ma; j++ )
if ( ia->at( j ) ) mfit++;
for ( j=0; j<mfit; j++ )
{
for ( k=0; k<=j; k++ ) alpha->at( j, k ) = (T)0;
beta->at( j ) = (T)0;
}
*chisq = (T)0;
for ( i=0; i<n; i++ )
{
//std::cerr << "" << << std::endl ;
ymod = lmFonc->eval( x->at( i ) );
sig2i = (T)1 / ( sig->at( i ) * sig->at( i ) );
dy = y->at( i ) - ymod;
for ( j=-1, l=0; l<ma; l++ )
{
if ( ia->at( l ) )
{
wt = lmFonc->derivative()[ l ] * sig2i;
for ( j++, k=-1, m=0; m<=l; m++ )
if ( ia->at( m ) )
alpha->at( j, ++k ) += wt * lmFonc->derivative()[ m ];
beta->at( j ) += dy * wt;
}
}
*chisq += dy * dy * sig2i;
}
for ( j=1; j<mfit; j++ )
for ( k=0; k<j; k++ ) alpha->at( k, j ) = alpha->at( j, k );
}
template void
LevenbergMarquardt< float >::mrqcof( rc_ptr<Volume< float > >& x,
rc_ptr<Volume< float > >& y,
rc_ptr<Volume< float > >& sig,
rc_ptr<Volume< int > >& ia,
float *chisq,
rc_ptr<Volume< float > >& alpha,
rc_ptr<Volume< float > >& beta );
template void
LevenbergMarquardt< double >::mrqcof( rc_ptr<Volume< double > >& x,
rc_ptr<Volume< double > >& y,
rc_ptr<Volume< double > >& sig,
rc_ptr<Volume< int > >& ia,
double *chisq,
rc_ptr<Volume< double > >& alpha,
rc_ptr<Volume< double > >& beta );
| 10,981 | 4,269 |
#include "task_simple.h"
#include <sstream>
std::unique_ptr<Task> TaskListSimple::get()
{
using namespace std;
unique_ptr<Task> ret;
while( !stream.eof() )
{
string buf;
getline(stream, buf);
if ( buf.empty() )
continue;
istringstream sbuf{ move(buf) };
string uri, fname;
sbuf >> uri;
sbuf >> fname;
if ( uri.empty() || fname.empty() )
continue;
ret = make_unique<Task>( move(uri), path + fname );
break;
}
return ret;
}
| 553 | 185 |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
**/
#include "cli/tests/DistributedCommandExecutorTestRunner.hpp"
#include <cstdio>
#include <memory>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "catalog/CatalogTypedefs.hpp"
#include "cli/CommandExecutorUtil.hpp"
#include "cli/Constants.hpp"
#include "cli/DropRelation.hpp"
#include "cli/PrintToScreen.hpp"
#include "parser/ParseStatement.hpp"
#include "query_execution/BlockLocator.hpp"
#include "query_execution/BlockLocatorUtil.hpp"
#include "query_execution/ForemanDistributed.hpp"
#include "query_execution/QueryExecutionTypedefs.hpp"
#include "query_execution/QueryExecutionUtil.hpp"
#include "query_optimizer/Optimizer.hpp"
#include "query_optimizer/OptimizerContext.hpp"
#include "query_optimizer/QueryHandle.hpp"
#include "query_optimizer/tests/TestDatabaseLoader.hpp"
#include "storage/DataExchangerAsync.hpp"
#include "storage/StorageManager.hpp"
#include "utility/MemStream.hpp"
#include "utility/SqlError.hpp"
#include "glog/logging.h"
#include "tmb/id_typedefs.h"
#include "tmb/message_bus.h"
#include "tmb/tagged_message.h"
using std::make_unique;
using std::string;
using std::vector;
using tmb::TaggedMessage;
namespace quickstep {
class CatalogRelation;
namespace C = cli;
const char *DistributedCommandExecutorTestRunner::kResetOption =
"reset_before_execution";
DistributedCommandExecutorTestRunner::DistributedCommandExecutorTestRunner(const string &storage_path)
: query_id_(0) {
bus_.Initialize();
cli_id_ = bus_.Connect();
bus_.RegisterClientAsSender(cli_id_, kAdmitRequestMessage);
bus_.RegisterClientAsSender(cli_id_, kPoisonMessage);
bus_.RegisterClientAsReceiver(cli_id_, kQueryExecutionSuccessMessage);
bus_.RegisterClientAsSender(cli_id_, kBlockDomainRegistrationMessage);
bus_.RegisterClientAsReceiver(cli_id_, kBlockDomainRegistrationResponseMessage);
block_locator_ = make_unique<BlockLocator>(&bus_);
block_locator_->start();
test_database_loader_ = make_unique<optimizer::TestDatabaseLoader>(
storage_path,
block_locator::getBlockDomain(
test_database_loader_data_exchanger_.network_address(), cli_id_, &locator_client_id_, &bus_),
locator_client_id_,
&bus_);
DCHECK_EQ(block_locator_->getBusClientID(), locator_client_id_);
test_database_loader_data_exchanger_.set_storage_manager(test_database_loader_->storage_manager());
test_database_loader_data_exchanger_.start();
test_database_loader_->createTestRelation(false /* allow_vchar */);
test_database_loader_->loadTestRelation();
// NOTE(zuyu): Foreman should initialize before Shiftboss so that the former
// could receive a registration message from the latter.
foreman_ = make_unique<ForemanDistributed>(*block_locator_, &bus_, test_database_loader_->catalog_database(),
nullptr /* query_processor */);
foreman_->start();
// We don't use the NUMA aware version of worker code.
const vector<numa_node_id> numa_nodes(1 /* Number of worker threads per instance */,
kAnyNUMANodeID);
bus_local_.Initialize();
worker_ = make_unique<Worker>(0 /* worker_thread_index */, &bus_local_);
const vector<tmb::client_id> worker_client_ids(1, worker_->getBusClientID());
worker_directory_ = make_unique<WorkerDirectory>(worker_client_ids.size(), worker_client_ids, numa_nodes);
storage_manager_ = make_unique<StorageManager>(
storage_path,
block_locator::getBlockDomain(
data_exchanger_.network_address(), cli_id_, &locator_client_id_, &bus_),
locator_client_id_, &bus_);
DCHECK_EQ(block_locator_->getBusClientID(), locator_client_id_);
data_exchanger_.set_storage_manager(storage_manager_.get());
shiftboss_ =
make_unique<Shiftboss>(&bus_, &bus_local_, storage_manager_.get(), worker_directory_.get(),
storage_manager_->hdfs());
data_exchanger_.start();
shiftboss_->start();
worker_->start();
}
DistributedCommandExecutorTestRunner::~DistributedCommandExecutorTestRunner() {
const tmb::MessageBus::SendStatus send_status =
QueryExecutionUtil::SendTMBMessage(&bus_, cli_id_, foreman_->getBusClientID(), TaggedMessage(kPoisonMessage));
CHECK(send_status == tmb::MessageBus::SendStatus::kOK);
worker_->join();
shiftboss_->join();
foreman_->join();
test_database_loader_data_exchanger_.shutdown();
test_database_loader_.reset();
data_exchanger_.shutdown();
storage_manager_.reset();
CHECK(MessageBus::SendStatus::kOK ==
QueryExecutionUtil::SendTMBMessage(&bus_, cli_id_, locator_client_id_, TaggedMessage(kPoisonMessage)));
test_database_loader_data_exchanger_.join();
data_exchanger_.join();
block_locator_->join();
}
void DistributedCommandExecutorTestRunner::runTestCase(
const string &input, const std::set<string> &options, string *output) {
// TODO(qzeng): Test multi-threaded query execution when we have a Sort operator.
VLOG(4) << "Test SQL(s): " << input;
if (options.find(kResetOption) != options.end()) {
test_database_loader_->clear();
test_database_loader_->createTestRelation(false /* allow_vchar */);
test_database_loader_->loadTestRelation();
}
MemStream output_stream;
sql_parser_.feedNextBuffer(new string(input));
while (true) {
ParseResult result = sql_parser_.getNextStatement();
if (result.condition != ParseResult::kSuccess) {
if (result.condition == ParseResult::kError) {
*output = result.error_message;
}
break;
}
const ParseStatement &parse_statement = *result.parsed_statement;
std::printf("%s\n", parse_statement.toString().c_str());
try {
if (parse_statement.getStatementType() == ParseStatement::kCommand) {
const ParseCommand &command = static_cast<const ParseCommand &>(parse_statement);
const PtrVector<ParseString> &arguments = *(command.arguments());
const string &command_str = command.command()->value();
string command_response;
if (command_str == C::kDescribeDatabaseCommand) {
command_response = C::ExecuteDescribeDatabase(arguments, *test_database_loader_->catalog_database());
} else if (command_str == C::kDescribeTableCommand) {
if (arguments.empty()) {
command_response = C::ExecuteDescribeDatabase(arguments, *test_database_loader_->catalog_database());
} else {
command_response = C::ExecuteDescribeTable(arguments, *test_database_loader_->catalog_database());
}
} else {
THROW_SQL_ERROR_AT(command.command()) << "Unsupported command";
}
std::fprintf(output_stream.file(), "%s", command_response.c_str());
} else {
optimizer::OptimizerContext optimizer_context;
auto query_handle = std::make_unique<QueryHandle>(query_id_++, cli_id_);
optimizer_.generateQueryHandle(parse_statement,
test_database_loader_->catalog_database(),
&optimizer_context,
query_handle.get());
const CatalogRelation *query_result_relation = query_handle->getQueryResultRelation();
QueryExecutionUtil::ConstructAndSendAdmitRequestMessage(
cli_id_, foreman_->getBusClientID(), query_handle.release(), &bus_);
const tmb::AnnotatedMessage annotated_message = bus_.Receive(cli_id_, 0, true);
DCHECK_EQ(kQueryExecutionSuccessMessage, annotated_message.tagged_message.message_type());
if (query_result_relation) {
PrintToScreen::PrintRelation(*query_result_relation,
test_database_loader_->storage_manager(),
output_stream.file());
DropRelation::Drop(*query_result_relation,
test_database_loader_->catalog_database(),
test_database_loader_->storage_manager());
}
}
} catch (const SqlError &error) {
*output = error.formatMessage(input);
break;
}
}
if (output->empty()) {
*output = output_stream.str();
}
}
} // namespace quickstep
| 9,030 | 2,684 |
#include "FingerPrinter.h"
int auto_page_id = 0;
AS_608 g_as608;
Config g_config;
int g_fd; // file char, return when serial opened
int g_verbose; // the details level of output
char g_error_desc[128]; // error info
uchar g_error_code; // the module return code when function return false
uchar g_order[64] = { 0 }; // the instruction package
uchar g_reply[64] = { 0 }; // the reply package
bool Get_search_CallBack(void* lpvoid, cb_search_ptr callback_param, uchar bufferID, int startPageID, int count, int* pPageID, int* pScore)
{
return callback_param(lpvoid, bufferID, startPageID, count, pPageID, pScore);
}
bool Get_getimage_CallBack(void* lpvoid, cb_getimage_ptr callback_param)
{
return callback_param(lpvoid);
}
bool Get_genchar_CallBack(void* lpvoid, cb_genchar_ptr callback_param, uchar a)
{
return callback_param(lpvoid, a);
}
bool Get_exit_CallBack(void* lpvoid, cb_exit_ptr callback_param)
{
return callback_param(lpvoid);
}
void interrupt()
{
printf("sdasdasd\n");
}
///////////////////////
/*
void FingerPrinter::registerCallback(CallbackInterface* cb) {
PS_Setupcallback = cb;
}*/
///////////////////////
void FingerPrinter::cb_add ()
{
printf("Please put your finger on the module.\n");
if (waitUntilDetectFinger(5000))
{
delay(2000);
if(Get_getimage_CallBack(this,getimage_CALLBACK)){
Get_genchar_CallBack(this,genchar_CALLBACK,1)||Get_exit_CallBack(this,exit_CALLBACK);
// Determine if the user has raised their finger,
printf("Ok.\nPlease raise your finger !\n");
if (waitUntilNotDetectFinger(5000)){
delay(100);
printf("Ok.\nPlease put your finger again!\n");
// input fingerprint for sencond time
if (waitUntilDetectFinger(5000)){
delay(500);
if(Get_getimage_CallBack (this,getimage_CALLBACK)){
Get_genchar_CallBack(this,genchar_CALLBACK,2)||Get_exit_CallBack(this,exit_CALLBACK);
int score = 0;
if ( PS_Match(&score)){
printf("Matched! score=%d\n", score);
if (g_error_code != 0x00)
Get_exit_CallBack(this,exit_CALLBACK);
else{
// Merge feature files
if(PS_RegModel()){
PS_StoreChar(2, auto_page_id);
printf("OK! New fingerprint saved to pageID=%d\n", auto_page_id);
auto_page_id++;
}
else
Get_exit_CallBack(this,exit_CALLBACK);
}
}
else{
printf("Not matched, raise your finger and put it on again.\n");
}
}
else
Get_exit_CallBack(this,exit_CALLBACK);
}
else{
printf("Error: Didn't detect finger!\n");
}
}
else{
printf("Error! Didn't raise your finger\n");
}
}
else
Get_exit_CallBack(this,exit_CALLBACK);
}
else{
printf("Error: Didn't detect finger!\n");
}
}
bool FingerPrinter::CB_Search(uchar bufferID, int startPageID, int count, int* pPageID, int* pScore)
{
int size = GenOrder(0x04, "%d%2d%2d", bufferID, startPageID, count);
SendOrder(g_order, size);
// receive the response pack, check the comfirmation pack and verify sum
return ( RecvReply(g_reply, 16) &&
Check(g_reply, 16) &&
(Merge((uint*)pPageID, g_reply+10, 2)) && // assign value to pageID, return true
(Merge((uint*)pScore, g_reply+12, 2)) // assign value to score, return true
);
}
bool FingerPrinter::CB_GetImage()
{
int size = GenOrder(0x01, "");
// send the command pack
SendOrder(g_order, size);
// receive the response pack, check the comfirmation pack and verify sum
return (RecvReply(g_reply, 12) && Check(g_reply, 12));
}
bool FingerPrinter::CB_GenChar(uchar bufferID)
{
int size = GenOrder(0x02, "%d", bufferID);
SendOrder(g_order, size);
// receive the response pack, check the comfirmation pack and verify sum
return (RecvReply(g_reply, 12) && Check(g_reply, 12));
}
bool FingerPrinter::CB_Exit()
{
printf("ERROR! code=%02X, desc=%s\n", g_error_code, PS_GetErrorDesc());
return true;
}
/*************************************************************************************************/
/************************ FingerPrint_CallBack definition ******************************/
/*************************************************************************************************/
bool FingerPrinter::search_CALLBACK(void* lpvoid, uchar bufferID, int startPageID, int count, int* pPageID, int* pScore)
{
FingerPrinter* exe_ptr = (FingerPrinter*)(lpvoid);
return exe_ptr->CB_Search(bufferID, startPageID, count, pPageID, pScore);
}
bool FingerPrinter::getimage_CALLBACK(void* lpvoid)
{
FingerPrinter* exe_ptr = (FingerPrinter*)(lpvoid);
return exe_ptr->CB_GetImage();
}
bool FingerPrinter::genchar_CALLBACK(void* lpvoid, uchar bufferID)
{
FingerPrinter* exe_ptr = (FingerPrinter*)(lpvoid);
return exe_ptr->CB_GenChar(bufferID);
}
bool FingerPrinter::exit_CALLBACK(void* lpvoid)
{
FingerPrinter* exe_ptr = (FingerPrinter*)(lpvoid);
return exe_ptr->CB_Exit();
}
void FingerPrinter::Test1()
{
printf("______________________IN____CB___SEARCH____________________\n");
//mu.lock();
if (Get_getimage_CallBack (this,getimage_CALLBACK)){
if(Get_genchar_CallBack(this,genchar_CALLBACK,1)){
int pageID = 0;
int score = 0;
if (! Get_search_CallBack(this,search_CALLBACK, 1, 0, 300, &pageID, &score))
Get_exit_CallBack(this,exit_CALLBACK);
else{
//lockerControl();
pinMode (SWITCH,OUTPUT);
printf("Your are No.%d pleace come in\n", pageID);
digitalWrite (SWITCH,LOW);//set it initially as high, is closed
delay(3000);
digitalWrite (SWITCH,HIGH);
}
}
else
Get_exit_CallBack(this,exit_CALLBACK);
fp_callback_ptr->cb_func1();
}
//mu.unlock();
}
void FingerPrinter::Test2()
{
printf("______________________IN___ADDING___________________\n");
cb_add();
delay(50);
fp_callback_ptr->cb_func2();
}
void FingerPrinter::registerCallback(FingerPrint_CallBack* cb)
{
fp_callback_ptr = cb;
}
void FingerPrinter::unRegisterCallback()
{
fp_callback_ptr = nullptr;
}
void FingerPrinter::start()
{
if (nullptr != thread_1 && nullptr != thread_2 ) {
// already running
return;
}
if (!readConfig())
exit(1);
if (g_verbose == 1)
printConfig();
if (-1 == wiringPiSetup()) {
printf("wiringPi setup failed!\n");
exit(0);
}
pinMode(g_config.detect_pin, INPUT);
if((g_fd = serialOpen(g_config.serial, g_config.baudrate)) < 0)
{
fprintf(stderr,"Unable to open serial device: %s\n", strerror(errno));
exit(0);
}
atexit(atExitFunc);
PS_Setup(g_config.address, g_config.password) || PS_Exit();
pinMode(key_pin,INPUT);
pullUpDnControl(key_pin,PUD_UP);
printf("asd%d\n",key_pin);
thread_2 = new thread(exec2,this);
}
void FingerPrinter::stop()
{
if (nullptr != thread_1 && nullptr != thread_2)
{
thread_1->join();
thread_2->join();
delete thread_1;
delete thread_2;
thread_1 = nullptr;
thread_2 = nullptr;
#ifdef DEBUG
fprintf(stderr,"DAQ thread stopped.\n");
#endif
}
}
/******************************************************************************
* FingerOrinter main Functions
******************************************************************************/
FingerPrinter::FingerPrinter()
{
}
FingerPrinter::~FingerPrinter()
{
unRegisterCallback();
thread_1 = nullptr;
thread_2 = nullptr;
delete fp_callback_ptr;
delete thread_1;
delete thread_2;
}
void FingerPrinter::lockerControl()
{
pinMode (SWITCH,OUTPUT);
printf("FBI open The Door!\n");
digitalWrite (SWITCH,LOW);//set it initially as high, is closed
delay(1000);
digitalWrite (SWITCH,HIGH);
pinMode(g_config.detect_pin, INPUT);
}
bool FingerPrinter::PS_Setup(uint chipAddr, uint password) {
g_as608.chip_addr = chipAddr;
g_as608.password = password;
if (g_verbose == 1)
printf("-------------------------Initializing-------------------------\n");
//verify the password
if (g_as608.has_password) {
if (!PS_VfyPwd(password))
return false;
}
// obtain the size of datapack and the baud rate ec.
if (PS_ReadSysPara() && g_as608.packet_size > 0) {
if (g_verbose == 1)
printf("-----------------------------Done-----------------------------\n");
return true;
}
if (g_verbose == 1)
printf("-----------------------------Done-----------------------------\n");
g_error_code = 0xC7;
return false;
}
bool FingerPrinter::PS_GetImage() {
int size = GenOrder(0x01, "");
// send the command pack
SendOrder(g_order, size);
// receive the response pack, check the comfirmation pack and verify sum
return (RecvReply(g_reply, 12) && Check(g_reply, 12));
}
bool FingerPrinter::PS_GenChar(uchar bufferID) {
int size = GenOrder(0x02, "%d", bufferID);
SendOrder(g_order, size);
// receive the response pack, check the comfirmation pack and verify sum
return (RecvReply(g_reply, 12) && Check(g_reply, 12));
}
bool FingerPrinter::PS_Match(int* pScore) {
int size = GenOrder(0x03, "");
SendOrder(g_order, size);
// receive the response pack, check the comfirmation pack and verify sum
return (RecvReply(g_reply, 14) &&
Check(g_reply, 14) &&
Merge((uint*)pScore, g_reply+10, 2));
}
bool FingerPrinter::PS_RegModel() {
int size = GenOrder(0x05, "");
SendOrder(g_order, size);
// receive the response pack, check the comfirmation pack and verify sum
return (RecvReply(g_reply, 12) &&
Check(g_reply, 12));
}
bool FingerPrinter::PS_StoreChar(uchar bufferID, int pageID) {
int size = GenOrder(0x06, "%d%2d", bufferID, pageID);
SendOrder(g_order, size);
// receive the response pack, check the comfirmation pack and verify sum
return (RecvReply(g_reply, 12) &&
Check(g_reply, 12));
}
bool FingerPrinter::PS_Search(uchar bufferID, int startPageID, int count, int* pPageID, int* pScore) {
int size = GenOrder(0x04, "%d%2d%2d", bufferID, startPageID, count);
SendOrder(g_order, size);
// receive the response pack, check the comfirmation pack and verify sum
return ( RecvReply(g_reply, 16) &&
Check(g_reply, 16) &&
(Merge((uint*)pPageID, g_reply+10, 2)) && // assign value to pageID, return true
(Merge((uint*)pScore, g_reply+12, 2)) // assign value to score, return true
);
}
bool FingerPrinter::PS_DetectFinger() {
return digitalRead(g_as608.detect_pin) == HIGH;
}
// Block until a finger is detected, the longest block wait_time is milliseconds
bool FingerPrinter::waitUntilDetectFinger(int wait_time) {
while (true) {
if ( PS_DetectFinger()) {
return true;
}
else {
delay(100);
wait_time -= 100;
if (wait_time < 0) {
return false;
}
}
}
}
bool FingerPrinter::waitUntilNotDetectFinger(int wait_time) {
while (true) {
if (! PS_DetectFinger()) {
return true;
}
else {
delay(100);
wait_time -= 100;
if (wait_time < 0) {
return false;
}
}
}
}
bool FingerPrinter::PS_Empty() {
int size = GenOrder(0x0d, "");
SendOrder(g_order, size);
// receive data, verify the confirmation code and the sum
return (RecvReply(g_reply, 12) && Check(g_reply, 12));
}
//The program exited because the function in as608.h failed to execute
bool FingerPrinter::PS_Exit()
{
printf("ERROR! code=%02X, desc=%s\n", g_error_code, PS_GetErrorDesc());
return true;
}
// obtain the defination of error code of g_error_code and assign value to g_error_desc
char* FingerPrinter::PS_GetErrorDesc()
{
switch (g_error_code) {
default: strcpy(g_error_desc, "Undefined error"); break;
case 0x00: strcpy(g_error_desc, "OK"); break;
case 0x01: strcpy(g_error_desc, "Recive packer error"); break;
case 0x02: strcpy(g_error_desc, "No finger on the sensor"); break;
case 0x03: strcpy(g_error_desc, "Failed to input fingerprint image"); break;
case 0x04: strcpy(g_error_desc, "Fingerprint images are too dry and bland to be characteristic"); break;
case 0x05: strcpy(g_error_desc, "Fingerprint images are too wet and mushy to produce features"); break;
case 0x06: strcpy(g_error_desc, "Fingerprint images are too messy to be characteristic"); break;
case 0x07: strcpy(g_error_desc, "The fingerprint image is normal, but there are too few feature points (or too small area) to produce a feature"); break;
case 0x08: strcpy(g_error_desc, "Fingerprint mismatch"); break;
case 0x09: strcpy(g_error_desc, "Not found in fingerprint libary"); break;
case 0x0A: strcpy(g_error_desc, "Feature merge failed"); break;
case 0x0B: strcpy(g_error_desc, "The address serial number is out of the range of fingerprint database when accessing fingerprint database"); break;
case 0x0C: strcpy(g_error_desc, "Error or invalid reading template from fingerprint database"); break;
case 0x0D: strcpy(g_error_desc, "Upload feature failed"); break;
case 0x0E: strcpy(g_error_desc, "The module cannot accept subsequent packets"); break;
case 0x0F: strcpy(g_error_desc, "Failed to upload image"); break;
case 0x10: strcpy(g_error_desc, "Failed to delete template"); break;
case 0x11: strcpy(g_error_desc, "Failed to clear the fingerprint database"); break;
case 0x12: strcpy(g_error_desc, "Cannot enter low power consumption state"); break;
case 0x13: strcpy(g_error_desc, "Incorrect password"); break;
case 0x14: strcpy(g_error_desc, "System reset failure"); break;
case 0x15: strcpy(g_error_desc, "An image cannot be generated without a valid original image in the buffer"); break;
case 0x16: strcpy(g_error_desc, "Online upgrade failed"); break;
case 0x17: strcpy(g_error_desc, "There was no movement of the finger between the two collections"); break;
case 0x18: strcpy(g_error_desc, "FLASH reading or writing error"); break;
case 0x19: strcpy(g_error_desc, "Undefined error"); break;
case 0x1A: strcpy(g_error_desc, "Invalid register number"); break;
case 0x1B: strcpy(g_error_desc, "Register setting error"); break;
case 0x1C: strcpy(g_error_desc, "Notepad page number specified incorrectly"); break;
case 0x1D: strcpy(g_error_desc, "Port operation failed"); break;
case 0x1E: strcpy(g_error_desc, "Automatic enrollment failed"); break;
case 0xFF: strcpy(g_error_desc, "Fingerprint is full"); break;
case 0x20: strcpy(g_error_desc, "Reserved. Wrong address or wrong password"); break;
case 0xF0: strcpy(g_error_desc, "There are instructions for subsequent packets, and reply with 0xf0 after correct reception"); break;
case 0xF1: strcpy(g_error_desc, "There are instructions for subsequent packets, and the command packet replies with 0xf1"); break;
case 0xF2: strcpy(g_error_desc, "Checksum error while burning internal FLASH"); break;
case 0xF3: strcpy(g_error_desc, "Package identification error while burning internal FLASH"); break;
case 0xF4: strcpy(g_error_desc, "Packet length error while burning internal FLASH"); break;
case 0xF5: strcpy(g_error_desc, "Code length is too long to burn internal FLASH"); break;
case 0xF6: strcpy(g_error_desc, "Burning internal FLASH failed"); break;
case 0xC1: strcpy(g_error_desc, "Array is too smalll to store all the data"); break;
case 0xC2: strcpy(g_error_desc, "Open local file failed!"); break;
case 0xC3: strcpy(g_error_desc, "Packet loss"); break;
case 0xC4: strcpy(g_error_desc, "No end packet received, please flush the buffer(PS_Flush)"); break;
case 0xC5: strcpy(g_error_desc, "Packet size not in 32, 64, 128 or 256"); break;
case 0xC6: strcpy(g_error_desc, "Array size is to big");break;
case 0xC7: strcpy(g_error_desc, "Setup failed! Please retry again later"); break;
case 0xC8: strcpy(g_error_desc, "The size of the data to send must be an integral multiple of the g_as608.packet_size"); break;
case 0xC9: strcpy(g_error_desc, "The size of the fingerprint image is not 74806bytes(about73.1kb)");break;
case 0xCA: strcpy(g_error_desc, "Error while reading local fingerprint imgae"); break;
}
return g_error_desc;
}
/******************************************************************************
* Helper Functions
******************************************************************************/
//split unsigned int val into seperate int val
void FingerPrinter::Split(uint num, uchar* buf, int count) {
for (int i = 0; i < count; ++i) {
*buf++ = (num & 0xff << 8*(count-i-1)) >> 8*(count-i-1);
}
}
bool FingerPrinter::Merge(uint* num, const uchar* startAddr, int count) {
*num = 0;
for (int i = 0; i < count; ++i)
*num += (int)(startAddr[i]) << (8*(count-i-1));
return true;
}
void FingerPrinter::PrintBuf(const uchar* buf, int size) {
for (int i = 0; i < size; ++i) {
printf("%02X ", buf[i]);
}
printf("\n");
}
int FingerPrinter::Calibrate(const uchar* buf, int size) {
int count = 0;
for (int i = 6; i < size - 2; ++i) {
count += buf[i];
}
return count;
}
bool FingerPrinter::Check(const uchar* buf, int size) {
//init check sum
int count_ = 0;
Merge((uint*)&count_, buf+size-2, 2);
// sum of check
int count = Calibrate(buf, size);
//avoid 0x00
return (buf[9] == 0x00 && count_ == count && buf[0] != 0x00);
}
int FingerPrinter::SendOrder(const uchar* order, int size) {
// print detials info
if (g_verbose == 1) {
printf("sent: ");
PrintBuf(order, size);
}
int ret = write(g_fd, order, size);
return ret;
}
bool FingerPrinter::RecvReply(uchar* hex, int size) {
int availCount = 0;
int timeCount = 0;
while (true) {
if (serialDataAvail(g_fd)) {
hex[availCount] = serialGetchar(g_fd);
availCount++;
if (availCount >= size) {
break;
}
}
usleep(10);
timeCount++;
if (timeCount > 300000) { //if delay >3s
break;
}
}
if (g_verbose == 1) {
printf("recv: ");
PrintBuf(hex, availCount);
}
// if no data return within required time
if (availCount < size) {
g_error_code = 0xff;
return false;
}
g_error_code = hex[9];
return true;
}
void FingerPrinter::PrintProcess(int done, int all) {
// progress bar showing as 0~100%,50 chars
char process[64] = { 0 };
double stepSize = (double)all / 100;
int doneStep = done / stepSize;
// update the progress bar if the step is even
// 50 chars used to display 100 the value of prgress
for (int i = 0; i < doneStep / 2 - 1; ++i)
process[i] = '=';
process[doneStep/2 - 1] = '>';
printf("\rProcess:[%-50s]%d%% ", process, doneStep);
if (done < all)
fflush(stdout);
else
printf("\n");
}
bool FingerPrinter::RecvPacket(uchar* pData, int validDataSize) {
if (g_as608.packet_size <= 0)
return false;
int realPacketSize = 11 + g_as608.packet_size; // how big every datapacks are in reality
int realDataSize = validDataSize * realPacketSize / g_as608.packet_size; // how big datapacks received totally
uchar readBufTmp[8] = { 0 }; // read 8 chars every time at most, implus to readBuf
uchar* readBuf = (uchar*)malloc(realPacketSize); // receiving full chars of realPacketSize means receiving a whole datapack, superadd into pData
int availSize = 0;
int readSize = 0;
int readCount = 0;
//unused variable
//int readBufTmpSize = 0;
int readBufSize = 0;
int offset = 0;
int timeCount = 0;
while (true) {
if ((availSize = serialDataAvail(g_fd)) > 0) {
timeCount = 0;
if (availSize > 8) {
availSize = 8;
}
if (readBufSize + availSize > realPacketSize) {
availSize = realPacketSize - readBufSize;
}
memset(readBufTmp, 0, 8);
readSize = read(g_fd, readBufTmp, availSize);
memcpy(readBuf+readBufSize, readBufTmp, readSize);
readBufSize += readSize;
readCount += readSize;
// export detailed message or not
if (g_verbose == 1) {
printf("%2d%% RecvData: %d count=%4d/%-4d ",
(int)((double)readCount/realDataSize*100), readSize, readCount, realDataSize);
PrintBuf(readBufTmp, readSize);
}
else if (g_verbose == 0){ // dispaly progress bar acquiescently
PrintProcess(readCount, realDataSize);
}
else {
// show nothing
}
// receive a whole datapack(139 bytes)
if (readBufSize >= realPacketSize) {
int count_ = 0;
Merge((uint*)&count_, readBuf+realPacketSize-2, 2);
if (Calibrate(readBuf, realPacketSize) != count_) {
free(readBuf);
g_error_code = 0x01;
return false;
}
memcpy(pData+offset, readBuf+9, g_as608.packet_size);
offset += g_as608.packet_size;
readBufSize = 0;
// received and terminate the pack
if (readBuf[6] == 0x08) {
break;
}
}
// received the effective chars of validDataSize, but haven't receive the ending datapack
if (readCount >= realDataSize) {
free(readBuf);
g_error_code = 0xC4;
return false;
}
} // end outer if
usleep(10); // wait for 10 um
timeCount++;
if (timeCount > 300000) { // block up to 3 seconds
break;
}
} // end while
free(readBuf);
// haven't recive the appointed size fa data within the maximum blocking time, return false
if (readCount < realDataSize) {
g_error_code = 0xC3;
return false;
}
g_error_code = 0x00;
return true;
}
bool FingerPrinter::SendPacket(uchar* pData, int validDataSize) {
if (g_as608.packet_size <= 0)
return false;
if (validDataSize % g_as608.packet_size != 0) {
g_error_code = 0xC8;
return false;
}
int realPacketSize = 11 + g_as608.packet_size; // the size of every datapack in reality
int realDataSize = validDataSize * realPacketSize / g_as608.packet_size; // the total size of data to be sent
// construct datapack
uchar* writeBuf = (uchar*)malloc(realPacketSize);
writeBuf[0] = 0xef; // the begining of datapack
writeBuf[1] = 0x01; // the begining of datapack
Split(g_as608.chip_addr, writeBuf+2, 4); // the address of chip
Split(g_as608.packet_size+2, writeBuf+7, 2); // the length of datapack
int offset = 0; // valid data sent
int writeCount = 0; // factual data sent
while (true) {
// fill the data zone
memcpy(writeBuf+9, pData+offset, g_as608.packet_size);
// datapack symbol
if (offset + g_as608.packet_size < (uint)validDataSize)
writeBuf[6] = 0x02; // ending pack(the final datapack)
else
writeBuf[6] = 0x08; // general datapack
// verify the sum
Split(Calibrate(writeBuf, realPacketSize), writeBuf+realPacketSize-2, 2);
// send datapack
write(g_fd, writeBuf, realPacketSize);
offset += g_as608.packet_size;
writeCount += realPacketSize;
// export detailed message or not
if (g_verbose == 1) {
printf("%2d%% SentData: %d count=%4d/%-4d ",
(int)((double)writeCount/realDataSize*100), realPacketSize, writeCount, realDataSize);
PrintBuf(writeBuf, realPacketSize);
}
else if (g_verbose == 0) {
// dispaly the prpgress bar
PrintProcess(writeCount, realDataSize);
}
else {
// show nothing
}
if (offset >= validDataSize)
break;
} // end while
free(writeBuf);
g_error_code = 0x00;
return true;
}
int FingerPrinter::GenOrder(uchar orderCode, const char* fmt, ...) {
g_order[0] = 0xef; // the begining of pack,0xef
g_order[1] = 0x01;
Split(g_as608.chip_addr, g_order+2, 4); // the address of chip, PS_Setup() is needed to initial setup
g_order[6] = 0x01; // the symbol of pack,0x01 stands for the command pack,0x02 datapack ,0x08 is ending(final) pack
g_order[9] = orderCode; // command
// calculate the total number of parameters
int count = 0;
for (const char* p = fmt; *p; ++p) {
if (*p == '%')
count++;
}
// fmt==""
if (count == 0) {
Split(0x03, g_order+7, 2); // the length of pack
Split(Calibrate(g_order, 0x0c), g_order+10, 2); // verify the sum(the length pf pack should be 12(0x0c) if without parameters
return 0x0c;
}
else {
va_list ap;
va_start(ap, fmt);
uint uintVal;
uchar ucharVal;
uchar* strVal;
int offset = 10; // the offset of pin g_order
int width = 1; // the width of modifier in fmt,such as:%4d, %32s
// dispose the uncertain parameters
for (; *fmt; ++fmt) {
width = 1;
if (*fmt == '%') {
const char* tmp = fmt+1;
// obtain the width, such as: %4u, %32s
if (*tmp >= '0' && *tmp <= '9') {
width = 0;
do {
width = (*tmp - '0') + width * 10;
tmp++;
} while(*tmp >= '0' && *tmp <= '9');
}
switch (*tmp) {
case 'u':
case 'd':
if (width > 4)
return 0;
uintVal = va_arg(ap, int);
Split(uintVal, g_order+offset, width);
break;
case 'c': // equal to "%d"
if (width > 1)
return 0;
ucharVal = va_arg(ap, int);
g_order[offset] = ucharVal;
break;
case 's':
strVal = va_arg(ap, uchar*);
memcpy(g_order+offset, strVal, width);
break;
default:
return 0;
} // end switch
offset += width;
} // end if (*p == '%')
} // end for
Split(offset+2-9, g_order+7, 2); // the length of pack
Split(Calibrate(g_order, offset+2), g_order+offset, 2); // verify the sum
va_end(ap);
return offset + 2;
} // end else (count != 0)
}
bool FingerPrinter::PS_VfyPwd(uint pwd) {
int size = GenOrder(0x13, "%4d", pwd);
SendOrder(g_order, size);
return (RecvReply(g_reply, 12) && Check(g_reply, 12));
}
bool FingerPrinter::PS_ReadSysPara() {
int size = GenOrder(0x0f, "");
SendOrder(g_order, size);
return (RecvReply(g_reply, 28) &&
Check(g_reply, 28) &&
Merge(&g_as608.status, g_reply+10, 2) &&
Merge(&g_as608.model, g_reply+12, 2) &&
Merge(&g_as608.capacity, g_reply+14, 2) &&
Merge(&g_as608.secure_level, g_reply+16, 2) &&
Merge(&g_as608.chip_addr, g_reply+18, 4) &&
Merge(&g_as608.packet_size, g_reply+22, 2) &&
Merge(&g_as608.baud_rate, g_reply+24, 2) &&
(g_as608.packet_size = 32 * (int)pow(2, g_as608.packet_size)) &&
(g_as608.baud_rate *= 9600)
);
}
bool FingerPrinter::readConfig() {
FILE* fp;
char filename[256] = { 0 };
sprintf(filename, "%s/.fpconfig", getenv("HOME"));
if (access(filename, F_OK) == 0) {
trimSpaceInFile(filename);
fp = fopen(filename, "r");
}
else {
g_config.address = 0xffffffff;
g_config.password= 0x00000000;
g_config.has_password = 0;
g_config.baudrate = 9600;
g_config.detect_pin = 1;
strcpy(g_config.serial, "/dev/ttyAMA0");
writeConfig();
printf("Please config the address and password in \"~/.fpconfig\"\n");
printf(" fp cfgaddr 0x[address]\n");
printf(" fp cfgpwd 0x[password]\n");
printf(" fp cfgserial [serialFile]\n");
printf(" fp cfgbaud [rate]\n");
printf(" fp cfgpin [GPIO_pin]\n");
return false;
}
char key[16] = { 0 };
char value[16] = { 0 };
char line[32] = { 0 };
char *tmp;
while (!feof(fp)) {
fgets(line, 32, fp);
if (tmp = strtok(line, "="))
trim(tmp, key);
else
continue;
if (tmp = strtok(NULL, "="))
trim(tmp, value);
else
continue;
while (!tmp)
tmp = strtok(NULL, "=");
int offset = 0;
if (value[0] == '0' && (value[1] == 'x' || value[1] == 'X'))
offset = 2;
if (strcmp(key, "address") == 0) {
g_config.address = toUInt(value+offset);
}
else if (strcmp(key, "password") == 0) {
if (strcmp(value, "none") == 0 || strcmp(value, "false") == 0) {
g_config.has_password = 0;
}
else {
g_config.has_password = 1;
g_config.password = toUInt(value+offset);
}
}
else if (strcmp(key, "serial") == 0) {
int len = strlen(value);
if (value[len-1] == '\n')
value[len-1] = 0;
strcpy(g_config.serial, value);
}
else if (strcmp(key, "baudrate") == 0) {
g_config.baudrate = toInt(value);
}
else if (strcmp(key, "detect_pin") == 0) {
g_config.detect_pin = toInt(value);
}
else {
printf("Unknown key:%s\n", key);
fclose(fp);
return false;
}
} // end while(!feof(fp))
asyncConfig();
fclose(fp);
return true;
}
void FingerPrinter::printConfig() {
printf("address=%08x\n", g_config.address);
if (g_config.has_password)
printf("password=%08x\n", g_config.password);
else
printf("password=none(no password)\n");
printf("serial_file=%s\n", g_config.serial);
printf("baudrate=%d\n", g_config.baudrate);
printf("detect_pin=%d\n", g_config.detect_pin);
}
void FingerPrinter::asyncConfig() {
g_as608.detect_pin = g_config.detect_pin;
g_as608.has_password = g_config.has_password;
g_as608.password = g_config.password;
g_as608.chip_addr = g_config.address;
g_as608.baud_rate = g_config.baudrate;
}
void FingerPrinter::atExitFunc() {
if (g_verbose == 1)
printf("Exit\n");
if (g_fd > 0)
serialClose(g_fd);
}
bool FingerPrinter::writeConfig() {
char filename[256] = { 0 };
sprintf(filename, "%s/.fpconfig", getenv("HOME"));
FILE* fp = fp = fopen(filename, "w+");
if (!fp) {
printf("Write config file error!\n");
exit(0);
}
fprintf(fp, "address=0x%08x\n", g_config.address);
if (g_config.has_password)
fprintf(fp, "password=0x%08x\n", g_config.password);
else
fprintf(fp, "password=none\n");
fprintf(fp, "baudrate=%d\n", g_config.baudrate);
fprintf(fp, "detect_pin=%d\n", g_config.detect_pin);
fprintf(fp, "serial=%s\n", g_config.serial);
fclose(fp);
}
void FingerPrinter::trimSpaceInFile(const char* filename) {
FILE* fp = fopen(filename, "r");
if (!fp)
return;
//buffer for input except white space and '\n'
char lineBuf[64] = { 0 };
char writeBuf[1024] = { 0 };
int offset = 0;
while (!feof(fp)) {
fgets(lineBuf, 64, fp);
if (feof(fp))
break;
for (int i = 0, len = strlen(lineBuf); i < len; ++i) {
if (lineBuf[i] != ' ' && lineBuf[i] != '\t') {
if (lineBuf[i] == '\n' && offset > 0 && writeBuf[offset-1] == '\n')
continue;
writeBuf[offset++] = lineBuf[i];
}
}
}
fclose(fp);
//overwrtie file
fp = fopen(filename, "w+");
if (!fp)
return;
fwrite(writeBuf, 1, strlen(writeBuf), fp);
fclose(fp);
}
void FingerPrinter::trim(const char* strIn, char* strOut) {
int i = 0;
int j = strlen(strIn) - 1;
//detect space
while (strIn[i] == ' ')
++i;
//detect '\n'
while (strIn[j] == ' ' || strIn[j] == '\n')
--j;
strncpy(strOut, strIn+i, j-i+1);
strOut[j-i+1] = 0;
}
int FingerPrinter::toInt(const char* str) {
int ret = 0;
sscanf(str, "%d", &ret);
return ret;
}
unsigned int FingerPrinter::toUInt(const char* str) {
unsigned int ret = 0;
if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
sscanf(str+2, "%x", &ret);
else
sscanf(str, "%x", &ret);
return ret;
}
| 31,493 | 12,263 |
// slang-check-constraint.cpp
#include "slang-check-impl.h"
// This file provides the core services for creating
// and solving constraint systems during semantic checking.
//
// We currently use constraint systems primarily to solve
// for the implied values to use for generic parameters when a
// generic declaration is being applied without explicit
// generic arguments.
//
// Conceptually, our constraint-solving strategy starts by
// trying to "unify" the actual argument types to a call
// with the parameter types of the callee (which may mention
// generic parameters). E.g., if we have a situation like:
//
// void doIt<T>(T a, vector<T,3> b);
//
// int x, y;
// ...
// doIt(x, y);
//
// then an we would try to unify the type of the argument
// `x` (which is `int`) with the type of the parameter `a`
// (which is `T`). Attempting to unify a concrete type
// and a generic type parameter would (in the simplest case)
// give rise to a constraint that, e.g., `T` must be `int`.
//
// In our example, unifying `y` and `b` creates a more complex
// scenario, because we cannot ever unify `int` with `vector<T,3>`;
// there is no possible value of `T` for which those two types
// are equivalent.
//
// So instead of the simpler approach to unification (which
// works well for languages without implicit type conversion),
// our approach to unification recognizes that scalar types
// can be promoted to vectors, and thus tries to unify the
// type of `y` with the element type of `b`.
//
// When it comes time to actually solve the constraints, we
// might have seemingly conflicting constraints:
//
// void another<U>(U a, U b);
//
// float x; int y;
// another(x, y);
//
// In this case we'd have constraints that `U` must be `int`,
// *and* that `U` must be `float`, which is clearly impossible
// to satisfy. Instead, our constraints are treated as a kind
// of "lower bound" on the type variable, and we combine
// those lower bounds using the "join" operation (in the
// sense of "meet" and "join" on lattices), which ideally
// gives us a type for `U` that all the argument types can
// convert to.
namespace Slang
{
Type* SemanticsVisitor::TryJoinVectorAndScalarType(
VectorExpressionType* vectorType,
BasicExpressionType* scalarType)
{
// Join( vector<T,N>, S ) -> vetor<Join(T,S), N>
//
// That is, the join of a vector and a scalar type is
// a vector type with a joined element type.
auto joinElementType = TryJoinTypes(
vectorType->elementType,
scalarType);
if(!joinElementType)
return nullptr;
return createVectorType(
joinElementType,
vectorType->elementCount);
}
Type* SemanticsVisitor::TryJoinTypeWithInterface(
Type* type,
DeclRef<InterfaceDecl> interfaceDeclRef)
{
// The most basic test here should be: does the type declare conformance to the trait.
if(isDeclaredSubtype(type, interfaceDeclRef))
return type;
// Just because `type` doesn't conform to the given `interfaceDeclRef`, that
// doesn't necessarily indicate a failure. It is possible that we have a call
// like `sqrt(2)` so that `type` is `int` and `interfaceDeclRef` is
// `__BuiltinFloatingPointType`. The "obvious" answer is that we should infer
// the type `float`, but it seems like the compiler would have to synthesize
// that answer from thin air.
//
// A robsut/correct solution here might be to enumerate set of types types `S`
// such that for each type `X` in `S`:
//
// * `type` is implicitly convertible to `X`
// * `X` conforms to the interface named by `interfaceDeclRef`
//
// If the set `S` is non-empty then we would try to pick the "best" type from `S`.
// The "best" type would be a type `Y` such that `Y` is implicitly convertible to
// every other type in `S`.
//
// We are going to implement a much simpler strategy for now, where we only apply
// the search process if `type` is a builtin scalar type, and then we only search
// through types `X` that are also builtin scalar types.
//
Type* bestType = nullptr;
if(auto basicType = dynamicCast<BasicExpressionType>(type))
{
for(Int baseTypeFlavorIndex = 0; baseTypeFlavorIndex < Int(BaseType::CountOf); baseTypeFlavorIndex++)
{
// Don't consider `type`, since we already know it doesn't work.
if(baseTypeFlavorIndex == Int(basicType->baseType))
continue;
// Look up the type in our session.
auto candidateType = type->getASTBuilder()->getBuiltinType(BaseType(baseTypeFlavorIndex));
if(!candidateType)
continue;
// We only want to consider types that implement the target interface.
if(!isDeclaredSubtype(candidateType, interfaceDeclRef))
continue;
// We only want to consider types where we can implicitly convert from `type`
if(!canConvertImplicitly(candidateType, type))
continue;
// At this point, we have a candidate type that is usable.
//
// If this is our first viable candidate, then it is our best one:
//
if(!bestType)
{
bestType = candidateType;
}
else
{
// Otherwise, we want to pick the "better" type between `candidateType`
// and `bestType`.
//
// We are going to be a bit loose here, and not worry about the
// case where conversion is allowed in both directions.
//
// TODO: make this completely robust.
//
if(canConvertImplicitly(bestType, candidateType))
{
// Our candidate can convert to the current "best" type, so
// it is logically a more specific type that satisfies our
// constraints, therefore we should keep it.
//
bestType = candidateType;
}
}
}
if(bestType)
return bestType;
}
// For all other cases, we will just bail out for now.
//
// TODO: In the future we should build some kind of side data structure
// to accelerate either one or both of these queries:
//
// * Given a type `T`, what types `U` can it convert to implicitly?
//
// * Given an interface `I`, what types `U` conform to it?
//
// The intersection of the sets returned by these two queries is
// the set of candidates we would like to consider here.
return nullptr;
}
Type* SemanticsVisitor::TryJoinTypes(
Type* left,
Type* right)
{
// Easy case: they are the same type!
if (left->equals(right))
return left;
// We can join two basic types by picking the "better" of the two
if (auto leftBasic = as<BasicExpressionType>(left))
{
if (auto rightBasic = as<BasicExpressionType>(right))
{
auto leftFlavor = leftBasic->baseType;
auto rightFlavor = rightBasic->baseType;
// TODO(tfoley): Need a special-case rule here that if
// either operand is of type `half`, then we promote
// to at least `float`
// Return the one that had higher rank...
if (leftFlavor > rightFlavor)
return left;
else
{
SLANG_ASSERT(rightFlavor > leftFlavor); // equality was handles at the top of this function
return right;
}
}
// We can also join a vector and a scalar
if(auto rightVector = as<VectorExpressionType>(right))
{
return TryJoinVectorAndScalarType(rightVector, leftBasic);
}
}
// We can join two vector types by joining their element types
// (and also their sizes...)
if( auto leftVector = as<VectorExpressionType>(left))
{
if(auto rightVector = as<VectorExpressionType>(right))
{
// Check if the vector sizes match
if(!leftVector->elementCount->equalsVal(rightVector->elementCount))
return nullptr;
// Try to join the element types
auto joinElementType = TryJoinTypes(
leftVector->elementType,
rightVector->elementType);
if(!joinElementType)
return nullptr;
return createVectorType(
joinElementType,
leftVector->elementCount);
}
// We can also join a vector and a scalar
if(auto rightBasic = as<BasicExpressionType>(right))
{
return TryJoinVectorAndScalarType(leftVector, rightBasic);
}
}
// HACK: trying to work trait types in here...
if(auto leftDeclRefType = as<DeclRefType>(left))
{
if( auto leftInterfaceRef = leftDeclRefType->declRef.as<InterfaceDecl>() )
{
//
return TryJoinTypeWithInterface(right, leftInterfaceRef);
}
}
if(auto rightDeclRefType = as<DeclRefType>(right))
{
if( auto rightInterfaceRef = rightDeclRefType->declRef.as<InterfaceDecl>() )
{
//
return TryJoinTypeWithInterface(left, rightInterfaceRef);
}
}
// TODO: all the cases for vectors apply to matrices too!
// Default case is that we just fail.
return nullptr;
}
SubstitutionSet SemanticsVisitor::TrySolveConstraintSystem(
ConstraintSystem* system,
DeclRef<GenericDecl> genericDeclRef)
{
// For now the "solver" is going to be ridiculously simplistic.
// The generic itself will have some constraints, and for now we add these
// to the system of constrains we will use for solving for the type variables.
//
// TODO: we need to decide whether constraints are used like this to influence
// how we solve for type/value variables, or whether constraints in the parameter
// list just work as a validation step *after* we've solved for the types.
//
// That is, should we allow `<T : Int>` to be written, and cause us to "infer"
// that `T` should be the type `Int`? That seems a little silly.
//
// Eventually, though, we may want to support type identity constraints, especially
// on associated types, like `<C where C : IContainer && C.IndexType == Int>`
// These seem more reasonable to have influence constraint solving, since it could
// conceivably let us specialize a `X<T> : IContainer` to `X<Int>` if we find
// that `X<T>.IndexType == T`.
for( auto constraintDeclRef : getMembersOfType<GenericTypeConstraintDecl>(genericDeclRef) )
{
if(!TryUnifyTypes(*system, getSub(m_astBuilder, constraintDeclRef), getSup(m_astBuilder, constraintDeclRef)))
return SubstitutionSet();
}
SubstitutionSet resultSubst = genericDeclRef.substitutions;
// We will loop over the generic parameters, and for
// each we will try to find a way to satisfy all
// the constraints for that parameter
List<Val*> args;
for (auto m : getMembers(genericDeclRef))
{
if (auto typeParam = m.as<GenericTypeParamDecl>())
{
Type* type = nullptr;
for (auto& c : system->constraints)
{
if (c.decl != typeParam.getDecl())
continue;
auto cType = as<Type>(c.val);
SLANG_RELEASE_ASSERT(cType);
if (!type)
{
type = cType;
}
else
{
auto joinType = TryJoinTypes(type, cType);
if (!joinType)
{
// failure!
return SubstitutionSet();
}
type = joinType;
}
c.satisfied = true;
}
if (!type)
{
// failure!
return SubstitutionSet();
}
args.add(type);
}
else if (auto valParam = m.as<GenericValueParamDecl>())
{
// TODO(tfoley): maybe support more than integers some day?
// TODO(tfoley): figure out how this needs to interact with
// compile-time integers that aren't just constants...
IntVal* val = nullptr;
for (auto& c : system->constraints)
{
if (c.decl != valParam.getDecl())
continue;
auto cVal = as<IntVal>(c.val);
SLANG_RELEASE_ASSERT(cVal);
if (!val)
{
val = cVal;
}
else
{
if(!val->equalsVal(cVal))
{
// failure!
return SubstitutionSet();
}
}
c.satisfied = true;
}
if (!val)
{
// failure!
return SubstitutionSet();
}
args.add(val);
}
else
{
// ignore anything that isn't a generic parameter
}
}
// After we've solved for the explicit arguments, we need to
// make a second pass and consider the implicit arguments,
// based on what we've already determined to be the values
// for the explicit arguments.
// Before we begin, we are going to go ahead and create the
// "solved" substitution that we will return if everything works.
// This is because we are going to use this substitution,
// partially filled in with the results we know so far,
// in order to specialize any constraints on the generic.
//
// E.g., if the generic parameters were `<T : ISidekick>`, and
// we've already decided that `T` is `Robin`, then we want to
// search for a conformance `Robin : ISidekick`, which involved
// apply the substitutions we already know...
GenericSubstitution* solvedSubst = m_astBuilder->create<GenericSubstitution>();
solvedSubst->genericDecl = genericDeclRef.getDecl();
solvedSubst->outer = genericDeclRef.substitutions.substitutions;
solvedSubst->args = args;
resultSubst.substitutions = solvedSubst;
for( auto constraintDecl : genericDeclRef.getDecl()->getMembersOfType<GenericTypeConstraintDecl>() )
{
DeclRef<GenericTypeConstraintDecl> constraintDeclRef(
constraintDecl,
solvedSubst);
// Extract the (substituted) sub- and super-type from the constraint.
auto sub = getSub(m_astBuilder, constraintDeclRef);
auto sup = getSup(m_astBuilder, constraintDeclRef);
// Search for a witness that shows the constraint is satisfied.
auto subTypeWitness = tryGetSubtypeWitness(sub, sup);
if(subTypeWitness)
{
// We found a witness, so it will become an (implicit) argument.
solvedSubst->args.add(subTypeWitness);
}
else
{
// No witness was found, so the inference will now fail.
//
// TODO: Ideally we should print an error message in
// this case, to let the user know why things failed.
return SubstitutionSet();
}
// TODO: We may need to mark some constrains in our constraint
// system as being solved now, as a result of the witness we found.
}
// Make sure we haven't constructed any spurious constraints
// that we aren't able to satisfy:
for (auto c : system->constraints)
{
if (!c.satisfied)
{
return SubstitutionSet();
}
}
return resultSubst;
}
bool SemanticsVisitor::TryUnifyVals(
ConstraintSystem& constraints,
Val* fst,
Val* snd)
{
// if both values are types, then unify types
if (auto fstType = as<Type>(fst))
{
if (auto sndType = as<Type>(snd))
{
return TryUnifyTypes(constraints, fstType, sndType);
}
}
// if both values are constant integers, then compare them
if (auto fstIntVal = as<ConstantIntVal>(fst))
{
if (auto sndIntVal = as<ConstantIntVal>(snd))
{
return fstIntVal->value == sndIntVal->value;
}
}
// Check if both are integer values in general
if (auto fstInt = as<IntVal>(fst))
{
if (auto sndInt = as<IntVal>(snd))
{
auto fstParam = as<GenericParamIntVal>(fstInt);
auto sndParam = as<GenericParamIntVal>(sndInt);
bool okay = false;
if (fstParam)
{
if(TryUnifyIntParam(constraints, fstParam->declRef, sndInt))
okay = true;
}
if (sndParam)
{
if(TryUnifyIntParam(constraints, sndParam->declRef, fstInt))
okay = true;
}
return okay;
}
}
if (auto fstWit = as<DeclaredSubtypeWitness>(fst))
{
if (auto sndWit = as<DeclaredSubtypeWitness>(snd))
{
auto constraintDecl1 = fstWit->declRef.as<TypeConstraintDecl>();
auto constraintDecl2 = sndWit->declRef.as<TypeConstraintDecl>();
SLANG_ASSERT(constraintDecl1);
SLANG_ASSERT(constraintDecl2);
return TryUnifyTypes(constraints,
constraintDecl1.getDecl()->getSup().type,
constraintDecl2.getDecl()->getSup().type);
}
}
SLANG_UNIMPLEMENTED_X("value unification case");
// default: fail
//return false;
}
bool SemanticsVisitor::tryUnifySubstitutions(
ConstraintSystem& constraints,
Substitutions* fst,
Substitutions* snd)
{
// They must both be NULL or non-NULL
if (!fst || !snd)
return !fst && !snd;
if(auto fstGeneric = as<GenericSubstitution>(fst))
{
if(auto sndGeneric = as<GenericSubstitution>(snd))
{
return tryUnifyGenericSubstitutions(
constraints,
fstGeneric,
sndGeneric);
}
}
// TODO: need to handle other cases here
return false;
}
bool SemanticsVisitor::tryUnifyGenericSubstitutions(
ConstraintSystem& constraints,
GenericSubstitution* fst,
GenericSubstitution* snd)
{
SLANG_ASSERT(fst);
SLANG_ASSERT(snd);
auto fstGen = fst;
auto sndGen = snd;
// They must be specializing the same generic
if (fstGen->genericDecl != sndGen->genericDecl)
return false;
// Their arguments must unify
SLANG_RELEASE_ASSERT(fstGen->args.getCount() == sndGen->args.getCount());
Index argCount = fstGen->args.getCount();
bool okay = true;
for (Index aa = 0; aa < argCount; ++aa)
{
if (!TryUnifyVals(constraints, fstGen->args[aa], sndGen->args[aa]))
{
okay = false;
}
}
// Their "base" specializations must unify
if (!tryUnifySubstitutions(constraints, fstGen->outer, sndGen->outer))
{
okay = false;
}
return okay;
}
bool SemanticsVisitor::TryUnifyTypeParam(
ConstraintSystem& constraints,
GenericTypeParamDecl* typeParamDecl,
Type* type)
{
// We want to constrain the given type parameter
// to equal the given type.
Constraint constraint;
constraint.decl = typeParamDecl;
constraint.val = type;
constraints.constraints.add(constraint);
return true;
}
bool SemanticsVisitor::TryUnifyIntParam(
ConstraintSystem& constraints,
GenericValueParamDecl* paramDecl,
IntVal* val)
{
// We only want to accumulate constraints on
// the parameters of the declarations being
// specialized (don't accidentially constrain
// parameters of a generic function based on
// calls in its body).
if(paramDecl->parentDecl != constraints.genericDecl)
return false;
// We want to constrain the given parameter to equal the given value.
Constraint constraint;
constraint.decl = paramDecl;
constraint.val = val;
constraints.constraints.add(constraint);
return true;
}
bool SemanticsVisitor::TryUnifyIntParam(
ConstraintSystem& constraints,
DeclRef<VarDeclBase> const& varRef,
IntVal* val)
{
if(auto genericValueParamRef = varRef.as<GenericValueParamDecl>())
{
return TryUnifyIntParam(constraints, genericValueParamRef.getDecl(), val);
}
else
{
return false;
}
}
bool SemanticsVisitor::TryUnifyTypesByStructuralMatch(
ConstraintSystem& constraints,
Type* fst,
Type* snd)
{
if (auto fstDeclRefType = as<DeclRefType>(fst))
{
auto fstDeclRef = fstDeclRefType->declRef;
if (auto typeParamDecl = as<GenericTypeParamDecl>(fstDeclRef.getDecl()))
return TryUnifyTypeParam(constraints, typeParamDecl, snd);
if (auto sndDeclRefType = as<DeclRefType>(snd))
{
auto sndDeclRef = sndDeclRefType->declRef;
if (auto typeParamDecl = as<GenericTypeParamDecl>(sndDeclRef.getDecl()))
return TryUnifyTypeParam(constraints, typeParamDecl, fst);
// can't be unified if they refer to different declarations.
if (fstDeclRef.getDecl() != sndDeclRef.getDecl()) return false;
// next we need to unify the substitutions applied
// to each declaration reference.
if (!tryUnifySubstitutions(
constraints,
fstDeclRef.substitutions.substitutions,
sndDeclRef.substitutions.substitutions))
{
return false;
}
return true;
}
}
return false;
}
bool SemanticsVisitor::TryUnifyConjunctionType(
ConstraintSystem& constraints,
AndType* fst,
Type* snd)
{
// Unifying a type `T` with `A & B` amounts to unifying
// `T` with `A` and also `T` with `B`.
//
// If either unification is impossible, then the full
// case is also impossible.
//
return TryUnifyTypes(constraints, fst->left, snd)
&& TryUnifyTypes(constraints, fst->right, snd);
}
bool SemanticsVisitor::TryUnifyTypes(
ConstraintSystem& constraints,
Type* fst,
Type* snd)
{
if (fst->equals(snd)) return true;
// An error type can unify with anything, just so we avoid cascading errors.
if (auto fstErrorType = as<ErrorType>(fst))
return true;
if (auto sndErrorType = as<ErrorType>(snd))
return true;
// If one or the other of the types is a conjunction `X & Y`,
// then we want to recurse on both `X` and `Y`.
//
// Note that we check this case *before* we check if one of
// the types is a generic parameter below, so that we should
// never end up trying to match up a type parameter with
// a conjunction directly, and will instead find all of the
// "leaf" types we need to constrain it to.
//
if( auto fstAndType = as<AndType>(fst) )
{
return TryUnifyConjunctionType(constraints, fstAndType, snd);
}
if( auto sndAndType = as<AndType>(snd) )
{
return TryUnifyConjunctionType(constraints, sndAndType, fst);
}
// A generic parameter type can unify with anything.
// TODO: there actually needs to be some kind of "occurs check" sort
// of thing here...
if (auto fstDeclRefType = as<DeclRefType>(fst))
{
auto fstDeclRef = fstDeclRefType->declRef;
if (auto typeParamDecl = as<GenericTypeParamDecl>(fstDeclRef.getDecl()))
{
if(typeParamDecl->parentDecl == constraints.genericDecl )
return TryUnifyTypeParam(constraints, typeParamDecl, snd);
}
}
if (auto sndDeclRefType = as<DeclRefType>(snd))
{
auto sndDeclRef = sndDeclRefType->declRef;
if (auto typeParamDecl = as<GenericTypeParamDecl>(sndDeclRef.getDecl()))
{
if(typeParamDecl->parentDecl == constraints.genericDecl )
return TryUnifyTypeParam(constraints, typeParamDecl, fst);
}
}
// If we can unify the types structurally, then we are golden
if(TryUnifyTypesByStructuralMatch(constraints, fst, snd))
return true;
// Now we need to consider cases where coercion might
// need to be applied. For now we can try to do this
// in a completely ad hoc fashion, but eventually we'd
// want to do it more formally.
if(auto fstVectorType = as<VectorExpressionType>(fst))
{
if(auto sndScalarType = as<BasicExpressionType>(snd))
{
return TryUnifyTypes(
constraints,
fstVectorType->elementType,
sndScalarType);
}
}
if(auto fstScalarType = as<BasicExpressionType>(fst))
{
if(auto sndVectorType = as<VectorExpressionType>(snd))
{
return TryUnifyTypes(
constraints,
fstScalarType,
sndVectorType->elementType);
}
}
// TODO: the same thing for vectors...
return false;
}
}
| 28,037 | 7,329 |
// decoderbin/nbest-to-ctm.cc
// Copyright 2012 Johns Hopkins University (Author: Daniel Povey)
// See ../../COPYING for clarification regarding multiple authors
//
// 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
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
// See the Apache 2 License for the specific language governing permissions and
// limitations under the License.
#include "base/kaldi-common.h"
#include "util/common-utils.h"
#include "lat/lattice-functions.h"
int main(int argc, char *argv[]) {
try {
using namespace eesen;
typedef eesen::int32 int32;
const char *usage =
"Takes as input lattices which must be linear (single path),\n"
"and must be in CompactLattice form where the transition-ids on the arcs\n"
"have been aligned with the word boundaries... typically the input will\n"
"be a lattice that has been piped through lattice-1best and then\n"
"lattice-word-align. It outputs ctm format (with integers in place of words),\n"
"assuming the frame length is 0.01 seconds by default (change this with the\n"
"--frame-length option). Note: the output is in the form\n"
"utterance-id 1 <begin-time> <end-time> <word-id>\n"
"and you can post-process this to account for segmentation issues and to \n"
"convert ints to words; note, the times are relative to start of the utterance.\n"
"\n"
"Usage: nbest-to-ctm [options] <aligned-linear-lattice-rspecifier> <ctm-wxfilename>\n"
"e.g.: lattice-1best --acoustic-weight=0.08333 ark:1.lats | \\\n"
" lattice-align-words data/lang/phones/word_boundary.int exp/dir/final.mdl ark:- ark:- | \\\n"
" nbest-to-ctm ark:- 1.ctm\n";
ParseOptions po(usage);
BaseFloat frame_shift = 0.01;
int32 precision = 2;
po.Register("frame-shift", &frame_shift, "Time in seconds between frames.\n");
po.Register("precision", &precision,
"Number of decimal places for start duration times\n");
po.Read(argc, argv);
if (po.NumArgs() != 2) {
po.PrintUsage();
exit(1);
}
std::string lats_rspecifier = po.GetArg(1),
ctm_wxfilename = po.GetArg(2);
SequentialCompactLatticeReader clat_reader(lats_rspecifier);
int32 n_done = 0, n_err = 0;
Output ko(ctm_wxfilename, false); // false == non-binary write mode.
ko.Stream() << std::fixed; // Set to "fixed" floating point model, where precision() specifies
// the #digits after the decimal point.
ko.Stream().precision(precision);
for (; !clat_reader.Done(); clat_reader.Next()) {
std::string key = clat_reader.Key();
CompactLattice clat = clat_reader.Value();
std::vector<int32> words, times, lengths;
if (!CompactLatticeToWordAlignment(clat, &words, ×, &lengths)) {
n_err++;
KALDI_WARN << "Format conversion failed for key " << key;
} else {
KALDI_ASSERT(words.size() == times.size() &&
words.size() == lengths.size());
for (size_t i = 0; i < words.size(); i++) {
if (words[i] == 0) // Don't output anything for <eps> links, which
continue; // correspond to silence....
ko.Stream() << key << " 1 " << (frame_shift * times[i]) << ' '
<< (frame_shift * lengths[i]) << ' ' << words[i] <<std::endl;
}
n_done++;
}
}
ko.Close(); // Note: we don't normally call Close() on these things,
// we just let them go out of scope and it happens automatically.
// We do it this time in order to avoid wrongly printing out a success message
// if the stream was going to fail to close
KALDI_LOG << "Converted " << n_done << " linear lattices to ctm format; "
<< n_err << " had errors.";
return (n_done != 0 ? 0 : 1);
} catch(const std::exception &e) {
std::cerr << e.what();
return -1;
}
}
| 4,366 | 1,454 |
/* !!!! GENERATED FILE - DO NOT EDIT !!!!
* --------------------------------------
*
* This file is part of liblcf. Copyright (c) 2019 liblcf authors.
* https://github.com/EasyRPG/liblcf - https://easyrpg.org
*
* liblcf is Free/Libre Open Source Software, released under the MIT License.
* For the full copyright and license information, please view the COPYING
* file that was distributed with this source code.
*/
// Headers
#include "lsd_reader.h"
#include "lsd_chunks.h"
#include "reader_struct_impl.h"
// Read SavePicture.
template <>
char const* const Struct<RPG::SavePicture>::name = "SavePicture";
template <>
Field<RPG::SavePicture> const* Struct<RPG::SavePicture>::fields[] = {
new TypedField<RPG::SavePicture, std::string>(
&RPG::SavePicture::name,
LSD_Reader::ChunkSavePicture::name,
"name",
0,
0
),
new TypedField<RPG::SavePicture, double>(
&RPG::SavePicture::start_x,
LSD_Reader::ChunkSavePicture::start_x,
"start_x",
0,
0
),
new TypedField<RPG::SavePicture, double>(
&RPG::SavePicture::start_y,
LSD_Reader::ChunkSavePicture::start_y,
"start_y",
0,
0
),
new TypedField<RPG::SavePicture, double>(
&RPG::SavePicture::current_x,
LSD_Reader::ChunkSavePicture::current_x,
"current_x",
0,
0
),
new TypedField<RPG::SavePicture, double>(
&RPG::SavePicture::current_y,
LSD_Reader::ChunkSavePicture::current_y,
"current_y",
0,
0
),
new TypedField<RPG::SavePicture, bool>(
&RPG::SavePicture::fixed_to_map,
LSD_Reader::ChunkSavePicture::fixed_to_map,
"fixed_to_map",
0,
0
),
new TypedField<RPG::SavePicture, double>(
&RPG::SavePicture::current_magnify,
LSD_Reader::ChunkSavePicture::current_magnify,
"current_magnify",
0,
0
),
new TypedField<RPG::SavePicture, double>(
&RPG::SavePicture::current_top_trans,
LSD_Reader::ChunkSavePicture::current_top_trans,
"current_top_trans",
0,
0
),
new TypedField<RPG::SavePicture, bool>(
&RPG::SavePicture::transparency,
LSD_Reader::ChunkSavePicture::transparency,
"transparency",
0,
0
),
new TypedField<RPG::SavePicture, double>(
&RPG::SavePicture::current_red,
LSD_Reader::ChunkSavePicture::current_red,
"current_red",
0,
0
),
new TypedField<RPG::SavePicture, double>(
&RPG::SavePicture::current_green,
LSD_Reader::ChunkSavePicture::current_green,
"current_green",
0,
0
),
new TypedField<RPG::SavePicture, double>(
&RPG::SavePicture::current_blue,
LSD_Reader::ChunkSavePicture::current_blue,
"current_blue",
0,
0
),
new TypedField<RPG::SavePicture, double>(
&RPG::SavePicture::current_sat,
LSD_Reader::ChunkSavePicture::current_sat,
"current_sat",
0,
0
),
new TypedField<RPG::SavePicture, int32_t>(
&RPG::SavePicture::effect_mode,
LSD_Reader::ChunkSavePicture::effect_mode,
"effect_mode",
0,
0
),
new TypedField<RPG::SavePicture, double>(
&RPG::SavePicture::current_effect,
LSD_Reader::ChunkSavePicture::current_effect,
"current_effect",
0,
0
),
new TypedField<RPG::SavePicture, double>(
&RPG::SavePicture::current_bot_trans,
LSD_Reader::ChunkSavePicture::current_bot_trans,
"current_bot_trans",
0,
0
),
new TypedField<RPG::SavePicture, int32_t>(
&RPG::SavePicture::spritesheet_cols,
LSD_Reader::ChunkSavePicture::spritesheet_cols,
"spritesheet_cols",
0,
0
),
new TypedField<RPG::SavePicture, int32_t>(
&RPG::SavePicture::spritesheet_rows,
LSD_Reader::ChunkSavePicture::spritesheet_rows,
"spritesheet_rows",
0,
0
),
new TypedField<RPG::SavePicture, int32_t>(
&RPG::SavePicture::spritesheet_frame,
LSD_Reader::ChunkSavePicture::spritesheet_frame,
"spritesheet_frame",
0,
0
),
new TypedField<RPG::SavePicture, int32_t>(
&RPG::SavePicture::spritesheet_speed,
LSD_Reader::ChunkSavePicture::spritesheet_speed,
"spritesheet_speed",
0,
0
),
new TypedField<RPG::SavePicture, int32_t>(
&RPG::SavePicture::frames,
LSD_Reader::ChunkSavePicture::frames,
"frames",
0,
0
),
new TypedField<RPG::SavePicture, bool>(
&RPG::SavePicture::spritesheet_play_once,
LSD_Reader::ChunkSavePicture::spritesheet_play_once,
"spritesheet_play_once",
0,
0
),
new TypedField<RPG::SavePicture, int32_t>(
&RPG::SavePicture::map_layer,
LSD_Reader::ChunkSavePicture::map_layer,
"map_layer",
0,
0
),
new TypedField<RPG::SavePicture, int32_t>(
&RPG::SavePicture::battle_layer,
LSD_Reader::ChunkSavePicture::battle_layer,
"battle_layer",
0,
0
),
new TypedField<RPG::SavePicture, RPG::SavePicture::Flags>(
&RPG::SavePicture::flags,
LSD_Reader::ChunkSavePicture::flags,
"flags",
0,
0
),
new TypedField<RPG::SavePicture, double>(
&RPG::SavePicture::finish_x,
LSD_Reader::ChunkSavePicture::finish_x,
"finish_x",
0,
0
),
new TypedField<RPG::SavePicture, double>(
&RPG::SavePicture::finish_y,
LSD_Reader::ChunkSavePicture::finish_y,
"finish_y",
0,
0
),
new TypedField<RPG::SavePicture, int32_t>(
&RPG::SavePicture::finish_magnify,
LSD_Reader::ChunkSavePicture::finish_magnify,
"finish_magnify",
0,
0
),
new TypedField<RPG::SavePicture, int32_t>(
&RPG::SavePicture::finish_top_trans,
LSD_Reader::ChunkSavePicture::finish_top_trans,
"finish_top_trans",
0,
0
),
new TypedField<RPG::SavePicture, int32_t>(
&RPG::SavePicture::finish_bot_trans,
LSD_Reader::ChunkSavePicture::finish_bot_trans,
"finish_bot_trans",
0,
0
),
new TypedField<RPG::SavePicture, int32_t>(
&RPG::SavePicture::finish_red,
LSD_Reader::ChunkSavePicture::finish_red,
"finish_red",
0,
0
),
new TypedField<RPG::SavePicture, int32_t>(
&RPG::SavePicture::finish_green,
LSD_Reader::ChunkSavePicture::finish_green,
"finish_green",
0,
0
),
new TypedField<RPG::SavePicture, int32_t>(
&RPG::SavePicture::finish_blue,
LSD_Reader::ChunkSavePicture::finish_blue,
"finish_blue",
0,
0
),
new TypedField<RPG::SavePicture, int32_t>(
&RPG::SavePicture::finish_sat,
LSD_Reader::ChunkSavePicture::finish_sat,
"finish_sat",
0,
0
),
new TypedField<RPG::SavePicture, int32_t>(
&RPG::SavePicture::finish_effect,
LSD_Reader::ChunkSavePicture::finish_effect,
"finish_effect",
0,
0
),
new TypedField<RPG::SavePicture, int32_t>(
&RPG::SavePicture::time_left,
LSD_Reader::ChunkSavePicture::time_left,
"time_left",
0,
0
),
new TypedField<RPG::SavePicture, double>(
&RPG::SavePicture::current_rotation,
LSD_Reader::ChunkSavePicture::current_rotation,
"current_rotation",
0,
0
),
new TypedField<RPG::SavePicture, int32_t>(
&RPG::SavePicture::current_waver,
LSD_Reader::ChunkSavePicture::current_waver,
"current_waver",
0,
0
),
NULL
};
template class Struct<RPG::SavePicture>;
| 6,676 | 2,937 |